]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
18af114502e63608e117444e4aaf2855bfc1be8e
[vlc] / modules / audio_output / alsa.c
1 /*****************************************************************************
2  * alsa.c : alsa plugin for vlc
3  *****************************************************************************
4  * Copyright (C) 2000-2001 VideoLAN
5  * $Id: alsa.c,v 1.25 2003/03/30 18:14:36 gbazin Exp $
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 DEBUG
58     snd_output_t      * p_snd_stderr;
59 #endif
60 };
61
62 #define A52_FRAME_NB 1536
63
64 /* These values are in frames.
65    To convert them to a number of bytes you have to multiply them by the
66    number of channel(s) (eg. 2 for stereo) and the size of a sample (eg.
67    2 for s16). */
68 #define ALSA_DEFAULT_PERIOD_SIZE        2048
69 #define ALSA_DEFAULT_BUFFER_SIZE        ( ALSA_DEFAULT_PERIOD_SIZE << 4 )
70 #define ALSA_SPDIF_PERIOD_SIZE          A52_FRAME_NB
71 #define ALSA_SPDIF_BUFFER_SIZE          ( ALSA_SPDIF_PERIOD_SIZE << 4 )
72 /* Why << 4 ? --Meuuh */
73 /* Why not ? --Bozo */
74 /* Right. --Meuuh */
75
76 #define DEFAULT_ALSA_DEVICE "default"
77
78 /*****************************************************************************
79  * Local prototypes
80  *****************************************************************************/
81 static int  Open         ( vlc_object_t * );
82 static void Close        ( vlc_object_t * );
83 static void Play         ( aout_instance_t * );
84 static int  ALSAThread   ( aout_instance_t * );
85 static void ALSAFill     ( aout_instance_t * );
86
87 /*****************************************************************************
88  * Module descriptor
89  *****************************************************************************/
90 vlc_module_begin();
91     add_category_hint( N_("ALSA"), NULL, VLC_FALSE );
92     add_string( "alsadev", DEFAULT_ALSA_DEVICE, aout_FindAndRestart,
93                 N_("ALSA device name"), NULL, VLC_FALSE );
94     set_description( _("ALSA audio output") );
95     set_capability( "audio output", 50 );
96     set_callbacks( Open, Close );
97 vlc_module_end();
98
99 /*****************************************************************************
100  * Probe: probe the audio device for available formats and channels
101  *****************************************************************************/
102 static void Probe( aout_instance_t * p_aout,
103                    const char * psz_device, const char * psz_iec_device,
104                    int i_snd_pcm_format )
105 {
106     struct aout_sys_t * p_sys = p_aout->output.p_sys;
107     vlc_value_t val;
108
109     var_Create ( p_aout, "audio-device", VLC_VAR_STRING | VLC_VAR_HASCHOICE );
110
111     /* Now test linear PCM capabilities */
112     if ( !snd_pcm_open( &p_sys->p_snd_pcm, psz_device,
113                         SND_PCM_STREAM_PLAYBACK, 0 ) )
114     {
115         int i_channels;
116         snd_pcm_hw_params_t * p_hw;
117         snd_pcm_hw_params_alloca (&p_hw);
118
119         if ( snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw ) < 0 )
120         {
121             msg_Warn( p_aout, "unable to retrieve initial hardware parameters"
122                               ", disabling linear PCM audio" );
123             snd_pcm_close( p_sys->p_snd_pcm );
124             return;
125         }
126
127         if ( snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
128                                            i_snd_pcm_format ) < 0 )
129         {
130             /* Assume a FPU enabled computer can handle float32 format.
131                If somebody tells us it's not always true then we'll have
132                to change this */
133             msg_Warn( p_aout, "unable to set stream sample size and word order"
134                               ", disabling linear PCM audio" );
135             snd_pcm_close( p_sys->p_snd_pcm );
136             return;
137         }
138
139         i_channels = aout_FormatNbChannels( &p_aout->output.output );
140
141         while ( i_channels > 0 )
142         {
143             /* Here we have to probe multi-channel capabilities but I have
144                no idea (at the moment) of how its managed by the ALSA
145                library.
146                It seems that '6' channels aren't well handled on a stereo
147                sound card like my i810 but it requires some more
148                investigations. That's why '4' and '6' cases are disabled.
149                -- Bozo */
150             if ( !snd_pcm_hw_params_test_channels( p_sys->p_snd_pcm, p_hw,
151                                                    i_channels ) )
152             {
153                 switch ( i_channels )
154                 {
155                 case 1:
156                     val.psz_string = N_("Mono");
157                     var_Change( p_aout, "audio-device",
158                                 VLC_VAR_ADDCHOICE, &val );
159                     break;
160                 case 2:
161                     val.psz_string = N_("Stereo");
162                     var_Change( p_aout, "audio-device",
163                                 VLC_VAR_ADDCHOICE, &val );
164                     break;
165 /*
166                 case 4:
167                     val.psz_string = N_("2 Front 2 Rear");
168                     var_Change( p_aout, "audio-device",
169                                 VLC_VAR_ADDCHOICE, &val );
170                     break;
171                 case 6:
172                     val.psz_string = N_("5.1");
173                     var_Change( p_aout, "audio-device",
174                                 VLC_VAR_ADDCHOICE, &val );
175                     break;
176 */
177                 }
178             }
179
180             --i_channels;
181         }
182
183         /* Close the previously opened device */
184         snd_pcm_close( p_sys->p_snd_pcm );
185     }
186
187     /* Test for S/PDIF device if needed */
188     if ( psz_iec_device )
189     {
190         /* Opening the device should be enough */
191         if ( !snd_pcm_open( &p_sys->p_snd_pcm, psz_iec_device,
192                                 SND_PCM_STREAM_PLAYBACK, 0 ) )
193         {
194             val.psz_string = N_("A/52 over S/PDIF");
195             var_Change( p_aout, "audio-device", VLC_VAR_ADDCHOICE, &val );
196             snd_pcm_close( p_sys->p_snd_pcm );
197             if( config_GetInt( p_aout, "spdif" ) )
198                 var_Set( p_aout, "audio-device", val );
199         }
200     }
201
202     /* Add final settings to the variable */
203     var_AddCallback( p_aout, "audio-device", aout_ChannelsRestart, NULL );
204     val.b_bool = VLC_TRUE;
205     var_Set( p_aout, "intf-change", val );
206 }
207
208 /*****************************************************************************
209  * Open: create a handle and open an alsa device
210  *****************************************************************************
211  * This function opens an alsa device, through the alsa API.
212  *
213  * Note: the only heap-allocated string is psz_device. All the other pointers
214  * are references to psz_device or to stack-allocated data.
215  *****************************************************************************/
216 static int Open( vlc_object_t *p_this )
217 {
218     aout_instance_t * p_aout = (aout_instance_t *)p_this;
219     struct aout_sys_t * p_sys;
220     vlc_value_t val;
221
222     char psz_default_iec_device[128]; /* Buffer used to store the default
223                                          S/PDIF device */
224     char * psz_device, * psz_iec_device; /* device names for PCM and S/PDIF
225                                             output */
226
227     int i_vlc_pcm_format; /* Audio format for VLC's data */
228     int i_snd_pcm_format; /* Audio format for ALSA's data */
229
230     snd_pcm_uframes_t i_buffer_size = 0;
231     snd_pcm_uframes_t i_period_size = 0;
232     int i_channels = 0;
233
234     snd_pcm_hw_params_t *p_hw;
235     snd_pcm_sw_params_t *p_sw;
236
237     int i_snd_rc = -1;
238
239     /* Allocate structures */
240     p_aout->output.p_sys = p_sys = malloc( sizeof( aout_sys_t ) );
241     if( p_sys == NULL )
242     {
243         msg_Err( p_aout, "out of memory" );
244         return VLC_ENOMEM;
245     }
246
247     /* Get device name */
248     if( (psz_device = config_GetPsz( p_aout, "alsadev" )) == NULL )
249     {
250         msg_Err( p_aout, "no audio device given (maybe \"default\" ?)" );
251         free( p_sys );
252         return VLC_EGENERIC;
253     }
254
255     /* Choose the IEC device for S/PDIF output:
256        if the device is overriden by the user then it will be the one
257        otherwise we compute the default device based on the output format. */
258     if( AOUT_FMT_NON_LINEAR( &p_aout->output.output )
259         && !strcmp( psz_device, DEFAULT_ALSA_DEVICE ) )
260     {
261         snprintf( psz_default_iec_device, sizeof(psz_default_iec_device),
262                   "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
263                   IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
264                   IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
265                   0,
266                   ( p_aout->output.output.i_rate == 48000 ?
267                     IEC958_AES3_CON_FS_48000 :
268                     ( p_aout->output.output.i_rate == 44100 ?
269                       IEC958_AES3_CON_FS_44100 : IEC958_AES3_CON_FS_32000 ) ) );
270         psz_iec_device = psz_default_iec_device;
271     }
272     else if( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
273     {
274         psz_iec_device = psz_device;
275     }
276     else
277     {
278         psz_iec_device = NULL;
279     }
280
281     /* Choose the linear PCM format (read the comment above about FPU
282        and float32) */
283     if( p_aout->p_libvlc->i_cpu & CPU_CAPABILITY_FPU )
284     {
285         i_vlc_pcm_format = VLC_FOURCC('f','l','3','2');
286         i_snd_pcm_format = SND_PCM_FORMAT_FLOAT;
287     }
288     else
289     {
290         i_vlc_pcm_format = AOUT_FMT_S16_NE;
291         i_snd_pcm_format = SND_PCM_FORMAT_S16;
292     }
293
294     /* If the variable doesn't exist then it's the first time we're called
295        and we have to probe the available audio formats and channels */
296     if ( var_Type( p_aout, "audio-device" ) == 0 )
297     {
298         Probe( p_aout, psz_device, psz_iec_device, i_snd_pcm_format );
299     }
300
301     if ( var_Get( p_aout, "audio-device", &val ) < 0 )
302     {
303         free( p_sys );
304         free( psz_device );
305         return VLC_EGENERIC;
306     }
307
308     if ( !strcmp( val.psz_string, N_("A/52 over S/PDIF") ) )
309     {
310         p_aout->output.output.i_format = VLC_FOURCC('s','p','d','i');
311     }
312     else if ( !strcmp( val.psz_string, N_("5.1") ) )
313     {
314         p_aout->output.output.i_format = i_vlc_pcm_format;
315         p_aout->output.output.i_physical_channels
316             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
317                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
318                | AOUT_CHAN_LFE;
319     }
320     else if ( !strcmp( val.psz_string, N_("2 Front 2 Rear") ) )
321     {
322         p_aout->output.output.i_format = i_vlc_pcm_format;
323         p_aout->output.output.i_physical_channels
324             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
325                | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
326     }
327     else if ( !strcmp( val.psz_string, N_("Stereo") ) )
328     {
329         p_aout->output.output.i_format = i_vlc_pcm_format;
330         p_aout->output.output.i_physical_channels
331             = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
332     }
333     else if ( !strcmp( val.psz_string, N_("Mono") ) )
334     {
335         p_aout->output.output.i_format = i_vlc_pcm_format;
336         p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
337     }
338
339     else
340     {
341         /* This should not happen ! */
342         msg_Err( p_aout, "internal: can't find audio-device (%s)",
343                  val.psz_string );
344         free( p_sys );
345         free( val.psz_string );
346         return VLC_EGENERIC;
347     }
348     free( val.psz_string );
349
350 #ifdef DEBUG
351     snd_output_stdio_attach( &p_sys->p_snd_stderr, stderr, 0 );
352 #endif
353
354     /* Open the device */
355     if ( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
356     {
357         if ( ( i_snd_rc = snd_pcm_open( &p_sys->p_snd_pcm, psz_iec_device,
358                             SND_PCM_STREAM_PLAYBACK, 0 ) ) < 0 )
359         {
360             msg_Err( p_aout, "cannot open ALSA device `%s' (%s)",
361                              psz_iec_device, snd_strerror( i_snd_rc ) );
362             free( p_sys );
363             free( psz_device );
364             return VLC_EGENERIC;
365         }
366         i_buffer_size = ALSA_SPDIF_BUFFER_SIZE;
367         i_snd_pcm_format = SND_PCM_FORMAT_S16;
368         i_channels = 2;
369
370         p_aout->output.i_nb_samples = i_period_size = ALSA_SPDIF_PERIOD_SIZE;
371         p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
372         p_aout->output.output.i_frame_length = A52_FRAME_NB;
373
374         aout_VolumeNoneInit( p_aout );
375     }
376     else
377     {
378         if ( ( i_snd_rc = snd_pcm_open( &p_sys->p_snd_pcm, psz_device,
379                             SND_PCM_STREAM_PLAYBACK, 0 ) ) < 0 )
380         {
381             msg_Err( p_aout, "cannot open ALSA device `%s' (%s)",
382                              psz_device, snd_strerror( i_snd_rc ) );
383             free( p_sys );
384             free( psz_device );
385             return VLC_EGENERIC;
386         }
387         i_buffer_size = ALSA_DEFAULT_BUFFER_SIZE;
388         i_channels = aout_FormatNbChannels( &p_aout->output.output );
389
390         p_aout->output.i_nb_samples = i_period_size = ALSA_DEFAULT_PERIOD_SIZE;
391
392         aout_VolumeSoftInit( p_aout );
393     }
394
395     /* Free psz_device so that all the remaining data is stack-allocated */
396     free( psz_device );
397
398     p_aout->output.pf_play = Play;
399
400     snd_pcm_hw_params_alloca(&p_hw);
401     snd_pcm_sw_params_alloca(&p_sw);
402
403     /* Get Initial hardware parameters */
404     if ( ( i_snd_rc = snd_pcm_hw_params_any( p_sys->p_snd_pcm, p_hw ) ) < 0 )
405     {
406         msg_Err( p_aout, "unable to retrieve initial hardware parameters (%s)",
407                          snd_strerror( i_snd_rc ) );
408         goto error;
409     }
410
411     /* Set format. */
412     if ( ( i_snd_rc = snd_pcm_hw_params_set_format( p_sys->p_snd_pcm, p_hw,
413                                                     i_snd_pcm_format ) ) < 0 )
414     {
415         msg_Err( p_aout, "unable to set stream sample size and word order (%s)",
416                          snd_strerror( i_snd_rc ) );
417         goto error;
418     }
419
420     if ( ( i_snd_rc = snd_pcm_hw_params_set_access( p_sys->p_snd_pcm, p_hw,
421                                     SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
422     {
423         msg_Err( p_aout, "unable to set interleaved stream format (%s)",
424                          snd_strerror( i_snd_rc ) );
425         goto error;
426     }
427
428     /* Set channels. */
429     if ( ( i_snd_rc = snd_pcm_hw_params_set_channels( p_sys->p_snd_pcm, p_hw,
430                                                       i_channels ) ) < 0 )
431     {
432         msg_Err( p_aout, "unable to set number of output channels (%s)",
433                          snd_strerror( i_snd_rc ) );
434         goto error;
435     }
436
437     /* Set rate. */
438 #ifdef HAVE_ALSA_NEW_API
439     if ( ( i_snd_rc = snd_pcm_hw_params_set_rate_near( p_sys->p_snd_pcm, p_hw,
440                                 &p_aout->output.output.i_rate, NULL ) ) < 0 )
441 #else
442     if ( ( i_snd_rc = snd_pcm_hw_params_set_rate_near( p_sys->p_snd_pcm, p_hw,
443                                 p_aout->output.output.i_rate, NULL ) ) < 0 )
444 #endif
445     {
446         msg_Err( p_aout, "unable to set sample rate (%s)",
447                          snd_strerror( i_snd_rc ) );
448         goto error;
449     }
450
451     /* Set buffer size. */
452 #ifdef HAVE_ALSA_NEW_API
453     if ( ( i_snd_rc = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm,
454                                     p_hw, &i_buffer_size ) ) < 0 )
455 #else
456     if ( ( i_snd_rc = snd_pcm_hw_params_set_buffer_size_near( p_sys->p_snd_pcm,
457                                     p_hw, i_buffer_size ) ) < 0 )
458 #endif
459     {
460         msg_Err( p_aout, "unable to set buffer size (%s)",
461                          snd_strerror( i_snd_rc ) );
462         goto error;
463     }
464
465     /* Set period size. */
466 #ifdef HAVE_ALSA_NEW_API
467     if ( ( i_snd_rc = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm,
468                                     p_hw, &i_period_size, NULL ) ) < 0 )
469 #else
470     if ( ( i_snd_rc = snd_pcm_hw_params_set_period_size_near( p_sys->p_snd_pcm,
471                                     p_hw, i_period_size, NULL ) ) < 0 )
472 #endif
473     {
474         msg_Err( p_aout, "unable to set period size (%s)",
475                          snd_strerror( i_snd_rc ) );
476         goto error;
477     }
478     p_aout->output.i_nb_samples = i_period_size;
479
480     /* Commit hardware parameters. */
481     if ( ( i_snd_rc = snd_pcm_hw_params( p_sys->p_snd_pcm, p_hw ) ) < 0 )
482     {
483         msg_Err( p_aout, "unable to commit hardware configuration (%s)",
484                          snd_strerror( i_snd_rc ) );
485         goto error;
486     }
487
488 #ifdef HAVE_ALSA_NEW_API
489     if( ( i_snd_rc = snd_pcm_hw_params_get_period_time( p_hw,
490                                     &p_sys->i_period_time, NULL ) ) < 0 )
491 #else
492     if( ( p_sys->i_period_time =
493                   snd_pcm_hw_params_get_period_time( p_hw, NULL ) ) < 0 )
494 #endif
495     {
496         msg_Err( p_aout, "unable to get period time (%s)",
497                          snd_strerror( i_snd_rc ) );
498         goto error;
499     }
500
501     /* Get Initial software parameters */
502     snd_pcm_sw_params_current( p_sys->p_snd_pcm, p_sw );
503
504     i_snd_rc = snd_pcm_sw_params_set_sleep_min( p_sys->p_snd_pcm, p_sw, 0 );
505
506     i_snd_rc = snd_pcm_sw_params_set_avail_min( p_sys->p_snd_pcm, p_sw,
507                                                 p_aout->output.i_nb_samples );
508
509     /* Commit software parameters. */
510     if ( snd_pcm_sw_params( p_sys->p_snd_pcm, p_sw ) < 0 )
511     {
512         msg_Err( p_aout, "unable to set software configuration" );
513         goto error;
514     }
515
516 #ifdef DEBUG
517     snd_output_printf( p_sys->p_snd_stderr, "\nALSA hardware setup:\n\n" );
518     snd_pcm_dump_hw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
519     snd_output_printf( p_sys->p_snd_stderr, "\nALSA software setup:\n\n" );
520     snd_pcm_dump_sw_setup( p_sys->p_snd_pcm, p_sys->p_snd_stderr );
521     snd_output_printf( p_sys->p_snd_stderr, "\n" );
522 #endif
523
524     /* Create ALSA thread and wait for its readiness. */
525     if( vlc_thread_create( p_aout, "aout", ALSAThread,
526                            VLC_THREAD_PRIORITY_OUTPUT, VLC_FALSE ) )
527     {
528         msg_Err( p_aout, "cannot create ALSA thread (%s)", strerror(errno) );
529         goto error;
530     }
531
532     return 0;
533
534 error:
535     snd_pcm_close( p_sys->p_snd_pcm );
536 #ifdef DEBUG
537     snd_output_close( p_sys->p_snd_stderr );
538 #endif
539     free( p_sys );
540     return VLC_EGENERIC;
541 }
542
543 /*****************************************************************************
544  * Play: nothing to do
545  *****************************************************************************/
546 static void Play( aout_instance_t *p_aout )
547 {
548 }
549
550 /*****************************************************************************
551  * Close: close the ALSA device
552  *****************************************************************************/
553 static void Close( vlc_object_t *p_this )
554 {
555     aout_instance_t *p_aout = (aout_instance_t *)p_this;
556     struct aout_sys_t * p_sys = p_aout->output.p_sys;
557     int i_snd_rc;
558
559     p_aout->b_die = VLC_TRUE;
560     vlc_thread_join( p_aout );
561     p_aout->b_die = VLC_FALSE;
562
563     i_snd_rc = snd_pcm_close( p_sys->p_snd_pcm );
564
565     if( i_snd_rc > 0 )
566     {
567         msg_Err( p_aout, "failed closing ALSA device (%s)",
568                          snd_strerror( i_snd_rc ) );
569     }
570
571 #ifdef DEBUG
572     snd_output_close( p_sys->p_snd_stderr );
573 #endif
574
575     free( p_sys );
576 }
577
578 /*****************************************************************************
579  * ALSAThread: asynchronous thread used to DMA the data to the device
580  *****************************************************************************/
581 static int ALSAThread( aout_instance_t * p_aout )
582 {
583     struct aout_sys_t * p_sys = p_aout->output.p_sys;
584
585     while ( !p_aout->b_die )
586     {
587         ALSAFill( p_aout );
588
589         /* Sleep during less than one period to avoid a lot of buffer
590            underruns */
591
592         /* Why do we need to sleep ? --Meuuh */
593         /* Maybe because I don't want to eat all the cpu by looping
594            all the time. --Bozo */
595         /* Shouldn't snd_pcm_wait() make us wait ? --Meuuh */
596         msleep( p_sys->i_period_time >> 1 );
597     }
598
599     return 0;
600 }
601
602 /*****************************************************************************
603  * ALSAFill: function used to fill the ALSA buffer as much as possible
604  *****************************************************************************/
605 static void ALSAFill( aout_instance_t * p_aout )
606 {
607     struct aout_sys_t * p_sys = p_aout->output.p_sys;
608
609     aout_buffer_t * p_buffer;
610     snd_pcm_status_t * p_status;
611     snd_timestamp_t ts_next;
612     int i_snd_rc;
613     mtime_t next_date;
614
615     snd_pcm_status_alloca( &p_status );
616
617     /* Wait for the device's readiness (ie. there is enough space in the
618        buffer to write at least one complete chunk) */
619     i_snd_rc = snd_pcm_wait( p_sys->p_snd_pcm, THREAD_SLEEP );
620     if( i_snd_rc < 0 )
621     {
622         msg_Err( p_aout, "ALSA device not ready !!! (%s)",
623                          snd_strerror( i_snd_rc ) );
624         return;
625     }
626
627     /* Fill in the buffer until space or audio output buffer shortage */
628     for ( ; ; )
629     {
630         /* Get the status */
631         i_snd_rc = snd_pcm_status( p_sys->p_snd_pcm, p_status );
632         if( i_snd_rc < 0 )
633         {
634             msg_Err( p_aout, "unable to get the device's status (%s)",
635                              snd_strerror( i_snd_rc ) );
636             return;
637         }
638
639         /* Handle buffer underruns and reget the status */
640         if( snd_pcm_status_get_state( p_status ) == SND_PCM_STATE_XRUN )
641         {
642             /* Prepare the device */
643             i_snd_rc = snd_pcm_prepare( p_sys->p_snd_pcm );
644
645             if( i_snd_rc == 0 )
646             {
647                 msg_Warn( p_aout, "recovered from buffer underrun" );
648
649                 /* Reget the status */
650                 i_snd_rc = snd_pcm_status( p_sys->p_snd_pcm, p_status );
651                 if( i_snd_rc < 0 )
652                 {
653                     msg_Err( p_aout,
654                         "unable to get the device's status after recovery (%s)",
655                         snd_strerror( i_snd_rc ) );
656                     return;
657                 }
658             }
659             else
660             {
661                 msg_Err( p_aout, "unable to recover from buffer underrun" );
662                 return;
663             }
664         }
665
666         /* Here the device should be either in the RUNNING state either in
667            the PREPARE state. p_status is valid. */
668
669         snd_pcm_status_get_tstamp( p_status, &ts_next );
670         next_date = (mtime_t)ts_next.tv_sec * 1000000 + ts_next.tv_usec;
671         next_date += (mtime_t)snd_pcm_status_get_delay(p_status)
672                      * 1000000 / p_aout->output.output.i_rate;
673
674         p_buffer = aout_OutputNextBuffer( p_aout, next_date,
675                         (p_aout->output.output.i_format ==
676                          VLC_FOURCC('s','p','d','i')) );
677
678         /* Audio output buffer shortage -> stop the fill process and
679            wait in ALSAThread */
680         if( p_buffer == NULL )
681             return;
682
683         i_snd_rc = snd_pcm_writei( p_sys->p_snd_pcm, p_buffer->p_buffer,
684                                    p_buffer->i_nb_samples );
685
686         if( i_snd_rc < 0 )
687         {
688             msg_Err( p_aout, "write failed (%s)",
689                              snd_strerror( i_snd_rc ) );
690         }
691
692         aout_BufferFree( p_buffer );
693
694         msleep( p_sys->i_period_time >> 2 );
695     }
696 }
697