]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
ALSA: no big deal if Probe() fails
[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         ( aout_instance_t * );
96 static void* ALSAThread   ( void * );
97 static void  ALSAFill     ( aout_instance_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[] = { "default" };
106 static const char *const ppsz_devices_text[] = { N_("Default") };
107 vlc_module_begin ()
108     set_shortname( "ALSA" )
109     set_description( N_("ALSA audio output") )
110     set_category( CAT_AUDIO )
111     set_subcategory( SUBCAT_AUDIO_AOUT )
112     add_string( "alsa-audio-device", DEFAULT_ALSA_DEVICE,
113                 N_("ALSA Device Name"), NULL, false )
114         add_deprecated_alias( "alsadev" )   /* deprecated since 0.9.3 */
115         change_string_list( ppsz_devices, ppsz_devices_text, FindDevicesCallback )
116         change_action_add( FindDevicesCallback, N_("Refresh list") )
117
118     set_capability( "audio output", 150 )
119     set_callbacks( Open, Close )
120 vlc_module_end ()
121
122 /*****************************************************************************
123  * Probe: probe the audio device for available formats and channels
124  *****************************************************************************/
125 static void Probe (aout_instance_t *p_aout,
126                    const char *psz_device, const char *psz_iec_device,
127                    int *pi_snd_pcm_format)
128 {
129     struct aout_sys_t * p_sys = p_aout->output.p_sys;
130     vlc_value_t val, text;
131     int i_ret;
132
133     var_Create ( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
134     text.psz_string = _("Audio Device");
135     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
136
137     /* We'll open the audio device in non blocking mode so we can just exit
138      * when it is already in use, but for the real stuff we'll still use
139      * the blocking mode */
140
141     /* Now test linear PCM capabilities */
142     i_ret = snd_pcm_open( &p_sys->p_snd_pcm, psz_device,
143                           SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK );
144     if( i_ret == 0 )
145     {
146         int i_channels;
147         snd_pcm_hw_params_t * p_hw;
148         snd_pcm_hw_params_alloca (&p_hw);
149
150         if ( snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw ) < 0 )
151         {
152             msg_Warn( p_aout, "unable to retrieve initial hardware parameters"
153                               ", disabling linear PCM audio" );
154             snd_pcm_close( p_sys->p_snd_pcm );
155             return;
156         }
157
158         if ( snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
159                                            *pi_snd_pcm_format ) < 0 )
160         {
161             int i_snd_rc = -1;
162
163             if( *pi_snd_pcm_format != SND_PCM_FORMAT_S16 )
164             {
165                 *pi_snd_pcm_format = SND_PCM_FORMAT_S16;
166                 i_snd_rc = snd_pcm_hw_params_set_format( p_sys->p_snd_pcm,
167                                                     p_hw, *pi_snd_pcm_format );
168             }
169             if ( i_snd_rc < 0 )
170             {
171                 msg_Warn( p_aout, "unable to set stream sample size and "
172                           "word order, disabling linear PCM audio" );
173                 snd_pcm_close( p_sys->p_snd_pcm );
174                 return;
175             }
176         }
177
178         i_channels = aout_FormatNbChannels( &p_aout->output.output );
179
180         while ( i_channels > 0 )
181         {
182             if ( !snd_pcm_hw_params_test_channels( p_sys->p_snd_pcm, p_hw,
183                                                    i_channels ) )
184             {
185                 switch ( i_channels )
186                 {
187                 case 1:
188                     val.i_int = AOUT_VAR_MONO;
189                     text.psz_string = _("Mono");
190                     var_Change( p_aout, "audio-device",
191                                 VLC_VAR_ADDCHOICE, &val, &text );
192                     break;
193                 case 2:
194                     val.i_int = AOUT_VAR_STEREO;
195                     text.psz_string = _("Stereo");
196                     var_Change( p_aout, "audio-device",
197                                 VLC_VAR_ADDCHOICE, &val, &text );
198                     var_Set( p_aout, "audio-device", val );
199                     break;
200                 case 4:
201                     val.i_int = AOUT_VAR_2F2R;
202                     text.psz_string = _("2 Front 2 Rear");
203                     var_Change( p_aout, "audio-device",
204                                 VLC_VAR_ADDCHOICE, &val, &text );
205                     break;
206                 case 6:
207                     val.i_int = AOUT_VAR_5_1;
208                     text.psz_string = (char *)"5.1";
209                     var_Change( p_aout, "audio-device",
210                                 VLC_VAR_ADDCHOICE, &val, &text );
211                     break;
212                 }
213             }
214
215             --i_channels;
216         }
217
218         /* Special case for mono on stereo only boards */
219         i_channels = aout_FormatNbChannels( &p_aout->output.output );
220         var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
221         if( val.i_int <= 0 && i_channels == 1 )
222         {
223             if ( !snd_pcm_hw_params_test_channels( p_sys->p_snd_pcm, p_hw, 2 ))
224             {
225                 val.i_int = AOUT_VAR_STEREO;
226                 text.psz_string = (char*)N_("Stereo");
227                 var_Change( p_aout, "audio-device",
228                             VLC_VAR_ADDCHOICE, &val, &text );
229                 var_Set( p_aout, "audio-device", val );
230             }
231         }
232
233         /* Close the previously opened device */
234         snd_pcm_close( p_sys->p_snd_pcm );
235     }
236     else if ( i_ret == -EBUSY )
237     {
238         msg_Warn( p_aout, "audio device: %s is already in use", psz_device );
239     }
240
241     /* Test for S/PDIF device if needed */
242     if ( psz_iec_device )
243     {
244         /* Opening the device should be enough */
245         i_ret = snd_pcm_open( &p_sys->p_snd_pcm, psz_iec_device,
246                               SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK );
247         if( i_ret == 0 )
248         {
249             val.i_int = AOUT_VAR_SPDIF;
250             text.psz_string = (char*)N_("A/52 over S/PDIF");
251             var_Change( p_aout, "audio-device",
252                         VLC_VAR_ADDCHOICE, &val, &text );
253             if( var_InheritBool( p_aout, "spdif" ) )
254                 var_Set( p_aout, "audio-device", val );
255
256             snd_pcm_close( p_sys->p_snd_pcm );
257         }
258         else if ( i_ret == -EBUSY )
259         {
260             msg_Warn( p_aout, "audio device: %s is already in use",
261                       psz_iec_device );
262         }
263     }
264
265     /* Add final settings to the variable */
266     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
267     var_TriggerCallback( p_aout, "intf-change" );
268 }
269
270 /*****************************************************************************
271  * Open: create a handle and open an alsa device
272  *****************************************************************************
273  * This function opens an alsa device, through the alsa API.
274  *
275  * Note: the only heap-allocated string is psz_device. All the other pointers
276  * are references to psz_device or to stack-allocated data.
277  *****************************************************************************/
278 static int Open( vlc_object_t *p_this )
279 {
280     aout_instance_t * p_aout = (aout_instance_t *)p_this;
281
282     /* Allocate structures */
283     aout_sys_t * p_sys = malloc( sizeof( aout_sys_t ) );
284     if( p_sys == NULL )
285         return VLC_ENOMEM;
286     p_aout->output.p_sys = p_sys;
287
288     /* Get device name */
289     char *psz_device = var_InheritString( p_aout, "alsa-audio-device" );
290     if( unlikely(psz_device == NULL) )
291     {
292         free( p_sys );
293         return VLC_EGENERIC;
294     }
295
296     /* Choose the IEC device for S/PDIF output:
297        if the device is overridden by the user then it will be the one
298        otherwise we compute the default device based on the output format. */
299     char *psz_iec_device = NULL;
300     if( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
301     {
302         if( !strcmp( psz_device, DEFAULT_ALSA_DEVICE ) )
303         {
304             unsigned aes3;
305
306             switch( p_aout->output.output.i_rate )
307             {
308               case 48000:
309                 aes3 = IEC958_AES3_CON_FS_48000;
310                 break;
311               case 44100:
312                 aes3 = IEC958_AES3_CON_FS_44100;
313                 break;
314               default:
315                 aes3 = IEC958_AES3_CON_FS_32000;
316                 break;
317             }
318
319             if( asprintf( &psz_iec_device,
320                           "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
321                           IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
322                           IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
323                           0, aes3 ) == -1 )
324             {
325                 free( psz_device );
326                 free( p_sys );
327                 return VLC_ENOMEM;
328             }
329         }
330         else
331             psz_iec_device = strdup( psz_device );
332     }
333
334     /* Choose the linear PCM format (read the comment above about FPU
335        and float32) */
336     int i_snd_pcm_format; /* Audio format for ALSA's data */
337     if( HAVE_FPU )
338         i_snd_pcm_format = SND_PCM_FORMAT_FLOAT;
339     else
340         i_snd_pcm_format = SND_PCM_FORMAT_S16;
341
342     /* If the variable doesn't exist then it's the first time we're called
343        and we have to probe the available audio formats and channels */
344     if (var_Type (p_aout, "audio-device") == 0)
345         Probe (p_aout, psz_device, psz_iec_device, &i_snd_pcm_format);
346
347     bool spdif = false;
348     switch( var_GetInteger( p_aout, "audio-device") )
349     {
350       case AOUT_VAR_5_1:
351         p_aout->output.output.i_physical_channels
352             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
353                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
354                | AOUT_CHAN_LFE;
355         free( psz_device );
356         psz_device = strdup( "surround51" );
357         break;
358       case AOUT_VAR_2F2R:
359         p_aout->output.output.i_physical_channels
360             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
361                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
362         free( psz_device );
363         psz_device = strdup( "surround40" );
364         break;
365     case AOUT_VAR_STEREO:
366         p_aout->output.output.i_physical_channels
367             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
368         break;
369     case AOUT_VAR_MONO:
370         p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
371         break;
372     case AOUT_VAR_SPDIF:
373         spdif = true;
374         free( psz_device );
375         psz_device = psz_iec_device;
376         psz_iec_device = NULL;
377         break;
378     default:
379         msg_Warn( p_aout, "cannot find audio-device" );
380     }
381
382 #ifdef ALSA_DEBUG
383     snd_output_stdio_attach( &p_sys->p_snd_stderr, stderr, 0 );
384 #endif
385
386     /* Open the device */
387     msg_Dbg( p_aout, "opening ALSA device `%s'", psz_device );
388     int val = snd_pcm_open (&p_sys->p_snd_pcm, psz_device,
389                             SND_PCM_STREAM_PLAYBACK, 0);
390 #if (SND_LIB_VERSION <= 0x010015)
391 # warning Please update alsa-lib to version > 1.0.21a.
392     var_Create (p_aout->p_libvlc, "alsa-working", VLC_VAR_BOOL);
393     if (val != 0 && var_GetBool (p_aout->p_libvlc, "alsa-working"))
394         dialog_Fatal (p_aout, "ALSA version problem",
395             "VLC failed to re-initialize your audio output device.\n"
396             "Please update alsa-lib to version 1.0.22 or higher "
397             "to fix this issue.");
398     var_SetBool (p_aout->p_libvlc, "alsa-working", !val);
399 #endif
400     if (val != 0)
401     {
402 #if (SND_LIB_VERSION <= 0x010017)
403 # warning Please update alsa-lib to version > 1.0.23.
404         var_Create (p_aout->p_libvlc, "alsa-broken", VLC_VAR_BOOL);
405         if (!var_GetBool (p_aout->p_libvlc, "alsa-broken"))
406         {
407             var_SetBool (p_aout->p_libvlc, "alsa-broken", true);
408             dialog_Fatal (p_aout, "Potential ALSA version problem",
409                 "VLC failed to initialize your audio output device (if any).\n"
410                 "Please update alsa-lib to version 1.0.24 or higher "
411                 "to try to fix this issue.");
412         }
413 #endif
414         msg_Err (p_aout, "cannot open ALSA device `%s' (%s)",
415                  psz_device, snd_strerror (val));
416         dialog_Fatal (p_aout, _("Audio output failed"),
417                       _("The audio device \"%s\" could not be used:\n%s."),
418                       psz_device, snd_strerror (val));
419         free (psz_device);
420         free (p_sys);
421         return VLC_EGENERIC;
422     }
423     free( psz_device );
424
425     snd_pcm_uframes_t i_buffer_size;
426     snd_pcm_uframes_t i_period_size;
427     int i_channels;
428
429     if( spdif )
430     {
431         i_buffer_size = ALSA_SPDIF_BUFFER_SIZE;
432         i_snd_pcm_format = SND_PCM_FORMAT_S16;
433         i_channels = 2;
434
435         p_aout->output.i_nb_samples = i_period_size = ALSA_SPDIF_PERIOD_SIZE;
436         p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
437         p_aout->output.output.i_frame_length = A52_FRAME_NB;
438
439         aout_VolumeNoneInit( p_aout );
440     }
441     else
442     {
443         i_buffer_size = ALSA_DEFAULT_BUFFER_SIZE;
444         i_channels = aout_FormatNbChannels( &p_aout->output.output );
445
446         p_aout->output.i_nb_samples = i_period_size = ALSA_DEFAULT_PERIOD_SIZE;
447
448         aout_VolumeSoftInit( p_aout );
449     }
450
451     p_aout->output.pf_play = Play;
452
453     snd_pcm_hw_params_t *p_hw;
454     snd_pcm_sw_params_t *p_sw;
455
456     snd_pcm_hw_params_alloca(&p_hw);
457     snd_pcm_sw_params_alloca(&p_sw);
458
459     /* Due to some bugs in alsa with some drivers, we need to retry in s16l
460        if snd_pcm_hw_params fails in fl32 */
461 retry:
462     /* Get Initial hardware parameters */
463     val = snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw );
464     if( val < 0 )
465     {
466         msg_Err( p_aout, "unable to retrieve hardware parameters (%s)",
467                 snd_strerror( val ) );
468         goto error;
469     }
470
471     /* Set format. */
472     val = snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
473                                         i_snd_pcm_format );
474     if( val < 0 )
475     {
476         if( i_snd_pcm_format != SND_PCM_FORMAT_S16 )
477         {
478             i_snd_pcm_format = SND_PCM_FORMAT_S16;
479             val = snd_pcm_hw_params_set_format( p_sys->p_snd_pcm,
480                                                     p_hw, i_snd_pcm_format );
481         }
482         if ( val < 0 )
483         {
484             msg_Err( p_aout, "unable to set stream sample size and "
485                      "word order (%s)", snd_strerror( val ) );
486             goto error;
487         }
488     }
489
490     vlc_fourcc_t i_vlc_pcm_format;
491     if( spdif )
492         i_vlc_pcm_format = VLC_CODEC_SPDIFL;
493     else
494         switch( i_snd_pcm_format )
495         {
496           case SND_PCM_FORMAT_FLOAT:
497             i_vlc_pcm_format = VLC_CODEC_FL32;
498             break;
499           case SND_PCM_FORMAT_S16:
500             i_vlc_pcm_format = VLC_CODEC_S16N;
501             break;
502           default:
503             assert(0);
504         }
505     p_aout->output.output.i_format = i_vlc_pcm_format;
506
507     val = snd_pcm_hw_params_set_access( p_sys->p_snd_pcm, p_hw,
508                                         SND_PCM_ACCESS_RW_INTERLEAVED );
509     if( val < 0 )
510     {
511         msg_Err( p_aout, "unable to set interleaved stream format (%s)",
512                  snd_strerror( val ) );
513         goto error;
514     }
515
516     /* Set channels. */
517     val = snd_pcm_hw_params_set_channels( p_sys->p_snd_pcm, p_hw, i_channels );
518     if( val < 0 )
519     {
520         msg_Err( p_aout, "unable to set number of output channels (%s)",
521                  snd_strerror( val ) );
522         goto error;
523     }
524
525     /* Set rate. */
526     unsigned i_old_rate = p_aout->output.output.i_rate;
527     val = snd_pcm_hw_params_set_rate_near( p_sys->p_snd_pcm, p_hw,
528                                            &p_aout->output.output.i_rate,
529                                            NULL );
530     if( val < 0 || p_aout->output.output.i_rate != i_old_rate )
531     {
532         msg_Warn( p_aout, "The rate %d Hz is not supported by your " \
533                   "hardware. Using %d Hz instead.\n", i_old_rate, \
534                   p_aout->output.output.i_rate );
535     }
536
537     /* Set period size. */
538     val = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm, p_hw,
539                                                   &i_period_size, NULL );
540     if( val < 0 )
541     {
542         msg_Err( p_aout, "unable to set period size (%s)",
543                  snd_strerror( val ) );
544         goto error;
545     }
546     p_aout->output.i_nb_samples = i_period_size;
547
548     /* Set buffer size. */
549     val = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm, p_hw,
550                                                   &i_buffer_size );
551     if( val )
552     {
553         msg_Err( p_aout, "unable to set buffer size (%s)",
554                  snd_strerror( val ) );
555         goto error;
556     }
557
558     /* Commit hardware parameters. */
559     val = snd_pcm_hw_params( p_sys->p_snd_pcm, p_hw );
560     if( val < 0 )
561     {
562         if( i_snd_pcm_format == SND_PCM_FORMAT_FLOAT )
563         {
564             i_snd_pcm_format = SND_PCM_FORMAT_S16;
565             p_aout->output.output.i_format = VLC_CODEC_S16N;
566             msg_Warn( p_aout, "unable to commit hardware configuration "
567                      "with fl32 samples (%s). Retrying with s16l.",
568                      snd_strerror( val ) );
569             goto retry;
570         }
571         msg_Err( p_aout, "unable to commit hardware configuration (%s)",
572                  snd_strerror( val ) );
573         goto error;
574     }
575
576     val = snd_pcm_hw_params_get_period_time( p_hw, &p_sys->i_period_time,
577                                              NULL );
578     if( val < 0 )
579     {
580         msg_Err( p_aout, "unable to get period time (%s)",
581                  snd_strerror( val ) );
582         goto error;
583     }
584
585     /* Get Initial software parameters */
586     snd_pcm_sw_params_current( p_sys->p_snd_pcm, p_sw );
587
588     snd_pcm_sw_params_set_avail_min( p_sys->p_snd_pcm, p_sw,
589                                      p_aout->output.i_nb_samples );
590     /* start playing when one period has been written */
591     val = snd_pcm_sw_params_set_start_threshold( p_sys->p_snd_pcm, p_sw,
592                                                  ALSA_DEFAULT_PERIOD_SIZE);
593     if( val < 0 )
594     {
595         msg_Err( p_aout, "unable to set start threshold (%s)",
596                  snd_strerror( val ) );
597         goto error;
598     }
599
600     /* Commit software parameters. */
601     if ( snd_pcm_sw_params( p_sys->p_snd_pcm, p_sw ) < 0 )
602     {
603         msg_Err( p_aout, "unable to set software configuration" );
604         goto error;
605     }
606
607 #ifdef ALSA_DEBUG
608     snd_output_printf( p_sys->p_snd_stderr, "\nALSA hardware setup:\n\n" );
609     snd_pcm_dump_hw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
610     snd_output_printf( p_sys->p_snd_stderr, "\nALSA software setup:\n\n" );
611     snd_pcm_dump_sw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
612     snd_output_printf( p_sys->p_snd_stderr, "\n" );
613 #endif
614
615     p_sys->start_date = 0;
616     vlc_sem_init( &p_sys->wait, 0 );
617
618     /* Create ALSA thread and wait for its readiness. */
619     if( vlc_clone( &p_sys->thread, ALSAThread, p_aout,
620                    VLC_THREAD_PRIORITY_OUTPUT ) )
621     {
622         msg_Err( p_aout, "cannot create ALSA thread (%m)" );
623         vlc_sem_destroy( &p_sys->wait );
624         goto error;
625     }
626
627     return 0;
628
629 error:
630     snd_pcm_close( p_sys->p_snd_pcm );
631 #ifdef ALSA_DEBUG
632     snd_output_close( p_sys->p_snd_stderr );
633 #endif
634     free( p_sys );
635     return VLC_EGENERIC;
636 }
637
638 static void PlayIgnore( aout_instance_t *p_aout )
639 {   /* Already playing - nothing to do */
640     (void) p_aout;
641 }
642
643 /*****************************************************************************
644  * Play: start playback
645  *****************************************************************************/
646 static void Play( aout_instance_t *p_aout )
647 {
648     p_aout->output.pf_play = PlayIgnore;
649
650     /* get the playing date of the first aout buffer */
651     p_aout->output.p_sys->start_date =
652         aout_FifoFirstDate( p_aout, &p_aout->output.fifo );
653
654     /* wake up the audio output thread */
655     sem_post( &p_aout->output.p_sys->wait );
656 }
657
658 /*****************************************************************************
659  * Close: close the ALSA device
660  *****************************************************************************/
661 static void Close( vlc_object_t *p_this )
662 {
663     aout_instance_t *p_aout = (aout_instance_t *)p_this;
664     struct aout_sys_t * p_sys = p_aout->output.p_sys;
665
666     /* Make sure that the thread will stop once it is waken up */
667     vlc_cancel( p_sys->thread );
668     vlc_join( p_sys->thread, NULL );
669     vlc_sem_destroy( &p_sys->wait );
670
671     snd_pcm_drop( p_sys->p_snd_pcm );
672     snd_pcm_close( p_sys->p_snd_pcm );
673 #ifdef ALSA_DEBUG
674     snd_output_close( p_sys->p_snd_stderr );
675 #endif
676     free( p_sys );
677 }
678
679 /*****************************************************************************
680  * ALSAThread: asynchronous thread used to DMA the data to the device
681  *****************************************************************************/
682 static void* ALSAThread( void *data )
683 {
684     aout_instance_t * p_aout = data;
685     struct aout_sys_t * p_sys = p_aout->output.p_sys;
686
687     /* Wait for the exact time to start playing (avoids resampling) */
688     vlc_sem_wait( &p_sys->wait );
689     mwait( p_sys->start_date - AOUT_PTS_TOLERANCE / 4 );
690
691     for(;;)
692         ALSAFill( p_aout );
693
694     assert(0);
695 }
696
697 /*****************************************************************************
698  * ALSAFill: function used to fill the ALSA buffer as much as possible
699  *****************************************************************************/
700 static void ALSAFill( aout_instance_t * p_aout )
701 {
702     struct aout_sys_t * p_sys = p_aout->output.p_sys;
703     snd_pcm_t *p_pcm = p_sys->p_snd_pcm;
704     snd_pcm_status_t * p_status;
705     int i_snd_rc;
706     mtime_t next_date;
707
708     int canc = vlc_savecancel();
709     /* Fill in the buffer until space or audio output buffer shortage */
710
711     /* Get the status */
712     snd_pcm_status_alloca(&p_status);
713     i_snd_rc = snd_pcm_status( p_pcm, p_status );
714     if( i_snd_rc < 0 )
715     {
716         msg_Err( p_aout, "cannot get device status" );
717         goto error;
718     }
719
720     /* Handle buffer underruns and get the status again */
721     if( snd_pcm_status_get_state( p_status ) == SND_PCM_STATE_XRUN )
722     {
723         /* Prepare the device */
724         i_snd_rc = snd_pcm_prepare( p_pcm );
725         if( i_snd_rc )
726         {
727             msg_Err( p_aout, "cannot recover from buffer underrun" );
728             goto error;
729         }
730
731         msg_Dbg( p_aout, "recovered from buffer underrun" );
732
733         /* Get the new status */
734         i_snd_rc = snd_pcm_status( p_pcm, p_status );
735         if( i_snd_rc < 0 )
736         {
737             msg_Err( p_aout, "cannot get device status after recovery" );
738             goto error;
739         }
740
741         /* Underrun, try to recover as quickly as possible */
742         next_date = mdate();
743     }
744     else
745     {
746         /* Here the device should be in RUNNING state, p_status is valid. */
747         snd_pcm_sframes_t delay = snd_pcm_status_get_delay( p_status );
748         if( delay == 0 ) /* workaround buggy alsa drivers */
749             if( snd_pcm_delay( p_pcm, &delay ) < 0 )
750                 delay = 0; /* FIXME: use a positive minimal delay */
751
752         size_t i_bytes = snd_pcm_frames_to_bytes( p_pcm, delay );
753         mtime_t delay_us = CLOCK_FREQ * i_bytes
754                 / p_aout->output.output.i_bytes_per_frame
755                 / p_aout->output.output.i_rate
756                 * p_aout->output.output.i_frame_length;
757
758 #ifdef ALSA_DEBUG
759         snd_pcm_state_t state = snd_pcm_status_get_state( p_status );
760         if( state != SND_PCM_STATE_RUNNING )
761             msg_Err( p_aout, "pcm status (%d) != RUNNING", state );
762
763         msg_Dbg( p_aout, "Delay is %ld frames (%zu bytes)", delay, i_bytes );
764
765         msg_Dbg( p_aout, "Bytes per frame: %d", p_aout->output.output.i_bytes_per_frame );
766         msg_Dbg( p_aout, "Rate: %d", p_aout->output.output.i_rate );
767         msg_Dbg( p_aout, "Frame length: %d", p_aout->output.output.i_frame_length );
768         msg_Dbg( p_aout, "Next date: in %"PRId64" microseconds", delay_us );
769 #endif
770         next_date = mdate() + delay_us;
771     }
772
773     block_t *p_buffer = aout_OutputNextBuffer( p_aout, next_date,
774            (p_aout->output.output.i_format ==  VLC_CODEC_SPDIFL) );
775
776     /* Audio output buffer shortage -> stop the fill process and wait */
777     if( p_buffer == NULL )
778         goto error;
779
780     block_cleanup_push( p_buffer );
781     for (;;)
782     {
783         int n = snd_pcm_poll_descriptors_count(p_pcm);
784         struct pollfd ufd[n];
785         unsigned short revents;
786
787         snd_pcm_poll_descriptors(p_pcm, ufd, n);
788         do
789         {
790             vlc_restorecancel(canc);
791             poll(ufd, n, -1);
792             canc = vlc_savecancel();
793             snd_pcm_poll_descriptors_revents(p_pcm, ufd, n, &revents);
794         }
795         while(!revents);
796
797         if(revents & POLLOUT)
798         {
799             i_snd_rc = snd_pcm_writei( p_pcm, p_buffer->p_buffer,
800                                        p_buffer->i_nb_samples );
801             if( i_snd_rc != -ESTRPIPE )
802                 break;
803         }
804
805         /* a suspend event occurred
806          * (stream is suspended and waiting for an application recovery) */
807         msg_Dbg( p_aout, "entering in suspend mode, trying to resume..." );
808
809         while( ( i_snd_rc = snd_pcm_resume( p_pcm ) ) == -EAGAIN )
810         {
811             vlc_restorecancel(canc);
812             msleep(CLOCK_FREQ); /* device still suspended, wait... */
813             canc = vlc_savecancel();
814         }
815
816         if( i_snd_rc < 0 )
817             /* Device does not support resuming, restart it */
818             i_snd_rc = snd_pcm_prepare( p_pcm );
819
820     }
821
822     if( i_snd_rc < 0 )
823         msg_Err( p_aout, "cannot write: %s", snd_strerror( i_snd_rc ) );
824
825     vlc_restorecancel(canc);
826     vlc_cleanup_run();
827     return;
828
829 error:
830     if( i_snd_rc < 0 )
831         msg_Err( p_aout, "ALSA error: %s", snd_strerror( i_snd_rc ) );
832
833     vlc_restorecancel(canc);
834     msleep(p_sys->i_period_time / 2);
835 }
836
837 /*****************************************************************************
838  * config variable callback
839  *****************************************************************************/
840 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
841                                vlc_value_t newval, vlc_value_t oldval, void *p_unused )
842 {
843     module_config_t *p_item;
844     (void)newval;
845     (void)oldval;
846     (void)p_unused;
847
848     p_item = config_FindConfig( p_this, psz_name );
849     if( !p_item ) return VLC_SUCCESS;
850
851     /* Clear-up the current list */
852     if( p_item->i_list )
853     {
854         int i;
855
856         /* Keep the first entrie */
857         for( i = 1; i < p_item->i_list; i++ )
858         {
859             free( (char *)p_item->ppsz_list[i] );
860             free( (char *)p_item->ppsz_list_text[i] );
861         }
862         /* TODO: Remove when no more needed */
863         p_item->ppsz_list[i] = NULL;
864         p_item->ppsz_list_text[i] = NULL;
865     }
866     p_item->i_list = 1;
867
868     GetDevices( p_this, p_item );
869
870     /* Signal change to the interface */
871     p_item->b_dirty = true;
872
873     return VLC_SUCCESS;
874 }
875
876
877 static void GetDevices (vlc_object_t *obj, module_config_t *item)
878 {
879     void **hints;
880
881     msg_Dbg(obj, "Available ALSA PCM devices:");
882
883     if (snd_device_name_hint(-1, "pcm", &hints) < 0)
884         return;
885
886     for (size_t i = 0; hints[i] != NULL; i++)
887     {
888         void *hint = hints[i];
889         char *name = snd_device_name_get_hint(hint, "NAME");
890         if (unlikely(name == NULL))
891             continue;
892
893         char *desc = snd_device_name_get_hint(hint, "DESC");
894         if (desc != NULL)
895             for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
896                  *lf = ' ';
897         msg_Dbg(obj, " %s (%s)", (desc != NULL) ? desc : name, name);
898
899         if (item != NULL)
900         {
901             item->ppsz_list = xrealloc(item->ppsz_list,
902                                        (item->i_list + 2) * sizeof(char *));
903             item->ppsz_list_text = xrealloc(item->ppsz_list_text,
904                                           (item->i_list + 2) * sizeof(char *));
905             item->ppsz_list[item->i_list] = name;
906             if (desc == NULL)
907                 desc = strdup(name);
908             item->ppsz_list_text[item->i_list] = desc;
909             item->i_list++;
910         }
911         else
912         {
913             free(desc);
914             free(name);
915         }
916     }
917
918     snd_device_name_free_hint(hints);
919
920     if (item != NULL)
921     {
922         item->ppsz_list[item->i_list] = NULL;
923         item->ppsz_list_text[item->i_list] = NULL;
924     }
925 }