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