]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
alsa.c: removed a printf, shut up a compiler warning
[vlc] / modules / audio_output / alsa.c
1 /*****************************************************************************
2  * alsa.c : alsa plugin for vlc
3  *****************************************************************************
4  * Copyright (C) 2000-2001 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <errno.h>                                                 /* ENOMEM */
31 #include <string.h>                                            /* strerror() */
32 #include <stdlib.h>                            /* calloc(), malloc(), free() */
33
34 #include <vlc/vlc.h>
35
36 #include <vlc/aout.h>
37
38 #include "aout_internal.h"
39
40 /* ALSA part
41    Note: we use the new API which is available since 0.9.0beta10a. */
42 #define ALSA_PCM_NEW_HW_PARAMS_API
43 #define ALSA_PCM_NEW_SW_PARAMS_API
44 #include <alsa/asoundlib.h>
45
46 /*****************************************************************************
47  * aout_sys_t: ALSA audio output method descriptor
48  *****************************************************************************
49  * This structure is part of the audio output thread descriptor.
50  * It describes the ALSA specific properties of an audio device.
51  *****************************************************************************/
52 struct aout_sys_t
53 {
54     snd_pcm_t         * p_snd_pcm;
55     int                 i_period_time;
56
57 #ifdef ALSA_DEBUG
58     snd_output_t      * p_snd_stderr;
59 #endif
60
61     int b_playing;                                         /* playing status */
62     mtime_t start_date;
63
64     vlc_mutex_t lock;
65     vlc_cond_t  wait ;
66
67     snd_pcm_status_t *p_status;
68 };
69
70 #define A52_FRAME_NB 1536
71
72 /* These values are in frames.
73    To convert them to a number of bytes you have to multiply them by the
74    number of channel(s) (eg. 2 for stereo) and the size of a sample (eg.
75    2 for int16_t). */
76 #define ALSA_DEFAULT_PERIOD_SIZE        1024
77 #define ALSA_DEFAULT_BUFFER_SIZE        ( ALSA_DEFAULT_PERIOD_SIZE << 8 )
78 #define ALSA_SPDIF_PERIOD_SIZE          A52_FRAME_NB
79 #define ALSA_SPDIF_BUFFER_SIZE          ( ALSA_SPDIF_PERIOD_SIZE << 4 )
80 /* Why << 4 ? --Meuuh */
81 /* Why not ? --Bozo */
82 /* Right. --Meuuh */
83
84 #define DEFAULT_ALSA_DEVICE N_("default")
85
86 /*****************************************************************************
87  * Local prototypes
88  *****************************************************************************/
89 static int  Open         ( vlc_object_t * );
90 static void Close        ( vlc_object_t * );
91 static void Play         ( aout_instance_t * );
92 static int  ALSAThread   ( aout_instance_t * );
93 static void ALSAFill     ( aout_instance_t * );
94 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
95                                 vlc_value_t newval, vlc_value_t oldval, void *p_unused );
96
97 /*****************************************************************************
98  * Module descriptor
99  *****************************************************************************/
100 static char *ppsz_devices[] = { "default" };
101 static char *ppsz_devices_text[] = { N_("Default") };
102 vlc_module_begin();
103     set_shortname( "ALSA" );
104     set_description( _("ALSA audio output") );
105     set_category( CAT_AUDIO );
106     set_subcategory( SUBCAT_AUDIO_AOUT );
107     add_string( "alsadev", DEFAULT_ALSA_DEVICE, aout_FindAndRestart,
108                 N_("ALSA Device Name"), NULL, VLC_FALSE );
109         change_string_list( ppsz_devices, ppsz_devices_text, FindDevicesCallback );
110         change_action_add( FindDevicesCallback, N_("Refresh list") );
111
112
113
114     set_capability( "audio output", 150 );
115     set_callbacks( Open, Close );
116 vlc_module_end();
117
118 /*****************************************************************************
119  * Probe: probe the audio device for available formats and channels
120  *****************************************************************************/
121 static void Probe( aout_instance_t * p_aout,
122                    const char * psz_device, const char * psz_iec_device,
123                    int *pi_snd_pcm_format )
124 {
125     struct aout_sys_t * p_sys = p_aout->output.p_sys;
126     vlc_value_t val, text;
127     int i_ret;
128
129     var_Create ( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
130     text.psz_string = _("Audio Device");
131     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
132
133     /* We'll open the audio device in non blocking mode so we can just exit
134      * when it is already in use, but for the real stuff we'll still use
135      * the blocking mode */
136
137     /* Now test linear PCM capabilities */
138     if ( !(i_ret = snd_pcm_open( &p_sys->p_snd_pcm, psz_device,
139                                  SND_PCM_STREAM_PLAYBACK,
140                                  SND_PCM_NONBLOCK ) ) )
141     {
142         int i_channels;
143         snd_pcm_hw_params_t * p_hw;
144         snd_pcm_hw_params_alloca (&p_hw);
145
146         if ( snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw ) < 0 )
147         {
148             msg_Warn( p_aout, "unable to retrieve initial hardware parameters"
149                               ", disabling linear PCM audio" );
150             snd_pcm_close( p_sys->p_snd_pcm );
151             var_Destroy( p_aout, "audio-device" );
152             return;
153         }
154
155         if ( snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
156                                            *pi_snd_pcm_format ) < 0 )
157         {
158             if( *pi_snd_pcm_format != SND_PCM_FORMAT_S16 )
159             {
160                 *pi_snd_pcm_format = SND_PCM_FORMAT_S16;
161                 if ( snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
162                                                    *pi_snd_pcm_format ) < 0 )
163                 {
164                     msg_Warn( p_aout, "unable to set stream sample size and "
165                               "word order, disabling linear PCM audio" );
166                     snd_pcm_close( p_sys->p_snd_pcm );
167                     var_Destroy( p_aout, "audio-device" );
168                     return;
169                 }
170             }
171         }
172
173         i_channels = aout_FormatNbChannels( &p_aout->output.output );
174
175         while ( i_channels > 0 )
176         {
177             if ( !snd_pcm_hw_params_test_channels( p_sys->p_snd_pcm, p_hw,
178                                                    i_channels ) )
179             {
180                 switch ( i_channels )
181                 {
182                 case 1:
183                     val.i_int = AOUT_VAR_MONO;
184                     text.psz_string = N_("Mono");
185                     var_Change( p_aout, "audio-device",
186                                 VLC_VAR_ADDCHOICE, &val, &text );
187                     break;
188                 case 2:
189                     val.i_int = AOUT_VAR_STEREO;
190                     text.psz_string = N_("Stereo");
191                     var_Change( p_aout, "audio-device",
192                                 VLC_VAR_ADDCHOICE, &val, &text );
193                     var_Set( p_aout, "audio-device", val );
194                     break;
195                 case 4:
196                     val.i_int = AOUT_VAR_2F2R;
197                     text.psz_string = N_("2 Front 2 Rear");
198                     var_Change( p_aout, "audio-device",
199                                 VLC_VAR_ADDCHOICE, &val, &text );
200                     break;
201                 case 6:
202                     val.i_int = AOUT_VAR_5_1;
203                     text.psz_string = N_("5.1");
204                     var_Change( p_aout, "audio-device",
205                                 VLC_VAR_ADDCHOICE, &val, &text );
206                     break;
207                 }
208             }
209
210             --i_channels;
211         }
212
213         /* Special case for mono on stereo only boards */
214         i_channels = aout_FormatNbChannels( &p_aout->output.output );        
215         var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
216         if( val.i_int <= 0 && i_channels == 1 )
217         {
218             if ( !snd_pcm_hw_params_test_channels( p_sys->p_snd_pcm, p_hw, 2 ))
219             {
220                 val.i_int = AOUT_VAR_STEREO;
221                 text.psz_string = N_("Stereo");
222                 var_Change( p_aout, "audio-device",
223                             VLC_VAR_ADDCHOICE, &val, &text );
224                 var_Set( p_aout, "audio-device", val );
225             }
226         }
227         
228         /* Close the previously opened device */
229         snd_pcm_close( p_sys->p_snd_pcm );
230     }
231     else if ( i_ret == -EBUSY )
232     {
233         msg_Warn( p_aout, "audio device: %s is already in use", psz_device );
234     }
235
236     /* Test for S/PDIF device if needed */
237     if ( psz_iec_device )
238     {
239         /* Opening the device should be enough */
240         if ( !(i_ret = snd_pcm_open( &p_sys->p_snd_pcm, psz_iec_device,
241                                      SND_PCM_STREAM_PLAYBACK,
242                                      SND_PCM_NONBLOCK ) ) )
243         {
244             val.i_int = AOUT_VAR_SPDIF;
245             text.psz_string = N_("A/52 over S/PDIF");
246             var_Change( p_aout, "audio-device",
247                         VLC_VAR_ADDCHOICE, &val, &text );
248             if( config_GetInt( p_aout, "spdif" ) )
249                 var_Set( p_aout, "audio-device", val );
250
251             snd_pcm_close( p_sys->p_snd_pcm );
252         }
253         else if ( i_ret == -EBUSY )
254         {
255             msg_Warn( p_aout, "audio device: %s is already in use",
256                       psz_iec_device );
257         }
258     }
259
260     var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
261     if( val.i_int <= 0 )
262     {
263         /* Probe() has failed. */
264         msg_Dbg( p_aout, "failed to find a useable alsa configuration" );
265         var_Destroy( p_aout, "audio-device" );
266         return;
267     }
268
269     /* Add final settings to the variable */
270     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
271     val.b_bool = VLC_TRUE;
272     var_Set( p_aout, "intf-change", val );
273 }
274
275 /*****************************************************************************
276  * Open: create a handle and open an alsa device
277  *****************************************************************************
278  * This function opens an alsa device, through the alsa API.
279  *
280  * Note: the only heap-allocated string is psz_device. All the other pointers
281  * are references to psz_device or to stack-allocated data.
282  *****************************************************************************/
283 static int Open( vlc_object_t *p_this )
284 {
285     aout_instance_t * p_aout = (aout_instance_t *)p_this;
286     struct aout_sys_t * p_sys;
287     vlc_value_t val;
288
289     char psz_default_iec_device[128]; /* Buffer used to store the default
290                                          S/PDIF device */
291     char * psz_device, * psz_iec_device; /* device names for PCM and S/PDIF
292                                             output */
293
294     int i_vlc_pcm_format; /* Audio format for VLC's data */
295     int i_snd_pcm_format; /* Audio format for ALSA's data */
296
297     snd_pcm_uframes_t i_buffer_size = 0;
298     snd_pcm_uframes_t i_period_size = 0;
299     int i_channels = 0;
300
301     snd_pcm_hw_params_t *p_hw;
302     snd_pcm_sw_params_t *p_sw;
303
304     int i_snd_rc = -1;
305     unsigned int i_old_rate;
306
307     /* Allocate structures */
308     p_aout->output.p_sys = p_sys = malloc( sizeof( aout_sys_t ) );
309     if( p_sys == NULL )
310     {
311         msg_Err( p_aout, "out of memory" );
312         return VLC_ENOMEM;
313     }
314     p_sys->b_playing = VLC_FALSE;
315     p_sys->start_date = 0;
316     p_sys->p_status = (snd_pcm_status_t *)malloc(snd_pcm_status_sizeof());
317     vlc_cond_init( p_aout, &p_sys->wait );
318     vlc_mutex_init( p_aout, &p_sys->lock );
319
320     /* Get device name */
321     if( (psz_device = config_GetPsz( p_aout, "alsadev" )) == NULL )
322     {
323         msg_Err( p_aout, "no audio device given (maybe \"default\" ?)" );
324         free( p_sys );
325         return VLC_EGENERIC;
326     }
327
328     /* Choose the IEC device for S/PDIF output:
329        if the device is overriden by the user then it will be the one
330        otherwise we compute the default device based on the output format. */
331     if( AOUT_FMT_NON_LINEAR( &p_aout->output.output )
332         && !strcmp( psz_device, DEFAULT_ALSA_DEVICE ) )
333     {
334         snprintf( psz_default_iec_device, sizeof(psz_default_iec_device),
335                   "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
336                   IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
337                   IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
338                   0,
339                   ( p_aout->output.output.i_rate == 48000 ?
340                     IEC958_AES3_CON_FS_48000 :
341                     ( p_aout->output.output.i_rate == 44100 ?
342                       IEC958_AES3_CON_FS_44100 : IEC958_AES3_CON_FS_32000 ) ) );
343         psz_iec_device = psz_default_iec_device;
344     }
345     else if( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
346     {
347         psz_iec_device = psz_device;
348     }
349     else
350     {
351         psz_iec_device = NULL;
352     }
353
354     /* Choose the linear PCM format (read the comment above about FPU
355        and float32) */
356     if( p_aout->p_libvlc->i_cpu & CPU_CAPABILITY_FPU )
357     {
358         i_vlc_pcm_format = VLC_FOURCC('f','l','3','2');
359         i_snd_pcm_format = SND_PCM_FORMAT_FLOAT;
360     }
361     else
362     {
363         i_vlc_pcm_format = AOUT_FMT_S16_NE;
364         i_snd_pcm_format = SND_PCM_FORMAT_S16;
365     }
366
367     /* If the variable doesn't exist then it's the first time we're called
368        and we have to probe the available audio formats and channels */
369     if ( var_Type( p_aout, "audio-device" ) == 0 )
370     {
371         Probe( p_aout, psz_device, psz_iec_device, &i_snd_pcm_format );
372         switch( i_snd_pcm_format )
373         {
374         case SND_PCM_FORMAT_FLOAT:
375             i_vlc_pcm_format = VLC_FOURCC('f','l','3','2');
376             break;
377         case SND_PCM_FORMAT_S16:
378             i_vlc_pcm_format = AOUT_FMT_S16_NE;
379             break;
380         }
381     }
382
383     if ( var_Get( p_aout, "audio-device", &val ) < 0 )
384     {
385         free( p_sys );
386         free( psz_device );
387         return VLC_EGENERIC;
388     }
389
390     if ( val.i_int == AOUT_VAR_SPDIF )
391     {
392         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
393     }
394     else if ( val.i_int == AOUT_VAR_5_1 )
395     {
396         p_aout->output.output.i_format = i_vlc_pcm_format;
397         p_aout->output.output.i_physical_channels
398             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
399                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
400                | AOUT_CHAN_LFE;
401         free( psz_device );
402         psz_device = strdup( "surround51" );
403     }
404     else if ( val.i_int == AOUT_VAR_2F2R )
405     {
406         p_aout->output.output.i_format = i_vlc_pcm_format;
407         p_aout->output.output.i_physical_channels
408             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
409                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
410         free( psz_device );
411         psz_device = strdup( "surround40" );
412     }
413     else if ( val.i_int == AOUT_VAR_STEREO )
414     {
415         p_aout->output.output.i_format = i_vlc_pcm_format;
416         p_aout->output.output.i_physical_channels
417             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
418     }
419     else if ( val.i_int == AOUT_VAR_MONO )
420     {
421         p_aout->output.output.i_format = i_vlc_pcm_format;
422         p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
423     }
424
425     else
426     {
427         /* This should not happen ! */
428         msg_Err( p_aout, "internal: can't find audio-device (%i)", val.i_int );
429         free( p_sys );
430         return VLC_EGENERIC;
431     }
432
433 #ifdef ALSA_DEBUG
434     snd_output_stdio_attach( &p_sys->p_snd_stderr, stderr, 0 );
435 #endif
436
437     /* Open the device */
438     if ( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
439     {
440         if ( ( i_snd_rc = snd_pcm_open( &p_sys->p_snd_pcm, psz_iec_device,
441                             SND_PCM_STREAM_PLAYBACK, 0 ) ) < 0 )
442         {
443             msg_Err( p_aout, "cannot open ALSA device `%s' (%s)",
444                              psz_iec_device, snd_strerror( i_snd_rc ) );
445             free( p_sys );
446             free( psz_device );
447             return VLC_EGENERIC;
448         }
449         i_buffer_size = ALSA_SPDIF_BUFFER_SIZE;
450         i_snd_pcm_format = SND_PCM_FORMAT_S16;
451         i_channels = 2;
452
453         p_aout->output.i_nb_samples = i_period_size = ALSA_SPDIF_PERIOD_SIZE;
454         p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
455         p_aout->output.output.i_frame_length = A52_FRAME_NB;
456
457         aout_VolumeNoneInit( p_aout );
458     }
459     else
460     {
461         msg_Dbg( p_aout, "opening ALSA device `%s'", psz_device );
462
463         if ( ( i_snd_rc = snd_pcm_open( &p_sys->p_snd_pcm, psz_device,
464                             SND_PCM_STREAM_PLAYBACK, 0 ) ) < 0 )
465         {
466             msg_Err( p_aout, "cannot open ALSA device `%s' (%s)",
467                              psz_device, snd_strerror( i_snd_rc ) );
468             free( p_sys );
469             free( psz_device );
470             return VLC_EGENERIC;
471         }
472         i_buffer_size = ALSA_DEFAULT_BUFFER_SIZE;
473         i_channels = aout_FormatNbChannels( &p_aout->output.output );
474
475         p_aout->output.i_nb_samples = i_period_size = ALSA_DEFAULT_PERIOD_SIZE;
476
477         aout_VolumeSoftInit( p_aout );
478     }
479
480     /* Free psz_device so that all the remaining data is stack-allocated */
481     free( psz_device );
482
483     p_aout->output.pf_play = Play;
484
485     snd_pcm_hw_params_alloca(&p_hw);
486     snd_pcm_sw_params_alloca(&p_sw);
487
488     /* Get Initial hardware parameters */
489     if ( ( i_snd_rc = snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw ) ) < 0 )
490     {
491         msg_Err( p_aout, "unable to retrieve initial hardware parameters (%s)",
492                          snd_strerror( i_snd_rc ) );
493         goto error;
494     }
495
496     /* Set format. */
497     if ( ( i_snd_rc = snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
498                                                     i_snd_pcm_format ) ) < 0 )
499     {
500         msg_Err( p_aout, "unable to set stream sample size and word order (%s)",
501                          snd_strerror( i_snd_rc ) );
502         goto error;
503     }
504
505     if ( ( i_snd_rc = snd_pcm_hw_params_set_access( p_sys->p_snd_pcm, p_hw,
506                                     SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
507     {
508         msg_Err( p_aout, "unable to set interleaved stream format (%s)",
509                          snd_strerror( i_snd_rc ) );
510         goto error;
511     }
512
513     /* Set channels. */
514     if ( ( i_snd_rc = snd_pcm_hw_params_set_channels( p_sys->p_snd_pcm, p_hw,
515                                                       i_channels ) ) < 0 )
516     {
517         msg_Err( p_aout, "unable to set number of output channels (%s)",
518                          snd_strerror( i_snd_rc ) );
519         goto error;
520     }
521
522     /* Set rate. */
523     i_old_rate = p_aout->output.output.i_rate;
524 #ifdef HAVE_ALSA_NEW_API
525     i_snd_rc = snd_pcm_hw_params_set_rate_near( p_sys->p_snd_pcm, p_hw,
526                                                 &p_aout->output.output.i_rate,
527                                                 NULL );
528 #else
529     i_snd_rc = snd_pcm_hw_params_set_rate_near( p_sys->p_snd_pcm, p_hw,
530                                                 p_aout->output.output.i_rate,
531                                                 NULL );
532 #endif
533     if( i_snd_rc < 0 || p_aout->output.output.i_rate != i_old_rate )
534     {
535         msg_Warn( p_aout, "The rate %d Hz is not supported by your hardware. "
536                   "Using %d Hz instead.\n", i_old_rate,
537                   p_aout->output.output.i_rate );
538     }
539
540     /* Set buffer size. */
541 #ifdef HAVE_ALSA_NEW_API
542     if ( ( i_snd_rc = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm,
543                                     p_hw, &i_buffer_size ) ) < 0 )
544 #else
545     if ( ( i_snd_rc = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm,
546                                     p_hw, i_buffer_size ) ) < 0 )
547 #endif
548     {
549         msg_Err( p_aout, "unable to set buffer size (%s)",
550                          snd_strerror( i_snd_rc ) );
551         goto error;
552     }
553
554     /* Set period size. */
555 #ifdef HAVE_ALSA_NEW_API
556     if ( ( i_snd_rc = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm,
557                                     p_hw, &i_period_size, NULL ) ) < 0 )
558 #else
559     if ( ( i_snd_rc = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm,
560                                     p_hw, i_period_size, NULL ) ) < 0 )
561 #endif
562     {
563         msg_Err( p_aout, "unable to set period size (%s)",
564                          snd_strerror( i_snd_rc ) );
565         goto error;
566     }
567     p_aout->output.i_nb_samples = i_period_size;
568
569     /* Commit hardware parameters. */
570     if ( ( i_snd_rc = snd_pcm_hw_params( p_sys->p_snd_pcm, p_hw ) ) < 0 )
571     {
572         msg_Err( p_aout, "unable to commit hardware configuration (%s)",
573                          snd_strerror( i_snd_rc ) );
574         goto error;
575     }
576
577 #ifdef HAVE_ALSA_NEW_API
578     if( ( i_snd_rc = snd_pcm_hw_params_get_period_time( p_hw,
579                                     &p_sys->i_period_time, NULL ) ) < 0 )
580 #else
581     if( ( p_sys->i_period_time =
582                   snd_pcm_hw_params_get_period_time( p_hw, NULL ) ) < 0 )
583 #endif
584     {
585         msg_Err( p_aout, "unable to get period time (%s)",
586                          snd_strerror( i_snd_rc ) );
587         goto error;
588     }
589
590     /* Get Initial software parameters */
591     snd_pcm_sw_params_current( p_sys->p_snd_pcm, p_sw );
592
593     i_snd_rc = snd_pcm_sw_params_set_sleep_min( p_sys->p_snd_pcm, p_sw, 0 );
594
595     i_snd_rc = snd_pcm_sw_params_set_avail_min( p_sys->p_snd_pcm, p_sw,
596                                                 p_aout->output.i_nb_samples );
597
598     /* Commit software parameters. */
599     if ( snd_pcm_sw_params( p_sys->p_snd_pcm, p_sw ) < 0 )
600     {
601         msg_Err( p_aout, "unable to set software configuration" );
602         goto error;
603     }
604
605 #ifdef ALSA_DEBUG
606     snd_output_printf( p_sys->p_snd_stderr, "\nALSA hardware setup:\n\n" );
607     snd_pcm_dump_hw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
608     snd_output_printf( p_sys->p_snd_stderr, "\nALSA software setup:\n\n" );
609     snd_pcm_dump_sw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
610     snd_output_printf( p_sys->p_snd_stderr, "\n" );
611 #endif
612
613     /* Create ALSA thread and wait for its readiness. */
614     if( vlc_thread_create( p_aout, "aout", ALSAThread,
615                            VLC_THREAD_PRIORITY_OUTPUT, VLC_FALSE ) )
616     {
617         msg_Err( p_aout, "cannot create ALSA thread (%s)", strerror(errno) );
618         goto error;
619     }
620
621     return 0;
622
623 error:
624     snd_pcm_close( p_sys->p_snd_pcm );
625 #ifdef ALSA_DEBUG
626     snd_output_close( p_sys->p_snd_stderr );
627 #endif
628     free( p_sys );
629     return VLC_EGENERIC;
630 }
631
632 /*****************************************************************************
633  * Play: nothing to do
634  *****************************************************************************/
635 static void Play( aout_instance_t *p_aout )
636 {
637     if( !p_aout->output.p_sys->b_playing )
638     {
639         p_aout->output.p_sys->b_playing = 1;
640
641         /* get the playing date of the first aout buffer */
642         p_aout->output.p_sys->start_date =
643             aout_FifoFirstDate( p_aout, &p_aout->output.fifo );
644
645         /* wake up the audio output thread */
646         vlc_mutex_lock( &p_aout->output.p_sys->lock );
647         vlc_cond_signal( &p_aout->output.p_sys->wait );
648         vlc_mutex_unlock( &p_aout->output.p_sys->lock );
649     }
650 }
651
652 /*****************************************************************************
653  * Close: close the ALSA device
654  *****************************************************************************/
655 static void Close( vlc_object_t *p_this )
656 {
657     aout_instance_t *p_aout = (aout_instance_t *)p_this;
658     struct aout_sys_t * p_sys = p_aout->output.p_sys;
659     int i_snd_rc;
660
661     /* make sure the audio output thread is waken up */
662     vlc_mutex_lock( &p_aout->output.p_sys->lock );
663     vlc_cond_signal( &p_aout->output.p_sys->wait );
664     vlc_mutex_unlock( &p_aout->output.p_sys->lock );
665
666     p_aout->b_die = VLC_TRUE;
667     vlc_thread_join( p_aout );
668     p_aout->b_die = VLC_FALSE;
669
670     i_snd_rc = snd_pcm_close( p_sys->p_snd_pcm );
671
672     if( i_snd_rc > 0 )
673     {
674         msg_Err( p_aout, "failed closing ALSA device (%s)",
675                          snd_strerror( i_snd_rc ) );
676     }
677
678 #ifdef ALSA_DEBUG
679     snd_output_close( p_sys->p_snd_stderr );
680 #endif
681
682     free( p_sys->p_status );
683     free( p_sys );
684 }
685
686 /*****************************************************************************
687  * ALSAThread: asynchronous thread used to DMA the data to the device
688  *****************************************************************************/
689 static int ALSAThread( aout_instance_t * p_aout )
690 {
691     /* Wait for the exact time to start playing (avoids resampling) */
692     vlc_mutex_lock( &p_aout->output.p_sys->lock );
693     if( !p_aout->output.p_sys->start_date )
694         vlc_cond_wait( &p_aout->output.p_sys->wait,
695                        &p_aout->output.p_sys->lock );
696     vlc_mutex_unlock( &p_aout->output.p_sys->lock );
697
698     mwait( p_aout->output.p_sys->start_date - AOUT_PTS_TOLERANCE / 4 );
699
700     while ( !p_aout->b_die )
701     {
702         ALSAFill( p_aout );
703     }
704
705     return 0;
706 }
707
708 /*****************************************************************************
709  * ALSAFill: function used to fill the ALSA buffer as much as possible
710  *****************************************************************************/
711 static void ALSAFill( aout_instance_t * p_aout )
712 {
713     struct aout_sys_t * p_sys = p_aout->output.p_sys;
714
715     aout_buffer_t * p_buffer;
716     snd_pcm_status_t * p_status = p_sys->p_status;
717     snd_timestamp_t ts_next;
718     int i_snd_rc;
719     mtime_t next_date;
720
721     /* Fill in the buffer until space or audio output buffer shortage */
722     {
723         /* Get the status */
724         i_snd_rc = snd_pcm_status( p_sys->p_snd_pcm, p_status );
725         if( i_snd_rc < 0 )
726         {
727             msg_Err( p_aout, "unable to get the device's status (%s)",
728                              snd_strerror( i_snd_rc ) );
729
730             msleep( p_sys->i_period_time >> 1 );
731             return;
732         }
733
734         /* Handle buffer underruns and reget the status */
735         if( snd_pcm_status_get_state( p_status ) == SND_PCM_STATE_XRUN )
736         {
737             /* Prepare the device */
738             i_snd_rc = snd_pcm_prepare( p_sys->p_snd_pcm );
739
740             if( i_snd_rc == 0 )
741             {
742                 msg_Warn( p_aout, "recovered from buffer underrun" );
743
744                 /* Reget the status */
745                 i_snd_rc = snd_pcm_status( p_sys->p_snd_pcm, p_status );
746                 if( i_snd_rc < 0 )
747                 {
748                     msg_Err( p_aout, "unable to get the device's status after "
749                              "recovery (%s)", snd_strerror( i_snd_rc ) );
750
751                     msleep( p_sys->i_period_time >> 1 );
752                     return;
753                 }
754             }
755             else
756             {
757                 msg_Err( p_aout, "unable to recover from buffer underrun" );
758
759                 msleep( p_sys->i_period_time >> 1 );
760                 return;
761             }
762
763             /* Underrun, try to recover as quickly as possible */
764             next_date = mdate();
765         }
766         else
767         {
768             /* Here the device should be either in the RUNNING state.
769              * p_status is valid. */
770
771             snd_pcm_status_get_tstamp( p_status, &ts_next );
772             next_date = (mtime_t)ts_next.tv_sec * 1000000 + ts_next.tv_usec;
773             if( next_date )
774             {
775                 next_date += (mtime_t)snd_pcm_status_get_delay(p_status)
776                         * 1000000 / p_aout->output.output.i_rate;
777             }
778             else
779             {
780                 /* With screwed ALSA drivers the timestamp is always zero;
781                  * use another method then */
782                 snd_pcm_sframes_t delay;
783                 ssize_t i_bytes = 0;
784
785                 if( !snd_pcm_delay( p_sys->p_snd_pcm, &delay ) )
786                 {
787                     i_bytes = snd_pcm_frames_to_bytes(p_sys->p_snd_pcm, delay);
788                 }
789                 next_date = mdate() + (mtime_t)i_bytes * 1000000
790                         / p_aout->output.output.i_bytes_per_frame
791                         / p_aout->output.output.i_rate
792                         * p_aout->output.output.i_frame_length;
793             }
794         }
795
796         p_buffer = aout_OutputNextBuffer( p_aout, next_date,
797                         (p_aout->output.output.i_format ==
798                          VLC_FOURCC('s','p','d','i')) );
799
800         /* Audio output buffer shortage -> stop the fill process and wait */
801         if( p_buffer == NULL )
802         {
803             msleep( p_sys->i_period_time >> 1 );
804             return;
805         }
806
807         i_snd_rc = snd_pcm_writei( p_sys->p_snd_pcm, p_buffer->p_buffer,
808                                    p_buffer->i_nb_samples );
809
810         if( i_snd_rc < 0 )
811         {
812             msg_Err( p_aout, "write failed (%s)",
813                              snd_strerror( i_snd_rc ) );
814         }
815
816         aout_BufferFree( p_buffer );
817     }
818 }
819
820 static void GetDevicesForCard(module_config_t *p_item, int i_card);
821 static void GetDevices( module_config_t *p_item );
822
823 /*****************************************************************************
824  * config variable callback
825  *****************************************************************************/
826 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
827                                vlc_value_t newval, vlc_value_t oldval, void *p_unused )
828 {
829     module_config_t *p_item;
830     int i;
831
832     p_item = config_FindConfig( p_this, psz_name );
833     if( !p_item ) return VLC_SUCCESS;
834
835     /* Clear-up the current list */
836     if( p_item->i_list )
837     {
838         /* Keep the first entrie */
839         for( i = 1; i < p_item->i_list; i++ )
840         {
841             free( p_item->ppsz_list[i] );
842             free( p_item->ppsz_list_text[i] );
843         }
844         /* TODO: Remove when no more needed */
845         p_item->ppsz_list[i] = NULL;
846         p_item->ppsz_list_text[i] = NULL;
847     }
848     p_item->i_list = 1;
849
850     GetDevices( p_item );
851
852     /* Signal change to the interface */
853     p_item->b_dirty = VLC_TRUE;
854
855     return VLC_SUCCESS;
856
857 }
858
859
860 static void GetDevicesForCard(module_config_t *p_item, int i_card)
861 {
862     int i_pcm_device = -1;
863     int i_err = 0;
864     snd_pcm_info_t *p_pcm_info;
865     snd_ctl_t *p_ctl;
866     char psz_dev[64];
867     char *psz_card_name;
868     
869     sprintf(psz_dev, "hw:%i", i_card);
870     
871     if (( i_err = snd_ctl_open(&p_ctl, psz_dev, 0)) < 0 )
872     {
873         return;
874     }
875     
876     if ((i_err = snd_card_get_name(i_card, &psz_card_name)) != 0)
877     {
878         psz_card_name = _("Unknown soundcard");
879     }
880
881     snd_pcm_info_alloca(&p_pcm_info);
882
883     for (;;)
884     {
885         char *psz_device, *psz_descr;
886         if ((i_err = snd_ctl_pcm_next_device(p_ctl, &i_pcm_device)) < 0)
887         {
888             i_pcm_device = -1;
889         }
890         if ( i_pcm_device < 0 )
891             break;
892
893         snd_pcm_info_set_device(p_pcm_info, i_pcm_device);
894         snd_pcm_info_set_subdevice(p_pcm_info, 0);
895         snd_pcm_info_set_stream(p_pcm_info, SND_PCM_STREAM_PLAYBACK);
896
897         if ((i_err = snd_ctl_pcm_info(p_ctl, p_pcm_info)) < 0)
898         {
899             if (i_err != -ENOENT)
900             {
901 /*                printf("get_devices_for_card(): "
902                          "snd_ctl_pcm_info() "
903                          "failed (%d:%d): %s.\n", i_card,
904                          i_pcm_device, snd_strerror(-i_err));*/
905             }
906             continue;
907         }
908
909         asprintf( &psz_device, "hw:%d,%d", i_card, i_pcm_device );
910         asprintf( &psz_descr, "%s: %s (%s)", psz_card_name,
911                   snd_pcm_info_get_name(p_pcm_info), psz_device );
912
913         p_item->ppsz_list =
914             (char **)realloc( p_item->ppsz_list,
915                               (p_item->i_list + 2) * sizeof(char *) );
916         p_item->ppsz_list_text =
917             (char **)realloc( p_item->ppsz_list_text,
918                               (p_item->i_list + 2) * sizeof(char *) );
919         p_item->ppsz_list[ p_item->i_list ] = psz_device;
920         p_item->ppsz_list_text[ p_item->i_list ] = psz_descr;
921         p_item->i_list++;
922         p_item->ppsz_list[ p_item->i_list ] = NULL;
923         p_item->ppsz_list_text[ p_item->i_list ] = NULL;
924                 
925     }
926
927     snd_ctl_close( p_ctl );
928 }
929
930
931
932 static void GetDevices( module_config_t *p_item )
933 {
934     int i_card = -1;
935     int i_err = 0;
936     
937     if ((i_err = snd_card_next(&i_card)) != 0)
938     {
939 //        g_warning("snd_next_card() failed: %s", snd_strerror(-err));
940         return;
941     }
942     
943     while (i_card > -1)
944     {
945         GetDevicesForCard(p_item, i_card);
946         if ((i_err = snd_card_next(&i_card)) != 0)
947         {
948 //            g_warning("snd_next_card() failed: %s",
949 //                  snd_strerror(-err));
950             break;
951         }
952     }
953 }
954