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