]> git.sesse.net Git - vlc/blob - modules/access/alsa.c
670fedd8c5078c7636984ce69982d513d2e53db4
[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( demux_t * );
115 static bool ProbeAudioDevAlsa( demux_t *, const char *psz_device );
116
117 struct demux_sys_t
118 {
119     const char *psz_device;  /* Alsa device from MRL */
120
121     /* Audio */
122     int i_cache;
123     unsigned int i_sample_rate;
124     bool b_stereo;
125     size_t i_max_frame_size;
126     block_t *p_block;
127     es_out_id_t *p_es;
128
129     /* ALSA Audio */
130     snd_pcm_t *p_alsa_pcm;
131     size_t i_alsa_frame_size;
132     int i_alsa_chunk_size;
133
134     int64_t i_next_demux_date; /* Used to handle alsa:// as input-slave properly */
135 };
136
137 static int FindMainDevice( demux_t *p_demux )
138 {
139     /* TODO: if using default device, loop through all alsa devices until
140      * one works. */
141     msg_Dbg( p_demux, "opening device '%s'", p_demux->p_sys->psz_device );
142     if( ProbeAudioDevAlsa( p_demux, p_demux->p_sys->psz_device ) )
143     {
144         msg_Dbg( p_demux, "'%s' is an audio device",
145                  p_demux->p_sys->psz_device );
146         OpenAudioDev( p_demux );
147     }
148
149     if( p_demux->p_sys->p_alsa_pcm == NULL )
150         return VLC_EGENERIC;
151     return VLC_SUCCESS;
152 }
153
154 /*****************************************************************************
155  * DemuxOpen: opens alsa device, access_demux callback
156  *****************************************************************************
157  *
158  * url: <alsa device>::::
159  *
160  *****************************************************************************/
161 static int DemuxOpen( vlc_object_t *p_this )
162 {
163     demux_t     *p_demux = (demux_t*)p_this;
164     demux_sys_t *p_sys;
165
166     /* Only when selected */
167     if( *p_demux->psz_access == '\0' ) return VLC_EGENERIC;
168
169     /* Set up p_demux */
170     p_demux->pf_control = DemuxControl;
171     p_demux->pf_demux = Demux;
172     p_demux->info.i_update = 0;
173     p_demux->info.i_title = 0;
174     p_demux->info.i_seekpoint = 0;
175
176     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
177     if( p_sys == NULL ) return VLC_ENOMEM;
178
179     p_sys->i_sample_rate = var_CreateGetInteger( p_demux, CFG_PREFIX "samplerate" );
180     p_sys->b_stereo = var_CreateGetBool( p_demux, CFG_PREFIX "stereo" );
181     p_sys->i_cache = var_CreateGetInteger( p_demux, CFG_PREFIX "caching" );
182     p_sys->p_es = NULL;
183     p_sys->p_block = NULL;
184     p_sys->i_next_demux_date = -1;
185
186     if( p_demux->psz_path && *p_demux->psz_path )
187         p_sys->psz_device = p_demux->psz_path;
188     else
189         p_sys->psz_device = ALSA_DEFAULT;
190
191     if( FindMainDevice( p_demux ) != VLC_SUCCESS )
192     {
193         DemuxClose( p_this );
194         return VLC_EGENERIC;
195     }
196
197     return VLC_SUCCESS;
198 }
199
200 /*****************************************************************************
201  * Close: close device, free resources
202  *****************************************************************************/
203 static void DemuxClose( vlc_object_t *p_this )
204 {
205     demux_t     *p_demux = (demux_t *)p_this;
206     demux_sys_t *p_sys   = p_demux->p_sys;
207
208     if( p_sys->p_alsa_pcm )
209     {
210         snd_pcm_close( p_sys->p_alsa_pcm );
211     }
212
213     if( p_sys->p_block ) block_Release( p_sys->p_block );
214
215     free( p_sys );
216 }
217
218 /*****************************************************************************
219  * DemuxControl:
220  *****************************************************************************/
221 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
222 {
223     demux_sys_t *p_sys = p_demux->p_sys;
224     bool *pb;
225     int64_t *pi64;
226
227     switch( i_query )
228     {
229         /* Special for access_demux */
230         case DEMUX_CAN_PAUSE:
231         case DEMUX_CAN_SEEK:
232         case DEMUX_SET_PAUSE_STATE:
233         case DEMUX_CAN_CONTROL_PACE:
234             pb = (bool*)va_arg( args, bool * );
235             *pb = false;
236             return VLC_SUCCESS;
237
238         case DEMUX_GET_PTS_DELAY:
239             pi64 = (int64_t*)va_arg( args, int64_t * );
240             *pi64 = (int64_t)p_sys->i_cache * 1000;
241             return VLC_SUCCESS;
242
243         case DEMUX_GET_TIME:
244             pi64 = (int64_t*)va_arg( args, int64_t * );
245             *pi64 = mdate();
246             return VLC_SUCCESS;
247
248         case DEMUX_SET_NEXT_DEMUX_TIME:
249             p_sys->i_next_demux_date = (int64_t)va_arg( args, int64_t );
250             return VLC_SUCCESS;
251
252         /* TODO implement others */
253         default:
254             return VLC_EGENERIC;
255     }
256
257     return VLC_EGENERIC;
258 }
259
260 /*****************************************************************************
261  * Demux: Processes the audio frame
262  *****************************************************************************/
263 static int Demux( demux_t *p_demux )
264 {
265     demux_sys_t *p_sys = p_demux->p_sys;
266
267     block_t *p_block = NULL;
268
269     do
270     {
271         if( p_block )
272         {
273             es_out_Send( p_demux->out, p_sys->p_es, p_block );
274             p_block = NULL;
275         }
276
277         /* Wait for data */
278         int i_wait = snd_pcm_wait( p_sys->p_alsa_pcm, 500 );
279         switch( i_wait )
280         {
281             case 1:
282             {
283                 p_block = GrabAudio( p_demux );
284                 if( p_block )
285                     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts );
286             }
287
288             /* FIXME: this is a copy paste from below. Shouldn't be needed
289              * twice. */
290             case -EPIPE:
291                 /* xrun */
292                 snd_pcm_prepare( p_sys->p_alsa_pcm );
293                 break;
294             case -ESTRPIPE:
295             {
296                 /* suspend */
297                 int i_resume = snd_pcm_resume( p_sys->p_alsa_pcm );
298                 if( i_resume < 0 && i_resume != -EAGAIN ) snd_pcm_prepare( p_sys->p_alsa_pcm );
299                 break;
300             }
301             /* </FIXME> */
302         }
303     } while( p_block && p_sys->i_next_demux_date > 0 &&
304              p_block->i_pts < p_sys->i_next_demux_date );
305
306     if( p_block )
307         es_out_Send( p_demux->out, p_sys->p_es, p_block );
308
309     return 1;
310 }
311
312
313 /*****************************************************************************
314  * GrabAudio: Grab an audio frame
315  *****************************************************************************/
316 static block_t* GrabAudio( demux_t *p_demux )
317 {
318     demux_sys_t *p_sys = p_demux->p_sys;
319     int i_read, i_correct;
320     block_t *p_block;
321
322     if( p_sys->p_block ) p_block = p_sys->p_block;
323     else p_block = block_New( p_demux, p_sys->i_max_frame_size );
324
325     if( !p_block )
326     {
327         msg_Warn( p_demux, "cannot get block" );
328         return 0;
329     }
330
331     p_sys->p_block = p_block;
332
333     /* ALSA */
334     i_read = snd_pcm_readi( p_sys->p_alsa_pcm, p_block->p_buffer, p_sys->i_alsa_chunk_size );
335     if( i_read <= 0 )
336     {
337         int i_resume;
338         switch( i_read )
339         {
340             case -EAGAIN:
341                 break;
342             case -EPIPE:
343                 /* xrun */
344                 snd_pcm_prepare( p_sys->p_alsa_pcm );
345                 break;
346             case -ESTRPIPE:
347                 /* suspend */
348                 i_resume = snd_pcm_resume( p_sys->p_alsa_pcm );
349                 if( i_resume < 0 && i_resume != -EAGAIN ) snd_pcm_prepare( p_sys->p_alsa_pcm );
350                 break;
351             default:
352                 msg_Err( p_demux, "Failed to read alsa frame (%s)", snd_strerror( i_read ) );
353                 return 0;
354         }
355     }
356     else
357     {
358         /* convert from frames to bytes */
359         i_read *= p_sys->i_alsa_frame_size;
360     }
361
362     if( i_read <= 0 ) return 0;
363
364     p_block->i_buffer = i_read;
365     p_sys->p_block = 0;
366
367     /* Correct the date because of kernel buffering */
368     i_correct = i_read;
369     /* ALSA */
370     int i_err;
371     snd_pcm_sframes_t delay = 0;
372     if( ( i_err = snd_pcm_delay( p_sys->p_alsa_pcm, &delay ) ) >= 0 )
373     {
374         size_t i_correction_delta = delay * p_sys->i_alsa_frame_size;
375         /* Test for overrun */
376         if( i_correction_delta > p_sys->i_max_frame_size )
377         {
378             msg_Warn( p_demux, "ALSA read overrun (%zu > %zu)",
379                       i_correction_delta, p_sys->i_max_frame_size );
380             i_correction_delta = p_sys->i_max_frame_size;
381             snd_pcm_prepare( p_sys->p_alsa_pcm );
382         }
383         i_correct += i_correction_delta;
384     }
385     else
386     {
387         /* delay failed so reset */
388         msg_Warn( p_demux, "ALSA snd_pcm_delay failed (%s)", snd_strerror( i_err ) );
389         snd_pcm_prepare( p_sys->p_alsa_pcm );
390     }
391
392     /* Timestamp */
393     p_block->i_pts = p_block->i_dts =
394         mdate() - INT64_C(1000000) * (mtime_t)i_correct /
395         2 / ( p_sys->b_stereo ? 2 : 1) / p_sys->i_sample_rate;
396
397     return p_block;
398 }
399
400 /*****************************************************************************
401  * OpenAudioDev: open and set up the audio device and probe for capabilities
402  *****************************************************************************/
403 static int OpenAudioDevAlsa( demux_t *p_demux )
404 {
405     demux_sys_t *p_sys = p_demux->p_sys;
406     const char *psz_device = p_sys->psz_device;
407     p_sys->p_alsa_pcm = NULL;
408     snd_pcm_hw_params_t *p_hw_params = NULL;
409     snd_pcm_uframes_t buffer_size;
410     snd_pcm_uframes_t chunk_size;
411
412     /* ALSA */
413     int i_err;
414
415     if( ( i_err = snd_pcm_open( &p_sys->p_alsa_pcm, psz_device,
416         SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0)
417     {
418         msg_Err( p_demux, "Cannot open ALSA audio device %s (%s)",
419                  psz_device, snd_strerror( i_err ) );
420         goto adev_fail;
421     }
422
423     if( ( i_err = snd_pcm_nonblock( p_sys->p_alsa_pcm, 1 ) ) < 0)
424     {
425         msg_Err( p_demux, "Cannot set ALSA nonblock (%s)",
426                  snd_strerror( i_err ) );
427         goto adev_fail;
428     }
429
430     /* Begin setting hardware parameters */
431
432     if( ( i_err = snd_pcm_hw_params_malloc( &p_hw_params ) ) < 0 )
433     {
434         msg_Err( p_demux,
435                  "ALSA: cannot allocate hardware parameter structure (%s)",
436                  snd_strerror( i_err ) );
437         goto adev_fail;
438     }
439
440     if( ( i_err = snd_pcm_hw_params_any( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
441     {
442         msg_Err( p_demux,
443                 "ALSA: cannot initialize hardware parameter structure (%s)",
444                  snd_strerror( i_err ) );
445         goto adev_fail;
446     }
447
448     /* Set Interleaved access */
449     if( ( i_err = snd_pcm_hw_params_set_access( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
450     {
451         msg_Err( p_demux, "ALSA: cannot set access type (%s)",
452                  snd_strerror( i_err ) );
453         goto adev_fail;
454     }
455
456     /* Set 16 bit little endian */
457     if( ( i_err = snd_pcm_hw_params_set_format( p_sys->p_alsa_pcm, p_hw_params, SND_PCM_FORMAT_S16_LE ) ) < 0 )
458     {
459         msg_Err( p_demux, "ALSA: cannot set sample format (%s)",
460                  snd_strerror( i_err ) );
461         goto adev_fail;
462     }
463
464     /* Set sample rate */
465 #ifdef HAVE_ALSA_NEW_API
466     i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, &p_sys->i_sample_rate, NULL );
467 #else
468     i_err = snd_pcm_hw_params_set_rate_near( p_sys->p_alsa_pcm, p_hw_params, p_sys->i_sample_rate, NULL );
469 #endif
470     if( i_err < 0 )
471     {
472         msg_Err( p_demux, "ALSA: cannot set sample rate (%s)",
473                  snd_strerror( i_err ) );
474         goto adev_fail;
475     }
476
477     /* Set channels */
478     unsigned int channels = p_sys->b_stereo ? 2 : 1;
479     if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
480     {
481         channels = ( channels==1 ) ? 2 : 1;
482         msg_Warn( p_demux, "ALSA: cannot set channel count (%s). "
483                   "Trying with channels=%d",
484                   snd_strerror( i_err ),
485                   channels );
486         if( ( i_err = snd_pcm_hw_params_set_channels( p_sys->p_alsa_pcm, p_hw_params, channels ) ) < 0 )
487         {
488             msg_Err( p_demux, "ALSA: cannot set channel count (%s)",
489                      snd_strerror( i_err ) );
490             goto adev_fail;
491         }
492         p_sys->b_stereo = ( channels == 2 );
493     }
494
495     /* Set metrics for buffer calculations later */
496     unsigned int buffer_time;
497     if( ( i_err = snd_pcm_hw_params_get_buffer_time_max(p_hw_params, &buffer_time, 0) ) < 0 )
498     {
499         msg_Err( p_demux, "ALSA: cannot get buffer time max (%s)",
500                  snd_strerror( i_err ) );
501         goto adev_fail;
502     }
503     if( buffer_time > 500000 ) buffer_time = 500000;
504
505     /* Set period time */
506     unsigned int period_time = buffer_time / 4;
507 #ifdef HAVE_ALSA_NEW_API
508     i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, &period_time, 0 );
509 #else
510     i_err = snd_pcm_hw_params_set_period_time_near( p_sys->p_alsa_pcm, p_hw_params, period_time, 0 );
511 #endif
512     if( i_err < 0 )
513     {
514         msg_Err( p_demux, "ALSA: cannot set period time (%s)",
515                  snd_strerror( i_err ) );
516         goto adev_fail;
517     }
518
519     /* Set buffer time */
520 #ifdef HAVE_ALSA_NEW_API
521     i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, &buffer_time, 0 );
522 #else
523     i_err = snd_pcm_hw_params_set_buffer_time_near( p_sys->p_alsa_pcm, p_hw_params, buffer_time, 0 );
524 #endif
525     if( i_err < 0 )
526     {
527         msg_Err( p_demux, "ALSA: cannot set buffer time (%s)",
528                  snd_strerror( i_err ) );
529         goto adev_fail;
530     }
531
532     /* Apply new hardware parameters */
533     if( ( i_err = snd_pcm_hw_params( p_sys->p_alsa_pcm, p_hw_params ) ) < 0 )
534     {
535         msg_Err( p_demux, "ALSA: cannot set hw parameters (%s)",
536                  snd_strerror( i_err ) );
537         goto adev_fail;
538     }
539
540     /* Get various buffer metrics */
541     snd_pcm_hw_params_get_period_size( p_hw_params, &chunk_size, 0 );
542     snd_pcm_hw_params_get_buffer_size( p_hw_params, &buffer_size );
543     if( chunk_size == buffer_size )
544     {
545         msg_Err( p_demux,
546                  "ALSA: period cannot equal buffer size (%lu == %lu)",
547                  chunk_size, buffer_size);
548         goto adev_fail;
549     }
550
551     int bits_per_sample = snd_pcm_format_physical_width(SND_PCM_FORMAT_S16_LE);
552     int bits_per_frame = bits_per_sample * channels;
553
554     p_sys->i_alsa_chunk_size = chunk_size;
555     p_sys->i_alsa_frame_size = bits_per_frame / 8;
556     p_sys->i_max_frame_size = chunk_size * bits_per_frame / 8;
557
558     snd_pcm_hw_params_free( p_hw_params );
559     p_hw_params = NULL;
560
561     /* Prep device */
562     if( ( i_err = snd_pcm_prepare( p_sys->p_alsa_pcm ) ) < 0 )
563     {
564         msg_Err( p_demux,
565                  "ALSA: cannot prepare audio interface for use (%s)",
566                  snd_strerror( i_err ) );
567         goto adev_fail;
568     }
569
570     snd_pcm_start( p_sys->p_alsa_pcm );
571
572     return VLC_SUCCESS;
573
574  adev_fail:
575
576     if( p_hw_params ) snd_pcm_hw_params_free( p_hw_params );
577     if( p_sys->p_alsa_pcm ) snd_pcm_close( p_sys->p_alsa_pcm );
578     p_sys->p_alsa_pcm = NULL;
579
580     return VLC_EGENERIC;
581
582 }
583
584 static int OpenAudioDev( demux_t *p_demux )
585 {
586     demux_sys_t *p_sys = p_demux->p_sys;
587     if( OpenAudioDevAlsa( p_demux ) != VLC_SUCCESS )
588         return VLC_EGENERIC;
589
590     msg_Dbg( p_demux, "opened adev=`%s' %s %dHz",
591              p_sys->psz_device, p_sys->b_stereo ? "stereo" : "mono",
592              p_sys->i_sample_rate );
593
594     es_format_t fmt;
595     es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('a','r','a','w') );
596
597     fmt.audio.i_channels = p_sys->b_stereo ? 2 : 1;
598     fmt.audio.i_rate = p_sys->i_sample_rate;
599     fmt.audio.i_bitspersample = 16;
600     fmt.audio.i_blockalign = fmt.audio.i_channels * fmt.audio.i_bitspersample / 8;
601     fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate * fmt.audio.i_bitspersample;
602
603     msg_Dbg( p_demux, "new audio es %d channels %dHz",
604              fmt.audio.i_channels, fmt.audio.i_rate );
605
606     p_sys->p_es = es_out_Add( p_demux->out, &fmt );
607
608     return VLC_SUCCESS;
609 }
610
611 /*****************************************************************************
612  * ProbeAudioDevAlsa: probe audio for capabilities
613  *****************************************************************************/
614 static bool ProbeAudioDevAlsa( demux_t *p_demux, const char *psz_device )
615 {
616     int i_err;
617     snd_pcm_t *p_alsa_pcm;
618
619     if( ( i_err = snd_pcm_open( &p_alsa_pcm, psz_device, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK ) ) < 0 )
620     {
621         msg_Err( p_demux, "cannot open device %s for ALSA audio (%s)", psz_device, snd_strerror( i_err ) );
622         return false;
623     }
624
625     snd_pcm_close( p_alsa_pcm );
626
627     return true;
628 }