Imported Upstream version 3.0
[debian/gnuradio] / gr-audio-alsa / src / audio_alsa_sink.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2004 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 2, 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_sink.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
39 static snd_pcm_format_t acceptable_formats[] = {
40   // these are in our preferred order...
41   SND_PCM_FORMAT_S32,
42   SND_PCM_FORMAT_S16
43 };
44
45 #define NELEMS(x) (sizeof(x)/sizeof(x[0]))
46
47
48 static std::string 
49 default_device_name ()
50 {
51   return gr_prefs::singleton()->get_string("audio_alsa", "default_output_device", "hw:0,0");
52 }
53
54 static double
55 default_period_time ()
56 {
57   return std::max(0.001, gr_prefs::singleton()->get_double("audio_alsa", "period_time", 0.010));
58 }
59
60 static int
61 default_nperiods ()
62 {
63   return std::max(2L, gr_prefs::singleton()->get_long("audio_alsa", "nperiods", 4));
64 }
65
66 // ----------------------------------------------------------------
67
68 audio_alsa_sink_sptr
69 audio_alsa_make_sink (int sampling_rate,
70                       const std::string dev,
71                       bool ok_to_block)
72 {
73   return audio_alsa_sink_sptr (new audio_alsa_sink (sampling_rate, dev,
74                                                     ok_to_block));
75 }
76
77 audio_alsa_sink::audio_alsa_sink (int sampling_rate,
78                                   const std::string device_name,
79                                   bool ok_to_block)
80   : gr_sync_block ("audio_alsa_sink",
81                    gr_make_io_signature (0, 0, 0),
82                    gr_make_io_signature (0, 0, 0)),
83     d_sampling_rate (sampling_rate),
84     d_device_name (device_name.empty() ? default_device_name() : device_name),
85     d_pcm_handle (0),
86     d_hw_params ((snd_pcm_hw_params_t *)(new char[snd_pcm_hw_params_sizeof()])),
87     d_sw_params ((snd_pcm_sw_params_t *)(new char[snd_pcm_sw_params_sizeof()])),
88     d_nperiods (default_nperiods()),
89     d_period_time_us ((unsigned int) (default_period_time() * 1e6)),
90     d_period_size (0),
91     d_buffer_size_bytes (0), d_buffer (0),
92     d_worker (0), d_special_case_mono_to_stereo (false),
93     d_nunderuns (0), d_nsuspends (0)
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 playback
101   error = snd_pcm_open(&d_pcm_handle, d_device_name.c_str (),
102                        SND_PCM_STREAM_PLAYBACK, 0);
103   if (error < 0){
104     fprintf (stderr, "audio_alsa_sink[%s]: %s\n",
105              d_device_name.c_str(), snd_strerror(error));
106     throw std::runtime_error ("audio_alsa_sink");
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
115   if (CHATTY_DEBUG)
116     gri_alsa_dump_hw_params (d_pcm_handle, d_hw_params, stdout);
117
118
119   // now that we know how many channels the h/w can handle, set input signature
120   unsigned int umin_chan, umax_chan;
121   snd_pcm_hw_params_get_channels_min (d_hw_params, &umin_chan);
122   snd_pcm_hw_params_get_channels_max (d_hw_params, &umax_chan);
123   int min_chan = std::min (umin_chan, 1000U);
124   int max_chan = std::min (umax_chan, 1000U);
125
126   // As a special case, if the hw's min_chan is two, we'll accept
127   // a single input and handle the duplication ourselves.
128
129   if (min_chan == 2){
130     min_chan = 1;
131     d_special_case_mono_to_stereo = true;
132   }
133   set_input_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_sink",
157                                         CHATTY_DEBUG))
158     throw std::runtime_error ("audio_alsa_sink");
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_sink[%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_sink: min_nperiods = %d, max_nperiods = %d\n",
183   // min_nperiods, max_nperiods);
184
185   unsigned int orig_nperiods = d_nperiods;
186   d_nperiods = std::min (std::max (min_nperiods, d_nperiods), max_nperiods);
187
188   // adjust period time so that total buffering remains more-or-less constant
189   d_period_time_us = (d_period_time_us * orig_nperiods) / d_nperiods;
190
191   error = snd_pcm_hw_params_set_periods (d_pcm_handle, d_hw_params,
192                                          d_nperiods, 0);
193   if (error < 0)
194     bail ("set_periods failed", error);
195
196   dir = 0;
197   error = snd_pcm_hw_params_set_period_time_near (d_pcm_handle, d_hw_params,
198                                                   &d_period_time_us, &dir);
199   if (error < 0)
200     bail ("set_period_time_near failed", error);
201
202   dir = 0;
203   error = snd_pcm_hw_params_get_period_size (d_hw_params,
204                                              &d_period_size, &dir);
205   if (error < 0)
206     bail ("get_period_size failed", error);
207   
208   set_output_multiple (d_period_size);
209 }
210
211
212 bool
213 audio_alsa_sink::check_topology (int ninputs, int noutputs)
214 {
215   // ninputs is how many channels the user has connected.
216   // Now we can finish up setting up the hw params...
217
218   int nchan = ninputs;
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_mono_to_stereo;
225   if (special_case)
226     nchan = 2;
227   
228   err = snd_pcm_hw_params_set_channels (d_pcm_handle, d_hw_params, nchan);
229
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   // get current s/w params
243   err = snd_pcm_sw_params_current (d_pcm_handle, d_sw_params);
244   if (err < 0)
245     bail ("snd_pcm_sw_params_current", err);
246   
247   // Tell the PCM device to wait to start until we've filled
248   // it's buffers half way full.  This helps avoid audio underruns.
249
250   err = snd_pcm_sw_params_set_start_threshold(d_pcm_handle,
251                                               d_sw_params,
252                                               d_nperiods * d_period_size / 2);
253   if (err < 0)
254     bail ("snd_pcm_sw_params_set_start_threshold", err);
255
256   // store the s/w params
257   err = snd_pcm_sw_params (d_pcm_handle, d_sw_params);
258   if (err < 0)
259     bail ("snd_pcm_sw_params", err);
260
261   d_buffer_size_bytes =
262     d_period_size * nchan * snd_pcm_format_size (d_format, 1);
263
264   d_buffer = new char [d_buffer_size_bytes];
265
266   if (CHATTY_DEBUG)
267     fprintf (stdout, "audio_alsa_sink[%s]: sample resolution = %d bits\n",
268              snd_pcm_name (d_pcm_handle),
269              snd_pcm_hw_params_get_sbits (d_hw_params));
270
271   switch (d_format){
272   case SND_PCM_FORMAT_S16:
273     if (special_case)
274       d_worker = &audio_alsa_sink::work_s16_1x2;
275     else
276       d_worker = &audio_alsa_sink::work_s16;
277     break;
278
279   case SND_PCM_FORMAT_S32:
280     if (special_case)
281       d_worker = &audio_alsa_sink::work_s32_1x2;
282     else
283       d_worker = &audio_alsa_sink::work_s32;
284     break;
285
286   default:
287     assert (0);
288   }
289
290   return true;
291 }
292
293 audio_alsa_sink::~audio_alsa_sink ()
294 {
295   if (snd_pcm_state (d_pcm_handle) == SND_PCM_STATE_RUNNING)
296     snd_pcm_drop (d_pcm_handle);
297
298   snd_pcm_close(d_pcm_handle);
299   delete [] ((char *) d_hw_params);
300   delete [] ((char *) d_sw_params);
301   delete [] d_buffer;
302 }
303
304 int
305 audio_alsa_sink::work (int noutput_items,
306                        gr_vector_const_void_star &input_items,
307                        gr_vector_void_star &output_items)
308 {
309   assert ((noutput_items % d_period_size) == 0);
310
311   // this is a call through a pointer to a method...
312   return (this->*d_worker)(noutput_items, input_items, output_items);
313 }
314
315 /*
316  * Work function that deals with float to S16 conversion
317  */
318 int
319 audio_alsa_sink::work_s16 (int noutput_items,
320                            gr_vector_const_void_star &input_items,
321                            gr_vector_void_star &output_items)
322 {
323   typedef gr_int16      sample_t;       // the type of samples we're creating
324   static const int NBITS = 16;          // # of bits in a sample
325   
326   unsigned int nchan = input_items.size ();
327   const float **in = (const float **) &input_items[0];
328   sample_t *buf = (sample_t *) d_buffer;
329   int bi;
330   int n;
331
332   unsigned int sizeof_frame = nchan * sizeof (sample_t);
333   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
334
335   for (n = 0; n < noutput_items; n += d_period_size){
336
337     // process one period of data
338     bi = 0;
339     for (unsigned int i = 0; i < d_period_size; i++){
340       for (unsigned int chan = 0; chan < nchan; chan++){
341         buf[bi++] = (sample_t) (in[chan][i] * (float) ((1L << (NBITS-1)) - 1));
342       }
343     }
344
345     // update src pointers
346     for (unsigned int chan = 0; chan < nchan; chan++)
347       in[chan] += d_period_size;
348
349     if (!write_buffer (buf, d_period_size, sizeof_frame))  
350       return -1;        // No fixing this problem.  Say we're done.
351   }
352
353   return n;
354 }
355
356
357 /*
358  * Work function that deals with float to S32 conversion
359  */
360 int
361 audio_alsa_sink::work_s32 (int noutput_items,
362                            gr_vector_const_void_star &input_items,
363                            gr_vector_void_star &output_items)
364 {
365   typedef gr_int32      sample_t;       // the type of samples we're creating
366   static const int NBITS = 32;          // # of bits in a sample
367   
368   unsigned int nchan = input_items.size ();
369   const float **in = (const float **) &input_items[0];
370   sample_t *buf = (sample_t *) d_buffer;
371   int bi;
372   int n;
373
374   unsigned int sizeof_frame = nchan * sizeof (sample_t);
375   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
376
377   for (n = 0; n < noutput_items; n += d_period_size){
378
379     // process one period of data
380     bi = 0;
381     for (unsigned int i = 0; i < d_period_size; i++){
382       for (unsigned int chan = 0; chan < nchan; chan++){
383         buf[bi++] = (sample_t) (in[chan][i] * (float) ((1L << (NBITS-1)) - 1));
384       }
385     }
386
387     // update src pointers
388     for (unsigned int chan = 0; chan < nchan; chan++)
389       in[chan] += d_period_size;
390
391     if (!write_buffer (buf, d_period_size, sizeof_frame))  
392       return -1;        // No fixing this problem.  Say we're done.
393   }
394
395   return n;
396 }
397
398 /*
399  * Work function that deals with float to S16 conversion and
400  * mono to stereo kludge.
401  */
402 int
403 audio_alsa_sink::work_s16_1x2 (int noutput_items,
404                                gr_vector_const_void_star &input_items,
405                                gr_vector_void_star &output_items)
406 {
407   typedef gr_int16      sample_t;       // the type of samples we're creating
408   static const int NBITS = 16;          // # of bits in a sample
409   
410   assert (input_items.size () == 1);
411   static const unsigned int nchan = 2;
412   const float **in = (const float **) &input_items[0];
413   sample_t *buf = (sample_t *) d_buffer;
414   int bi;
415   int n;
416
417   unsigned int sizeof_frame = nchan * sizeof (sample_t);
418   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
419
420   for (n = 0; n < noutput_items; n += d_period_size){
421
422     // process one period of data
423     bi = 0;
424     for (unsigned int i = 0; i < d_period_size; i++){
425       sample_t t = (sample_t) (in[0][i] * (float) ((1L << (NBITS-1)) - 1));
426       buf[bi++] = t;
427       buf[bi++] = t;
428     }
429
430     // update src pointers
431     in[0] += d_period_size;
432
433     if (!write_buffer (buf, d_period_size, sizeof_frame))  
434       return -1;        // No fixing this problem.  Say we're done.
435   }
436
437   return n;
438 }
439
440 /*
441  * Work function that deals with float to S32 conversion and
442  * mono to stereo kludge.
443  */
444 int
445 audio_alsa_sink::work_s32_1x2 (int noutput_items,
446                                gr_vector_const_void_star &input_items,
447                                gr_vector_void_star &output_items)
448 {
449   typedef gr_int32      sample_t;       // the type of samples we're creating
450   static const int NBITS = 32;          // # of bits in a sample
451   
452   assert (input_items.size () == 1);
453   static unsigned int nchan = 2;
454   const float **in = (const float **) &input_items[0];
455   sample_t *buf = (sample_t *) d_buffer;
456   int bi;
457   int n;
458
459   unsigned int sizeof_frame = nchan * sizeof (sample_t);
460   assert (d_buffer_size_bytes == d_period_size * sizeof_frame);
461
462   for (n = 0; n < noutput_items; n += d_period_size){
463
464     // process one period of data
465     bi = 0;
466     for (unsigned int i = 0; i < d_period_size; i++){
467       sample_t t = (sample_t) (in[0][i] * (float) ((1L << (NBITS-1)) - 1));
468       buf[bi++] = t;
469       buf[bi++] = t;
470     }
471
472     // update src pointers
473     in[0] += d_period_size;
474
475     if (!write_buffer (buf, d_period_size, sizeof_frame))  
476       return -1;        // No fixing this problem.  Say we're done.
477   }
478
479   return n;
480 }
481
482 bool
483 audio_alsa_sink::write_buffer (const void *vbuffer,
484                                unsigned nframes, unsigned sizeof_frame)
485 {
486   const unsigned char *buffer = (const unsigned char *) vbuffer;
487
488   while (nframes > 0){
489     int r = snd_pcm_writei (d_pcm_handle, buffer, nframes);
490     if (r == -EAGAIN)
491       continue;                 // try again
492
493     else if (r == -EPIPE){      // underrun
494       d_nunderuns++;
495       fputs ("aU", stderr);
496       if ((r = snd_pcm_prepare (d_pcm_handle)) < 0){
497         output_error_msg ("snd_pcm_prepare failed. Can't recover from underrun", r);
498         return false;
499       }
500       continue;                 // try again
501     }
502
503     else if (r == -ESTRPIPE){   // h/w is suspended (whatever that means)
504                                 // This is apparently related to power management
505       d_nsuspends++;
506       if ((r = snd_pcm_resume (d_pcm_handle)) < 0){
507         output_error_msg ("failed to resume from suspend", r);
508         return false;
509       }
510       continue;                 // try again
511     }
512
513     else if (r < 0){
514       output_error_msg ("snd_pcm_writei failed", r);
515       return false;
516     }
517
518     nframes -= r;
519     buffer += r * sizeof_frame;
520   }
521
522   return true;
523 }
524
525
526 void
527 audio_alsa_sink::output_error_msg (const char *msg, int err)
528 {
529   fprintf (stderr, "audio_alsa_sink[%s]: %s: %s\n",
530            snd_pcm_name (d_pcm_handle), msg,  snd_strerror (err));
531 }
532
533 void
534 audio_alsa_sink::bail (const char *msg, int err) throw (std::runtime_error)
535 {
536   output_error_msg (msg, err);
537   throw std::runtime_error ("audio_alsa_sink");
538 }