Imported Upstream version 3.2.2
[debian/gnuradio] / gr-audio-portaudio / src / audio_portaudio_sink.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 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 he 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_portaudio_sink.h>
28 #include <gr_io_signature.h>
29 #include <gr_prefs.h>
30 #include <stdio.h>
31 #include <iostream>
32 #include <unistd.h>
33 #include <stdexcept>
34 #include <gri_portaudio.h>
35 #include <gnuradio/omnithread.h>
36 #include <string.h>
37
38 #define LOGGING   0             // define to 0 or 1
39
40 #define SAMPLE_FORMAT           paFloat32
41 typedef float sample_t;
42
43 // Number of portaudio buffers in the ringbuffer
44 static const unsigned int N_BUFFERS = 4;
45
46 static std::string 
47 default_device_name ()
48 {
49   return gr_prefs::singleton()->get_string("audio_portaudio", "default_output_device", "");
50 }
51
52 void
53 audio_portaudio_sink::create_ringbuffer(void)
54 {
55   int bufsize_samples = d_portaudio_buffer_size_frames * d_output_parameters.channelCount;
56   
57   if (d_verbose)
58     fprintf(stderr,"ring buffer size  = %d frames\n",
59             N_BUFFERS*bufsize_samples/d_output_parameters.channelCount);
60
61   // FYI, the buffer indicies are in units of samples.
62   d_writer = gr_make_buffer(N_BUFFERS * bufsize_samples, sizeof(sample_t));
63   d_reader = gr_buffer_add_reader(d_writer, 0);
64 }
65
66 /*
67  * This routine will be called by the PortAudio engine when audio is needed.
68  * It may called at interrupt level on some machines so don't do anything
69  * that could mess up the system like calling malloc() or free().
70  *
71  * Our job is to write framesPerBuffer frames into outputBuffer.
72  */
73 int
74 portaudio_sink_callback (const void *inputBuffer,
75                          void *outputBuffer,
76                          unsigned long framesPerBuffer,
77                          const PaStreamCallbackTimeInfo* timeInfo,
78                          PaStreamCallbackFlags statusFlags,
79                          void *arg)
80 {
81   audio_portaudio_sink *self = (audio_portaudio_sink *)arg;
82   int nreqd_samples =
83     framesPerBuffer * self->d_output_parameters.channelCount;
84
85   int navail_samples = self->d_reader->items_available();
86   
87   if (nreqd_samples <= navail_samples){  // We've got enough data...
88     if (LOGGING)
89       self->d_log->printf("PAsink cb: f/b = %4ld\n", framesPerBuffer);
90     // copy from ringbuffer into output buffer
91     memcpy(outputBuffer,
92            self->d_reader->read_pointer(),
93            nreqd_samples * sizeof(sample_t));
94     self->d_reader->update_read_pointer(nreqd_samples);
95          
96     // Tell the sink thread there is new room in the ringbuffer.
97     self->d_ringbuffer_ready.post();
98     return paContinue;
99   }
100
101   else {                        // underrun
102     if (LOGGING)
103       self->d_log->printf("PAsink cb: f/b = %4ld UNDERRUN\n", framesPerBuffer);
104
105     self->d_nunderuns++;
106     ::write(2, "aU", 2);        // FIXME change to non-blocking call
107
108     // FIXME we should transfer what we've got and pad the rest
109     memset(outputBuffer, 0, nreqd_samples * sizeof(sample_t));
110
111     self->d_ringbuffer_ready.post();  // Tell the sink to get going!
112     return paContinue;
113   }
114 }
115
116
117 // ----------------------------------------------------------------
118
119 audio_portaudio_sink_sptr
120 audio_portaudio_make_sink (int sampling_rate, const std::string dev, bool ok_to_block)
121 {
122   return audio_portaudio_sink_sptr (new audio_portaudio_sink (sampling_rate,
123                                                               dev, ok_to_block));
124 }
125
126 audio_portaudio_sink::audio_portaudio_sink(int sampling_rate,
127                                            const std::string device_name,
128                                            bool ok_to_block)
129   : gr_sync_block ("audio_portaudio_sink",
130                    gr_make_io_signature(0, 0, 0),
131                    gr_make_io_signature(0, 0, 0)),
132     d_sampling_rate(sampling_rate),
133     d_device_name(device_name.empty() ? default_device_name() : device_name),
134     d_ok_to_block(ok_to_block),
135     d_verbose(gr_prefs::singleton()->get_bool("audio_portaudio", "verbose", false)),
136     d_portaudio_buffer_size_frames(0),
137     d_stream(0),
138     d_ringbuffer_ready(1, 1),           // binary semaphore
139     d_nunderuns(0)
140 {
141   memset(&d_output_parameters, 0, sizeof(d_output_parameters));
142   if (LOGGING)
143     d_log = gri_logger::singleton();
144
145   PaError             err;
146   int                 i, numDevices;
147   PaDeviceIndex       device = 0;
148   const PaDeviceInfo *deviceInfo = NULL;
149
150   err = Pa_Initialize();
151   if (err != paNoError) {
152     bail ("Initialize failed", err);
153   }
154
155   if (d_verbose)
156     gri_print_devices();
157
158   numDevices = Pa_GetDeviceCount();
159   if (numDevices < 0)
160     bail("Pa Device count failed", 0);
161   if (numDevices == 0)
162     bail("no devices available", 0);
163
164   if (d_device_name.empty()) 
165   {
166     // FIXME Get smarter about picking something
167     fprintf(stderr,"\nUsing Default Device\n");
168     device = Pa_GetDefaultOutputDevice();
169     deviceInfo = Pa_GetDeviceInfo(device);
170     fprintf(stderr,"%s is the chosen device using %s as the host\n",
171             deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
172   }
173   else
174   {
175     bool found = false;
176     fprintf(stderr,"\nTest Devices\n");
177     for (i=0;i<numDevices;i++) {
178       deviceInfo = Pa_GetDeviceInfo( i );
179       fprintf(stderr,"Testing device name: %s",deviceInfo->name);
180       if (deviceInfo->maxOutputChannels <= 0) {
181         fprintf(stderr,"\n");
182         continue;
183       }
184       if (strstr(deviceInfo->name, d_device_name.c_str())){
185         fprintf(stderr,"  Chosen!\n");
186         device = i;
187         fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(),
188                 Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr);
189         found = true;
190         deviceInfo = Pa_GetDeviceInfo(device);
191         i = numDevices;         // force loop exit
192       }
193       else
194         fprintf(stderr,"\n"),fflush(stderr);
195     }
196
197     if (!found){
198       bail("Failed to find specified device name", 0);
199       exit(1);
200     }
201   }
202
203
204   d_output_parameters.device = device;
205   d_output_parameters.channelCount     = deviceInfo->maxOutputChannels;
206   d_output_parameters.sampleFormat     = SAMPLE_FORMAT;
207   d_output_parameters.suggestedLatency = deviceInfo->defaultLowOutputLatency;
208   d_output_parameters.hostApiSpecificStreamInfo = NULL;
209
210   // We fill in the real channelCount in check_topology when we know
211   // how many inputs are connected to us.
212
213   // Now that we know the maximum number of channels (allegedly)
214   // supported by the h/w, we can compute a reasonable input
215   // signature.  The portaudio specs say that they'll accept any
216   // number of channels from 1 to max.
217   set_input_signature(gr_make_io_signature(1, deviceInfo->maxOutputChannels,
218                                            sizeof (sample_t)));
219 }
220
221
222 bool
223 audio_portaudio_sink::check_topology (int ninputs, int noutputs)
224 {
225   PaError err;
226
227   if (Pa_IsStreamActive(d_stream))
228   {
229       Pa_CloseStream(d_stream);
230       d_stream = 0;
231       d_reader.reset();         // boost::shared_ptr for d_reader = 0
232       d_writer.reset();         // boost::shared_ptr for d_write = 0
233   }
234
235   d_output_parameters.channelCount = ninputs;   // # of channels we're really using
236
237 #if 1
238   d_portaudio_buffer_size_frames = (int)(0.0213333333  * d_sampling_rate + 0.5);  // Force 1024 frame buffers at 48000
239   fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms
240           0.0213333333, (double)d_sampling_rate);
241 #endif
242   err = Pa_OpenStream(&d_stream,
243                       NULL,                     // No input
244                       &d_output_parameters,
245                       d_sampling_rate,
246                       d_portaudio_buffer_size_frames,
247                       paClipOff,
248                       &portaudio_sink_callback,
249                       (void*)this);
250
251   if (err != paNoError) {
252     output_error_msg ("OpenStream failed", err);
253     return false;
254   }
255
256 #if 0  
257   const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream);
258
259   d_portaudio_buffer_size_frames = (int)(d_output_parameters.suggestedLatency  * psi->sampleRate);
260   fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n",
261           d_output_parameters.suggestedLatency, psi->sampleRate);
262 #endif
263
264   fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames);
265
266   assert(d_portaudio_buffer_size_frames != 0);
267
268   create_ringbuffer();
269
270   err = Pa_StartStream(d_stream);
271   if (err != paNoError) {
272     output_error_msg ("StartStream failed", err);
273     return false;
274   }
275
276   return true;
277 }
278
279 audio_portaudio_sink::~audio_portaudio_sink ()
280 {
281   Pa_StopStream(d_stream);      // wait for output to drain
282   Pa_CloseStream(d_stream);
283   Pa_Terminate();
284 }
285
286 /*
287  * This version consumes everything sent to it, blocking if required.
288  * I think this will allow us better control of the total buffering/latency
289  * in the audio path.
290  */
291 int
292 audio_portaudio_sink::work (int noutput_items,
293                             gr_vector_const_void_star &input_items,
294                             gr_vector_void_star &output_items)
295 {
296   const float **in = (const float **) &input_items[0];
297   const unsigned nchan = d_output_parameters.channelCount; // # of channels == samples/frame
298
299   int k;
300   for (k = 0; k < noutput_items; ){
301
302     int nframes = d_writer->space_available() / nchan;  // How much space in ringbuffer
303     if (nframes == 0){                  // no room...
304       if (d_ok_to_block){
305         d_ringbuffer_ready.wait();      // block here, then try again
306         continue;
307       }
308       else {
309         // There's no room and we're not allowed to block.
310         // (A USRP is most likely controlling the pacing through the pipeline.)
311         // We drop the samples on the ground, and say we processed them all ;)
312         //
313         // FIXME, there's probably room for a bit more finesse here.
314         return noutput_items;
315       }
316     }
317
318     // We can write the smaller of the request and the room we've got
319     int nf = std::min(noutput_items - k, nframes);
320
321     float *p = (float *) d_writer->write_pointer();
322     for (int i = 0; i < nf; i++){
323       for (unsigned int c = 0; c < nchan; c++){
324         *p++ = in[c][k + i];
325       }
326     }
327     d_writer->update_write_pointer(nf * nchan);
328     k += nf;
329   }
330
331   return k;  // tell how many we actually did
332 }
333
334 void
335 audio_portaudio_sink::output_error_msg (const char *msg, int err)
336 {
337   fprintf (stderr, "audio_portaudio_sink[%s]: %s: %s\n",
338            d_device_name.c_str (), msg, Pa_GetErrorText(err));
339 }
340
341 void
342 audio_portaudio_sink::bail (const char *msg, int err) throw (std::runtime_error)
343 {
344   output_error_msg (msg, err);
345   throw std::runtime_error ("audio_portaudio_sink");
346 }