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