]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
aout: add an optional flush/drain callback
[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     p_aout->pf_flush = NULL;
373
374     snd_pcm_hw_params_t *p_hw;
375     snd_pcm_sw_params_t *p_sw;
376
377     snd_pcm_hw_params_alloca(&p_hw);
378     snd_pcm_sw_params_alloca(&p_sw);
379
380     /* Get Initial hardware parameters */
381     val = snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw );
382     if( val < 0 )
383     {
384         msg_Err( p_aout, "unable to retrieve hardware parameters (%s)",
385                 snd_strerror( val ) );
386         goto error;
387     }
388
389     /* Set format. */
390     val = snd_pcm_hw_params_set_format (p_sys->p_snd_pcm, p_hw, pcm_format);
391     if( val < 0 )
392     {
393         msg_Err (p_aout, "cannot set sample format: %s", snd_strerror (val));
394         goto error;
395     }
396
397     val = snd_pcm_hw_params_set_access( p_sys->p_snd_pcm, p_hw,
398                                         SND_PCM_ACCESS_RW_INTERLEAVED );
399     if( val < 0 )
400     {
401         msg_Err( p_aout, "unable to set interleaved stream format (%s)",
402                  snd_strerror( val ) );
403         goto error;
404     }
405
406     /* Set channels. */
407     val = snd_pcm_hw_params_set_channels (p_sys->p_snd_pcm, p_hw, channels);
408     if (val < 0 && channels > 2) /* Fallback to stereo */
409     {
410         val = snd_pcm_hw_params_set_channels (p_sys->p_snd_pcm, p_hw, 2);
411         channels = 2;
412     }
413     if (val < 0)
414     {
415         msg_Err( p_aout, "unable to set number of output channels (%s)",
416                  snd_strerror( val ) );
417         goto error;
418     }
419
420     /* Set rate. */
421     unsigned rate = p_aout->format.i_rate;
422     val = snd_pcm_hw_params_set_rate_near (p_sys->p_snd_pcm, p_hw, &rate,
423                                            NULL);
424     if (val < 0)
425     {
426         msg_Err (p_aout, "unable to set sampling rate (%s)",
427                  snd_strerror (val));
428         goto error;
429     }
430     if (p_aout->format.i_rate != rate)
431         msg_Warn (p_aout, "resampling from %d Hz to %d Hz",
432                   p_aout->format.i_rate, rate);
433
434     /* Set period size. */
435     val = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm, p_hw,
436                                                   &i_period_size, NULL );
437     if( val < 0 )
438     {
439         msg_Err( p_aout, "unable to set period size (%s)",
440                  snd_strerror( val ) );
441         goto error;
442     }
443     p_aout->i_nb_samples = i_period_size;
444
445     /* Set buffer size. */
446     val = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm, p_hw,
447                                                   &i_buffer_size );
448     if( val )
449     {
450         msg_Err( p_aout, "unable to set buffer size (%s)",
451                  snd_strerror( val ) );
452         goto error;
453     }
454
455     /* Commit hardware parameters. */
456     val = snd_pcm_hw_params( p_sys->p_snd_pcm, p_hw );
457     if( val < 0 )
458     {
459         msg_Err( p_aout, "unable to commit hardware configuration (%s)",
460                  snd_strerror( val ) );
461         goto error;
462     }
463
464     val = snd_pcm_hw_params_get_period_time( p_hw, &p_sys->i_period_time,
465                                              NULL );
466     if( val < 0 )
467     {
468         msg_Err( p_aout, "unable to get period time (%s)",
469                  snd_strerror( val ) );
470         goto error;
471     }
472
473     /* Get Initial software parameters */
474     snd_pcm_sw_params_current( p_sys->p_snd_pcm, p_sw );
475
476     snd_pcm_sw_params_set_avail_min( p_sys->p_snd_pcm, p_sw,
477                                      p_aout->i_nb_samples );
478     /* start playing when one period has been written */
479     val = snd_pcm_sw_params_set_start_threshold( p_sys->p_snd_pcm, p_sw,
480                                                  ALSA_DEFAULT_PERIOD_SIZE);
481     if( val < 0 )
482     {
483         msg_Err( p_aout, "unable to set start threshold (%s)",
484                  snd_strerror( val ) );
485         goto error;
486     }
487
488     /* Commit software parameters. */
489     if ( snd_pcm_sw_params( p_sys->p_snd_pcm, p_sw ) < 0 )
490     {
491         msg_Err( p_aout, "unable to set software configuration" );
492         goto error;
493     }
494
495 #ifdef ALSA_DEBUG
496     snd_output_printf( p_sys->p_snd_stderr, "\nALSA hardware setup:\n\n" );
497     snd_pcm_dump_hw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
498     snd_output_printf( p_sys->p_snd_stderr, "\nALSA software setup:\n\n" );
499     snd_pcm_dump_sw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
500     snd_output_printf( p_sys->p_snd_stderr, "\n" );
501 #endif
502
503     p_sys->start_date = 0;
504     vlc_sem_init( &p_sys->wait, 0 );
505
506     /* Create ALSA thread and wait for its readiness. */
507     if( vlc_clone( &p_sys->thread, ALSAThread, p_aout,
508                    VLC_THREAD_PRIORITY_OUTPUT ) )
509     {
510         msg_Err( p_aout, "cannot create ALSA thread (%m)" );
511         vlc_sem_destroy( &p_sys->wait );
512         goto error;
513     }
514
515     p_aout->format.i_format = fourcc;
516     p_aout->format.i_rate = rate;
517     if (channels == 2)
518         p_aout->format.i_physical_channels = AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT;
519
520     Probe (obj);
521     return 0;
522
523 error:
524     snd_pcm_close( p_sys->p_snd_pcm );
525 #ifdef ALSA_DEBUG
526     snd_output_close( p_sys->p_snd_stderr );
527 #endif
528     free( p_sys );
529     return VLC_EGENERIC;
530 }
531
532 static void PlayIgnore( audio_output_t *p_aout )
533 {   /* Already playing - nothing to do */
534     (void) p_aout;
535 }
536
537 /*****************************************************************************
538  * Play: start playback
539  *****************************************************************************/
540 static void Play( audio_output_t *p_aout )
541 {
542     p_aout->pf_play = PlayIgnore;
543
544     /* get the playing date of the first aout buffer */
545     p_aout->sys->start_date = aout_FifoFirstDate( &p_aout->fifo );
546
547     /* wake up the audio output thread */
548     sem_post( &p_aout->sys->wait );
549 }
550
551 /*****************************************************************************
552  * Close: close the ALSA device
553  *****************************************************************************/
554 static void Close (vlc_object_t *obj)
555 {
556     audio_output_t *p_aout = (audio_output_t *)obj;
557     struct aout_sys_t * p_sys = p_aout->sys;
558
559     /* Make sure that the thread will stop once it is waken up */
560     vlc_cancel( p_sys->thread );
561     vlc_join( p_sys->thread, NULL );
562     vlc_sem_destroy( &p_sys->wait );
563
564     snd_pcm_drop( p_sys->p_snd_pcm );
565     snd_pcm_close( p_sys->p_snd_pcm );
566 #ifdef ALSA_DEBUG
567     snd_output_close( p_sys->p_snd_stderr );
568 #endif
569     free( p_sys );
570 }
571
572 /*****************************************************************************
573  * ALSAThread: asynchronous thread used to DMA the data to the device
574  *****************************************************************************/
575 static void* ALSAThread( void *data )
576 {
577     audio_output_t * p_aout = data;
578     struct aout_sys_t * p_sys = p_aout->sys;
579
580     /* Wait for the exact time to start playing (avoids resampling) */
581     vlc_sem_wait( &p_sys->wait );
582     mwait( p_sys->start_date - AOUT_MAX_PTS_ADVANCE / 4 );
583 #warning Should wait for buffer availability instead!
584
585     for(;;)
586         ALSAFill( p_aout );
587
588     assert(0);
589 }
590
591 /*****************************************************************************
592  * ALSAFill: function used to fill the ALSA buffer as much as possible
593  *****************************************************************************/
594 static void ALSAFill( audio_output_t * p_aout )
595 {
596     struct aout_sys_t * p_sys = p_aout->sys;
597     snd_pcm_t *p_pcm = p_sys->p_snd_pcm;
598     snd_pcm_status_t * p_status;
599     int i_snd_rc;
600     mtime_t next_date;
601
602     int canc = vlc_savecancel();
603     /* Fill in the buffer until space or audio output buffer shortage */
604
605     /* Get the status */
606     snd_pcm_status_alloca(&p_status);
607     i_snd_rc = snd_pcm_status( p_pcm, p_status );
608     if( i_snd_rc < 0 )
609     {
610         msg_Err( p_aout, "cannot get device status" );
611         goto error;
612     }
613
614     /* Handle buffer underruns and get the status again */
615     if( snd_pcm_status_get_state( p_status ) == SND_PCM_STATE_XRUN )
616     {
617         /* Prepare the device */
618         i_snd_rc = snd_pcm_prepare( p_pcm );
619         if( i_snd_rc )
620         {
621             msg_Err( p_aout, "cannot recover from buffer underrun" );
622             goto error;
623         }
624
625         msg_Dbg( p_aout, "recovered from buffer underrun" );
626
627         /* Get the new status */
628         i_snd_rc = snd_pcm_status( p_pcm, p_status );
629         if( i_snd_rc < 0 )
630         {
631             msg_Err( p_aout, "cannot get device status after recovery" );
632             goto error;
633         }
634
635         /* Underrun, try to recover as quickly as possible */
636         next_date = mdate();
637     }
638     else
639     {
640         /* Here the device should be in RUNNING state, p_status is valid. */
641         snd_pcm_sframes_t delay = snd_pcm_status_get_delay( p_status );
642         if( delay == 0 ) /* workaround buggy alsa drivers */
643             if( snd_pcm_delay( p_pcm, &delay ) < 0 )
644                 delay = 0; /* FIXME: use a positive minimal delay */
645
646         size_t i_bytes = snd_pcm_frames_to_bytes( p_pcm, delay );
647         mtime_t delay_us = CLOCK_FREQ * i_bytes
648                 / p_aout->format.i_bytes_per_frame
649                 / p_aout->format.i_rate
650                 * p_aout->format.i_frame_length;
651
652 #ifdef ALSA_DEBUG
653         snd_pcm_state_t state = snd_pcm_status_get_state( p_status );
654         if( state != SND_PCM_STATE_RUNNING )
655             msg_Err( p_aout, "pcm status (%d) != RUNNING", state );
656
657         msg_Dbg( p_aout, "Delay is %ld frames (%zu bytes)", delay, i_bytes );
658
659         msg_Dbg( p_aout, "Bytes per frame: %d", p_aout->format.i_bytes_per_frame );
660         msg_Dbg( p_aout, "Rate: %d", p_aout->format.i_rate );
661         msg_Dbg( p_aout, "Frame length: %d", p_aout->format.i_frame_length );
662         msg_Dbg( p_aout, "Next date: in %"PRId64" microseconds", delay_us );
663 #endif
664         next_date = mdate() + delay_us;
665     }
666
667     block_t *p_buffer = aout_OutputNextBuffer( p_aout, next_date,
668            (p_aout->format.i_format ==  VLC_CODEC_SPDIFL) );
669
670     /* Audio output buffer shortage -> stop the fill process and wait */
671     if( p_buffer == NULL )
672         goto error;
673
674     block_cleanup_push( p_buffer );
675     for (;;)
676     {
677         int n = snd_pcm_poll_descriptors_count(p_pcm);
678         struct pollfd ufd[n];
679         unsigned short revents;
680
681         snd_pcm_poll_descriptors(p_pcm, ufd, n);
682         do
683         {
684             vlc_restorecancel(canc);
685             poll(ufd, n, -1);
686             canc = vlc_savecancel();
687             snd_pcm_poll_descriptors_revents(p_pcm, ufd, n, &revents);
688         }
689         while(!revents);
690
691         if(revents & POLLOUT)
692         {
693             i_snd_rc = snd_pcm_writei( p_pcm, p_buffer->p_buffer,
694                                        p_buffer->i_nb_samples );
695             if( i_snd_rc != -ESTRPIPE )
696                 break;
697         }
698
699         /* a suspend event occurred
700          * (stream is suspended and waiting for an application recovery) */
701         msg_Dbg( p_aout, "entering in suspend mode, trying to resume..." );
702
703         while( ( i_snd_rc = snd_pcm_resume( p_pcm ) ) == -EAGAIN )
704         {
705             vlc_restorecancel(canc);
706             msleep(CLOCK_FREQ); /* device still suspended, wait... */
707             canc = vlc_savecancel();
708         }
709
710         if( i_snd_rc < 0 )
711             /* Device does not support resuming, restart it */
712             i_snd_rc = snd_pcm_prepare( p_pcm );
713
714     }
715
716     if( i_snd_rc < 0 )
717         msg_Err( p_aout, "cannot write: %s", snd_strerror( i_snd_rc ) );
718
719     vlc_restorecancel(canc);
720     vlc_cleanup_run();
721     return;
722
723 error:
724     if( i_snd_rc < 0 )
725         msg_Err( p_aout, "ALSA error: %s", snd_strerror( i_snd_rc ) );
726
727     vlc_restorecancel(canc);
728     msleep(p_sys->i_period_time / 2);
729 }
730
731 /*****************************************************************************
732  * config variable callback
733  *****************************************************************************/
734 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
735                                vlc_value_t newval, vlc_value_t oldval, void *p_unused )
736 {
737     module_config_t *p_item;
738     (void)newval;
739     (void)oldval;
740     (void)p_unused;
741
742     p_item = config_FindConfig( p_this, psz_name );
743     if( !p_item ) return VLC_SUCCESS;
744
745     /* Clear-up the current list */
746     if( p_item->i_list )
747     {
748         int i;
749
750         /* Keep the first entrie */
751         for( i = 1; i < p_item->i_list; i++ )
752         {
753             free( (char *)p_item->ppsz_list[i] );
754             free( (char *)p_item->ppsz_list_text[i] );
755         }
756         /* TODO: Remove when no more needed */
757         p_item->ppsz_list[i] = NULL;
758         p_item->ppsz_list_text[i] = NULL;
759     }
760     p_item->i_list = 1;
761
762     GetDevices( p_this, p_item );
763
764     /* Signal change to the interface */
765     p_item->b_dirty = true;
766
767     return VLC_SUCCESS;
768 }
769
770
771 static void GetDevices (vlc_object_t *obj, module_config_t *item)
772 {
773     void **hints;
774
775     msg_Dbg(obj, "Available ALSA PCM devices:");
776
777     if (snd_device_name_hint(-1, "pcm", &hints) < 0)
778         return;
779
780     for (size_t i = 0; hints[i] != NULL; i++)
781     {
782         void *hint = hints[i];
783         char *dev;
784
785         char *name = snd_device_name_get_hint(hint, "NAME");
786         if (unlikely(name == NULL))
787             continue;
788         if (unlikely(asprintf (&dev, "plug:'%s'", name) == -1))
789         {
790             free(name);
791             continue;
792         }
793
794         char *desc = snd_device_name_get_hint(hint, "DESC");
795         if (desc != NULL)
796             for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
797                  *lf = ' ';
798         msg_Dbg(obj, "%s (%s)", (desc != NULL) ? desc : name, name);
799
800         if (item != NULL)
801         {
802             item->ppsz_list = xrealloc(item->ppsz_list,
803                                        (item->i_list + 2) * sizeof(char *));
804             item->ppsz_list_text = xrealloc(item->ppsz_list_text,
805                                           (item->i_list + 2) * sizeof(char *));
806             item->ppsz_list[item->i_list] = dev;
807             if (desc == NULL)
808                 desc = strdup(name);
809             item->ppsz_list_text[item->i_list] = desc;
810             item->i_list++;
811         }
812         else
813         {
814             vlc_value_t val, text;
815
816             val.psz_string = dev;
817             text.psz_string = desc;
818             var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
819             free(desc);
820             free(dev);
821             free(name);
822         }
823     }
824
825     snd_device_name_free_hint(hints);
826
827     if (item != NULL)
828     {
829         item->ppsz_list[item->i_list] = NULL;
830         item->ppsz_list_text[item->i_list] = NULL;
831     }
832 }