UTF8 encode windows device names - potential fix for #6418
[ardour.git] / libs / backends / portaudio / portaudio_io.cc
1 /*
2  * Copyright (C) 2015 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <assert.h>
23 #include <glibmm.h>
24 #include "portaudio_io.h"
25
26 #define INTERLEAVED_INPUT
27 #define INTERLEAVED_OUTPUT
28
29 using namespace ARDOUR;
30
31 PortAudioIO::PortAudioIO ()
32         : _state (-1)
33         , _initialized (false)
34         , _capture_channels (0)
35         , _playback_channels (0)
36         , _stream (0)
37         , _input_buffer (0)
38         , _output_buffer (0)
39         , _cur_sample_rate (0)
40         , _cur_input_latency (0)
41         , _cur_output_latency (0)
42 {
43 }
44
45 PortAudioIO::~PortAudioIO ()
46 {
47         if (_state == 0) {
48                 pcm_stop();
49         }
50         if (_initialized) {
51                 Pa_Terminate();
52         }
53
54         for (std::map<int, paDevice*>::const_iterator i = _devices.begin (); i != _devices.end(); ++i) {
55                 delete i->second;
56         }
57         _devices.clear();
58
59         free (_input_buffer); _input_buffer = NULL;
60         free (_output_buffer); _output_buffer = NULL;
61 }
62
63
64 int
65 PortAudioIO::available_sample_rates(int device_id, std::vector<float>& sampleRates)
66 {
67         static const float ardourRates[] = { 8000.0, 22050.0, 24000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0};
68
69         assert(_initialized);
70
71         // TODO use  separate int device_input, int device_output ?!
72         if (device_id == -1) {
73                 device_id = Pa_GetDefaultInputDevice();
74         }
75 #ifndef NDEBUG
76         printf("PortAudio: Querying Samplerates for device %d\n", device_id);
77 #endif
78
79         sampleRates.clear();
80         const PaDeviceInfo* nfo = Pa_GetDeviceInfo(device_id);
81
82         if (nfo) {
83                 PaStreamParameters inputParam;
84                 PaStreamParameters outputParam;
85
86                 inputParam.device = device_id;
87                 inputParam.channelCount = nfo->maxInputChannels;
88                 inputParam.sampleFormat = paFloat32;
89                 inputParam.suggestedLatency = 0;
90                 inputParam.hostApiSpecificStreamInfo = 0;
91
92                 outputParam.device = device_id;
93                 outputParam.channelCount = nfo->maxOutputChannels;
94                 outputParam.sampleFormat = paFloat32;
95                 outputParam.suggestedLatency = 0;
96                 outputParam.hostApiSpecificStreamInfo = 0;
97
98                 for (uint32_t i = 0; i < sizeof(ardourRates)/sizeof(float); ++i) {
99                         if (paFormatIsSupported == Pa_IsFormatSupported(
100                                                 nfo->maxInputChannels > 0 ? &inputParam : NULL,
101                                                 nfo->maxOutputChannels > 0 ? &outputParam : NULL,
102                                                 ardourRates[i])) {
103                                 sampleRates.push_back (ardourRates[i]);
104                         }
105                 }
106         }
107
108         if (sampleRates.empty()) {
109                 // fill in something..
110                 sampleRates.push_back (44100.0);
111                 sampleRates.push_back (48000.0);
112         }
113
114         return 0;
115 }
116
117 int
118 PortAudioIO::available_buffer_sizes(int device_id, std::vector<uint32_t>& bufferSizes)
119 {
120         // TODO
121         static const uint32_t ardourSizes[] = { 64, 128, 256, 512, 1024, 2048, 4096 };
122         for(uint32_t i = 0; i < sizeof(ardourSizes)/sizeof(uint32_t); ++i) {
123                 bufferSizes.push_back (ardourSizes[i]);
124         }
125         return 0;
126 }
127
128 void
129 PortAudioIO::device_list (std::map<int, std::string> &devices) const {
130         devices.clear();
131         for (std::map<int, paDevice*>::const_iterator i = _devices.begin (); i != _devices.end(); ++i) {
132                 devices.insert (std::pair<int, std::string> (i->first, Glib::locale_to_utf8(i->second->name)));
133         }
134 }
135
136 void
137 PortAudioIO::discover()
138 {
139         for (std::map<int, paDevice*>::const_iterator i = _devices.begin (); i != _devices.end(); ++i) {
140                 delete i->second;
141         }
142         _devices.clear();
143         
144         PaError err = paNoError;
145
146         if (!_initialized) {
147                 err = Pa_Initialize();
148         }
149         if (err != paNoError) {
150                 return;
151         }
152
153         _initialized = true;
154
155         {
156                 const PaDeviceInfo* nfo_i = Pa_GetDeviceInfo(Pa_GetDefaultInputDevice());
157                 const PaDeviceInfo* nfo_o = Pa_GetDeviceInfo(Pa_GetDefaultOutputDevice());
158                 if (nfo_i && nfo_o) {
159                         _devices.insert (std::pair<int, paDevice*> (-1,
160                                                 new paDevice("Default",
161                                                         nfo_i->maxInputChannels,
162                                                         nfo_o->maxOutputChannels
163                                                         )));
164                 }
165         }
166
167         int n_devices = Pa_GetDeviceCount();
168 #ifndef NDEBUG
169         printf("PortAudio %d devices found:\n", n_devices);
170 #endif
171
172         for (int i = 0 ; i < n_devices; ++i) {
173                 const PaDeviceInfo* nfo = Pa_GetDeviceInfo(i);
174                 if (!nfo) continue;
175 #ifndef NDEBUG
176                 printf(" (%d) '%s' in: %d (lat: %.1f .. %.1f) out: %d (lat: %.1f .. %.1f) sr:%.2f\n",
177                                 i, nfo->name,
178                                 nfo->maxInputChannels,
179                                 nfo->defaultLowInputLatency * 1e3,
180                                 nfo->defaultHighInputLatency * 1e3,
181                                 nfo->maxOutputChannels,
182                                 nfo->defaultLowOutputLatency * 1e3,
183                                 nfo->defaultHighOutputLatency * 1e3,
184                                 nfo->defaultSampleRate);
185 #endif
186                 if ( nfo->maxInputChannels == 0 && nfo->maxOutputChannels == 0) {
187                         continue;
188                 }
189                 _devices.insert (std::pair<int, paDevice*> (i, new paDevice(
190                                                 nfo->name,
191                                                 nfo->maxInputChannels,
192                                                 nfo->maxOutputChannels
193                                                 )));
194         }
195 }
196
197 void
198 PortAudioIO::pcm_stop ()
199 {
200         if (_stream) {
201                 Pa_CloseStream (_stream);
202         }
203         _stream = NULL;
204
205         _capture_channels = 0;
206         _playback_channels = 0;
207         _cur_sample_rate = 0;
208         _cur_input_latency = 0;
209         _cur_output_latency = 0;
210
211         free (_input_buffer); _input_buffer = NULL;
212         free (_output_buffer); _output_buffer = NULL;
213         _state = -1;
214 }
215
216 int
217 PortAudioIO::pcm_start()
218 {
219         PaError err = Pa_StartStream (_stream);
220
221         if (err != paNoError) {
222                 _state = -1;
223                 return -1;
224         }
225         return 0;
226 }
227
228 #ifdef __APPLE__
229 static uint32_t lower_power_of_two (uint32_t v) {
230         v--;
231         v |= v >> 1;
232         v |= v >> 2;
233         v |= v >> 4;
234         v |= v >> 8;
235         v |= v >> 16;
236         v++;
237         return v >> 1;
238 }
239 #endif
240
241 int
242 PortAudioIO::pcm_setup (
243                 int device_input, int device_output,
244                 double sample_rate, uint32_t samples_per_period)
245 {
246         _state = -2;
247
248         // TODO error reporting sans fprintf()
249
250         PaError err = paNoError;
251         const PaDeviceInfo *nfo_in;
252         const PaDeviceInfo *nfo_out;
253         const PaStreamInfo *nfo_s;
254                 
255         if (!_initialized) {
256                 err = Pa_Initialize();
257         }
258         if (err != paNoError) {
259                 fprintf(stderr, "PortAudio Initialization Failed\n");
260                 goto error;
261         }
262         _initialized = true;
263
264
265         if (device_input == -1) {
266                 device_input = Pa_GetDefaultInputDevice();
267         }
268         if (device_output == -1) {
269                 device_output = Pa_GetDefaultOutputDevice();
270         }
271
272         _capture_channels = 0;
273         _playback_channels = 0;
274         _cur_sample_rate = 0;
275         _cur_input_latency = 0;
276         _cur_output_latency = 0;
277
278 #ifndef NDEBUG
279         printf("PortAudio Device IDs: i:%d o:%d\n", device_input, device_output);
280 #endif
281
282         nfo_in = Pa_GetDeviceInfo(device_input);
283         nfo_out = Pa_GetDeviceInfo(device_output);
284
285         if (!nfo_in && ! nfo_out) {
286                 fprintf(stderr, "PortAudio Cannot Query Device Info\n");
287                 goto error;
288         }
289
290         if (nfo_in) {
291                 _capture_channels = nfo_in->maxInputChannels;
292         }
293         if (nfo_out) {
294                 _playback_channels = nfo_out->maxOutputChannels;
295         }
296
297         if(_capture_channels == 0 && _playback_channels == 0) {
298                 fprintf(stderr, "PortAudio no Input and no output channels.\n");
299                 goto error;
300         }
301
302
303 #ifdef __APPLE__
304         // pa_mac_core_blocking.c pa_stable_v19_20140130
305         // BUG: ringbuffer alloc requires power-of-two chn count.
306         if ((_capture_channels & (_capture_channels - 1)) != 0) {
307                 printf("Adjusted capture channes to power of two (portaudio rb bug)\n");
308                 _capture_channels = lower_power_of_two (_capture_channels);
309         }
310
311         if ((_playback_channels & (_playback_channels - 1)) != 0) {
312                 printf("Adjusted capture channes to power of two (portaudio rb bug)\n");
313                 _playback_channels = lower_power_of_two (_playback_channels);
314         }
315 #endif
316         
317 #ifndef NDEBUG
318         printf("PortAudio Channels: in:%d out:%d\n",
319                         _capture_channels, _playback_channels);
320 #endif
321
322         PaStreamParameters inputParam;
323         PaStreamParameters outputParam;
324
325         if (nfo_in) {
326                 inputParam.device = device_input;
327                 inputParam.channelCount = _capture_channels;
328 #ifdef INTERLEAVED_INPUT
329                 inputParam.sampleFormat = paFloat32;
330 #else
331                 inputParam.sampleFormat = paFloat32 | paNonInterleaved;
332 #endif
333                 inputParam.suggestedLatency = nfo_in->defaultLowInputLatency;
334                 inputParam.hostApiSpecificStreamInfo = NULL;
335         }
336
337         if (nfo_out) {
338                 outputParam.device = device_output;
339                 outputParam.channelCount = _playback_channels;
340 #ifdef INTERLEAVED_OUTPUT
341                 outputParam.sampleFormat = paFloat32;
342 #else
343                 outputParam.sampleFormat = paFloat32 | paNonInterleaved;
344 #endif
345                 outputParam.suggestedLatency = nfo_out->defaultLowOutputLatency;
346                 outputParam.hostApiSpecificStreamInfo = NULL;
347         }
348
349         // XXX re-consider using callback API, testing needed.
350         err = Pa_OpenStream (
351                         &_stream,
352                         _capture_channels > 0 ? &inputParam: NULL,
353                         _playback_channels > 0 ? &outputParam: NULL,
354                         sample_rate,
355                         samples_per_period,
356                         paClipOff | paDitherOff,
357                         NULL, NULL);
358
359         if (err != paNoError) {
360                 fprintf(stderr, "PortAudio failed to start stream.\n");
361                 goto error;
362         }
363
364         nfo_s = Pa_GetStreamInfo (_stream);
365         if (!nfo_s) {
366                 fprintf(stderr, "PortAudio failed to query stream information.\n");
367                 pcm_stop();
368                 goto error;
369         }
370
371         _cur_sample_rate = nfo_s->sampleRate;
372         _cur_input_latency = nfo_s->inputLatency * _cur_sample_rate;
373         _cur_output_latency = nfo_s->outputLatency * _cur_sample_rate;
374
375 #ifndef NDEBUG
376         printf("PA Sample Rate  %.1f SPS\n", _cur_sample_rate);
377         printf("PA Input Latency  %.1fms  %d spl\n", 1e3 * nfo_s->inputLatency, _cur_input_latency);
378         printf("PA Output Latency %.1fms  %d spl\n", 1e3 * nfo_s->outputLatency, _cur_output_latency);
379 #endif
380
381         _state = 0;
382
383         if (_capture_channels > 0) {
384                 _input_buffer = (float*) malloc (samples_per_period * _capture_channels * sizeof(float));
385                 if (!_input_buffer) {
386                         fprintf(stderr, "PortAudio failed to allocate input buffer.\n");
387                         pcm_stop();
388                         goto error;
389                 }
390         }
391
392         if (_playback_channels > 0) {
393                 _output_buffer = (float*) calloc (samples_per_period * _playback_channels, sizeof(float));
394                 if (!_output_buffer) {
395                         fprintf(stderr, "PortAudio failed to allocate output buffer.\n");
396                         pcm_stop();
397                         goto error;
398                 }
399         }
400
401         return 0;
402
403 error:
404         _capture_channels = 0;
405         _playback_channels = 0;
406         free (_input_buffer); _input_buffer = NULL;
407         free (_output_buffer); _output_buffer = NULL;
408         Pa_Terminate();
409         return -1;
410 }
411
412 int
413 PortAudioIO::next_cycle (uint32_t n_samples)
414 {
415         bool xrun = false;
416         PaError err;
417         err = Pa_IsStreamActive (_stream);
418         if (err != 1) {
419                 //   0: inactive / aborted
420                 // < 0: error
421                 return -1;
422         }
423
424         // TODO, check drift..  process part with larger capacity first.
425         // Pa_GetStreamReadAvailable(_stream) < Pa_GetStreamWriteAvailable(_stream)
426
427         if (_playback_channels > 0) {
428                 err = Pa_WriteStream (_stream, _output_buffer, n_samples);
429                 if (err) xrun = true;
430         }
431
432         if (_capture_channels > 0) {
433                 err = Pa_ReadStream (_stream, _input_buffer, n_samples);
434                 if (err) {
435                         memset (_input_buffer, 0, sizeof(float) * n_samples * _capture_channels);
436                         xrun = true;
437                 }
438         }
439
440
441         return xrun ? 1 : 0;
442 }
443
444
445 #ifdef INTERLEAVED_INPUT
446
447 int
448 PortAudioIO::get_capture_channel (uint32_t chn, float *input, uint32_t n_samples)
449 {
450         assert(chn < _capture_channels);
451         const uint32_t stride = _capture_channels;
452         float *ptr = _input_buffer + chn;
453         while (n_samples-- > 0) {
454                 *input++ = *ptr;
455                 ptr += stride;
456         }
457         return 0;
458 }
459
460 #else
461
462 int
463 PortAudioIO::get_capture_channel (uint32_t chn, float *input, uint32_t n_samples)
464 {
465         assert(chn < _capture_channels);
466         memcpy((void*)input, &(_input_buffer[chn * n_samples]), n_samples * sizeof(float));
467         return 0;
468 }
469
470 #endif
471
472
473 #ifdef INTERLEAVED_OUTPUT
474
475 int
476 PortAudioIO::set_playback_channel (uint32_t chn, const float *output, uint32_t n_samples)
477 {
478         assert(chn < _playback_channels);
479         const uint32_t stride = _playback_channels;
480         float *ptr = _output_buffer + chn;
481         while (n_samples-- > 0) {
482                 *ptr = *output++;
483                 ptr += stride;
484         }
485         return 0;
486 }
487
488 #else
489
490 int
491 PortAudioIO::set_playback_channel (uint32_t chn, const float *output, uint32_t n_samples)
492 {
493         assert(chn < _playback_channels);
494         memcpy((void*)&(_output_buffer[chn * n_samples]), (void*)output, n_samples * sizeof(float));
495         return 0;
496 }
497
498 #endif