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_sink.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_output_device", "");
52 audio_portaudio_sink::create_ringbuffer(void)
54 int bufsize_samples = d_portaudio_buffer_size_frames * d_output_parameters.channelCount;
57 fprintf(stderr,"ring buffer size = %d frames\n",
58 N_BUFFERS*bufsize_samples/d_output_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 write framesPerBuffer frames into outputBuffer.
73 portaudio_sink_callback (const void *inputBuffer,
75 unsigned long framesPerBuffer,
76 const PaStreamCallbackTimeInfo* timeInfo,
77 PaStreamCallbackFlags statusFlags,
80 audio_portaudio_sink *self = (audio_portaudio_sink *)arg;
82 framesPerBuffer * self->d_output_parameters.channelCount;
84 int navail_samples = self->d_reader->items_available();
86 if (nreqd_samples <= navail_samples){ // We've got enough data...
88 self->d_log->printf("PAsink cb: f/b = %4ld\n", framesPerBuffer);
89 // copy from ringbuffer into output buffer
91 self->d_reader->read_pointer(),
92 nreqd_samples * sizeof(sample_t));
93 self->d_reader->update_read_pointer(nreqd_samples);
95 // Tell the sink thread there is new room in the ringbuffer.
96 self->d_ringbuffer_ready.post();
102 self->d_log->printf("PAsink cb: f/b = %4ld UNDERRUN\n", framesPerBuffer);
105 ::write(2, "aU", 2); // FIXME change to non-blocking call
107 // FIXME we should transfer what we've got and pad the rest
108 memset(outputBuffer, 0, nreqd_samples * sizeof(sample_t));
110 self->d_ringbuffer_ready.post(); // Tell the sink to get going!
116 // ----------------------------------------------------------------
118 audio_portaudio_sink_sptr
119 audio_portaudio_make_sink (int sampling_rate, const std::string dev, bool ok_to_block)
121 return audio_portaudio_sink_sptr (new audio_portaudio_sink (sampling_rate,
125 audio_portaudio_sink::audio_portaudio_sink(int sampling_rate,
126 const std::string device_name,
128 : gr_sync_block ("audio_portaudio_sink",
129 gr_make_io_signature(0, 0, 0),
130 gr_make_io_signature(0, 0, 0)),
131 d_sampling_rate(sampling_rate),
132 d_device_name(device_name.empty() ? default_device_name() : device_name),
133 d_ok_to_block(ok_to_block),
134 d_verbose(gr_prefs::singleton()->get_bool("audio_portaudio", "verbose", false)),
135 d_portaudio_buffer_size_frames(0),
137 d_ringbuffer_ready(1, 1), // binary semaphore
140 memset(&d_output_parameters, 0, sizeof(d_output_parameters));
142 d_log = gri_logger::singleton();
146 PaDeviceIndex device = 0;
147 const PaDeviceInfo *deviceInfo = NULL;
149 err = Pa_Initialize();
150 if (err != paNoError) {
151 bail ("Initialize failed", err);
157 numDevices = Pa_GetDeviceCount();
159 bail("Pa Device count failed", 0);
161 bail("no devices available", 0);
163 if (d_device_name.empty())
165 // FIXME Get smarter about picking something
166 fprintf(stderr,"\nUsing Default Device\n");
167 device = Pa_GetDefaultOutputDevice();
168 deviceInfo = Pa_GetDeviceInfo(device);
169 fprintf(stderr,"%s is the chosen device using %s as the host\n",
170 deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
175 fprintf(stderr,"\nTest Devices\n");
176 for (i=0;i<numDevices;i++) {
177 deviceInfo = Pa_GetDeviceInfo( i );
178 fprintf(stderr,"Testing device name: %s",deviceInfo->name);
179 if (deviceInfo->maxOutputChannels <= 0) {
180 fprintf(stderr,"\n");
183 if (strstr(deviceInfo->name, d_device_name.c_str())){
184 fprintf(stderr," Chosen!\n");
186 fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(),
187 Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr);
189 deviceInfo = Pa_GetDeviceInfo(device);
190 i = numDevices; // force loop exit
193 fprintf(stderr,"\n"),fflush(stderr);
197 bail("Failed to find specified device name", 0);
203 d_output_parameters.device = device;
204 d_output_parameters.channelCount = deviceInfo->maxOutputChannels;
205 d_output_parameters.sampleFormat = SAMPLE_FORMAT;
206 d_output_parameters.suggestedLatency = deviceInfo->defaultLowOutputLatency;
207 d_output_parameters.hostApiSpecificStreamInfo = NULL;
209 // We fill in the real channelCount in check_topology when we know
210 // how many inputs are connected to us.
212 // Now that we know the maximum number of channels (allegedly)
213 // supported by the h/w, we can compute a reasonable input
214 // signature. The portaudio specs say that they'll accept any
215 // number of channels from 1 to max.
216 set_input_signature(gr_make_io_signature(1, deviceInfo->maxOutputChannels,
222 audio_portaudio_sink::check_topology (int ninputs, int noutputs)
226 if (Pa_IsStreamActive(d_stream))
228 Pa_CloseStream(d_stream);
230 d_reader.reset(); // boost::shared_ptr for d_reader = 0
231 d_writer.reset(); // boost::shared_ptr for d_write = 0
234 d_output_parameters.channelCount = ninputs; // # of channels we're really using
237 d_portaudio_buffer_size_frames = (int)(0.0213333333 * d_sampling_rate + 0.5); // Force 1024 frame buffers at 48000
238 fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms
239 0.0213333333, (double)d_sampling_rate);
241 err = Pa_OpenStream(&d_stream,
243 &d_output_parameters,
245 d_portaudio_buffer_size_frames,
247 &portaudio_sink_callback,
250 if (err != paNoError) {
251 output_error_msg ("OpenStream failed", err);
256 const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream);
258 d_portaudio_buffer_size_frames = (int)(d_output_parameters.suggestedLatency * psi->sampleRate);
259 fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n",
260 d_output_parameters.suggestedLatency, psi->sampleRate);
263 fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames);
265 assert(d_portaudio_buffer_size_frames != 0);
269 err = Pa_StartStream(d_stream);
270 if (err != paNoError) {
271 output_error_msg ("StartStream failed", err);
278 audio_portaudio_sink::~audio_portaudio_sink ()
280 Pa_StopStream(d_stream); // wait for output to drain
281 Pa_CloseStream(d_stream);
286 * This version consumes everything sent to it, blocking if required.
287 * I think this will allow us better control of the total buffering/latency
291 audio_portaudio_sink::work (int noutput_items,
292 gr_vector_const_void_star &input_items,
293 gr_vector_void_star &output_items)
295 const float **in = (const float **) &input_items[0];
296 const unsigned nchan = d_output_parameters.channelCount; // # of channels == samples/frame
299 for (k = 0; k < noutput_items; ){
301 int nframes = d_writer->space_available() / nchan; // How much space in ringbuffer
302 if (nframes == 0){ // no room...
304 d_ringbuffer_ready.wait(); // block here, then try again
308 // There's no room and we're not allowed to block.
309 // (A USRP is most likely controlling the pacing through the pipeline.)
310 // We drop the samples on the ground, and say we processed them all ;)
312 // FIXME, there's probably room for a bit more finesse here.
313 return noutput_items;
317 // We can write the smaller of the request and the room we've got
318 int nf = std::min(noutput_items - k, nframes);
320 float *p = (float *) d_writer->write_pointer();
321 for (int i = 0; i < nf; i++){
322 for (unsigned int c = 0; c < nchan; c++){
326 d_writer->update_write_pointer(nf * nchan);
330 return k; // tell how many we actually did
334 audio_portaudio_sink::output_error_msg (const char *msg, int err)
336 fprintf (stderr, "audio_portaudio_sink[%s]: %s: %s\n",
337 d_device_name.c_str (), msg, Pa_GetErrorText(err));
341 audio_portaudio_sink::bail (const char *msg, int err) throw (std::runtime_error)
343 output_error_msg (msg, err);
344 throw std::runtime_error ("audio_portaudio_sink");