Removing warnings in portaudio source/sink.
[debian/gnuradio] / gr-audio-portaudio / src / audio_portaudio_sink.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2006,2010 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_sink.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_output_device", "");
49 }
50
51 void
52 audio_portaudio_sink::create_ringbuffer(void)
53 {
54   int bufsize_samples = d_portaudio_buffer_size_frames * d_output_parameters.channelCount;
55   
56   if (d_verbose)
57     fprintf(stderr,"ring buffer size  = %d frames\n",
58             N_BUFFERS*bufsize_samples/d_output_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 write framesPerBuffer frames into outputBuffer.
71  */
72 int
73 portaudio_sink_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_sink *self = (audio_portaudio_sink *)arg;
81   int nreqd_samples =
82     framesPerBuffer * self->d_output_parameters.channelCount;
83
84   int navail_samples = self->d_reader->items_available();
85   
86   if (nreqd_samples <= navail_samples) {  // We've got enough data...
87     {
88       gruel::scoped_lock guard(self->d_ringbuffer_mutex);
89
90       memcpy(outputBuffer,
91              self->d_reader->read_pointer(),
92              nreqd_samples * sizeof(sample_t));
93       self->d_reader->update_read_pointer(nreqd_samples);
94
95       self->d_ringbuffer_ready = true;
96     }
97
98     // Tell the sink thread there is new room in the ringbuffer.
99     self->d_ringbuffer_cond.notify_one();
100     return paContinue;
101   }
102
103   else {                        // underrun
104     self->d_nunderuns++;
105     ssize_t r = ::write(2, "aU", 2);    // FIXME change to non-blocking call
106     if(r == -1) {
107       perror("audio_portaudio_source::portaudio_source_callback write error to stderr.");
108     }
109
110     // FIXME we should transfer what we've got and pad the rest
111     memset(outputBuffer, 0, nreqd_samples * sizeof(sample_t));
112
113     self->d_ringbuffer_ready = true;
114     self->d_ringbuffer_cond.notify_one();  // Tell the sink to get going!
115
116     return paContinue;
117   }
118 }
119
120
121 // ----------------------------------------------------------------
122
123 audio_portaudio_sink_sptr
124 audio_portaudio_make_sink (int sampling_rate, const std::string dev, bool ok_to_block)
125 {
126   return gnuradio::get_initial_sptr(new audio_portaudio_sink (sampling_rate,
127                                                               dev, ok_to_block));
128 }
129
130 audio_portaudio_sink::audio_portaudio_sink(int sampling_rate,
131                                            const std::string device_name,
132                                            bool ok_to_block)
133   : gr_sync_block ("audio_portaudio_sink",
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),
141     d_stream(0),
142     d_ringbuffer_mutex(),
143     d_ringbuffer_cond(),
144     d_ringbuffer_ready(false),
145     d_nunderuns(0)
146 {
147   memset(&d_output_parameters, 0, sizeof(d_output_parameters));
148   //if (LOGGING)
149   //  d_log = gri_logger::singleton();
150
151   PaError             err;
152   int                 i, numDevices;
153   PaDeviceIndex       device = 0;
154   const PaDeviceInfo *deviceInfo = NULL;
155
156   err = Pa_Initialize();
157   if (err != paNoError) {
158     bail ("Initialize failed", err);
159   }
160
161   if (d_verbose)
162     gri_print_devices();
163
164   numDevices = Pa_GetDeviceCount();
165   if (numDevices < 0)
166     bail("Pa Device count failed", 0);
167   if (numDevices == 0)
168     bail("no devices available", 0);
169
170   if (d_device_name.empty()) 
171   {
172     // FIXME Get smarter about picking something
173     fprintf(stderr,"\nUsing Default Device\n");
174     device = Pa_GetDefaultOutputDevice();
175     deviceInfo = Pa_GetDeviceInfo(device);
176     fprintf(stderr,"%s is the chosen device using %s as the host\n",
177             deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
178   }
179   else
180   {
181     bool found = false;
182     fprintf(stderr,"\nTest Devices\n");
183     for (i=0;i<numDevices;i++) {
184       deviceInfo = Pa_GetDeviceInfo( i );
185       fprintf(stderr,"Testing device name: %s",deviceInfo->name);
186       if (deviceInfo->maxOutputChannels <= 0) {
187         fprintf(stderr,"\n");
188         continue;
189       }
190       if (strstr(deviceInfo->name, d_device_name.c_str())){
191         fprintf(stderr,"  Chosen!\n");
192         device = i;
193         fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(),
194                 Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr);
195         found = true;
196         deviceInfo = Pa_GetDeviceInfo(device);
197         i = numDevices;         // force loop exit
198       }
199       else
200         fprintf(stderr,"\n"),fflush(stderr);
201     }
202
203     if (!found){
204       bail("Failed to find specified device name", 0);
205       exit(1);
206     }
207   }
208
209
210   d_output_parameters.device = device;
211   d_output_parameters.channelCount     = deviceInfo->maxOutputChannels;
212   d_output_parameters.sampleFormat     = SAMPLE_FORMAT;
213   d_output_parameters.suggestedLatency = deviceInfo->defaultLowOutputLatency;
214   d_output_parameters.hostApiSpecificStreamInfo = NULL;
215
216   // We fill in the real channelCount in check_topology when we know
217   // how many inputs are connected to us.
218
219   // Now that we know the maximum number of channels (allegedly)
220   // supported by the h/w, we can compute a reasonable input
221   // signature.  The portaudio specs say that they'll accept any
222   // number of channels from 1 to max.
223   set_input_signature(gr_make_io_signature(1, deviceInfo->maxOutputChannels,
224                                            sizeof (sample_t)));
225 }
226
227
228 bool
229 audio_portaudio_sink::check_topology (int ninputs, int noutputs)
230 {
231   PaError err;
232
233   if (Pa_IsStreamActive(d_stream))
234   {
235       Pa_CloseStream(d_stream);
236       d_stream = 0;
237       d_reader.reset();         // boost::shared_ptr for d_reader = 0
238       d_writer.reset();         // boost::shared_ptr for d_write = 0
239   }
240
241   d_output_parameters.channelCount = ninputs;   // # of channels we're really using
242
243 #if 1
244   d_portaudio_buffer_size_frames = (int)(0.0213333333  * d_sampling_rate + 0.5);  // Force 1024 frame buffers at 48000
245   fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms
246           0.0213333333, (double)d_sampling_rate);
247 #endif
248   err = Pa_OpenStream(&d_stream,
249                       NULL,                     // No input
250                       &d_output_parameters,
251                       d_sampling_rate,
252                       d_portaudio_buffer_size_frames,
253                       paClipOff,
254                       &portaudio_sink_callback,
255                       (void*)this);
256
257   if (err != paNoError) {
258     output_error_msg ("OpenStream failed", err);
259     return false;
260   }
261
262 #if 0  
263   const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream);
264
265   d_portaudio_buffer_size_frames = (int)(d_output_parameters.suggestedLatency  * psi->sampleRate);
266   fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n",
267           d_output_parameters.suggestedLatency, psi->sampleRate);
268 #endif
269
270   fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames);
271
272   assert(d_portaudio_buffer_size_frames != 0);
273
274   create_ringbuffer();
275
276   err = Pa_StartStream(d_stream);
277   if (err != paNoError) {
278     output_error_msg ("StartStream failed", err);
279     return false;
280   }
281
282   return true;
283 }
284
285 audio_portaudio_sink::~audio_portaudio_sink ()
286 {
287   Pa_StopStream(d_stream);      // wait for output to drain
288   Pa_CloseStream(d_stream);
289   Pa_Terminate();
290 }
291
292 /*
293  * This version consumes everything sent to it, blocking if required.
294  * I think this will allow us better control of the total buffering/latency
295  * in the audio path.
296  */
297 int
298 audio_portaudio_sink::work (int noutput_items,
299                             gr_vector_const_void_star &input_items,
300                             gr_vector_void_star &output_items)
301 {
302   const float **in = (const float **) &input_items[0];
303   const unsigned nchan = d_output_parameters.channelCount; // # of channels == samples/frame
304
305   int k;
306
307   for (k = 0; k < noutput_items; ){
308     int nframes = d_writer->space_available() / nchan;  // How much space in ringbuffer
309     if (nframes == 0){                  // no room...
310       if (d_ok_to_block){
311         {
312           gruel::scoped_lock guard(d_ringbuffer_mutex);
313           while (!d_ringbuffer_ready)
314             d_ringbuffer_cond.wait(guard);
315         }
316
317         continue;
318       }
319       else {
320         // There's no room and we're not allowed to block.
321         // (A USRP is most likely controlling the pacing through the pipeline.)
322         // We drop the samples on the ground, and say we processed them all ;)
323         //
324         // FIXME, there's probably room for a bit more finesse here.
325         return noutput_items;
326       }
327     }
328
329     // We can write the smaller of the request and the room we've got
330     {
331       gruel::scoped_lock guard(d_ringbuffer_mutex);
332
333       int nf = std::min(noutput_items - k, nframes);
334       float *p = (float *) d_writer->write_pointer();
335       
336       for (int i = 0; i < nf; i++)
337         for (unsigned int c = 0; c < nchan; c++)
338           *p++ = in[c][k + i];
339       
340       d_writer->update_write_pointer(nf * nchan);
341       k += nf;
342
343       d_ringbuffer_ready = false;
344     }
345   }
346
347   return k;  // tell how many we actually did
348 }
349
350 void
351 audio_portaudio_sink::output_error_msg (const char *msg, int err)
352 {
353   fprintf (stderr, "audio_portaudio_sink[%s]: %s: %s\n",
354            d_device_name.c_str (), msg, Pa_GetErrorText(err));
355 }
356
357 void
358 audio_portaudio_sink::bail (const char *msg, int err) throw (std::runtime_error)
359 {
360   output_error_msg (msg, err);
361   throw std::runtime_error ("audio_portaudio_sink");
362 }