switch source package format to 3.0 quilt
[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 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_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 <string.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     {
91       gruel::scoped_lock(d_ringbuffer_mutex);
92
93       memcpy(self->d_writer->write_pointer(),
94              inputBuffer,
95              nframes_to_copy * nchan * sizeof(sample_t));
96       self->d_writer->update_write_pointer(nframes_to_copy * nchan);
97          
98       // Tell the source thread there is new data in the ringbuffer.
99       self->d_ringbuffer_ready = true;
100     }
101
102     self->d_ringbuffer_cond.notify_one();
103     return paContinue;
104   }
105
106   else {                        // overrun
107     self->d_noverruns++;
108     ::write(2, "aO", 2);        // FIXME change to non-blocking call
109
110     self->d_ringbuffer_ready = false;
111     self->d_ringbuffer_cond.notify_one();  // Tell the sink to get going!
112     return paContinue;
113   }
114 }
115
116
117 // ----------------------------------------------------------------
118
119 audio_portaudio_source_sptr
120 audio_portaudio_make_source (int sampling_rate, const std::string dev, bool ok_to_block)
121 {
122   return audio_portaudio_source_sptr (new audio_portaudio_source (sampling_rate,
123                                                                   dev, ok_to_block));
124 }
125
126 audio_portaudio_source::audio_portaudio_source(int sampling_rate,
127                                                const std::string device_name,
128                                                bool ok_to_block)
129   : gr_sync_block ("audio_portaudio_source",
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_mutex(),
139     d_ringbuffer_cond(),
140     d_ringbuffer_ready(false),
141     d_noverruns(0)
142 {
143   memset(&d_input_parameters, 0, sizeof(d_input_parameters));
144   //if (LOGGING)
145   //  d_log = gri_logger::singleton();
146
147   PaError             err;
148   int                 i, numDevices;
149   PaDeviceIndex       device = 0;
150   const PaDeviceInfo *deviceInfo = NULL;
151
152
153   err = Pa_Initialize();
154   if (err != paNoError) {
155     bail ("Initialize failed", err);
156   }
157
158   if (d_verbose)
159     gri_print_devices();
160
161   numDevices = Pa_GetDeviceCount();
162   if (numDevices < 0)
163     bail("Pa Device count failed", 0);
164   if (numDevices == 0)
165     bail("no devices available", 0);
166
167   if (d_device_name.empty()) 
168   {
169     // FIXME Get smarter about picking something
170     device = Pa_GetDefaultInputDevice();
171     deviceInfo = Pa_GetDeviceInfo(device);
172     fprintf(stderr,"%s is the chosen device using %s as the host\n",
173             deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
174   }
175   else
176   {
177     bool found = false;
178     
179     for (i=0;i<numDevices;i++) {
180       deviceInfo = Pa_GetDeviceInfo( i );
181       fprintf(stderr,"Testing device name: %s",deviceInfo->name);
182       if (deviceInfo->maxInputChannels <= 0) {
183         fprintf(stderr,"\n");
184         continue;
185       }
186       if (strstr(deviceInfo->name, d_device_name.c_str())){
187         fprintf(stderr,"  Chosen!\n");
188         device = i;
189         fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(),
190                 Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr);
191         found = true;
192         deviceInfo = Pa_GetDeviceInfo(device);
193         i = numDevices;         // force loop exit
194       }
195       else
196         fprintf(stderr,"\n"),fflush(stderr);
197     }
198
199     if (!found){
200       bail("Failed to find specified device name", 0);
201     }
202   }
203
204
205   d_input_parameters.device = device;
206   d_input_parameters.channelCount     = deviceInfo->maxInputChannels;
207   d_input_parameters.sampleFormat     = SAMPLE_FORMAT;
208   d_input_parameters.suggestedLatency = deviceInfo->defaultLowInputLatency;
209   d_input_parameters.hostApiSpecificStreamInfo = NULL;
210
211   // We fill in the real channelCount in check_topology when we know
212   // how many inputs are connected to us.
213
214   // Now that we know the maximum number of channels (allegedly)
215   // supported by the h/w, we can compute a reasonable output
216   // signature.  The portaudio specs say that they'll accept any
217   // number of channels from 1 to max.
218   set_output_signature(gr_make_io_signature(1, deviceInfo->maxInputChannels,
219                                             sizeof (sample_t)));
220 }
221
222
223 bool
224 audio_portaudio_source::check_topology (int ninputs, int noutputs)
225 {
226   PaError err;
227
228   if (Pa_IsStreamActive(d_stream))
229   {
230       Pa_CloseStream(d_stream);
231       d_stream = 0;
232       d_reader.reset();         // boost::shared_ptr for d_reader = 0
233       d_writer.reset();         // boost::shared_ptr for d_write = 0
234   }
235
236   d_input_parameters.channelCount = noutputs;   // # of channels we're really using
237
238 #if 1
239   d_portaudio_buffer_size_frames = (int)(0.0213333333  * d_sampling_rate + 0.5);  // Force 512 frame buffers at 48000
240   fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms
241           0.0213333333, (double)d_sampling_rate);
242 #endif
243   err = Pa_OpenStream(&d_stream,
244                       &d_input_parameters,
245                       NULL,                     // No output
246                       d_sampling_rate,
247                       d_portaudio_buffer_size_frames,
248                       paClipOff,
249                       &portaudio_source_callback,
250                       (void*)this);
251
252   if (err != paNoError) {
253     output_error_msg ("OpenStream failed", err);
254     return false;
255   }
256
257 #if 0  
258   const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream);
259
260   d_portaudio_buffer_size_frames = (int)(d_input_parameters.suggestedLatency  * psi->sampleRate);
261   fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n",
262           d_input_parameters.suggestedLatency, psi->sampleRate);
263 #endif
264
265   fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames);
266
267   assert(d_portaudio_buffer_size_frames != 0);
268
269   create_ringbuffer();
270
271   err = Pa_StartStream(d_stream);
272   if (err != paNoError) {
273     output_error_msg ("StartStream failed", err);
274     return false;
275   }
276
277   return true;
278 }
279
280 audio_portaudio_source::~audio_portaudio_source ()
281 {
282   Pa_StopStream(d_stream);      // wait for output to drain
283   Pa_CloseStream(d_stream);
284   Pa_Terminate();
285 }
286
287 int
288 audio_portaudio_source::work (int noutput_items,
289                               gr_vector_const_void_star &input_items,
290                               gr_vector_void_star &output_items)
291 {
292   float **out = (float **) &output_items[0];
293   const unsigned nchan = d_input_parameters.channelCount; // # of channels == samples/frame
294
295   int k;
296   for (k = 0; k < noutput_items; ){
297
298     int nframes = d_reader->items_available() / nchan;  // # of frames in ringbuffer
299     if (nframes == 0){          // no data right now...
300       if (k > 0)                // If we've produced anything so far, return that
301         return k;
302
303       if (d_ok_to_block) {
304         gruel:: scoped_lock guard(d_ringbuffer_mutex);
305         while (d_ringbuffer_ready == false)
306           d_ringbuffer_cond.wait(guard);        // block here, then try again
307         continue;
308       }
309       
310       assert(k == 0);
311
312       // There's no data and we're not allowed to block.
313       // (A USRP is most likely controlling the pacing through the pipeline.)
314       // This is an underun.  The scheduler wouldn't have called us if it
315       // had anything better to do.  Thus we really need to produce some amount
316       // of "fill".
317       //
318       // There are lots of options for comfort noise, etc.
319       // FIXME We'll fill with zeros for now.  Yes, it will "click"...
320
321       // Fill with some frames of zeros
322       {
323         gruel::scoped_lock guard(d_ringbuffer_mutex);
324
325         int nf = std::min(noutput_items - k, (int) d_portaudio_buffer_size_frames);
326         for (int i = 0; i < nf; i++){
327           for (unsigned int c = 0; c < nchan; c++){
328             out[c][k + i] = 0;
329           }
330         }
331         k += nf;
332
333         d_ringbuffer_ready = false;
334         return k;
335       }
336     }
337
338     // We can read the smaller of the request and what's in the buffer.
339     {
340       gruel::scoped_lock guard(d_ringbuffer_mutex);
341
342       int nf = std::min(noutput_items - k, nframes);
343       
344       const float *p = (const float *) d_reader->read_pointer();
345       for (int i = 0; i < nf; i++){
346         for (unsigned int c = 0; c < nchan; c++){
347           out[c][k + i] = *p++;
348         }
349       }
350       d_reader->update_read_pointer(nf * nchan);
351       k += nf;
352       d_ringbuffer_ready = false;
353     }
354   }
355
356   return k;  // tell how many we actually did
357 }
358
359 void
360 audio_portaudio_source::output_error_msg (const char *msg, int err)
361 {
362   fprintf (stderr, "audio_portaudio_source[%s]: %s: %s\n",
363            d_device_name.c_str (), msg, Pa_GetErrorText(err));
364 }
365
366 void
367 audio_portaudio_source::bail (const char *msg, int err) throw (std::runtime_error)
368 {
369   output_error_msg (msg, err);
370   throw std::runtime_error ("audio_portaudio_source");
371 }