]> git.sesse.net Git - vlc/blob - modules/access/alsa.c
Fix alsa polling.
[vlc] / modules / access / alsa.c
1 /*****************************************************************************
2  * alsa.c : Alsa input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Benjamin Pracht <bigben at videolan dot org>
8  *          Richard Hosking <richard at hovis dot net>
9  *          Antoine Cellerier <dionoea at videolan d.t org>
10  *          Dennis Lou <dlou99 at yahoo dot com>
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*
28  * ALSA support based on parts of
29  * http://www.equalarea.com/paul/alsa-audio.html
30  * and hints taken from alsa-utils (aplay/arecord)
31  * http://www.alsa-project.org
32  */
33
34 /*****************************************************************************
35  * Preamble
36  *****************************************************************************/
37
38 #ifdef HAVE_CONFIG_H
39 # include "config.h"
40 #endif
41
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_access.h>
45 #include <vlc_demux.h>
46 #include <vlc_input.h>
47 #include <vlc_vout.h>
48
49 #include <ctype.h>
50 #include <fcntl.h>
51 #include <unistd.h>
52 #include <sys/ioctl.h>
53 #include <sys/mman.h>
54
55 #include <sys/soundcard.h>
56
57 #define ALSA_PCM_NEW_HW_PARAMS_API
58 #define ALSA_PCM_NEW_SW_PARAMS_API
59 #include <alsa/asoundlib.h>
60
61 #include <poll.h>
62
63 /*****************************************************************************
64  * Module descriptior
65  *****************************************************************************/
66
67 static int  DemuxOpen ( vlc_object_t * );
68 static void DemuxClose( vlc_object_t * );
69
70 #define STEREO_TEXT N_( "Stereo" )
71 #define STEREO_LONGTEXT N_( \
72     "Capture the audio stream in stereo." )
73
74 #define SAMPLERATE_TEXT N_( "Samplerate" )
75 #define SAMPLERATE_LONGTEXT N_( \
76     "Samplerate of the captured audio stream, in Hz (eg: 11025, 22050, 44100, 48000)" )
77
78 #define CACHING_TEXT N_("Caching value in ms")
79 #define CACHING_LONGTEXT N_( \
80     "Caching value for Alsa captures. This " \
81     "value should be set in milliseconds." )
82
83 #define ALSA_DEFAULT "hw"
84 #define CFG_PREFIX "alsa-"
85
86 vlc_module_begin();
87     set_shortname( N_("Alsa") );
88     set_description( N_("Alsa audio capture input") );
89     set_category( CAT_INPUT );
90     set_subcategory( SUBCAT_INPUT_ACCESS );
91
92     add_shortcut( "alsa" );
93     set_capability( "access_demux", 10 );
94     set_callbacks( DemuxOpen, DemuxClose );
95
96     add_bool( CFG_PREFIX "stereo", true, NULL, STEREO_TEXT, STEREO_LONGTEXT,
97                 true );
98     add_integer( CFG_PREFIX "samplerate", 48000, NULL, SAMPLERATE_TEXT,
99                 SAMPLERATE_LONGTEXT, true );
100     add_integer( CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, NULL,
101                 CACHING_TEXT, CACHING_LONGTEXT, true );
102 vlc_module_end();
103
104 /*****************************************************************************
105  * Access: local prototypes
106  *****************************************************************************/
107
108 static int DemuxControl( demux_t *, int, va_list );
109
110 static int Demux( demux_t * );
111
112 static block_t* GrabAudio( demux_t *p_demux );
113
114 static int OpenAudioDev( vlc_object_t *, demux_sys_t * );
115 static bool ProbeAudioDevAlsa( vlc_object_t *, const char *psz_device );
116
117 struct demux_sys_t
118 {
119     const char *psz_device;  /* Alsa device from MRL */
120     int  i_fd_audio;
121
122     /* Audio */
123     int i_pts;
124     unsigned int i_sample_rate;
125     bool b_stereo;
126     size_t i_audio_max_frame_size;
127     block_t *p_block_audio;
128     es_out_id_t *p_es_audio;
129
130     int i_audio_method;
131
132     /* ALSA Audio */
133     snd_pcm_t *p_alsa_pcm;
134     size_t i_alsa_frame_size;
135     int i_alsa_chunk_size;
136
137     struct pollfd *p_pollfd;
138     int i_pollfd;
139 };
140
141 static int FindMainDevice( vlc_object_t *p_this, demux_sys_t *p_sys )
142 {
143     msg_Dbg( p_this, "opening device '%s'", p_sys->psz_device );
144     if( ProbeAudioDevAlsa( p_this, p_sys->psz_device ) )
145     {
146         msg_Dbg( p_this, "'%s' is an audio device", p_sys->psz_device );
147         p_sys->i_fd_audio = OpenAudioDev( p_this, p_sys );
148     }
149
150     if( p_sys->i_fd_audio < 0 )
151         return VLC_EGENERIC;
152     return VLC_SUCCESS;
153 }
154
155 /*****************************************************************************
156  * DemuxOpen: opens alsa device, access_demux callback
157  *****************************************************************************
158  *
159  * url: <alsa device>::::
160  *
161  *****************************************************************************/
162 static int DemuxOpen( vlc_object_t *p_this )
163 {
164     demux_t     *p_demux = (demux_t*)p_this;
165     demux_sys_t *p_sys;
166
167     /* Only when selected */
168     if( *p_demux->psz_access == '\0' ) return VLC_EGENERIC;
169
170     /* Set up p_demux */
171     p_demux->pf_control = DemuxControl;
172     p_demux->pf_demux = Demux;
173     p_demux->info.i_update = 0;
174     p_demux->info.i_title = 0;
175     p_demux->info.i_seekpoint = 0;
176
177     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
178     if( p_sys == NULL ) return VLC_ENOMEM;
179
180     p_sys->i_sample_rate = var_CreateGetInteger( p_demux, CFG_PREFIX "samplerate" );
181     p_sys->b_stereo = var_CreateGetBool( p_demux, CFG_PREFIX "stereo" );
182     p_sys->i_pts = var_CreateGetInteger( p_demux, CFG_PREFIX "caching" );
183     p_sys->psz_device = NULL;
184     p_sys->i_fd_audio = -1;
185     p_sys->p_es_audio = NULL;
186     p_sys->p_block_audio = NULL;
187     p_sys->p_pollfd = NULL;
188
189     if( p_demux->psz_path && *p_demux->psz_path )
190         p_sys->psz_device = p_demux->psz_path;
191     else
192         p_sys->psz_device = ALSA_DEFAULT;
193
194     if( FindMainDevice( p_this, p_sys ) != VLC_SUCCESS )
195     {
196         DemuxClose( p_this );
197         return VLC_EGENERIC;
198     }
199
200     return VLC_SUCCESS;
201 }
202
203 /*****************************************************************************
204  * Close: close device, free resources
205  *****************************************************************************/
206 static void DemuxClose( vlc_object_t *p_this )
207 {
208     demux_t     *p_demux = (demux_t *)p_this;
209     demux_sys_t *p_sys   = p_demux->p_sys;
210
211     if( p_sys->p_alsa_pcm )
212     {
213         snd_pcm_close( p_sys->p_alsa_pcm );
214         p_sys->i_fd_audio = -1;
215     }
216     if( p_sys->i_fd_audio >= 0 ) close( p_sys->i_fd_audio );
217
218     if( p_sys->p_block_audio ) block_Release( p_sys->p_block_audio );
219
220     free( p_sys->p_pollfd );
221
222     free( p_sys );
223 }
224
225 /*****************************************************************************
226  * DemuxControl:
227  *****************************************************************************/
228 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
229 {
230     demux_sys_t *p_sys = p_demux->p_sys;
231     bool *pb;
232     int64_t *pi64;
233
234     switch( i_query )
235     {
236         /* Special for access_demux */
237         case DEMUX_CAN_PAUSE:
238         case DEMUX_CAN_SEEK:
239         case DEMUX_SET_PAUSE_STATE:
240         case DEMUX_CAN_CONTROL_PACE:
241             pb = (bool*)va_arg( args, bool * );
242             *pb = false;
243             return VLC_SUCCESS;
244
245         case DEMUX_GET_PTS_DELAY:
246             pi64 = (int64_t*)va_arg( args, int64_t * );
247             *pi64 = (int64_t)p_sys->i_pts * 1000;
248             return VLC_SUCCESS;
249
250         case DEMUX_GET_TIME:
251             pi64 = (int64_t*)va_arg( args, int64_t * );
252             *pi64 = mdate();
253             return VLC_SUCCESS;
254
255         /* TODO implement others */
256         default:
257             return VLC_EGENERIC;
258     }
259
260     return VLC_EGENERIC;
261 }
262
263 /*****************************************************************************
264  * Demux: Processes the audio frame
265  *****************************************************************************/
266 static int Demux( demux_t *p_demux )
267 {
268     demux_sys_t *p_sys = p_demux->p_sys;
269
270     int i_wait = snd_pcm_wait( p_sys->p_alsa_pcm, 500 );
271     switch( i_wait )
272     {
273         case 1:
274         {
275             block_t *p_block = GrabAudio( p_demux );
276             if( p_block )
277             {
278                 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
279                 es_out_Send( p_demux->out, p_sys->p_es_audio, p_block );
280             }
281         }
282
283         case -EPIPE:
284             /* xrun */
285             snd_pcm_prepare( p_sys->p_alsa_pcm );
286             break;
287         case -ESTRPIPE:
288         {
289             /* suspend */
290             int i_resume = snd_pcm_resume( p_sys->p_alsa_pcm );
291             if( i_resume < 0 && i_resume != -EAGAIN ) snd_pcm_prepare( p_sys->p_alsa_pcm );
292             break;
293         }
294     }
295
296     return 1;
297 }
298
299
300 /*****************************************************************************
301  * GrabAudio: Grab an audio frame
302  *****************************************************************************/
303 static block_t* GrabAudio( demux_t *p_demux )
304 {
305     demux_sys_t *p_sys = p_demux->p_sys;
306     int i_read, i_correct;
307     block_t *p_block;
308
309     if( p_sys->p_block_audio ) p_block = p_sys->p_block_audio;
310     else p_block = block_New( p_demux, p_sys->i_audio_max_frame_size );
311
312     if( !p_block )
313     {
314         msg_Warn( p_demux, "cannot get block" );
315         return 0;
316     }
317
318     p_sys->p_block_audio = p_block;
319
320     /* ALSA */
321     i_read = snd_pcm_readi( p_sys->p_alsa_pcm, p_block->p_buffer, p_sys->i_alsa_chunk_size );
322     if( i_read <= 0 )
323     {
324         int i_resume;
325         switch( i_read )
326         {
327             case -EAGAIN:
328                 break;
329             case -EPIPE:
330                 /* xrun */
331                 snd_pcm_prepare( p_sys->p_alsa_pcm );
332                 break;
333             case -ESTRPIPE:
334                 /* suspend */
335                 i_resume = snd_pcm_resume( p_sys->p_alsa_pcm );
336                 if( i_resume < 0 && i_resume != -EAGAIN ) snd_pcm_prepare( p_sys->p_alsa_pcm );
337                 break;
338             default:
339                 msg_Err( p_demux, "Failed to read alsa frame (%s)", snd_strerror( i_read ) );
340                 return 0;
341         }
342     }
343     else
344     {
345         /* convert from frames to bytes */
346         i_read *= p_sys->i_alsa_frame_size;
347     }
348
349     if( i_read <= 0 ) return 0;
350
351     p_block->i_buffer = i_read;
352     p_sys->p_block_audio = 0;
353
354     /* Correct the date because of kernel buffering */
355     i_correct = i_read;
356     /* ALSA */
357     int i_err;
358     snd_pcm_sframes_t delay = 0;
359     if( ( i_err = snd_pcm_delay( p_sys->p_alsa_pcm, &delay ) ) >= 0 )
360     {
361         size_t i_correction_delta = delay * p_sys->i_alsa_frame_size;
362         /* Test for overrun */
363         if( i_correction_delta > p_sys->i_audio_max_frame_size )
364         {
365             msg_Warn( p_demux, "ALSA read overrun (%zu > %zu)",
366                       i_correction_delta, p_sys->i_audio_max_frame_size );
367             i_correction_delta = p_sys->i_audio_max_frame_size;
368             snd_pcm_prepare( p_sys->p_alsa_pcm );
369         }
370         i_correct += i_correction_delta;
371     }
372     else
373     {
374         /* delay failed so reset */
375         msg_Warn( p_demux, "ALSA snd_pcm_delay failed (%s)", snd_strerror( i_err ) );
376         snd_pcm_prepare( p_sys->p_alsa_pcm );
377     }
378
379     /* Timestamp */
380     p_block->i_pts = p_block->i_dts =
381         mdate() - INT64_C(1000000) * (mtime_t)i_correct /
382         2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;
383
384     return p_block;
385 }
386
387 /*****************************************************************************
388  * OpenAudioDev: open and set up the audio device and probe for capabilities
389  *****************************************************************************/
390 static int OpenAudioDevAlsa( vlc_object_t *p_this, demux_sys_t *p_sys )
391 {
392     const char *psz_device = p_sys->psz_device;
393     p_sys->p_alsa_pcm = NULL;
394     snd_pcm_hw_params_t *p_hw_params = NULL;
395     snd_pcm_uframes_t buffer_size;
396     snd_pcm_uframes_t chunk_size;
397
398     /* ALSA */
399     int i_err;
400
401     if( ( i_err = snd_pcm_open( &p_sys->p_alsa_pcm, psz_device,
402         SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0)
403     {
404         msg_Err( p_this, "Cannot open ALSA audio device %s (%s)",
405                  psz_device, snd_strerror( i_err ) );
406         goto adev_fail;
407     }
408
409     if( ( i_err = snd_pcm_nonblock( p_sys->p_alsa_pcm, 1 ) ) < 0)
410     {
411         msg_Err( p_this, "Cannot set ALSA nonblock (%s)",
412                  snd_strerror( i_err ) );
413         goto adev_fail;
414     }
415
416     /* Begin setting hardware parameters */
417
418     if( ( i_err = snd_pcm_hw_params_malloc( &p_hw_params ) ) < 0 )
419     {
420         msg_Err( p_this,
421                  "ALSA: cannot allocate hardware parameter structure (%s)",
422                  snd_strerror( i_err ) );
423         goto adev_fail;
424     }
425
426     if( ( i_err = snd_pcm_hw_params_any( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
427     {
428         msg_Err( p_this,
429                 "ALSA: cannot initialize hardware parameter structure (%s)",
430                  snd_strerror( i_err ) );
431         goto adev_fail;
432     }
433
434     /* Set Interleaved access */
435     if( ( i_err = snd_pcm_hw_params_set_access( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
436     {
437         msg_Err( p_this, "ALSA: cannot set access type (%s)",
438                  snd_strerror( i_err ) );
439         goto adev_fail;
440     }
441
442     /* Set 16 bit little endian */
443     if( ( i_err = snd_pcm_hw_params_set_format( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_FORMAT_S16_LE ) ) < 0 )
444     {
445         msg_Err( p_this, "ALSA: cannot set sample format (%s)",
446                  snd_strerror( i_err ) );
447         goto adev_fail;
448     }
449
450     /* Set sample rate */
451 #ifdef HAVE_ALSA_NEW_API
452     i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, &p_sys->i_sample_rate, NULL );
453 #else
454     i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, p_sys->i_sample_rate, NULL );
455 #endif
456     if( i_err < 0 )
457     {
458         msg_Err( p_this, "ALSA: cannot set sample rate (%s)",
459                  snd_strerror( i_err ) );
460         goto adev_fail;
461     }
462
463     /* Set channels */
464     unsigned int channels = p_sys->b_stereo ? 2 : 1;
465     if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
466     {
467         channels = ( channels==1 ) ? 2 : 1;
468         msg_Warn( p_this, "ALSA: cannot set channel count (%s). "
469                   "Trying with channels=%d",
470                   snd_strerror( i_err ),
471                   channels );
472         if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
473         {
474             msg_Err( p_this, "ALSA: cannot set channel count (%s)",
475                      snd_strerror( i_err ) );
476             goto adev_fail;
477         }
478         p_sys->b_stereo = ( channels == 2 );
479     }
480
481     /* Set metrics for buffer calculations later */
482     unsigned int buffer_time;
483     if( ( i_err = snd_pcm_hw_params_get_buffer_time_max(p_hw_params, &buffer_time, 0) ) < 0 )
484     {
485         msg_Err( p_this, "ALSA: cannot get buffer time max (%s)",
486                  snd_strerror( i_err ) );
487         goto adev_fail;
488     }
489     if( buffer_time > 500000 ) buffer_time = 500000;
490
491     /* Set period time */
492     unsigned int period_time = buffer_time / 4;
493 #ifdef HAVE_ALSA_NEW_API
494     i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, &period_time, 0 );
495 #else
496     i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, period_time, 0 );
497 #endif
498     if( i_err < 0 )
499     {
500         msg_Err( p_this, "ALSA: cannot set period time (%s)",
501                  snd_strerror( i_err ) );
502         goto adev_fail;
503     }
504
505     /* Set buffer time */
506 #ifdef HAVE_ALSA_NEW_API
507     i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, &buffer_time, 0 );
508 #else
509     i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, buffer_time, 0 );
510 #endif
511     if( i_err < 0 )
512     {
513         msg_Err( p_this, "ALSA: cannot set buffer time (%s)",
514                  snd_strerror( i_err ) );
515         goto adev_fail;
516     }
517
518     /* Apply new hardware parameters */
519     if( ( i_err = snd_pcm_hw_params( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
520     {
521         msg_Err( p_this, "ALSA: cannot set hw parameters (%s)",
522                  snd_strerror( i_err ) );
523         goto adev_fail;
524     }
525
526     /* Get various buffer metrics */
527     snd_pcm_hw_params_get_period_size( p_hw_params, &chunk_size, 0 );
528     snd_pcm_hw_params_get_buffer_size( p_hw_params, &buffer_size );
529     if( chunk_size == buffer_size )
530     {
531         msg_Err( p_this,
532                  "ALSA: period cannot equal buffer size (%lu == %lu)",
533                  chunk_size, buffer_size);
534         goto adev_fail;
535     }
536
537     int bits_per_sample = snd_pcm_format_physical_width(SND_PCM_FORMAT_S16_LE);
538     int bits_per_frame = bits_per_sample * channels;
539
540     p_sys->i_alsa_chunk_size = chunk_size;
541     p_sys->i_alsa_frame_size = bits_per_frame / 8;
542     p_sys->i_audio_max_frame_size = chunk_size * bits_per_frame / 8;
543
544     snd_pcm_hw_params_free( p_hw_params );
545     p_hw_params = NULL;
546
547     /* Prep device */
548     if( ( i_err = snd_pcm_prepare( p_sys->p_alsa_pcm ) ) < 0 )
549     {
550         msg_Err( p_this,
551                  "ALSA: cannot prepare audio interface for use (%s)",
552                  snd_strerror( i_err ) );
553         goto adev_fail;
554     }
555
556     snd_pcm_start( p_sys->p_alsa_pcm );
557
558     /* Return a fake handle so other tests work */
559     return 1;
560
561  adev_fail:
562
563     if( p_hw_params ) snd_pcm_hw_params_free( p_hw_params );
564     if( p_sys->p_alsa_pcm ) snd_pcm_close( p_sys->p_alsa_pcm );
565     p_sys->p_alsa_pcm = NULL;
566
567     return -1;
568
569 }
570
571 static int OpenAudioDev( vlc_object_t *p_this, demux_sys_t *p_sys )
572 {
573     int i_fd  = OpenAudioDevAlsa( p_this, p_sys );
574
575     if( i_fd < 0 )
576         return i_fd;
577
578     msg_Dbg( p_this, "opened adev=`%s' %s %dHz",
579              p_sys->psz_device, p_sys->b_stereo ? "stereo" : "mono",
580              p_sys->i_sample_rate );
581
582     es_format_t fmt;
583     es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
584
585     fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
586     fmt.audio.i_rate = p_sys->i_sample_rate;
587     fmt.audio.i_bitspersample = 16;
588     fmt.audio.i_blockalign = fmt.audio.i_channels * fmt.audio.i_bitspersample / 8;
589     fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate * fmt.audio.i_bitspersample;
590
591     msg_Dbg( p_this, "new audio es %d channels %dHz",
592              fmt.audio.i_channels, fmt.audio.i_rate );
593
594     demux_t *p_demux = (demux_t *)p_this;
595     p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
596
597     return i_fd;
598 }
599
600 /*****************************************************************************
601  * ProbeAudioDevAlsa: probe audio for capabilities
602  *****************************************************************************/
603 static bool ProbeAudioDevAlsa( vlc_object_t *p_this, const char *psz_device )
604 {
605     int i_err;
606     snd_pcm_t *p_alsa_pcm;
607
608     if( ( i_err = snd_pcm_open( &p_alsa_pcm, psz_device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0 )
609     {
610         msg_Err( p_this, "cannot open device %s for ALSA audio (%s)", psz_device, snd_strerror( i_err ) );
611         return false;
612     }
613
614     snd_pcm_close( p_alsa_pcm );
615
616     return true;
617 }