]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
Improvements to preferences
[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
95 /*****************************************************************************
96  * Module descriptor
97  *****************************************************************************/
98 vlc_module_begin();
99     set_description( _("ALSA audio output") );
100     set_category( CAT_AUDIO );
101     set_subcategory( SUBCAT_AUDIO_AOUT );
102     add_string( "alsadev", DEFAULT_ALSA_DEVICE, aout_FindAndRestart,
103                 N_("ALSA Device Name"), NULL, VLC_FALSE );
104     set_capability( "audio output", 150 );
105     set_callbacks( Open, Close );
106 vlc_module_end();
107
108 /*****************************************************************************
109  * Probe: probe the audio device for available formats and channels
110  *****************************************************************************/
111 static void Probe( aout_instance_t * p_aout,
112                    const char * psz_device, const char * psz_iec_device,
113                    int *pi_snd_pcm_format )
114 {
115     struct aout_sys_t * p_sys = p_aout->output.p_sys;
116     vlc_value_t val, text;
117     int i_ret;
118
119     var_Create ( p_aout, "audio-device", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
120     text.psz_string = _("Audio Device");
121     var_Change( p_aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL );
122
123     /* We'll open the audio device in non blocking mode so we can just exit
124      * when it is already in use, but for the real stuff we'll still use
125      * the blocking mode */
126
127     /* Now test linear PCM capabilities */
128     if ( !(i_ret = snd_pcm_open( &p_sys->p_snd_pcm, psz_device,
129                                  SND_PCM_STREAM_PLAYBACK,
130                                  SND_PCM_NONBLOCK ) ) )
131     {
132         int i_channels;
133         snd_pcm_hw_params_t * p_hw;
134         snd_pcm_hw_params_alloca (&p_hw);
135
136         if ( snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw ) < 0 )
137         {
138             msg_Warn( p_aout, "unable to retrieve initial hardware parameters"
139                               ", disabling linear PCM audio" );
140             snd_pcm_close( p_sys->p_snd_pcm );
141             var_Destroy( p_aout, "audio-device" );
142             return;
143         }
144
145         if ( snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
146                                            *pi_snd_pcm_format ) < 0 )
147         {
148             if( *pi_snd_pcm_format != SND_PCM_FORMAT_S16 )
149             {
150                 *pi_snd_pcm_format = SND_PCM_FORMAT_S16;
151                 if ( snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
152                                                    *pi_snd_pcm_format ) < 0 )
153                 {
154                     msg_Warn( p_aout, "unable to set stream sample size and "
155                               "word order, disabling linear PCM audio" );
156                     snd_pcm_close( p_sys->p_snd_pcm );
157                     var_Destroy( p_aout, "audio-device" );
158                     return;
159                 }
160             }
161         }
162
163         i_channels = aout_FormatNbChannels( &p_aout->output.output );
164
165         while ( i_channels > 0 )
166         {
167             if ( !snd_pcm_hw_params_test_channels( p_sys->p_snd_pcm, p_hw,
168                                                    i_channels ) )
169             {
170                 switch ( i_channels )
171                 {
172                 case 1:
173                     val.i_int = AOUT_VAR_MONO;
174                     text.psz_string = N_("Mono");
175                     var_Change( p_aout, "audio-device",
176                                 VLC_VAR_ADDCHOICE, &val, &text );
177                     break;
178                 case 2:
179                     val.i_int = AOUT_VAR_STEREO;
180                     text.psz_string = N_("Stereo");
181                     var_Change( p_aout, "audio-device",
182                                 VLC_VAR_ADDCHOICE, &val, &text );
183                     var_Set( p_aout, "audio-device", val );
184                     break;
185                 case 4:
186                     val.i_int = AOUT_VAR_2F2R;
187                     text.psz_string = N_("2 Front 2 Rear");
188                     var_Change( p_aout, "audio-device",
189                                 VLC_VAR_ADDCHOICE, &val, &text );
190                     break;
191                 case 6:
192                     val.i_int = AOUT_VAR_5_1;
193                     text.psz_string = N_("5.1");
194                     var_Change( p_aout, "audio-device",
195                                 VLC_VAR_ADDCHOICE, &val, &text );
196                     break;
197                 }
198             }
199
200             --i_channels;
201         }
202
203         /* Special case for mono on stereo only boards */
204         i_channels = aout_FormatNbChannels( &p_aout->output.output );        
205         var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
206         if( val.i_int <= 0 && i_channels == 1 )
207         {
208             if ( !snd_pcm_hw_params_test_channels( p_sys->p_snd_pcm, p_hw, 2 ))
209             {
210                 val.i_int = AOUT_VAR_STEREO;
211                 text.psz_string = N_("Stereo");
212                 var_Change( p_aout, "audio-device",
213                             VLC_VAR_ADDCHOICE, &val, &text );
214                 var_Set( p_aout, "audio-device", val );
215             }
216         }
217         
218         /* Close the previously opened device */
219         snd_pcm_close( p_sys->p_snd_pcm );
220     }
221     else if ( i_ret == -EBUSY )
222     {
223         msg_Warn( p_aout, "audio device: %s is already in use", psz_device );
224     }
225
226     /* Test for S/PDIF device if needed */
227     if ( psz_iec_device )
228     {
229         /* Opening the device should be enough */
230         if ( !(i_ret = snd_pcm_open( &p_sys->p_snd_pcm, psz_iec_device,
231                                      SND_PCM_STREAM_PLAYBACK,
232                                      SND_PCM_NONBLOCK ) ) )
233         {
234             val.i_int = AOUT_VAR_SPDIF;
235             text.psz_string = N_("A/52 over S/PDIF");
236             var_Change( p_aout, "audio-device",
237                         VLC_VAR_ADDCHOICE, &val, &text );
238             if( config_GetInt( p_aout, "spdif" ) )
239                 var_Set( p_aout, "audio-device", val );
240
241             snd_pcm_close( p_sys->p_snd_pcm );
242         }
243         else if ( i_ret == -EBUSY )
244         {
245             msg_Warn( p_aout, "audio device: %s is already in use",
246                       psz_iec_device );
247         }
248     }
249
250     var_Change( p_aout, "audio-device", VLC_VAR_CHOICESCOUNT, &val, NULL );
251     if( val.i_int <= 0 )
252     {
253         /* Probe() has failed. */
254         msg_Dbg( p_aout, "failed to find a useable alsa configuration" );
255         var_Destroy( p_aout, "audio-device" );
256         return;
257     }
258
259     /* Add final settings to the variable */
260     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
261     val.b_bool = VLC_TRUE;
262     var_Set( p_aout, "intf-change", val );
263 }
264
265 /*****************************************************************************
266  * Open: create a handle and open an alsa device
267  *****************************************************************************
268  * This function opens an alsa device, through the alsa API.
269  *
270  * Note: the only heap-allocated string is psz_device. All the other pointers
271  * are references to psz_device or to stack-allocated data.
272  *****************************************************************************/
273 static int Open( vlc_object_t *p_this )
274 {
275     aout_instance_t * p_aout = (aout_instance_t *)p_this;
276     struct aout_sys_t * p_sys;
277     vlc_value_t val;
278
279     char psz_default_iec_device[128]; /* Buffer used to store the default
280                                          S/PDIF device */
281     char * psz_device, * psz_iec_device; /* device names for PCM and S/PDIF
282                                             output */
283
284     int i_vlc_pcm_format; /* Audio format for VLC's data */
285     int i_snd_pcm_format; /* Audio format for ALSA's data */
286
287     snd_pcm_uframes_t i_buffer_size = 0;
288     snd_pcm_uframes_t i_period_size = 0;
289     int i_channels = 0;
290
291     snd_pcm_hw_params_t *p_hw;
292     snd_pcm_sw_params_t *p_sw;
293
294     int i_snd_rc = -1;
295     int i_old_rate;
296
297     /* Allocate structures */
298     p_aout->output.p_sys = p_sys = malloc( sizeof( aout_sys_t ) );
299     if( p_sys == NULL )
300     {
301         msg_Err( p_aout, "out of memory" );
302         return VLC_ENOMEM;
303     }
304     p_sys->b_playing = VLC_FALSE;
305     p_sys->start_date = 0;
306     p_sys->p_status = (snd_pcm_status_t *)malloc(snd_pcm_status_sizeof());
307     vlc_cond_init( p_aout, &p_sys->wait );
308     vlc_mutex_init( p_aout, &p_sys->lock );
309
310     /* Get device name */
311     if( (psz_device = config_GetPsz( p_aout, "alsadev" )) == NULL )
312     {
313         msg_Err( p_aout, "no audio device given (maybe \"default\" ?)" );
314         free( p_sys );
315         return VLC_EGENERIC;
316     }
317
318     /* Choose the IEC device for S/PDIF output:
319        if the device is overriden by the user then it will be the one
320        otherwise we compute the default device based on the output format. */
321     if( AOUT_FMT_NON_LINEAR( &p_aout->output.output )
322         && !strcmp( psz_device, DEFAULT_ALSA_DEVICE ) )
323     {
324         snprintf( psz_default_iec_device, sizeof(psz_default_iec_device),
325                   "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
326                   IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
327                   IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
328                   0,
329                   ( p_aout->output.output.i_rate == 48000 ?
330                     IEC958_AES3_CON_FS_48000 :
331                     ( p_aout->output.output.i_rate == 44100 ?
332                       IEC958_AES3_CON_FS_44100 : IEC958_AES3_CON_FS_32000 ) ) );
333         psz_iec_device = psz_default_iec_device;
334     }
335     else if( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
336     {
337         psz_iec_device = psz_device;
338     }
339     else
340     {
341         psz_iec_device = NULL;
342     }
343
344     /* Choose the linear PCM format (read the comment above about FPU
345        and float32) */
346     if( p_aout->p_libvlc->i_cpu & CPU_CAPABILITY_FPU )
347     {
348         i_vlc_pcm_format = VLC_FOURCC('f','l','3','2');
349         i_snd_pcm_format = SND_PCM_FORMAT_FLOAT;
350     }
351     else
352     {
353         i_vlc_pcm_format = AOUT_FMT_S16_NE;
354         i_snd_pcm_format = SND_PCM_FORMAT_S16;
355     }
356
357     /* If the variable doesn't exist then it's the first time we're called
358        and we have to probe the available audio formats and channels */
359     if ( var_Type( p_aout, "audio-device" ) == 0 )
360     {
361         Probe( p_aout, psz_device, psz_iec_device, &i_snd_pcm_format );
362         switch( i_snd_pcm_format )
363         {
364         case SND_PCM_FORMAT_FLOAT:
365             i_vlc_pcm_format = VLC_FOURCC('f','l','3','2');
366             break;
367         case SND_PCM_FORMAT_S16:
368             i_vlc_pcm_format = AOUT_FMT_S16_NE;
369             break;
370         }
371     }
372
373     if ( var_Get( p_aout, "audio-device", &val ) < 0 )
374     {
375         free( p_sys );
376         free( psz_device );
377         return VLC_EGENERIC;
378     }
379
380     if ( val.i_int == AOUT_VAR_SPDIF )
381     {
382         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
383     }
384     else if ( val.i_int == AOUT_VAR_5_1 )
385     {
386         p_aout->output.output.i_format = i_vlc_pcm_format;
387         p_aout->output.output.i_physical_channels
388             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
389                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
390                | AOUT_CHAN_LFE;
391         free( psz_device );
392         psz_device = strdup( "surround51" );
393     }
394     else if ( val.i_int == AOUT_VAR_2F2R )
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
399                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
400         free( psz_device );
401         psz_device = strdup( "surround40" );
402     }
403     else if ( val.i_int == AOUT_VAR_STEREO )
404     {
405         p_aout->output.output.i_format = i_vlc_pcm_format;
406         p_aout->output.output.i_physical_channels
407             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
408     }
409     else if ( val.i_int == AOUT_VAR_MONO )
410     {
411         p_aout->output.output.i_format = i_vlc_pcm_format;
412         p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
413     }
414
415     else
416     {
417         /* This should not happen ! */
418         msg_Err( p_aout, "internal: can't find audio-device (%i)", val.i_int );
419         free( p_sys );
420         return VLC_EGENERIC;
421     }
422
423 #ifdef ALSA_DEBUG
424     snd_output_stdio_attach( &p_sys->p_snd_stderr, stderr, 0 );
425 #endif
426
427     /* Open the device */
428     if ( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
429     {
430         if ( ( i_snd_rc = snd_pcm_open( &p_sys->p_snd_pcm, psz_iec_device,
431                             SND_PCM_STREAM_PLAYBACK, 0 ) ) < 0 )
432         {
433             msg_Err( p_aout, "cannot open ALSA device `%s' (%s)",
434                              psz_iec_device, snd_strerror( i_snd_rc ) );
435             free( p_sys );
436             free( psz_device );
437             return VLC_EGENERIC;
438         }
439         i_buffer_size = ALSA_SPDIF_BUFFER_SIZE;
440         i_snd_pcm_format = SND_PCM_FORMAT_S16;
441         i_channels = 2;
442
443         p_aout->output.i_nb_samples = i_period_size = ALSA_SPDIF_PERIOD_SIZE;
444         p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
445         p_aout->output.output.i_frame_length = A52_FRAME_NB;
446
447         aout_VolumeNoneInit( p_aout );
448     }
449     else
450     {
451         msg_Dbg( p_aout, "opening ALSA device `%s'", psz_device );
452
453         if ( ( i_snd_rc = snd_pcm_open( &p_sys->p_snd_pcm, psz_device,
454                             SND_PCM_STREAM_PLAYBACK, 0 ) ) < 0 )
455         {
456             msg_Err( p_aout, "cannot open ALSA device `%s' (%s)",
457                              psz_device, snd_strerror( i_snd_rc ) );
458             free( p_sys );
459             free( psz_device );
460             return VLC_EGENERIC;
461         }
462         i_buffer_size = ALSA_DEFAULT_BUFFER_SIZE;
463         i_channels = aout_FormatNbChannels( &p_aout->output.output );
464
465         p_aout->output.i_nb_samples = i_period_size = ALSA_DEFAULT_PERIOD_SIZE;
466
467         aout_VolumeSoftInit( p_aout );
468     }
469
470     /* Free psz_device so that all the remaining data is stack-allocated */
471     free( psz_device );
472
473     p_aout->output.pf_play = Play;
474
475     snd_pcm_hw_params_alloca(&p_hw);
476     snd_pcm_sw_params_alloca(&p_sw);
477
478     /* Get Initial hardware parameters */
479     if ( ( i_snd_rc = snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw ) ) < 0 )
480     {
481         msg_Err( p_aout, "unable to retrieve initial hardware parameters (%s)",
482                          snd_strerror( i_snd_rc ) );
483         goto error;
484     }
485
486     /* Set format. */
487     if ( ( i_snd_rc = snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
488                                                     i_snd_pcm_format ) ) < 0 )
489     {
490         msg_Err( p_aout, "unable to set stream sample size and word order (%s)",
491                          snd_strerror( i_snd_rc ) );
492         goto error;
493     }
494
495     if ( ( i_snd_rc = snd_pcm_hw_params_set_access( p_sys->p_snd_pcm, p_hw,
496                                     SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
497     {
498         msg_Err( p_aout, "unable to set interleaved stream format (%s)",
499                          snd_strerror( i_snd_rc ) );
500         goto error;
501     }
502
503     /* Set channels. */
504     if ( ( i_snd_rc = snd_pcm_hw_params_set_channels( p_sys->p_snd_pcm, p_hw,
505                                                       i_channels ) ) < 0 )
506     {
507         msg_Err( p_aout, "unable to set number of output channels (%s)",
508                          snd_strerror( i_snd_rc ) );
509         goto error;
510     }
511
512     /* Set rate. */
513     i_old_rate = p_aout->output.output.i_rate;
514 #ifdef HAVE_ALSA_NEW_API
515     i_snd_rc = snd_pcm_hw_params_set_rate_near( p_sys->p_snd_pcm, p_hw,
516                                                 &p_aout->output.output.i_rate,
517                                                 NULL );
518 #else
519     i_snd_rc = snd_pcm_hw_params_set_rate_near( p_sys->p_snd_pcm, p_hw,
520                                                 p_aout->output.output.i_rate,
521                                                 NULL );
522 #endif
523     if( i_snd_rc < 0 || p_aout->output.output.i_rate != i_old_rate )
524     {
525         msg_Warn( p_aout, "The rate %d Hz is not supported by your hardware. "
526                   "Using %d Hz instead.\n", i_old_rate,
527                   p_aout->output.output.i_rate );
528     }
529
530     /* Set buffer size. */
531 #ifdef HAVE_ALSA_NEW_API
532     if ( ( i_snd_rc = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm,
533                                     p_hw, &i_buffer_size ) ) < 0 )
534 #else
535     if ( ( i_snd_rc = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm,
536                                     p_hw, i_buffer_size ) ) < 0 )
537 #endif
538     {
539         msg_Err( p_aout, "unable to set buffer size (%s)",
540                          snd_strerror( i_snd_rc ) );
541         goto error;
542     }
543
544     /* Set period size. */
545 #ifdef HAVE_ALSA_NEW_API
546     if ( ( i_snd_rc = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm,
547                                     p_hw, &i_period_size, NULL ) ) < 0 )
548 #else
549     if ( ( i_snd_rc = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm,
550                                     p_hw, i_period_size, NULL ) ) < 0 )
551 #endif
552     {
553         msg_Err( p_aout, "unable to set period size (%s)",
554                          snd_strerror( i_snd_rc ) );
555         goto error;
556     }
557     p_aout->output.i_nb_samples = i_period_size;
558
559     /* Commit hardware parameters. */
560     if ( ( i_snd_rc = snd_pcm_hw_params( p_sys->p_snd_pcm, p_hw ) ) < 0 )
561     {
562         msg_Err( p_aout, "unable to commit hardware configuration (%s)",
563                          snd_strerror( i_snd_rc ) );
564         goto error;
565     }
566
567 #ifdef HAVE_ALSA_NEW_API
568     if( ( i_snd_rc = snd_pcm_hw_params_get_period_time( p_hw,
569                                     &p_sys->i_period_time, NULL ) ) < 0 )
570 #else
571     if( ( p_sys->i_period_time =
572                   snd_pcm_hw_params_get_period_time( p_hw, NULL ) ) < 0 )
573 #endif
574     {
575         msg_Err( p_aout, "unable to get period time (%s)",
576                          snd_strerror( i_snd_rc ) );
577         goto error;
578     }
579
580     /* Get Initial software parameters */
581     snd_pcm_sw_params_current( p_sys->p_snd_pcm, p_sw );
582
583     i_snd_rc = snd_pcm_sw_params_set_sleep_min( p_sys->p_snd_pcm, p_sw, 0 );
584
585     i_snd_rc = snd_pcm_sw_params_set_avail_min( p_sys->p_snd_pcm, p_sw,
586                                                 p_aout->output.i_nb_samples );
587
588     /* Commit software parameters. */
589     if ( snd_pcm_sw_params( p_sys->p_snd_pcm, p_sw ) < 0 )
590     {
591         msg_Err( p_aout, "unable to set software configuration" );
592         goto error;
593     }
594
595 #ifdef ALSA_DEBUG
596     snd_output_printf( p_sys->p_snd_stderr, "\nALSA hardware setup:\n\n" );
597     snd_pcm_dump_hw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
598     snd_output_printf( p_sys->p_snd_stderr, "\nALSA software setup:\n\n" );
599     snd_pcm_dump_sw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
600     snd_output_printf( p_sys->p_snd_stderr, "\n" );
601 #endif
602
603     /* Create ALSA thread and wait for its readiness. */
604     if( vlc_thread_create( p_aout, "aout", ALSAThread,
605                            VLC_THREAD_PRIORITY_OUTPUT, VLC_FALSE ) )
606     {
607         msg_Err( p_aout, "cannot create ALSA thread (%s)", strerror(errno) );
608         goto error;
609     }
610
611     return 0;
612
613 error:
614     snd_pcm_close( p_sys->p_snd_pcm );
615 #ifdef ALSA_DEBUG
616     snd_output_close( p_sys->p_snd_stderr );
617 #endif
618     free( p_sys );
619     return VLC_EGENERIC;
620 }
621
622 /*****************************************************************************
623  * Play: nothing to do
624  *****************************************************************************/
625 static void Play( aout_instance_t *p_aout )
626 {
627     if( !p_aout->output.p_sys->b_playing )
628     {
629         p_aout->output.p_sys->b_playing = 1;
630
631         /* get the playing date of the first aout buffer */
632         p_aout->output.p_sys->start_date =
633             aout_FifoFirstDate( p_aout, &p_aout->output.fifo );
634
635         /* wake up the audio output thread */
636         vlc_mutex_lock( &p_aout->output.p_sys->lock );
637         vlc_cond_signal( &p_aout->output.p_sys->wait );
638         vlc_mutex_unlock( &p_aout->output.p_sys->lock );
639     }
640 }
641
642 /*****************************************************************************
643  * Close: close the ALSA device
644  *****************************************************************************/
645 static void Close( vlc_object_t *p_this )
646 {
647     aout_instance_t *p_aout = (aout_instance_t *)p_this;
648     struct aout_sys_t * p_sys = p_aout->output.p_sys;
649     int i_snd_rc;
650
651     /* make sure the audio output thread is waken up */
652     vlc_mutex_lock( &p_aout->output.p_sys->lock );
653     vlc_cond_signal( &p_aout->output.p_sys->wait );
654     vlc_mutex_unlock( &p_aout->output.p_sys->lock );
655
656     p_aout->b_die = VLC_TRUE;
657     vlc_thread_join( p_aout );
658     p_aout->b_die = VLC_FALSE;
659
660     i_snd_rc = snd_pcm_close( p_sys->p_snd_pcm );
661
662     if( i_snd_rc > 0 )
663     {
664         msg_Err( p_aout, "failed closing ALSA device (%s)",
665                          snd_strerror( i_snd_rc ) );
666     }
667
668 #ifdef ALSA_DEBUG
669     snd_output_close( p_sys->p_snd_stderr );
670 #endif
671
672     free( p_sys->p_status );
673     free( p_sys );
674 }
675
676 /*****************************************************************************
677  * ALSAThread: asynchronous thread used to DMA the data to the device
678  *****************************************************************************/
679 static int ALSAThread( aout_instance_t * p_aout )
680 {
681     /* Wait for the exact time to start playing (avoids resampling) */
682     vlc_mutex_lock( &p_aout->output.p_sys->lock );
683     if( !p_aout->output.p_sys->start_date )
684         vlc_cond_wait( &p_aout->output.p_sys->wait,
685                        &p_aout->output.p_sys->lock );
686     vlc_mutex_unlock( &p_aout->output.p_sys->lock );
687
688     mwait( p_aout->output.p_sys->start_date - AOUT_PTS_TOLERANCE / 4 );
689
690     while ( !p_aout->b_die )
691     {
692         ALSAFill( p_aout );
693     }
694
695     return 0;
696 }
697
698 /*****************************************************************************
699  * ALSAFill: function used to fill the ALSA buffer as much as possible
700  *****************************************************************************/
701 static void ALSAFill( aout_instance_t * p_aout )
702 {
703     struct aout_sys_t * p_sys = p_aout->output.p_sys;
704
705     aout_buffer_t * p_buffer;
706     snd_pcm_status_t * p_status = p_sys->p_status;
707     snd_timestamp_t ts_next;
708     int i_snd_rc;
709     mtime_t next_date;
710
711     /* Fill in the buffer until space or audio output buffer shortage */
712     {
713         /* Get the status */
714         i_snd_rc = snd_pcm_status( p_sys->p_snd_pcm, p_status );
715         if( i_snd_rc < 0 )
716         {
717             msg_Err( p_aout, "unable to get the device's status (%s)",
718                              snd_strerror( i_snd_rc ) );
719
720             msleep( p_sys->i_period_time >> 1 );
721             return;
722         }
723
724         /* Handle buffer underruns and reget the status */
725         if( snd_pcm_status_get_state( p_status ) == SND_PCM_STATE_XRUN )
726         {
727             /* Prepare the device */
728             i_snd_rc = snd_pcm_prepare( p_sys->p_snd_pcm );
729
730             if( i_snd_rc == 0 )
731             {
732                 msg_Warn( p_aout, "recovered from buffer underrun" );
733
734                 /* Reget the status */
735                 i_snd_rc = snd_pcm_status( p_sys->p_snd_pcm, p_status );
736                 if( i_snd_rc < 0 )
737                 {
738                     msg_Err( p_aout, "unable to get the device's status after "
739                              "recovery (%s)", snd_strerror( i_snd_rc ) );
740
741                     msleep( p_sys->i_period_time >> 1 );
742                     return;
743                 }
744             }
745             else
746             {
747                 msg_Err( p_aout, "unable to recover from buffer underrun" );
748
749                 msleep( p_sys->i_period_time >> 1 );
750                 return;
751             }
752
753             /* Underrun, try to recover as quickly as possible */
754             next_date = mdate();
755         }
756         else
757         {
758             /* Here the device should be either in the RUNNING state.
759              * p_status is valid. */
760
761             snd_pcm_status_get_tstamp( p_status, &ts_next );
762             next_date = (mtime_t)ts_next.tv_sec * 1000000 + ts_next.tv_usec;
763             if( next_date )
764             {
765                 next_date += (mtime_t)snd_pcm_status_get_delay(p_status)
766                         * 1000000 / p_aout->output.output.i_rate;
767             }
768             else
769             {
770                 /* With screwed ALSA drivers the timestamp is always zero;
771                  * use another method then */
772                 snd_pcm_sframes_t delay;
773                 ssize_t i_bytes = 0;
774
775                 if( !snd_pcm_delay( p_sys->p_snd_pcm, &delay ) )
776                 {
777                     i_bytes = snd_pcm_frames_to_bytes(p_sys->p_snd_pcm, delay);
778                 }
779                 next_date = mdate() + (mtime_t)i_bytes * 1000000
780                         / p_aout->output.output.i_bytes_per_frame
781                         / p_aout->output.output.i_rate
782                         * p_aout->output.output.i_frame_length;
783             }
784         }
785
786         p_buffer = aout_OutputNextBuffer( p_aout, next_date,
787                         (p_aout->output.output.i_format ==
788                          VLC_FOURCC('s','p','d','i')) );
789
790         /* Audio output buffer shortage -> stop the fill process and wait */
791         if( p_buffer == NULL )
792         {
793             msleep( p_sys->i_period_time >> 1 );
794             return;
795         }
796
797         i_snd_rc = snd_pcm_writei( p_sys->p_snd_pcm, p_buffer->p_buffer,
798                                    p_buffer->i_nb_samples );
799
800         if( i_snd_rc < 0 )
801         {
802             msg_Err( p_aout, "write failed (%s)",
803                              snd_strerror( i_snd_rc ) );
804         }
805
806         aout_BufferFree( p_buffer );
807     }
808 }