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_sink.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_output_device", "");
53 audio_portaudio_sink::create_ringbuffer(void)
55 int bufsize_samples = d_portaudio_buffer_size_frames * d_output_parameters.channelCount;
58 fprintf(stderr,"ring buffer size = %d frames\n",
59 N_BUFFERS*bufsize_samples/d_output_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 write framesPerBuffer frames into outputBuffer.
74 portaudio_sink_callback (const void *inputBuffer,
76 unsigned long framesPerBuffer,
77 const PaStreamCallbackTimeInfo* timeInfo,
78 PaStreamCallbackFlags statusFlags,
81 audio_portaudio_sink *self = (audio_portaudio_sink *)arg;
83 framesPerBuffer * self->d_output_parameters.channelCount;
85 int navail_samples = self->d_reader->items_available();
87 if (nreqd_samples <= navail_samples){ // We've got enough data...
89 // self->d_log->printf("PAsink cb: f/b = %4ld\n", framesPerBuffer);
90 // copy from ringbuffer into output buffer
92 self->d_reader->read_pointer(),
93 nreqd_samples * sizeof(sample_t));
94 self->d_reader->update_read_pointer(nreqd_samples);
96 // Tell the sink thread there is new room in the ringbuffer.
97 self->d_ringbuffer_ready.post();
103 // self->d_log->printf("PAsink cb: f/b = %4ld UNDERRUN\n", framesPerBuffer);
106 ::write(2, "aU", 2); // FIXME change to non-blocking call
108 // FIXME we should transfer what we've got and pad the rest
109 memset(outputBuffer, 0, nreqd_samples * sizeof(sample_t));
111 self->d_ringbuffer_ready.post(); // Tell the sink to get going!
117 // ----------------------------------------------------------------
119 audio_portaudio_sink_sptr
120 audio_portaudio_make_sink (int sampling_rate, const std::string dev, bool ok_to_block)
122 return audio_portaudio_sink_sptr (new audio_portaudio_sink (sampling_rate,
126 audio_portaudio_sink::audio_portaudio_sink(int sampling_rate,
127 const std::string device_name,
129 : gr_sync_block ("audio_portaudio_sink",
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),
138 d_ringbuffer_ready(1, 1), // binary semaphore
141 memset(&d_output_parameters, 0, sizeof(d_output_parameters));
143 // d_log = gri_logger::singleton();
147 PaDeviceIndex device = 0;
148 const PaDeviceInfo *deviceInfo = NULL;
150 err = Pa_Initialize();
151 if (err != paNoError) {
152 bail ("Initialize failed", err);
158 numDevices = Pa_GetDeviceCount();
160 bail("Pa Device count failed", 0);
162 bail("no devices available", 0);
164 if (d_device_name.empty())
166 // FIXME Get smarter about picking something
167 fprintf(stderr,"\nUsing Default Device\n");
168 device = Pa_GetDefaultOutputDevice();
169 deviceInfo = Pa_GetDeviceInfo(device);
170 fprintf(stderr,"%s is the chosen device using %s as the host\n",
171 deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
176 fprintf(stderr,"\nTest Devices\n");
177 for (i=0;i<numDevices;i++) {
178 deviceInfo = Pa_GetDeviceInfo( i );
179 fprintf(stderr,"Testing device name: %s",deviceInfo->name);
180 if (deviceInfo->maxOutputChannels <= 0) {
181 fprintf(stderr,"\n");
184 if (strstr(deviceInfo->name, d_device_name.c_str())){
185 fprintf(stderr," Chosen!\n");
187 fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(),
188 Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr);
190 deviceInfo = Pa_GetDeviceInfo(device);
191 i = numDevices; // force loop exit
194 fprintf(stderr,"\n"),fflush(stderr);
198 bail("Failed to find specified device name", 0);
204 d_output_parameters.device = device;
205 d_output_parameters.channelCount = deviceInfo->maxOutputChannels;
206 d_output_parameters.sampleFormat = SAMPLE_FORMAT;
207 d_output_parameters.suggestedLatency = deviceInfo->defaultLowOutputLatency;
208 d_output_parameters.hostApiSpecificStreamInfo = NULL;
210 // We fill in the real channelCount in check_topology when we know
211 // how many inputs are connected to us.
213 // Now that we know the maximum number of channels (allegedly)
214 // supported by the h/w, we can compute a reasonable input
215 // signature. The portaudio specs say that they'll accept any
216 // number of channels from 1 to max.
217 set_input_signature(gr_make_io_signature(1, deviceInfo->maxOutputChannels,
223 audio_portaudio_sink::check_topology (int ninputs, int noutputs)
227 if (Pa_IsStreamActive(d_stream))
229 Pa_CloseStream(d_stream);
231 d_reader.reset(); // boost::shared_ptr for d_reader = 0
232 d_writer.reset(); // boost::shared_ptr for d_write = 0
235 d_output_parameters.channelCount = ninputs; // # of channels we're really using
238 d_portaudio_buffer_size_frames = (int)(0.0213333333 * d_sampling_rate + 0.5); // Force 1024 frame buffers at 48000
239 fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms
240 0.0213333333, (double)d_sampling_rate);
242 err = Pa_OpenStream(&d_stream,
244 &d_output_parameters,
246 d_portaudio_buffer_size_frames,
248 &portaudio_sink_callback,
251 if (err != paNoError) {
252 output_error_msg ("OpenStream failed", err);
257 const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream);
259 d_portaudio_buffer_size_frames = (int)(d_output_parameters.suggestedLatency * psi->sampleRate);
260 fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n",
261 d_output_parameters.suggestedLatency, psi->sampleRate);
264 fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames);
266 assert(d_portaudio_buffer_size_frames != 0);
270 err = Pa_StartStream(d_stream);
271 if (err != paNoError) {
272 output_error_msg ("StartStream failed", err);
279 audio_portaudio_sink::~audio_portaudio_sink ()
281 Pa_StopStream(d_stream); // wait for output to drain
282 Pa_CloseStream(d_stream);
287 * This version consumes everything sent to it, blocking if required.
288 * I think this will allow us better control of the total buffering/latency
292 audio_portaudio_sink::work (int noutput_items,
293 gr_vector_const_void_star &input_items,
294 gr_vector_void_star &output_items)
296 const float **in = (const float **) &input_items[0];
297 const unsigned nchan = d_output_parameters.channelCount; // # of channels == samples/frame
300 for (k = 0; k < noutput_items; ){
302 int nframes = d_writer->space_available() / nchan; // How much space in ringbuffer
303 if (nframes == 0){ // no room...
305 d_ringbuffer_ready.wait(); // block here, then try again
309 // There's no room and we're not allowed to block.
310 // (A USRP is most likely controlling the pacing through the pipeline.)
311 // We drop the samples on the ground, and say we processed them all ;)
313 // FIXME, there's probably room for a bit more finesse here.
314 return noutput_items;
318 // We can write the smaller of the request and the room we've got
319 int nf = std::min(noutput_items - k, nframes);
321 float *p = (float *) d_writer->write_pointer();
322 for (int i = 0; i < nf; i++){
323 for (unsigned int c = 0; c < nchan; c++){
327 d_writer->update_write_pointer(nf * nchan);
331 return k; // tell how many we actually did
335 audio_portaudio_sink::output_error_msg (const char *msg, int err)
337 fprintf (stderr, "audio_portaudio_sink[%s]: %s: %s\n",
338 d_device_name.c_str (), msg, Pa_GetErrorText(err));
342 audio_portaudio_sink::bail (const char *msg, int err) throw (std::runtime_error)
344 output_error_msg (msg, err);
345 throw std::runtime_error ("audio_portaudio_sink");