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