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 2, 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 <omnithread.h>
37 #define LOGGING 0 // define to 0 or 1
39 #define SAMPLE_FORMAT paFloat32
40 typedef float sample_t;
42 // Number of portaudio buffers in the ringbuffer
43 static const unsigned int N_BUFFERS = 4;
46 default_device_name ()
48 return gr_prefs::singleton()->get_string("audio_portaudio", "default_input_device", "");
52 audio_portaudio_source::create_ringbuffer(void)
54 int bufsize_samples = d_portaudio_buffer_size_frames * d_input_parameters.channelCount;
57 fprintf(stderr, "ring buffer size = %d frames\n",
58 N_BUFFERS*bufsize_samples/d_input_parameters.channelCount);
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);
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().
70 * Our job is to copy framesPerBuffer frames from inputBuffer.
73 portaudio_source_callback (const void *inputBuffer,
75 unsigned long framesPerBuffer,
76 const PaStreamCallbackTimeInfo* timeInfo,
77 PaStreamCallbackFlags statusFlags,
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;
85 if (nframes_to_copy <= nframes_room){ // We've got room for the data ..
87 self->d_log->printf("PAsrc cb: f/b = %4ld\n", framesPerBuffer);
89 // copy from input buffer to ringbuffer
90 memcpy(self->d_writer->write_pointer(),
92 nframes_to_copy * nchan * sizeof(sample_t));
93 self->d_writer->update_write_pointer(nframes_to_copy * nchan);
95 // Tell the source thread there is new data in the ringbuffer.
96 self->d_ringbuffer_ready.post();
102 self->d_log->printf("PAsrc cb: f/b = %4ld OVERRUN\n", framesPerBuffer);
105 ::write(2, "aO", 2); // FIXME change to non-blocking call
108 // copy any frames that will fit
109 memcpy(self->d_writer->write_pointer(),
111 nframes_room * nchan * sizeof(sample_t));
112 self->d_writer->update_write_pointer(nframes_room * nchan);
115 self->d_ringbuffer_ready.post(); // Tell the sink to get going!
121 // ----------------------------------------------------------------
123 audio_portaudio_source_sptr
124 audio_portaudio_make_source (int sampling_rate, const std::string dev, bool ok_to_block)
126 return audio_portaudio_source_sptr (new audio_portaudio_source (sampling_rate,
130 audio_portaudio_source::audio_portaudio_source(int sampling_rate,
131 const std::string device_name,
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),
142 d_ringbuffer_ready(1, 1), // binary semaphore
145 memset(&d_input_parameters, 0, sizeof(d_input_parameters));
147 d_log = gri_logger::singleton();
151 PaDeviceIndex device = 0;
152 const PaDeviceInfo *deviceInfo = NULL;
155 err = Pa_Initialize();
156 if (err != paNoError) {
157 bail ("Initialize failed", err);
163 numDevices = Pa_GetDeviceCount();
165 bail("Pa Device count failed", 0);
167 bail("no devices available", 0);
169 if (d_device_name.empty())
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);
181 for (i=0;i<numDevices;i++) {
182 deviceInfo = Pa_GetDeviceInfo( i );
183 fprintf(stderr,"Testing device name: %s",deviceInfo->name);
184 if (deviceInfo->maxInputChannels <= 0) {
185 fprintf(stderr,"\n");
188 if (strstr(deviceInfo->name, d_device_name.c_str())){
189 fprintf(stderr," Chosen!\n");
191 fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(),
192 Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr);
194 deviceInfo = Pa_GetDeviceInfo(device);
195 i = numDevices; // force loop exit
198 fprintf(stderr,"\n"),fflush(stderr);
202 bail("Failed to find specified device name", 0);
207 d_input_parameters.device = device;
208 d_input_parameters.channelCount = deviceInfo->maxInputChannels;
209 d_input_parameters.sampleFormat = SAMPLE_FORMAT;
210 d_input_parameters.suggestedLatency = deviceInfo->defaultLowInputLatency;
211 d_input_parameters.hostApiSpecificStreamInfo = NULL;
213 // We fill in the real channelCount in check_topology when we know
214 // how many inputs are connected to us.
216 // Now that we know the maximum number of channels (allegedly)
217 // supported by the h/w, we can compute a reasonable output
218 // signature. The portaudio specs say that they'll accept any
219 // number of channels from 1 to max.
220 set_output_signature(gr_make_io_signature(1, deviceInfo->maxInputChannels,
226 audio_portaudio_source::check_topology (int ninputs, int noutputs)
230 if (Pa_IsStreamActive(d_stream))
232 Pa_CloseStream(d_stream);
234 d_reader.reset(); // boost::shared_ptr for d_reader = 0
235 d_writer.reset(); // boost::shared_ptr for d_write = 0
238 d_input_parameters.channelCount = noutputs; // # of channels we're really using
241 d_portaudio_buffer_size_frames = (int)(0.0213333333 * d_sampling_rate + 0.5); // Force 512 frame buffers at 48000
242 fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms
243 0.0213333333, (double)d_sampling_rate);
245 err = Pa_OpenStream(&d_stream,
249 d_portaudio_buffer_size_frames,
251 &portaudio_source_callback,
254 if (err != paNoError) {
255 output_error_msg ("OpenStream failed", err);
260 const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream);
262 d_portaudio_buffer_size_frames = (int)(d_input_parameters.suggestedLatency * psi->sampleRate);
263 fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n",
264 d_input_parameters.suggestedLatency, psi->sampleRate);
267 fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames);
269 assert(d_portaudio_buffer_size_frames != 0);
273 err = Pa_StartStream(d_stream);
274 if (err != paNoError) {
275 output_error_msg ("StartStream failed", err);
282 audio_portaudio_source::~audio_portaudio_source ()
284 Pa_StopStream(d_stream); // wait for output to drain
285 Pa_CloseStream(d_stream);
290 audio_portaudio_source::work (int noutput_items,
291 gr_vector_const_void_star &input_items,
292 gr_vector_void_star &output_items)
294 float **out = (float **) &output_items[0];
295 const unsigned nchan = d_input_parameters.channelCount; // # of channels == samples/frame
298 for (k = 0; k < noutput_items; ){
300 int nframes = d_reader->items_available() / nchan; // # of frames in ringbuffer
301 if (nframes == 0){ // no data right now...
302 if (k > 0) // If we've produced anything so far, return that
306 d_ringbuffer_ready.wait(); // block here, then try again
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
318 // There are lots of options for comfort noise, etc.
319 // FIXME We'll fill with zeros for now. Yes, it will "click"...
321 // Fill with some frames of zeros
322 int nf = std::min(noutput_items - k, (int) d_portaudio_buffer_size_frames);
323 for (int i = 0; i < nf; i++){
324 for (unsigned int c = 0; c < nchan; c++){
332 // We can read the smaller of the request and what's in the buffer.
333 int nf = std::min(noutput_items - k, nframes);
335 const float *p = (const float *) d_reader->read_pointer();
336 for (int i = 0; i < nf; i++){
337 for (unsigned int c = 0; c < nchan; c++){
338 out[c][k + i] = *p++;
341 d_reader->update_read_pointer(nf * nchan);
345 return k; // tell how many we actually did
349 audio_portaudio_source::output_error_msg (const char *msg, int err)
351 fprintf (stderr, "audio_portaudio_source[%s]: %s: %s\n",
352 d_device_name.c_str (), msg, Pa_GetErrorText(err));
356 audio_portaudio_source::bail (const char *msg, int err) throw (std::runtime_error)
358 output_error_msg (msg, err);
359 throw std::runtime_error ("audio_portaudio_source");