]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
696c405908fd939d7ad1eefe437e51a4cd69ed70
[vlc] / modules / audio_output / alsa.c
1 /*****************************************************************************
2  * alsa.c : alsa plugin for vlc
3  *****************************************************************************
4  * Copyright (C) 2000-2001 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Henri Fallon <henri@videolan.org> - Original Author
8  *          Jeffrey Baker <jwbaker@acm.org> - Port to ALSA 1.0 API
9  *          John Paul Lorenti <jpl31@columbia.edu> - Device selection
10  *          Arnaud de Bossoreille de Ribou <bozo@via.ecp.fr> - S/PDIF and aout3
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <assert.h>
35
36 #include <vlc_common.h>
37 #include <vlc_plugin.h>
38
39 #include <errno.h>                                                 /* ENOMEM */
40 #include <vlc_dialog.h>
41
42 #include <vlc_aout.h>
43 #include <vlc_cpu.h>
44
45 /* ALSA part
46    Note: we use the new API which is available since 0.9.0beta10a. */
47 #define ALSA_PCM_NEW_HW_PARAMS_API
48 #define ALSA_PCM_NEW_SW_PARAMS_API
49 #include <alsa/asoundlib.h>
50 #include <alsa/version.h>
51
52 /*#define ALSA_DEBUG*/
53
54 /*****************************************************************************
55  * aout_sys_t: ALSA audio output method descriptor
56  *****************************************************************************
57  * This structure is part of the audio output thread descriptor.
58  * It describes the ALSA specific properties of an audio device.
59  *****************************************************************************/
60 struct aout_sys_t
61 {
62     snd_pcm_t         * p_snd_pcm;
63     unsigned int                 i_period_time;
64
65 #ifdef ALSA_DEBUG
66     snd_output_t      * p_snd_stderr;
67 #endif
68
69     mtime_t      start_date;
70     vlc_thread_t thread;
71     vlc_sem_t    wait;
72 };
73
74 #define A52_FRAME_NB 1536
75
76 /* These values are in frames.
77    To convert them to a number of bytes you have to multiply them by the
78    number of channel(s) (eg. 2 for stereo) and the size of a sample (eg.
79    2 for int16_t). */
80 #define ALSA_DEFAULT_PERIOD_SIZE        1024
81 #define ALSA_DEFAULT_BUFFER_SIZE        ( ALSA_DEFAULT_PERIOD_SIZE << 8 )
82 #define ALSA_SPDIF_PERIOD_SIZE          A52_FRAME_NB
83 #define ALSA_SPDIF_BUFFER_SIZE          ( ALSA_SPDIF_PERIOD_SIZE << 4 )
84 /* Why << 4 ? --Meuuh */
85 /* Why not ? --Bozo */
86 /* Right. --Meuuh */
87
88 #define DEFAULT_ALSA_DEVICE "default"
89
90 /*****************************************************************************
91  * Local prototypes
92  *****************************************************************************/
93 static int   Open         ( vlc_object_t * );
94 static void  Close        ( vlc_object_t * );
95 static void  Play         ( audio_output_t * );
96 static void* ALSAThread   ( void * );
97 static void  ALSAFill     ( audio_output_t * );
98 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
99                                 vlc_value_t newval, vlc_value_t oldval, void *p_unused );
100 static void GetDevices( vlc_object_t *, module_config_t * );
101
102 /*****************************************************************************
103  * Module descriptor
104  *****************************************************************************/
105 static const char *const ppsz_devices[] = {
106     "default", "plug:front",
107     "plug:side", "plug:rear", "plug:center_lfe",
108     "plug:surround40", "plug:surround41",
109     "plug:surround50", "plug:surround51",
110     "plug:surround71",
111     "hdmi", "iec958",
112 };
113 static const char *const ppsz_devices_text[] = {
114     N_("Default"), N_("Front speakers"),
115     N_("Side speakers"), N_("Rear speakers"), N_("Center and subwoofer"),
116     N_("Surround 4.0"), N_("Surround 4.1"),
117     N_("Surround 5.0"), N_("Surround 5.1"),
118     N_("Surround 7.1"),
119     N_("HDMI"), N_("S/PDIF"),
120 };
121 vlc_module_begin ()
122     set_shortname( "ALSA" )
123     set_description( N_("ALSA audio output") )
124     set_category( CAT_AUDIO )
125     set_subcategory( SUBCAT_AUDIO_AOUT )
126     add_string( "alsa-audio-device", DEFAULT_ALSA_DEVICE,
127                 N_("ALSA Device Name"), NULL, false )
128         add_deprecated_alias( "alsadev" )   /* deprecated since 0.9.3 */
129         change_string_list( ppsz_devices, ppsz_devices_text, FindDevicesCallback )
130         change_action_add( FindDevicesCallback, N_("Refresh list") )
131
132     set_capability( "audio output", 150 )
133     set_callbacks( Open, Close )
134 vlc_module_end ()
135
136 /* VLC will insert a resampling filter in any case, so it is best to turn off
137  * ALSA (plug) resampling. */
138 static const int mode = SND_PCM_NO_AUTO_RESAMPLE
139 /* ALSA just discards extra channels. Not good. Disable it. */
140                       | SND_PCM_NO_AUTO_CHANNELS
141 /* VLC is currently unable to leverage ALSA softvol. Disable it. */
142                       | SND_PCM_NO_SOFTVOL;
143
144 /**
145  * Initializes list of devices.
146  */
147 static void Probe (vlc_object_t *obj)
148 {
149     /* Due to design bug in audio output core, this hack is required: */
150     if (var_Type (obj, "audio-device"))
151         return;
152
153     /* The variable does not exist - first call. */
154     vlc_value_t text;
155
156     var_Create (obj, "audio-device", VLC_VAR_STRING | VLC_VAR_HASCHOICE);
157     text.psz_string = _("Audio Device");
158     var_Change (obj, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
159
160     GetDevices (obj, NULL);
161
162     var_AddCallback (obj, "audio-device", aout_ChannelsRestart, NULL);
163     var_TriggerCallback (obj, "intf-change");
164 }
165
166 /*****************************************************************************
167  * Open: create a handle and open an alsa device
168  *****************************************************************************
169  * This function opens an alsa device, through the alsa API.
170  *
171  * Note: the only heap-allocated string is psz_device. All the other pointers
172  * are references to psz_device or to stack-allocated data.
173  *****************************************************************************/
174 static int Open (vlc_object_t *obj)
175 {
176     audio_output_t * p_aout = (audio_output_t *)obj;
177
178     /* Get device name */
179     char *psz_device;
180
181     if (var_Type (p_aout, "audio-device"))
182         psz_device = var_GetString (p_aout, "audio-device");
183     else
184         psz_device = var_InheritString( p_aout, "alsa-audio-device" );
185     if (unlikely(psz_device == NULL))
186         return VLC_ENOMEM;
187
188     snd_pcm_format_t pcm_format; /* ALSA sample format */
189     vlc_fourcc_t fourcc = p_aout->format.i_format;
190     bool spdif = false;
191
192     switch (fourcc)
193     {
194         case VLC_CODEC_F64B:
195             pcm_format = SND_PCM_FORMAT_FLOAT64_BE;
196             break;
197         case VLC_CODEC_F64L:
198             pcm_format = SND_PCM_FORMAT_FLOAT64_LE;
199             break;
200         case VLC_CODEC_F32B:
201             pcm_format = SND_PCM_FORMAT_FLOAT_BE;
202             break;
203         case VLC_CODEC_F32L:
204             pcm_format = SND_PCM_FORMAT_FLOAT_LE;
205             break;
206         case VLC_CODEC_FI32:
207             fourcc = VLC_CODEC_FL32;
208             pcm_format = SND_PCM_FORMAT_FLOAT;
209             break;
210         case VLC_CODEC_S32B:
211             pcm_format = SND_PCM_FORMAT_S32_BE;
212             break;
213         case VLC_CODEC_S32L:
214             pcm_format = SND_PCM_FORMAT_S32_LE;
215             break;
216         case VLC_CODEC_S24B:
217             pcm_format = SND_PCM_FORMAT_S24_3BE;
218             break;
219         case VLC_CODEC_S24L:
220             pcm_format = SND_PCM_FORMAT_S24_3LE;
221             break;
222         case VLC_CODEC_U24B:
223             pcm_format = SND_PCM_FORMAT_U24_3BE;
224             break;
225         case VLC_CODEC_U24L:
226             pcm_format = SND_PCM_FORMAT_U24_3LE;
227             break;
228         case VLC_CODEC_S16B:
229             pcm_format = SND_PCM_FORMAT_S16_BE;
230             break;
231         case VLC_CODEC_S16L:
232             pcm_format = SND_PCM_FORMAT_S16_LE;
233             break;
234         case VLC_CODEC_U16B:
235             pcm_format = SND_PCM_FORMAT_U16_BE;
236             break;
237         case VLC_CODEC_U16L:
238             pcm_format = SND_PCM_FORMAT_U16_LE;
239             break;
240         case VLC_CODEC_S8:
241             pcm_format = SND_PCM_FORMAT_S8;
242             break;
243         case VLC_CODEC_U8:
244             pcm_format = SND_PCM_FORMAT_U8;
245             break;
246         default:
247             if (AOUT_FMT_NON_LINEAR(&p_aout->format))
248                 spdif = var_InheritBool (p_aout, "spdif");
249             if (HAVE_FPU)
250             {
251                 fourcc = VLC_CODEC_FL32;
252                 pcm_format = SND_PCM_FORMAT_FLOAT;
253             }
254             else
255             {
256                 fourcc = VLC_CODEC_S16N;
257                 pcm_format = SND_PCM_FORMAT_S16;
258             }
259     }
260
261     /* Choose the IEC device for S/PDIF output:
262        if the device is overridden by the user then it will be the one
263        otherwise we compute the default device based on the output format. */
264     if (spdif && !strcmp (psz_device, DEFAULT_ALSA_DEVICE))
265     {
266         unsigned aes3;
267
268         switch (p_aout->format.i_rate)
269         {
270 #define FS(freq) \
271             case freq: aes3 = IEC958_AES3_CON_FS_ ## freq; break;
272             FS( 44100) /* def. */ FS( 48000) FS( 32000)
273             FS( 22050)            FS( 24000)
274             FS( 88200) FS(768000) FS( 96000)
275             FS(176400)            FS(192000)
276 #undef FS
277             default:
278                 aes3 = IEC958_AES3_CON_FS_NOTID;
279                 break;
280         }
281
282         free (psz_device);
283         if (asprintf (&psz_device,
284                       "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
285                       IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
286                       IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
287                       0, aes3) == -1)
288             return VLC_ENOMEM;
289     }
290
291     /* Allocate structures */
292     aout_sys_t *p_sys = malloc (sizeof (*p_sys));
293     if (unlikely(p_sys == NULL))
294     {
295         free (psz_device);
296         return VLC_ENOMEM;
297     }
298     p_aout->sys = p_sys;
299
300 #ifdef ALSA_DEBUG
301     snd_output_stdio_attach( &p_sys->p_snd_stderr, stderr, 0 );
302 #endif
303
304     /* Open the device */
305     msg_Dbg( p_aout, "opening ALSA device `%s'", psz_device );
306     int val = snd_pcm_open (&p_sys->p_snd_pcm, psz_device,
307                             SND_PCM_STREAM_PLAYBACK, mode);
308 #if (SND_LIB_VERSION <= 0x010015)
309 # warning Please update alsa-lib to version > 1.0.21a.
310     var_Create (p_aout->p_libvlc, "alsa-working", VLC_VAR_BOOL);
311     if (val != 0 && var_GetBool (p_aout->p_libvlc, "alsa-working"))
312         dialog_Fatal (p_aout, "ALSA version problem",
313             "VLC failed to re-initialize your audio output device.\n"
314             "Please update alsa-lib to version 1.0.22 or higher "
315             "to fix this issue.");
316     var_SetBool (p_aout->p_libvlc, "alsa-working", !val);
317 #endif
318     if (val != 0)
319     {
320 #if (SND_LIB_VERSION <= 0x010017)
321 # warning Please update alsa-lib to version > 1.0.23.
322         var_Create (p_aout->p_libvlc, "alsa-broken", VLC_VAR_BOOL);
323         if (!var_GetBool (p_aout->p_libvlc, "alsa-broken"))
324         {
325             var_SetBool (p_aout->p_libvlc, "alsa-broken", true);
326             dialog_Fatal (p_aout, "Potential ALSA version problem",
327                 "VLC failed to initialize your audio output device (if any).\n"
328                 "Please update alsa-lib to version 1.0.24 or higher "
329                 "to try to fix this issue.");
330         }
331 #endif
332         msg_Err (p_aout, "cannot open ALSA device `%s' (%s)",
333                  psz_device, snd_strerror (val));
334         dialog_Fatal (p_aout, _("Audio output failed"),
335                       _("The audio device \"%s\" could not be used:\n%s."),
336                       psz_device, snd_strerror (val));
337         free (psz_device);
338         free (p_sys);
339         return VLC_EGENERIC;
340     }
341     free( psz_device );
342
343     snd_pcm_uframes_t i_buffer_size;
344     snd_pcm_uframes_t i_period_size;
345     unsigned channels;
346
347     if (spdif)
348     {
349         fourcc = VLC_CODEC_SPDIFL;
350         i_buffer_size = ALSA_SPDIF_BUFFER_SIZE;
351         pcm_format = SND_PCM_FORMAT_S16;
352         channels = 2;
353
354         p_aout->i_nb_samples = i_period_size = ALSA_SPDIF_PERIOD_SIZE;
355         p_aout->format.i_bytes_per_frame = AOUT_SPDIF_SIZE;
356         p_aout->format.i_frame_length = A52_FRAME_NB;
357
358         aout_VolumeNoneInit( p_aout );
359     }
360     else
361     {
362         i_buffer_size = ALSA_DEFAULT_BUFFER_SIZE;
363         channels = aout_FormatNbChannels( &p_aout->format );
364
365         p_aout->i_nb_samples = i_period_size = ALSA_DEFAULT_PERIOD_SIZE;
366
367         aout_VolumeSoftInit( p_aout );
368     }
369
370     p_aout->pf_play = Play;
371     p_aout->pf_pause = NULL;
372
373     snd_pcm_hw_params_t *p_hw;
374     snd_pcm_sw_params_t *p_sw;
375
376     snd_pcm_hw_params_alloca(&p_hw);
377     snd_pcm_sw_params_alloca(&p_sw);
378
379     /* Get Initial hardware parameters */
380     val = snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw );
381     if( val < 0 )
382     {
383         msg_Err( p_aout, "unable to retrieve hardware parameters (%s)",
384                 snd_strerror( val ) );
385         goto error;
386     }
387
388     /* Set format. */
389     val = snd_pcm_hw_params_set_format (p_sys->p_snd_pcm, p_hw, pcm_format);
390     if( val < 0 )
391     {
392         msg_Err (p_aout, "cannot set sample format: %s", snd_strerror (val));
393         goto error;
394     }
395
396     val = snd_pcm_hw_params_set_access( p_sys->p_snd_pcm, p_hw,
397                                         SND_PCM_ACCESS_RW_INTERLEAVED );
398     if( val < 0 )
399     {
400         msg_Err( p_aout, "unable to set interleaved stream format (%s)",
401                  snd_strerror( val ) );
402         goto error;
403     }
404
405     /* Set channels. */
406     val = snd_pcm_hw_params_set_channels (p_sys->p_snd_pcm, p_hw, channels);
407     if (val < 0 && channels > 2) /* Fallback to stereo */
408     {
409         val = snd_pcm_hw_params_set_channels (p_sys->p_snd_pcm, p_hw, 2);
410         channels = 2;
411     }
412     if (val < 0)
413     {
414         msg_Err( p_aout, "unable to set number of output channels (%s)",
415                  snd_strerror( val ) );
416         goto error;
417     }
418
419     /* Set rate. */
420     unsigned rate = p_aout->format.i_rate;
421     val = snd_pcm_hw_params_set_rate_near (p_sys->p_snd_pcm, p_hw, &rate,
422                                            NULL);
423     if (val < 0)
424     {
425         msg_Err (p_aout, "unable to set sampling rate (%s)",
426                  snd_strerror (val));
427         goto error;
428     }
429     if (p_aout->format.i_rate != rate)
430         msg_Warn (p_aout, "resampling from %d Hz to %d Hz",
431                   p_aout->format.i_rate, rate);
432
433     /* Set period size. */
434     val = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm, p_hw,
435                                                   &i_period_size, NULL );
436     if( val < 0 )
437     {
438         msg_Err( p_aout, "unable to set period size (%s)",
439                  snd_strerror( val ) );
440         goto error;
441     }
442     p_aout->i_nb_samples = i_period_size;
443
444     /* Set buffer size. */
445     val = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm, p_hw,
446                                                   &i_buffer_size );
447     if( val )
448     {
449         msg_Err( p_aout, "unable to set buffer size (%s)",
450                  snd_strerror( val ) );
451         goto error;
452     }
453
454     /* Commit hardware parameters. */
455     val = snd_pcm_hw_params( p_sys->p_snd_pcm, p_hw );
456     if( val < 0 )
457     {
458         msg_Err( p_aout, "unable to commit hardware configuration (%s)",
459                  snd_strerror( val ) );
460         goto error;
461     }
462
463     val = snd_pcm_hw_params_get_period_time( p_hw, &p_sys->i_period_time,
464                                              NULL );
465     if( val < 0 )
466     {
467         msg_Err( p_aout, "unable to get period time (%s)",
468                  snd_strerror( val ) );
469         goto error;
470     }
471
472     /* Get Initial software parameters */
473     snd_pcm_sw_params_current( p_sys->p_snd_pcm, p_sw );
474
475     snd_pcm_sw_params_set_avail_min( p_sys->p_snd_pcm, p_sw,
476                                      p_aout->i_nb_samples );
477     /* start playing when one period has been written */
478     val = snd_pcm_sw_params_set_start_threshold( p_sys->p_snd_pcm, p_sw,
479                                                  ALSA_DEFAULT_PERIOD_SIZE);
480     if( val < 0 )
481     {
482         msg_Err( p_aout, "unable to set start threshold (%s)",
483                  snd_strerror( val ) );
484         goto error;
485     }
486
487     /* Commit software parameters. */
488     if ( snd_pcm_sw_params( p_sys->p_snd_pcm, p_sw ) < 0 )
489     {
490         msg_Err( p_aout, "unable to set software configuration" );
491         goto error;
492     }
493
494 #ifdef ALSA_DEBUG
495     snd_output_printf( p_sys->p_snd_stderr, "\nALSA hardware setup:\n\n" );
496     snd_pcm_dump_hw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
497     snd_output_printf( p_sys->p_snd_stderr, "\nALSA software setup:\n\n" );
498     snd_pcm_dump_sw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
499     snd_output_printf( p_sys->p_snd_stderr, "\n" );
500 #endif
501
502     p_sys->start_date = 0;
503     vlc_sem_init( &p_sys->wait, 0 );
504
505     /* Create ALSA thread and wait for its readiness. */
506     if( vlc_clone( &p_sys->thread, ALSAThread, p_aout,
507                    VLC_THREAD_PRIORITY_OUTPUT ) )
508     {
509         msg_Err( p_aout, "cannot create ALSA thread (%m)" );
510         vlc_sem_destroy( &p_sys->wait );
511         goto error;
512     }
513
514     p_aout->format.i_format = fourcc;
515     p_aout->format.i_rate = rate;
516     if (channels == 2)
517         p_aout->format.i_physical_channels = AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT;
518
519     Probe (obj);
520     return 0;
521
522 error:
523     snd_pcm_close( p_sys->p_snd_pcm );
524 #ifdef ALSA_DEBUG
525     snd_output_close( p_sys->p_snd_stderr );
526 #endif
527     free( p_sys );
528     return VLC_EGENERIC;
529 }
530
531 static void PlayIgnore( audio_output_t *p_aout )
532 {   /* Already playing - nothing to do */
533     (void) p_aout;
534 }
535
536 /*****************************************************************************
537  * Play: start playback
538  *****************************************************************************/
539 static void Play( audio_output_t *p_aout )
540 {
541     p_aout->pf_play = PlayIgnore;
542
543     /* get the playing date of the first aout buffer */
544     p_aout->sys->start_date = aout_FifoFirstDate( &p_aout->fifo );
545
546     /* wake up the audio output thread */
547     sem_post( &p_aout->sys->wait );
548 }
549
550 /*****************************************************************************
551  * Close: close the ALSA device
552  *****************************************************************************/
553 static void Close (vlc_object_t *obj)
554 {
555     audio_output_t *p_aout = (audio_output_t *)obj;
556     struct aout_sys_t * p_sys = p_aout->sys;
557
558     /* Make sure that the thread will stop once it is waken up */
559     vlc_cancel( p_sys->thread );
560     vlc_join( p_sys->thread, NULL );
561     vlc_sem_destroy( &p_sys->wait );
562
563     snd_pcm_drop( p_sys->p_snd_pcm );
564     snd_pcm_close( p_sys->p_snd_pcm );
565 #ifdef ALSA_DEBUG
566     snd_output_close( p_sys->p_snd_stderr );
567 #endif
568     free( p_sys );
569 }
570
571 /*****************************************************************************
572  * ALSAThread: asynchronous thread used to DMA the data to the device
573  *****************************************************************************/
574 static void* ALSAThread( void *data )
575 {
576     audio_output_t * p_aout = data;
577     struct aout_sys_t * p_sys = p_aout->sys;
578
579     /* Wait for the exact time to start playing (avoids resampling) */
580     vlc_sem_wait( &p_sys->wait );
581     mwait( p_sys->start_date - AOUT_MAX_PTS_ADVANCE / 4 );
582 #warning Should wait for buffer availability instead!
583
584     for(;;)
585         ALSAFill( p_aout );
586
587     assert(0);
588 }
589
590 /*****************************************************************************
591  * ALSAFill: function used to fill the ALSA buffer as much as possible
592  *****************************************************************************/
593 static void ALSAFill( audio_output_t * p_aout )
594 {
595     struct aout_sys_t * p_sys = p_aout->sys;
596     snd_pcm_t *p_pcm = p_sys->p_snd_pcm;
597     snd_pcm_status_t * p_status;
598     int i_snd_rc;
599     mtime_t next_date;
600
601     int canc = vlc_savecancel();
602     /* Fill in the buffer until space or audio output buffer shortage */
603
604     /* Get the status */
605     snd_pcm_status_alloca(&p_status);
606     i_snd_rc = snd_pcm_status( p_pcm, p_status );
607     if( i_snd_rc < 0 )
608     {
609         msg_Err( p_aout, "cannot get device status" );
610         goto error;
611     }
612
613     /* Handle buffer underruns and get the status again */
614     if( snd_pcm_status_get_state( p_status ) == SND_PCM_STATE_XRUN )
615     {
616         /* Prepare the device */
617         i_snd_rc = snd_pcm_prepare( p_pcm );
618         if( i_snd_rc )
619         {
620             msg_Err( p_aout, "cannot recover from buffer underrun" );
621             goto error;
622         }
623
624         msg_Dbg( p_aout, "recovered from buffer underrun" );
625
626         /* Get the new status */
627         i_snd_rc = snd_pcm_status( p_pcm, p_status );
628         if( i_snd_rc < 0 )
629         {
630             msg_Err( p_aout, "cannot get device status after recovery" );
631             goto error;
632         }
633
634         /* Underrun, try to recover as quickly as possible */
635         next_date = mdate();
636     }
637     else
638     {
639         /* Here the device should be in RUNNING state, p_status is valid. */
640         snd_pcm_sframes_t delay = snd_pcm_status_get_delay( p_status );
641         if( delay == 0 ) /* workaround buggy alsa drivers */
642             if( snd_pcm_delay( p_pcm, &delay ) < 0 )
643                 delay = 0; /* FIXME: use a positive minimal delay */
644
645         size_t i_bytes = snd_pcm_frames_to_bytes( p_pcm, delay );
646         mtime_t delay_us = CLOCK_FREQ * i_bytes
647                 / p_aout->format.i_bytes_per_frame
648                 / p_aout->format.i_rate
649                 * p_aout->format.i_frame_length;
650
651 #ifdef ALSA_DEBUG
652         snd_pcm_state_t state = snd_pcm_status_get_state( p_status );
653         if( state != SND_PCM_STATE_RUNNING )
654             msg_Err( p_aout, "pcm status (%d) != RUNNING", state );
655
656         msg_Dbg( p_aout, "Delay is %ld frames (%zu bytes)", delay, i_bytes );
657
658         msg_Dbg( p_aout, "Bytes per frame: %d", p_aout->format.i_bytes_per_frame );
659         msg_Dbg( p_aout, "Rate: %d", p_aout->format.i_rate );
660         msg_Dbg( p_aout, "Frame length: %d", p_aout->format.i_frame_length );
661         msg_Dbg( p_aout, "Next date: in %"PRId64" microseconds", delay_us );
662 #endif
663         next_date = mdate() + delay_us;
664     }
665
666     block_t *p_buffer = aout_OutputNextBuffer( p_aout, next_date,
667            (p_aout->format.i_format ==  VLC_CODEC_SPDIFL) );
668
669     /* Audio output buffer shortage -> stop the fill process and wait */
670     if( p_buffer == NULL )
671         goto error;
672
673     block_cleanup_push( p_buffer );
674     for (;;)
675     {
676         int n = snd_pcm_poll_descriptors_count(p_pcm);
677         struct pollfd ufd[n];
678         unsigned short revents;
679
680         snd_pcm_poll_descriptors(p_pcm, ufd, n);
681         do
682         {
683             vlc_restorecancel(canc);
684             poll(ufd, n, -1);
685             canc = vlc_savecancel();
686             snd_pcm_poll_descriptors_revents(p_pcm, ufd, n, &revents);
687         }
688         while(!revents);
689
690         if(revents & POLLOUT)
691         {
692             i_snd_rc = snd_pcm_writei( p_pcm, p_buffer->p_buffer,
693                                        p_buffer->i_nb_samples );
694             if( i_snd_rc != -ESTRPIPE )
695                 break;
696         }
697
698         /* a suspend event occurred
699          * (stream is suspended and waiting for an application recovery) */
700         msg_Dbg( p_aout, "entering in suspend mode, trying to resume..." );
701
702         while( ( i_snd_rc = snd_pcm_resume( p_pcm ) ) == -EAGAIN )
703         {
704             vlc_restorecancel(canc);
705             msleep(CLOCK_FREQ); /* device still suspended, wait... */
706             canc = vlc_savecancel();
707         }
708
709         if( i_snd_rc < 0 )
710             /* Device does not support resuming, restart it */
711             i_snd_rc = snd_pcm_prepare( p_pcm );
712
713     }
714
715     if( i_snd_rc < 0 )
716         msg_Err( p_aout, "cannot write: %s", snd_strerror( i_snd_rc ) );
717
718     vlc_restorecancel(canc);
719     vlc_cleanup_run();
720     return;
721
722 error:
723     if( i_snd_rc < 0 )
724         msg_Err( p_aout, "ALSA error: %s", snd_strerror( i_snd_rc ) );
725
726     vlc_restorecancel(canc);
727     msleep(p_sys->i_period_time / 2);
728 }
729
730 /*****************************************************************************
731  * config variable callback
732  *****************************************************************************/
733 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
734                                vlc_value_t newval, vlc_value_t oldval, void *p_unused )
735 {
736     module_config_t *p_item;
737     (void)newval;
738     (void)oldval;
739     (void)p_unused;
740
741     p_item = config_FindConfig( p_this, psz_name );
742     if( !p_item ) return VLC_SUCCESS;
743
744     /* Clear-up the current list */
745     if( p_item->i_list )
746     {
747         int i;
748
749         /* Keep the first entrie */
750         for( i = 1; i < p_item->i_list; i++ )
751         {
752             free( (char *)p_item->ppsz_list[i] );
753             free( (char *)p_item->ppsz_list_text[i] );
754         }
755         /* TODO: Remove when no more needed */
756         p_item->ppsz_list[i] = NULL;
757         p_item->ppsz_list_text[i] = NULL;
758     }
759     p_item->i_list = 1;
760
761     GetDevices( p_this, p_item );
762
763     /* Signal change to the interface */
764     p_item->b_dirty = true;
765
766     return VLC_SUCCESS;
767 }
768
769
770 static void GetDevices (vlc_object_t *obj, module_config_t *item)
771 {
772     void **hints;
773
774     msg_Dbg(obj, "Available ALSA PCM devices:");
775
776     if (snd_device_name_hint(-1, "pcm", &hints) < 0)
777         return;
778
779     for (size_t i = 0; hints[i] != NULL; i++)
780     {
781         void *hint = hints[i];
782         char *dev;
783
784         char *name = snd_device_name_get_hint(hint, "NAME");
785         if (unlikely(name == NULL))
786             continue;
787         if (unlikely(asprintf (&dev, "plug:'%s'", name) == -1))
788         {
789             free(name);
790             continue;
791         }
792
793         char *desc = snd_device_name_get_hint(hint, "DESC");
794         if (desc != NULL)
795             for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
796                  *lf = ' ';
797         msg_Dbg(obj, "%s (%s)", (desc != NULL) ? desc : name, name);
798
799         if (item != NULL)
800         {
801             item->ppsz_list = xrealloc(item->ppsz_list,
802                                        (item->i_list + 2) * sizeof(char *));
803             item->ppsz_list_text = xrealloc(item->ppsz_list_text,
804                                           (item->i_list + 2) * sizeof(char *));
805             item->ppsz_list[item->i_list] = dev;
806             if (desc == NULL)
807                 desc = strdup(name);
808             item->ppsz_list_text[item->i_list] = desc;
809             item->i_list++;
810         }
811         else
812         {
813             vlc_value_t val, text;
814
815             val.psz_string = dev;
816             text.psz_string = desc;
817             var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
818             free(desc);
819             free(dev);
820             free(name);
821         }
822     }
823
824     snd_device_name_free_hint(hints);
825
826     if (item != NULL)
827     {
828         item->ppsz_list[item->i_list] = NULL;
829         item->ppsz_list_text[item->i_list] = NULL;
830     }
831 }