Imported Upstream version 3.0.4
[debian/gnuradio] / gr-audio-alsa / src / audio_alsa_source.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2004,2006 Free Software Foundation, Inc.
4  * 
5  * This file is part of GNU Radio
6  * 
7  * GNU Radio is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3, or (at your option)
10  * any later version.
11  * 
12  * GNU Radio is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with GNU Radio; see the file COPYING.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <audio_alsa_source.h>
28 #include <gr_io_signature.h>
29 #include <gr_prefs.h>
30 #include <stdio.h>
31 #include <iostream>
32 #include <stdexcept>
33 #include <gri_alsa.h>
34
35
36 static bool CHATTY_DEBUG = false;
37
38 static snd_pcm_format_t acceptable_formats[] = {
39   // these are in our preferred order...
40   SND_PCM_FORMAT_S32,
41   SND_PCM_FORMAT_S16
42 };
43
44 #define NELEMS(x) (sizeof(x)/sizeof(x[0]))
45
46
47 static std::string 
48 default_device_name ()
49 {
50   return gr_prefs::singleton()->get_string("audio_alsa", "default_input_device", "hw:0,0");
51 }
52
53 static double
54 default_period_time ()
55 {
56   return std::max(0.001, gr_prefs::singleton()->get_double("audio_alsa", "period_time", 0.010));
57 }
58
59 static int
60 default_nperiods ()
61 {
62   return std::max(2L, gr_prefs::singleton()->get_long("audio_alsa", "nperiods", 4));
63 }
64
65 // ----------------------------------------------------------------
66
67 audio_alsa_source_sptr
68 audio_alsa_make_source (int sampling_rate, const std::string dev,
69                         bool ok_to_block)
70 {
71   return audio_alsa_source_sptr (new audio_alsa_source (sampling_rate, dev,
72                                                         ok_to_block));
73 }
74
75 audio_alsa_source::audio_alsa_source (int sampling_rate,
76                                       const std::string device_name,
77                                       bool ok_to_block)
78   : gr_sync_block ("audio_alsa_source",
79                    gr_make_io_signature (0, 0, 0),
80                    gr_make_io_signature (0, 0, 0)),
81     d_sampling_rate (sampling_rate),
82     d_device_name (device_name.empty() ? default_device_name() : device_name),
83     d_pcm_handle (0),
84     d_hw_params ((snd_pcm_hw_params_t *)(new char[snd_pcm_hw_params_sizeof()])),
85     d_sw_params ((snd_pcm_sw_params_t *)(new char[snd_pcm_sw_params_sizeof()])),
86     d_nperiods (default_nperiods()),
87     d_period_time_us ((unsigned int) (default_period_time() * 1e6)),
88     d_period_size (0),
89     d_buffer_size_bytes (0), d_buffer (0),
90     d_worker (0), d_hw_nchan (0),
91     d_special_case_stereo_to_mono (false),
92     d_noverruns (0), d_nsuspends (0)
93 {
94
95   CHATTY_DEBUG = gr_prefs::singleton()->get_bool("audio_alsa", "verbose", false);
96
97   int   error;
98   int   dir;
99
100   // open the device for capture
101   error = snd_pcm_open(&d_pcm_handle, d_device_name.c_str (),
102                        SND_PCM_STREAM_CAPTURE, 0);
103   if (error < 0){
104     fprintf (stderr, "audio_alsa_source[%s]: %s\n",
105              d_device_name.c_str(), snd_strerror(error));
106     throw std::runtime_error ("audio_alsa_source");
107   }
108
109   // Fill params with a full configuration space for a PCM.
110   error = snd_pcm_hw_params_any(d_pcm_handle, d_hw_params);
111   if (error < 0)
112     bail ("broken configuration for playback", error);
113
114   if (CHATTY_DEBUG)
115     gri_alsa_dump_hw_params (d_pcm_handle, d_hw_params, stdout);
116
117   // now that we know how many channels the h/w can handle, set output signature
118   unsigned int umax_chan;
119   unsigned int umin_chan;
120   snd_pcm_hw_params_get_channels_min (d_hw_params, &umin_chan);
121   snd_pcm_hw_params_get_channels_max (d_hw_params, &umax_chan);
122   int min_chan = std::min (umin_chan, 1000U);
123   int max_chan = std::min (umax_chan, 1000U);
124
125   // As a special case, if the hw's min_chan is two, we'll accept
126   // a single output and handle the demux ourselves.
127
128   if (min_chan == 2){
129     min_chan = 1;
130     d_special_case_stereo_to_mono = true;
131   }
132   
133   set_output_signature (gr_make_io_signature (min_chan, max_chan,
134                                               sizeof (float)));
135   
136   // fill in portions of the d_hw_params that we know now...
137
138   // Specify the access methods we implement
139   // For now, we only handle RW_INTERLEAVED...
140   snd_pcm_access_mask_t *access_mask;
141   snd_pcm_access_mask_alloca (&access_mask);
142   snd_pcm_access_mask_none (access_mask);
143   snd_pcm_access_mask_set (access_mask, SND_PCM_ACCESS_RW_INTERLEAVED);
144   // snd_pcm_access_mask_set (access_mask, SND_PCM_ACCESS_RW_NONINTERLEAVED);
145
146   if ((error = snd_pcm_hw_params_set_access_mask (d_pcm_handle,
147                                                   d_hw_params, access_mask)) < 0)
148     bail ("failed to set access mask", error);
149
150
151   // set sample format
152   if (!gri_alsa_pick_acceptable_format (d_pcm_handle, d_hw_params,
153                                         acceptable_formats,
154                                         NELEMS (acceptable_formats),
155                                         &d_format,
156                                         "audio_alsa_source",
157                                         CHATTY_DEBUG))
158     throw std::runtime_error ("audio_alsa_source");
159   
160
161   // sampling rate
162   unsigned int orig_sampling_rate = d_sampling_rate;
163   if ((error = snd_pcm_hw_params_set_rate_near (d_pcm_handle, d_hw_params,
164                                                 &d_sampling_rate, 0)) < 0)
165     bail ("failed to set rate near", error);
166   
167   if (orig_sampling_rate != d_sampling_rate){
168     fprintf (stderr, "audio_alsa_source[%s]: unable to support sampling rate %d\n",
169              snd_pcm_name (d_pcm_handle), orig_sampling_rate);
170     fprintf (stderr, "  card requested %d instead.\n", d_sampling_rate);
171   }
172
173   /*
174    * ALSA transfers data in units of "periods".
175    * We indirectly determine the underlying buffersize by specifying
176    * the number of periods we want (typically 4) and the length of each
177    * period in units of time (typically 1ms).
178    */
179   unsigned int min_nperiods, max_nperiods;
180   snd_pcm_hw_params_get_periods_min (d_hw_params, &min_nperiods, &dir);
181   snd_pcm_hw_params_get_periods_max (d_hw_params, &max_nperiods, &dir);
182   //fprintf (stderr, "alsa_source: min_nperiods = %d, max_nperiods = %d\n",
183   // min_nperiods, max_nperiods);
184
185
186   unsigned int orig_nperiods = d_nperiods;
187   d_nperiods = std::min (std::max (min_nperiods, d_nperiods), max_nperiods);
188
189   // adjust period time so that total buffering remains more-or-less constant
190   d_period_time_us = (d_period_time_us * orig_nperiods) / d_nperiods;
191
192   error = snd_pcm_hw_params_set_periods (d_pcm_handle, d_hw_params,
193                                          d_nperiods, 0);
194   if (error < 0)
195     bail ("set_periods failed", error);
196
197   dir = 0;
198   error = snd_pcm_hw_params_set_period_time_near (d_pcm_handle, d_hw_params,
199                                                   &d_period_time_us, &dir);
200   if (error < 0)
201     bail ("set_period_time_near failed", error);
202
203   dir = 0;
204   error = snd_pcm_hw_params_get_period_size (d_hw_params,
205                                              &d_period_size, &dir);
206   if (error < 0)
207     bail ("get_period_size failed", error);
208   
209   set_output_multiple (d_period_size);
210 }
211
212 bool
213 audio_alsa_source::check_topology (int ninputs, int noutputs)
214 {
215   // noutputs is how many channels the user has connected.
216   // Now we can finish up setting up the hw params...
217
218   unsigned int nchan = noutputs;
219   int err;
220
221   // FIXME check_topology may be called more than once.
222   // Ensure that the pcm is in a state where we can still mess with the hw_params
223
224   bool special_case = nchan == 1 && d_special_case_stereo_to_mono;
225   if (special_case)
226     nchan = 2;
227
228   d_hw_nchan = nchan;
229   err = snd_pcm_hw_params_set_channels (d_pcm_handle, d_hw_params, d_hw_nchan);
230   if (err < 0){
231     output_error_msg ("set_channels failed", err);
232     return false;
233   }
234
235   // set the parameters into the driver...
236   err = snd_pcm_hw_params(d_pcm_handle, d_hw_params);
237   if (err < 0){
238     output_error_msg ("snd_pcm_hw_params failed", err);
239     return false;
240   }
241
242   d_buffer_size_bytes =
243     d_period_size * d_hw_nchan * snd_pcm_format_size (d_format, 1);
244
245   d_buffer = new char [d_buffer_size_bytes];
246
247   if (CHATTY_DEBUG)
248     fprintf (stdout, "audio_alsa_source[%s]: sample resolution = %d bits\n",
249              snd_pcm_name (d_pcm_handle),
250              snd_pcm_hw_params_get_sbits (d_hw_params));
251
252   switch (d_format){
253   case SND_PCM_FORMAT_S16:
254     if (special_case)
255       d_worker = &audio_alsa_source::work_s16_2x1;
256     else
257       d_worker = &audio_alsa_source::work_s16;
258     break;
259
260   case SND_PCM_FORMAT_S32:
261     if (special_case)
262       d_worker = &audio_alsa_source::work_s32_2x1;
263     else
264       d_worker = &audio_alsa_source::work_s32;
265     break;
266
267   default:
268     assert (0);
269   }
270
271   return true;
272 }
273
274 audio_alsa_source::~audio_alsa_source ()
275 {
276   if (snd_pcm_state (d_pcm_handle) == SND_PCM_STATE_RUNNING)
277     snd_pcm_drop (d_pcm_handle);
278
279   snd_pcm_close(d_pcm_handle);
280   delete [] ((char *) d_hw_params);
281   delete [] ((char *) d_sw_params);
282   delete [] d_buffer;
283 }
284
285 int
286 audio_alsa_source::work (int noutput_items,
287                          gr_vector_const_void_star &input_items,
288                          gr_vector_void_star &output_items)
289 {
290   assert ((noutput_items % d_period_size) == 0);
291   assert (noutput_items != 0);
292
293   // this is a call through a pointer to a method...
294   return (this->*d_worker)(noutput_items, input_items, output_items);
295 }
296
297 /*
298  * Work function that deals with float to S16 conversion
299  */
300 int
301 audio_alsa_source::work_s16 (int noutput_items,
302                              gr_vector_const_void_star &input_items,
303                              gr_vector_void_star &output_items)
304 {
305   typedef gr_int16      sample_t;       // the type of samples we're creating
306   static const int NBITS = 16;          // # of bits in a sample
307   
308   unsigned int nchan = output_items.size ();
309   float **out = (float **) &output_items[0];
310   sample_t *buf = (sample_t *) d_buffer;
311   int bi;
312
313   unsigned int sizeof_frame = d_hw_nchan * sizeof (sample_t);
314   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
315
316   // To minimize latency, return at most a single period's worth of samples.
317   // [We could also read the first one in a blocking mode and subsequent
318   //  ones in non-blocking mode, but we'll leave that for later (or never).]
319   
320   if (!read_buffer (buf, d_period_size, sizeof_frame))
321     return -1;          // No fixing this problem.  Say we're done.
322
323   // process one period of data
324   bi = 0;
325   for (unsigned int i = 0; i < d_period_size; i++){
326     for (unsigned int chan = 0; chan < nchan; chan++){
327       out[chan][i] = (float) buf[bi++] * (1.0 / (float) ((1L << (NBITS-1)) - 1));
328     }
329   }
330
331   return d_period_size;
332 }
333
334 /*
335  * Work function that deals with float to S16 conversion
336  * and stereo to mono kludge...
337  */
338 int
339 audio_alsa_source::work_s16_2x1 (int noutput_items,
340                                  gr_vector_const_void_star &input_items,
341                                  gr_vector_void_star &output_items)
342 {
343   typedef gr_int16      sample_t;       // the type of samples we're creating
344   static const int NBITS = 16;          // # of bits in a sample
345   
346   unsigned int nchan = output_items.size ();
347   float **out = (float **) &output_items[0];
348   sample_t *buf = (sample_t *) d_buffer;
349   int bi;
350
351   assert (nchan == 1);
352
353   unsigned int sizeof_frame = d_hw_nchan * sizeof (sample_t);
354   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
355
356   // To minimize latency, return at most a single period's worth of samples.
357   // [We could also read the first one in a blocking mode and subsequent
358   //  ones in non-blocking mode, but we'll leave that for later (or never).]
359   
360   if (!read_buffer (buf, d_period_size, sizeof_frame))
361     return -1;          // No fixing this problem.  Say we're done.
362
363   // process one period of data
364   bi = 0;
365   for (unsigned int i = 0; i < d_period_size; i++){
366     int t = (buf[bi] + buf[bi+1]) / 2;
367     bi += 2;
368     out[0][i] = (float) t * (1.0 / (float) ((1L << (NBITS-1)) - 1));
369   }
370
371   return d_period_size;
372 }
373
374 /*
375  * Work function that deals with float to S32 conversion
376  */
377 int
378 audio_alsa_source::work_s32 (int noutput_items,
379                              gr_vector_const_void_star &input_items,
380                              gr_vector_void_star &output_items)
381 {
382   typedef gr_int32      sample_t;       // the type of samples we're creating
383   static const int NBITS = 32;          // # of bits in a sample
384   
385   unsigned int nchan = output_items.size ();
386   float **out = (float **) &output_items[0];
387   sample_t *buf = (sample_t *) d_buffer;
388   int bi;
389
390   unsigned int sizeof_frame = d_hw_nchan * sizeof (sample_t);
391   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
392
393   // To minimize latency, return at most a single period's worth of samples.
394   // [We could also read the first one in a blocking mode and subsequent
395   //  ones in non-blocking mode, but we'll leave that for later (or never).]
396   
397   if (!read_buffer (buf, d_period_size, sizeof_frame))
398     return -1;          // No fixing this problem.  Say we're done.
399
400   // process one period of data
401   bi = 0;
402   for (unsigned int i = 0; i < d_period_size; i++){
403     for (unsigned int chan = 0; chan < nchan; chan++){
404       out[chan][i] = (float) buf[bi++] * (1.0 / (float) ((1L << (NBITS-1)) - 1));
405     }
406   }
407
408   return d_period_size;
409 }
410
411 /*
412  * Work function that deals with float to S32 conversion
413  * and stereo to mono kludge...
414  */
415 int
416 audio_alsa_source::work_s32_2x1 (int noutput_items,
417                                  gr_vector_const_void_star &input_items,
418                                  gr_vector_void_star &output_items)
419 {
420   typedef gr_int32      sample_t;       // the type of samples we're creating
421   static const int NBITS = 32;          // # of bits in a sample
422   
423   unsigned int nchan = output_items.size ();
424   float **out = (float **) &output_items[0];
425   sample_t *buf = (sample_t *) d_buffer;
426   int bi;
427
428   assert (nchan == 1);
429
430   unsigned int sizeof_frame = d_hw_nchan * sizeof (sample_t);
431   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
432
433   // To minimize latency, return at most a single period's worth of samples.
434   // [We could also read the first one in a blocking mode and subsequent
435   //  ones in non-blocking mode, but we'll leave that for later (or never).]
436   
437   if (!read_buffer (buf, d_period_size, sizeof_frame))
438     return -1;          // No fixing this problem.  Say we're done.
439
440   // process one period of data
441   bi = 0;
442   for (unsigned int i = 0; i < d_period_size; i++){
443     int t = (buf[bi] + buf[bi+1]) / 2;
444     bi += 2;
445     out[0][i] = (float) t * (1.0 / (float) ((1L << (NBITS-1)) - 1));
446   }
447
448   return d_period_size;
449 }
450
451 bool
452 audio_alsa_source::read_buffer (void *vbuffer, unsigned nframes, unsigned sizeof_frame)
453 {
454   unsigned char *buffer = (unsigned char *) vbuffer;
455
456   while (nframes > 0){
457     int r = snd_pcm_readi (d_pcm_handle, buffer, nframes);
458     if (r == -EAGAIN)
459       continue;                 // try again
460
461     else if (r == -EPIPE){      // overrun
462       d_noverruns++;
463       fputs ("aO", stderr);
464       if ((r = snd_pcm_prepare (d_pcm_handle)) < 0){
465         output_error_msg ("snd_pcm_prepare failed. Can't recover from overrun", r);
466         return false;
467       }
468       continue;                 // try again
469     }
470
471     else if (r == -ESTRPIPE){   // h/w is suspended (whatever that means)
472                                 // This is apparently related to power management
473       d_nsuspends++;
474       if ((r = snd_pcm_resume (d_pcm_handle)) < 0){
475         output_error_msg ("failed to resume from suspend", r);
476         return false;
477       }
478       continue;                 // try again
479     }
480
481     else if (r < 0){
482       output_error_msg ("snd_pcm_readi failed", r);
483       return false;
484     }
485
486     nframes -= r;
487     buffer += r * sizeof_frame;
488   }
489
490   return true;
491 }
492
493
494 void
495 audio_alsa_source::output_error_msg (const char *msg, int err)
496 {
497   fprintf (stderr, "audio_alsa_source[%s]: %s: %s\n",
498            snd_pcm_name (d_pcm_handle), msg,  snd_strerror (err));
499 }
500
501 void
502 audio_alsa_source::bail (const char *msg, int err) throw (std::runtime_error)
503 {
504   output_error_msg (msg, err);
505   throw std::runtime_error ("audio_alsa_source");
506 }