3 * Copyright 2006 Free Software Foundation, Inc.
5 * This file is part of GNU Radio
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)
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.
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.
27 #include <audio_portaudio_source.h>
28 #include <gr_io_signature.h>
34 #include <gri_portaudio.h>
35 #include <gnuradio/omnithread.h>
38 #define LOGGING 0 // define to 0 or 1
40 #define SAMPLE_FORMAT paFloat32
41 typedef float sample_t;
43 // Number of portaudio buffers in the ringbuffer
44 static const unsigned int N_BUFFERS = 4;
47 default_device_name ()
49 return gr_prefs::singleton()->get_string("audio_portaudio", "default_input_device", "");
53 audio_portaudio_source::create_ringbuffer(void)
55 int bufsize_samples = d_portaudio_buffer_size_frames * d_input_parameters.channelCount;
58 fprintf(stderr, "ring buffer size = %d frames\n",
59 N_BUFFERS*bufsize_samples/d_input_parameters.channelCount);
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);
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().
71 * Our job is to copy framesPerBuffer frames from inputBuffer.
74 portaudio_source_callback (const void *inputBuffer,
76 unsigned long framesPerBuffer,
77 const PaStreamCallbackTimeInfo* timeInfo,
78 PaStreamCallbackFlags statusFlags,
81 audio_portaudio_source *self = (audio_portaudio_source *)arg;
82 int nchan = self->d_input_parameters.channelCount;
83 int nframes_to_copy = framesPerBuffer;
84 int nframes_room = self->d_writer->space_available() / nchan;
86 if (nframes_to_copy <= nframes_room){ // We've got room for the data ..
88 self->d_log->printf("PAsrc cb: f/b = %4ld\n", framesPerBuffer);
90 // copy from input buffer to ringbuffer
91 memcpy(self->d_writer->write_pointer(),
93 nframes_to_copy * nchan * sizeof(sample_t));
94 self->d_writer->update_write_pointer(nframes_to_copy * nchan);
96 // Tell the source thread there is new data in the ringbuffer.
97 self->d_ringbuffer_ready.post();
103 self->d_log->printf("PAsrc cb: f/b = %4ld OVERRUN\n", framesPerBuffer);
106 ::write(2, "aO", 2); // FIXME change to non-blocking call
109 // copy any frames that will fit
110 memcpy(self->d_writer->write_pointer(),
112 nframes_room * nchan * sizeof(sample_t));
113 self->d_writer->update_write_pointer(nframes_room * nchan);
116 self->d_ringbuffer_ready.post(); // Tell the sink to get going!
122 // ----------------------------------------------------------------
124 audio_portaudio_source_sptr
125 audio_portaudio_make_source (int sampling_rate, const std::string dev, bool ok_to_block)
127 return audio_portaudio_source_sptr (new audio_portaudio_source (sampling_rate,
131 audio_portaudio_source::audio_portaudio_source(int sampling_rate,
132 const std::string device_name,
134 : gr_sync_block ("audio_portaudio_source",
135 gr_make_io_signature(0, 0, 0),
136 gr_make_io_signature(0, 0, 0)),
137 d_sampling_rate(sampling_rate),
138 d_device_name(device_name.empty() ? default_device_name() : device_name),
139 d_ok_to_block(ok_to_block),
140 d_verbose(gr_prefs::singleton()->get_bool("audio_portaudio", "verbose", false)),
141 d_portaudio_buffer_size_frames(0),
143 d_ringbuffer_ready(1, 1), // binary semaphore
146 memset(&d_input_parameters, 0, sizeof(d_input_parameters));
148 d_log = gri_logger::singleton();
152 PaDeviceIndex device = 0;
153 const PaDeviceInfo *deviceInfo = NULL;
156 err = Pa_Initialize();
157 if (err != paNoError) {
158 bail ("Initialize failed", err);
164 numDevices = Pa_GetDeviceCount();
166 bail("Pa Device count failed", 0);
168 bail("no devices available", 0);
170 if (d_device_name.empty())
172 // FIXME Get smarter about picking something
173 device = Pa_GetDefaultInputDevice();
174 deviceInfo = Pa_GetDeviceInfo(device);
175 fprintf(stderr,"%s is the chosen device using %s as the host\n",
176 deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
182 for (i=0;i<numDevices;i++) {
183 deviceInfo = Pa_GetDeviceInfo( i );
184 fprintf(stderr,"Testing device name: %s",deviceInfo->name);
185 if (deviceInfo->maxInputChannels <= 0) {
186 fprintf(stderr,"\n");
189 if (strstr(deviceInfo->name, d_device_name.c_str())){
190 fprintf(stderr," Chosen!\n");
192 fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(),
193 Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr);
195 deviceInfo = Pa_GetDeviceInfo(device);
196 i = numDevices; // force loop exit
199 fprintf(stderr,"\n"),fflush(stderr);
203 bail("Failed to find specified device name", 0);
208 d_input_parameters.device = device;
209 d_input_parameters.channelCount = deviceInfo->maxInputChannels;
210 d_input_parameters.sampleFormat = SAMPLE_FORMAT;
211 d_input_parameters.suggestedLatency = deviceInfo->defaultLowInputLatency;
212 d_input_parameters.hostApiSpecificStreamInfo = NULL;
214 // We fill in the real channelCount in check_topology when we know
215 // how many inputs are connected to us.
217 // Now that we know the maximum number of channels (allegedly)
218 // supported by the h/w, we can compute a reasonable output
219 // signature. The portaudio specs say that they'll accept any
220 // number of channels from 1 to max.
221 set_output_signature(gr_make_io_signature(1, deviceInfo->maxInputChannels,
227 audio_portaudio_source::check_topology (int ninputs, int noutputs)
231 if (Pa_IsStreamActive(d_stream))
233 Pa_CloseStream(d_stream);
235 d_reader.reset(); // boost::shared_ptr for d_reader = 0
236 d_writer.reset(); // boost::shared_ptr for d_write = 0
239 d_input_parameters.channelCount = noutputs; // # of channels we're really using
242 d_portaudio_buffer_size_frames = (int)(0.0213333333 * d_sampling_rate + 0.5); // Force 512 frame buffers at 48000
243 fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms
244 0.0213333333, (double)d_sampling_rate);
246 err = Pa_OpenStream(&d_stream,
250 d_portaudio_buffer_size_frames,
252 &portaudio_source_callback,
255 if (err != paNoError) {
256 output_error_msg ("OpenStream failed", err);
261 const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream);
263 d_portaudio_buffer_size_frames = (int)(d_input_parameters.suggestedLatency * psi->sampleRate);
264 fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n",
265 d_input_parameters.suggestedLatency, psi->sampleRate);
268 fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames);
270 assert(d_portaudio_buffer_size_frames != 0);
274 err = Pa_StartStream(d_stream);
275 if (err != paNoError) {
276 output_error_msg ("StartStream failed", err);
283 audio_portaudio_source::~audio_portaudio_source ()
285 Pa_StopStream(d_stream); // wait for output to drain
286 Pa_CloseStream(d_stream);
291 audio_portaudio_source::work (int noutput_items,
292 gr_vector_const_void_star &input_items,
293 gr_vector_void_star &output_items)
295 float **out = (float **) &output_items[0];
296 const unsigned nchan = d_input_parameters.channelCount; // # of channels == samples/frame
299 for (k = 0; k < noutput_items; ){
301 int nframes = d_reader->items_available() / nchan; // # of frames in ringbuffer
302 if (nframes == 0){ // no data right now...
303 if (k > 0) // If we've produced anything so far, return that
307 d_ringbuffer_ready.wait(); // block here, then try again
313 // There's no data and we're not allowed to block.
314 // (A USRP is most likely controlling the pacing through the pipeline.)
315 // This is an underun. The scheduler wouldn't have called us if it
316 // had anything better to do. Thus we really need to produce some amount
319 // There are lots of options for comfort noise, etc.
320 // FIXME We'll fill with zeros for now. Yes, it will "click"...
322 // Fill with some frames of zeros
323 int nf = std::min(noutput_items - k, (int) d_portaudio_buffer_size_frames);
324 for (int i = 0; i < nf; i++){
325 for (unsigned int c = 0; c < nchan; c++){
333 // We can read the smaller of the request and what's in the buffer.
334 int nf = std::min(noutput_items - k, nframes);
336 const float *p = (const float *) d_reader->read_pointer();
337 for (int i = 0; i < nf; i++){
338 for (unsigned int c = 0; c < nchan; c++){
339 out[c][k + i] = *p++;
342 d_reader->update_read_pointer(nf * nchan);
346 return k; // tell how many we actually did
350 audio_portaudio_source::output_error_msg (const char *msg, int err)
352 fprintf (stderr, "audio_portaudio_source[%s]: %s: %s\n",
353 d_device_name.c_str (), msg, Pa_GetErrorText(err));
357 audio_portaudio_source::bail (const char *msg, int err) throw (std::runtime_error)
359 output_error_msg (msg, err);
360 throw std::runtime_error ("audio_portaudio_source");