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