]> git.sesse.net Git - vlc/blob - modules/access/alsa.c
Qt4: fix prototype
[vlc] / modules / access / alsa.c
1 /*****************************************************************************
2  * alsa.c: ALSA capture module for VLC
3  *****************************************************************************
4  * Copyright (C) 2012 RĂ©mi Denis-Courmont
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation; either version 2.1 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the Lesser GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19  *****************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include <assert.h>
26 #include <sys/types.h>
27 #include <poll.h>
28 #include <alsa/asoundlib.h>
29
30 #include <vlc_common.h>
31 #include <vlc_demux.h>
32 #include <vlc_aout.h>
33 #include <vlc_plugin.h>
34
35 #define HELP_TEXT N_( \
36     "Pass alsa:// to open the default ALSA capture device, " \
37     "or alsa://SOURCE to open a specific device named SOURCE.")
38 #define STEREO_TEXT N_("Stereo")
39 #define RATE_TEXT N_("Sample rate")
40
41 static int Open (vlc_object_t *);
42 static void Close (vlc_object_t *);
43
44 static const int rate_values[] = { 192000, 176400,
45     96000, 88200, 48000, 44100,
46     32000, 22050, 24000, 16000,
47     11025, 8000, 4000
48 };
49 static const const char *rate_names[] = { N_("192000 Hz"), N_("176400 Hz"),
50     N_("96000 Hz"), N_("88200 Hz"), N_("48000 Hz"), N_("44100 Hz"),
51     N_("32000 Hz"), N_("22050 Hz"), N_("24000 Hz"), N_("16000 Hz"),
52     N_("11025 Hz"), N_("8000 Hz"), N_("4000 Hz")
53 };
54
55 vlc_module_begin ()
56     set_shortname (N_("ALSA"))
57     set_description (N_("ALSA audio capture"))
58     set_capability ("access_demux", 0)
59     set_category (CAT_INPUT)
60     set_subcategory (SUBCAT_INPUT_ACCESS)
61     set_help (HELP_TEXT)
62
63     add_obsolete_string ("alsa-format") /* since 2.1.0 */
64     add_bool ("alsa-stereo", true, STEREO_TEXT, STEREO_TEXT, true)
65     add_integer ("alsa-samplerate", 48000, RATE_TEXT, RATE_TEXT, true)
66         change_integer_list (rate_values, rate_names)
67
68     add_shortcut ("alsa")
69     set_callbacks (Open, Close)
70 vlc_module_end ()
71
72 /** Helper for ALSA -> VLC debugging output */
73 /** XXX: duplicated from ALSA output */
74 static void Dump (vlc_object_t *obj, const char *msg,
75                   int (*cb)(void *, snd_output_t *), void *p)
76 {
77     snd_output_t *output;
78     char *str;
79
80     if (unlikely(snd_output_buffer_open (&output)))
81         return;
82
83     int val = cb (p, output);
84     if (val)
85     {
86         msg_Warn (obj, "cannot get info: %s", snd_strerror (val));
87         return;
88     }
89
90     size_t len = snd_output_buffer_string (output, &str);
91     if (len > 0 && str[len - 1])
92         len--; /* strip trailing newline */
93     msg_Dbg (obj, "%s%.*s", msg, (int)len, str);
94     snd_output_close (output);
95 }
96 #define Dump(o, m, cb, p) \
97         Dump(VLC_OBJECT(o), m, (int (*)(void *, snd_output_t *))(cb), p)
98
99 static void DumpDevice (vlc_object_t *obj, snd_pcm_t *pcm)
100 {
101     snd_pcm_info_t *info;
102
103     Dump (obj, " ", snd_pcm_dump, pcm);
104     snd_pcm_info_alloca (&info);
105     if (snd_pcm_info (pcm, info) == 0)
106     {
107         msg_Dbg (obj, " device name   : %s", snd_pcm_info_get_name (info));
108         msg_Dbg (obj, " device ID     : %s", snd_pcm_info_get_id (info));
109         msg_Dbg (obj, " subdevice name: %s",
110                 snd_pcm_info_get_subdevice_name (info));
111     }
112 }
113
114 static void DumpDeviceStatus (vlc_object_t *obj, snd_pcm_t *pcm)
115 {
116     snd_pcm_status_t *status;
117
118     snd_pcm_status_alloca (&status);
119     snd_pcm_status (pcm, status);
120     Dump (obj, "current status:\n", snd_pcm_status_dump, status);
121 }
122 #define DumpDeviceStatus(o, p) DumpDeviceStatus(VLC_OBJECT(o), p)
123
124
125 struct demux_sys_t
126 {
127     snd_pcm_t *pcm;
128     es_out_id_t *es;
129     vlc_thread_t thread;
130
131     mtime_t caching;
132     snd_pcm_uframes_t period_size;
133     unsigned rate;
134 };
135
136 static void Poll (snd_pcm_t *pcm, int canc)
137 {
138     int n = snd_pcm_poll_descriptors_count (pcm);
139     struct pollfd ufd[n];
140     unsigned short revents;
141
142     snd_pcm_poll_descriptors (pcm, ufd, n);
143     do
144     {
145         vlc_restorecancel (canc);
146         poll (ufd, n, -1);
147         canc = vlc_savecancel ();
148         snd_pcm_poll_descriptors_revents (pcm, ufd, n, &revents);
149     }
150     while (!revents);
151 }
152
153 static void *Thread (void *data)
154 {
155     demux_t *demux = data;
156     demux_sys_t *sys = demux->p_sys;
157     snd_pcm_t *pcm = sys->pcm;
158     size_t bytes;
159     int canc, val;
160
161     canc = vlc_savecancel ();
162     bytes = snd_pcm_frames_to_bytes (pcm, sys->period_size);
163     val = snd_pcm_start (pcm);
164     if (val)
165     {
166         msg_Err (demux, "cannot prepare device: %s", snd_strerror (val));
167         return NULL;
168     }
169
170     for (;;)
171     {
172         block_t *block = block_Alloc (bytes);
173         if (unlikely(block == NULL))
174             break;
175
176         /* Wait for data */
177         Poll (pcm, canc);
178
179         /* Read data */
180         snd_pcm_sframes_t frames, delay;
181         mtime_t pts;
182
183         frames = snd_pcm_readi (pcm, block->p_buffer, sys->period_size);
184         pts = mdate ();
185         if (frames < 0)
186         {
187             if (frames == -EAGAIN)
188                 continue;
189
190             val = snd_pcm_recover (pcm, frames, 1);
191             if (val == 0)
192             {
193                 msg_Warn (demux, "cannot read samples: %s",
194                           snd_strerror (frames));
195                 continue;
196             }
197             msg_Err (demux, "cannot recover record stream: %s",
198                      snd_strerror (val));
199             DumpDeviceStatus (demux, pcm);
200             break;
201         }
202
203         /* Compute time stamp */
204         if (snd_pcm_delay (pcm, &delay))
205             delay = 0;
206         delay += frames;
207         pts -= (CLOCK_FREQ * delay) / sys->rate;
208
209         block->i_buffer = snd_pcm_frames_to_bytes (pcm, frames);
210         block->i_nb_samples = frames;
211         block->i_pts = pts;
212         block->i_length = (CLOCK_FREQ * frames) / sys->rate;
213
214         es_out_Control (demux->out, ES_OUT_SET_PCR, block->i_pts);
215         es_out_Send (demux->out, sys->es, block);
216     }
217     return NULL;
218 }
219
220 static int Control (demux_t *demux, int query, va_list ap)
221 {
222     demux_sys_t *sys = demux->p_sys;
223
224     switch (query)
225     {
226         case DEMUX_GET_TIME:
227             *va_arg (ap, int64_t *) = mdate();
228             break;
229
230         case DEMUX_GET_PTS_DELAY:
231             *va_arg (ap, int64_t *) = sys->caching;
232             break;
233
234         //case DEMUX_SET_NEXT_DEMUX_TIME: still needed?
235
236         case DEMUX_HAS_UNSUPPORTED_META:
237         case DEMUX_CAN_RECORD:
238         case DEMUX_CAN_PAUSE:
239         case DEMUX_CAN_CONTROL_PACE:
240         case DEMUX_CAN_CONTROL_RATE:
241         case DEMUX_CAN_SEEK:
242             *va_arg (ap, bool *) = false;
243             break;;
244
245         default:
246             return VLC_EGENERIC;
247     }
248
249     return VLC_SUCCESS;
250 }
251
252 static const vlc_fourcc_t formats[] = {
253     [SND_PCM_FORMAT_S8]                 = VLC_CODEC_S8,
254     [SND_PCM_FORMAT_U8]                 = VLC_CODEC_U8,
255     [SND_PCM_FORMAT_S16_LE]             = VLC_CODEC_S16L,
256     [SND_PCM_FORMAT_S16_BE]             = VLC_CODEC_S16B,
257     [SND_PCM_FORMAT_U16_LE]             = VLC_CODEC_U16L,
258     [SND_PCM_FORMAT_U16_BE]             = VLC_CODEC_U16B,
259   //[SND_PCM_FORMAT_S24_LE]             = VLC_CODEC_?,
260   //[SND_PCM_FORMAT_S24_BE]             = VLC_CODEC_?,
261     [SND_PCM_FORMAT_U24_LE]             = VLC_CODEC_U32L, // TODO: replay gain
262     [SND_PCM_FORMAT_U24_BE]             = VLC_CODEC_U32B, // ^
263     [SND_PCM_FORMAT_S32_LE]             = VLC_CODEC_S32L,
264     [SND_PCM_FORMAT_S32_BE]             = VLC_CODEC_S32B,
265     [SND_PCM_FORMAT_U32_LE]             = VLC_CODEC_U32L,
266     [SND_PCM_FORMAT_U32_BE]             = VLC_CODEC_U32B,
267     [SND_PCM_FORMAT_FLOAT_LE]           = VLC_CODEC_F32L,
268     [SND_PCM_FORMAT_FLOAT_BE]           = VLC_CODEC_F32B,
269     [SND_PCM_FORMAT_FLOAT64_LE]         = VLC_CODEC_F32L,
270     [SND_PCM_FORMAT_FLOAT64_BE]         = VLC_CODEC_F32B,
271   //[SND_PCM_FORMAT_IEC958_SUBFRAME_LE] = VLC_CODEC_SPDIFL,
272   //[SND_PCM_FORMAT_IEC958_SUBFRAME_BE] = VLC_CODEC_SPDIFB,
273     [SND_PCM_FORMAT_MU_LAW]             = VLC_CODEC_MULAW,
274     [SND_PCM_FORMAT_A_LAW]              = VLC_CODEC_ALAW,
275   //[SND_PCM_FORMAT_IMA_ADPCM]          = VLC_CODEC_ADPCM_?, // XXX: which one?
276     [SND_PCM_FORMAT_MPEG]               = VLC_CODEC_MPGA,
277     [SND_PCM_FORMAT_GSM]                = VLC_CODEC_GSM,
278   //[SND_PCM_FORMAT_SPECIAL]            = VLC_CODEC_?
279     [SND_PCM_FORMAT_S24_3LE]            = VLC_CODEC_S24L,
280     [SND_PCM_FORMAT_S24_3BE]            = VLC_CODEC_S24B,
281     [SND_PCM_FORMAT_U24_3LE]            = VLC_CODEC_U24L,
282     [SND_PCM_FORMAT_U24_3BE]            = VLC_CODEC_U24B,
283     [SND_PCM_FORMAT_S20_3LE]            = VLC_CODEC_S24L, // TODO: replay gain
284     [SND_PCM_FORMAT_S20_3BE]            = VLC_CODEC_S24B, // ^
285     [SND_PCM_FORMAT_U20_3LE]            = VLC_CODEC_U24L, // ^
286     [SND_PCM_FORMAT_U20_3BE]            = VLC_CODEC_U24B, // ^
287     [SND_PCM_FORMAT_S18_3LE]            = VLC_CODEC_S24L, // ^
288     [SND_PCM_FORMAT_S18_3BE]            = VLC_CODEC_S24B, // ^
289     [SND_PCM_FORMAT_U18_3LE]            = VLC_CODEC_U24L, // ^
290     [SND_PCM_FORMAT_U18_3BE]            = VLC_CODEC_U24B, // ^
291 };
292
293 #ifdef WORDS_BIGENDIAN
294 # define C(f) f##BE, f##LE
295 #else
296 # define C(f) f##LE, f##BE
297 #endif
298
299 /* Formats in order of decreasing preference */
300 static const uint8_t choices[] = {
301     C(SND_PCM_FORMAT_FLOAT_),
302     C(SND_PCM_FORMAT_S32_),
303     C(SND_PCM_FORMAT_U32_),
304     C(SND_PCM_FORMAT_S16_),
305     C(SND_PCM_FORMAT_U16_),
306     C(SND_PCM_FORMAT_FLOAT64_),
307     C(SND_PCM_FORMAT_S24_3),
308     C(SND_PCM_FORMAT_U24_3),
309     SND_PCM_FORMAT_MPEG,
310     SND_PCM_FORMAT_GSM,
311     SND_PCM_FORMAT_MU_LAW,
312     SND_PCM_FORMAT_A_LAW,
313     SND_PCM_FORMAT_S8,
314     SND_PCM_FORMAT_U8,
315 };
316
317 static uint16_t channel_maps[] = {
318     AOUT_CHAN_CENTER, AOUT_CHANS_2_0, AOUT_CHANS_3_0 /* ? */,
319     AOUT_CHANS_4_0, AOUT_CHANS_5_0 /* ? */, AOUT_CHANS_5_1,
320     /* TODO: support 7-8 channels - need channels reodering */
321 };
322
323 static int Open (vlc_object_t *obj)
324 {
325     demux_t *demux = (demux_t *)obj;
326     demux_sys_t *sys = malloc (sizeof (*sys));
327
328     static_assert (sizeof (formats) / sizeof (formats[0]) ==
329                    SND_PCM_FORMAT_LAST + 1, "unknown formats");
330
331     if (unlikely(sys == NULL))
332         return VLC_ENOMEM;
333
334     /* Open the device */
335     const char *device = demux->psz_location;
336     if (device == NULL || !device[0])
337         device = "default";
338
339     const int mode = SND_PCM_NONBLOCK
340                  /*| SND_PCM_NO_AUTO_RESAMPLE*/
341                    | SND_PCM_NO_AUTO_CHANNELS
342                  /*| SND_PCM_NO_AUTO_FORMAT*/;
343     snd_pcm_t *pcm;
344     int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_CAPTURE, mode);
345     if (val != 0)
346     {
347         msg_Err (demux, "cannot open ALSA device \"%s\": %s", device,
348                  snd_strerror (val));
349         free (sys);
350         return VLC_EGENERIC;
351     }
352     sys->pcm = pcm;
353     msg_Dbg (demux, "using ALSA device: %s", device);
354     DumpDevice (VLC_OBJECT(demux), pcm);
355
356     /* Negotiate capture parameters */
357     snd_pcm_hw_params_t *hw;
358     es_format_t fmt;
359     unsigned param;
360     int dir;
361
362     snd_pcm_hw_params_alloca (&hw);
363     snd_pcm_hw_params_any (pcm, hw);
364     Dump (demux, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
365
366     val = snd_pcm_hw_params_set_rate_resample (pcm, hw, 0);
367     if (val)
368     {
369         msg_Err (demux, "cannot disable resampling: %s", snd_strerror (val));
370         goto error;
371     }
372
373     val = snd_pcm_hw_params_set_access (pcm, hw,
374                                         SND_PCM_ACCESS_RW_INTERLEAVED);
375     if (val)
376     {
377         msg_Err (demux, "cannot set access mode: %s", snd_strerror (val));
378         goto error;
379     }
380
381     snd_pcm_format_t format = SND_PCM_FORMAT_UNKNOWN;
382     for (size_t i = 0; i < sizeof (choices) / sizeof (choices[0]); i++)
383         if (snd_pcm_hw_params_test_format (pcm, hw, choices[i]) == 0)
384         {
385             val = snd_pcm_hw_params_set_format (pcm, hw, choices[i]);
386             if (val)
387             {
388                 msg_Err (demux, "cannot set sample format: %s",
389                          snd_strerror (val));
390                 goto error;
391             }
392             format = choices[i];
393             break;
394         }
395
396     if (format == SND_PCM_FORMAT_UNKNOWN)
397     {
398         msg_Err (demux, "no supported sample format");
399         goto error;
400     }
401
402     assert ((size_t)format < (sizeof (formats) / sizeof (formats[0])));
403     es_format_Init (&fmt, AUDIO_ES, formats[format]);
404     fmt.audio.i_format = fmt.i_codec;
405
406     param = 1 + var_InheritBool (demux, "alsa-stereo");
407     val = snd_pcm_hw_params_set_channels_max (pcm, hw, &param);
408     if (val)
409     {
410         msg_Err (demux, "cannot restrict channels count: %s",
411                  snd_strerror (val));
412         goto error;
413     }
414     val = snd_pcm_hw_params_set_channels_last (pcm, hw, &param);
415     if (val)
416     {
417         msg_Err (demux, "cannot set channels count: %s", snd_strerror (val));
418         goto error;
419     }
420     assert (param > 0);
421     assert (param < (sizeof (channel_maps) / sizeof (channel_maps[0])));
422     fmt.audio.i_channels = param;
423     fmt.audio.i_original_channels =
424     fmt.audio.i_physical_channels = channel_maps[param - 1];
425
426     param = var_InheritInteger (demux, "alsa-samplerate");
427     val = snd_pcm_hw_params_set_rate_max (pcm, hw, &param, NULL);
428     if (val)
429     {
430         msg_Err (demux, "cannot restrict rate to %u Hz or less: %s", 192000,
431                  snd_strerror (val));
432         goto error;
433     }
434     val = snd_pcm_hw_params_set_rate_last (pcm, hw, &param, &dir);
435     if (val)
436     {
437         msg_Err (demux, "cannot set sample rate: %s", snd_strerror (val));
438         goto error;
439     }
440     if (dir)
441         msg_Warn (demux, "sample rate is not integral");
442     fmt.audio.i_rate = param;
443     sys->rate = param;
444
445     sys->caching = INT64_C(1000) * var_InheritInteger (demux, "live-caching");
446     param = sys->caching;
447     val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, &param, NULL);
448     if (val)
449     {
450         msg_Err (demux, "cannot set buffer duration: %s", snd_strerror (val));
451         goto error;
452     }
453
454     param /= 4;
455     val = snd_pcm_hw_params_set_period_time_near (pcm, hw, &param, NULL);
456     if (val)
457     {
458         msg_Err (demux, "cannot set period: %s", snd_strerror (val));
459         goto error;
460     }
461
462     val = snd_pcm_hw_params_get_period_size (hw, &sys->period_size, &dir);
463     if (val)
464     {
465         msg_Err (demux, "cannot get period size: %s", snd_strerror (val));
466         goto error;
467     }
468     if (dir > 0)
469         sys->period_size++;
470
471     /* Commit hardware parameters */
472     val = snd_pcm_hw_params (pcm, hw);
473     if (val)
474     {
475         msg_Err (demux, "cannot commit hardware parameters: %s",
476                  snd_strerror (val));
477         goto error;
478     }
479     Dump (demux, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
480
481     /* Kick recording */
482     aout_FormatPrepare (&fmt.audio);
483     sys->es = es_out_Add (demux->out, &fmt);
484
485     if (vlc_clone (&sys->thread, Thread, demux, VLC_THREAD_PRIORITY_INPUT))
486     {
487         es_out_Del (demux->out, sys->es);
488         goto error;
489     }
490
491     demux->p_sys = sys;
492     demux->pf_demux = NULL;
493     demux->pf_control = Control;
494     return VLC_SUCCESS;
495 error:
496     snd_pcm_close (pcm);
497     free (sys);
498     return VLC_EGENERIC;
499 }
500
501 static void Close (vlc_object_t *obj)
502 {
503     demux_t *demux = (demux_t *)obj;
504     demux_sys_t *sys = demux->p_sys;
505
506     vlc_cancel (sys->thread);
507     vlc_join (sys->thread, NULL);
508
509     snd_pcm_close (sys->pcm);
510     free (sys);
511 }