Debian Codegraph @

src/host/chuck_audio.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // name: chuck_audio.cpp
28 // desc: chuck host digital audio I/O, using RtAudio
29 //
30 // author: Ge Wang ([email protected] | [email protected])
31 // Spencer Salazar ([email protected])
32 // RtAudio by: Gary Scavone
33 //
34 // date: Spring 2004 -- initial versions
35 // Fall 2017 -- REFACTOR-2017: clean up to be more modular
36 //-----------------------------------------------------------------------------
37 #include "chuck_audio.h"
38 #include "chuck_errmsg.h"
39 #include "util_string.h"
40 #include "util_thread.h"
41 #include "util_platforms.h"
42 #include <limits.h>
43 #include "rtmidi.h"
44
45 #if (defined(__PLATFORM_WINDOWS__) && !defined(__WINDOWS_PTHREAD__))
46 #include <windows.h>
47 #include <sys/timeb.h>
48 #else
49 #include <unistd.h>
50 #include <sys/time.h>
51 #endif
52
53
54 // sample
55 #if defined(__CHUCK_USE_64_BIT_SAMPLE__)
56 #define CK_RTAUDIO_FORMAT RTAUDIO_FLOAT64
57 #else
58 #define CK_RTAUDIO_FORMAT RTAUDIO_FLOAT32
59 #endif
60
61
62 // real-time watch dog
63 t_CKBOOL g_do_watchdog = FALSE;
64 // countermeasure
65 #ifdef __PLATFORM_APPLE__
66 t_CKUINT g_watchdog_countermeasure_priority = 10;
67 #elif defined(__PLATFORM_WINDOWS__) && !defined(__WINDOWS_PTHREAD__)
68 t_CKUINT g_watchdog_countermeasure_priority = THREAD_PRIORITY_LOWEST;
69 #else
70 t_CKUINT g_watchdog_countermeasure_priority = 0;
71 #endif
72 // watchdog timeout
73 t_CKFLOAT g_watchdog_timeout = 0.5;
74
75
76 // static initialization
77 t_CKBOOL ChuckAudio::m_init = FALSE;
78 t_CKBOOL ChuckAudio::m_start = FALSE;
79 t_CKBOOL ChuckAudio::m_go = FALSE;
80 t_CKBOOL ChuckAudio::m_silent = FALSE;
81 t_CKBOOL ChuckAudio::m_expand_in_mono2stereo= FALSE;
82 t_CKUINT ChuckAudio::m_num_channels_out = CK_NUM_CHANNELS_DEFAULT;
83 t_CKUINT ChuckAudio::m_num_channels_in = CK_NUM_CHANNELS_DEFAULT;
84 t_CKUINT ChuckAudio::m_num_channels_max = CK_NUM_CHANNELS_DEFAULT;
85 t_CKUINT ChuckAudio::m_sample_rate = CK_SAMPLE_RATE_DEFAULT;
86 t_CKUINT ChuckAudio::m_buffer_size = CK_BUFFER_SIZE_DEFAULT;
87 t_CKUINT ChuckAudio::m_num_buffers = CK_NUM_BUFFERS_DEFAULT;
88 SAMPLE * ChuckAudio::m_buffer_out = NULL;
89 SAMPLE * ChuckAudio::m_buffer_in = NULL;
90 SAMPLE * ChuckAudio::m_extern_in = NULL;
91 SAMPLE * ChuckAudio::m_extern_out = NULL;
92 t_CKINT ChuckAudio::m_dac_n = 0;
93 t_CKINT ChuckAudio::m_adc_n = 0;
94 std::string ChuckAudio::m_dac_name = "";
95 std::string ChuckAudio::m_adc_name = "";
96 std::string ChuckAudio::m_driver_name = "";
97 RtAudio * ChuckAudio::m_rtaudio = NULL;
98 ck_f_audio_cb ChuckAudio::m_audio_cb = NULL;
99 void * ChuckAudio::m_cb_user_data = NULL;
100
101
102
103
104 //-----------------------------------------------------------------------------
105 // global symbols expected from RtAudio | 1.5.0.1 (ge) added
106 //-----------------------------------------------------------------------------
107 extern "C" const unsigned int rtaudio_num_compiled_apis;
108 extern "C" const unsigned int rtaudio_compiled_apis[];
109 extern "C" const char* rtaudio_api_names[][2];
110
111
112
113
114 //-----------------------------------------------------------------------------
115 // name: driverNameToApi()
116 // desc: look up from driver name to API/driver
117 //-----------------------------------------------------------------------------
118 static RtAudio::Api driverNameToApi( const char * driver )
119 {
120 RtAudio::Api api = RtAudio::UNSPECIFIED;
121 if( driver )
122 {
123 // get lowercase version
124 std::string driverLower = ::tolower(::trim(driver));
125 // from what is available, match by driver name
126 #if defined(__WINDOWS_ASIO__)
127 if( driverLower == "asio" )
128 api = RtAudio::WINDOWS_ASIO;
129 #endif
130 #if defined(__WINDOWS_DS__)
131 if( driverLower == "ds" || driverLower == "directsound" )
132 api = RtAudio::WINDOWS_DS;
133 #endif
134 #if defined(__WINDOWS_WASAPI__)
135 if( driverLower == "wasapi" )
136 api = RtAudio::WINDOWS_WASAPI;
137 #endif
138 #if defined(__LINUX_ALSA__)
139 if( driverLower == "alsa" )
140 api = RtAudio::LINUX_ALSA;
141 #endif
142 #if defined(__LINUX_PULSE__)
143 if( driverLower == "pulse" )
144 api = RtAudio::LINUX_PULSE;
145 #endif
146 #if defined(__LINUX_OSS__)
147 if( driverLower == "oss" )
148 api = RtAudio::LINUX_OSS;
149 #endif
150 #if defined(__UNIX_JACK__)
151 if( driverLower == "jack" )
152 api = RtAudio::UNIX_JACK;
153 #endif
154 #if defined(__MACOSX_CORE__)
155 if( driverLower == "coreaudio" || driverLower == "core" )
156 api = RtAudio::MACOSX_CORE;
157 #endif
158
159 // check for Dummy
160 if( driverLower == "(dummy)" )
161 api = RtAudio::RTAUDIO_DUMMY;
162
163 // XXX: add swap between ALSA, PULSE, OSS? and JACK
164 if( api == RtAudio::UNSPECIFIED )
165 {
166 EM_error2( 0, "unsupported audio driver: %s", driver );
167 }
168 }
169
170 // 1.5.0.0 (nshaheed) If the audio driver is UNSPECIFIED then
171 // return a default driver. This will depend on OS and, in the
172 // case of linux, which drivers chuck is being compiled with.
173 if( api == RtAudio::UNSPECIFIED )
174 {
175 #if defined(__PLATFORM_WINDOWS__)
176 // traditional chuck default behavior:
177 // DirectSound is most general albeit high-latency
178 api = RtAudio::WINDOWS_DS;
179 #elif defined(__PLATFORM_LINUX__) && defined(__LINUX_ALSA__)
180 api = RtAudio::LINUX_ALSA;
181 #elif defined(__PLATFORM_LINUX__) && defined(__LINUX_PULSE__)
182 api = RtAudio::LINUX_PULSE;
183 #elif defined(__PLATFORM_LINUX__) && defined(__LINUX_OSS__)
184 api = RtAudio::LINUX_OSS;
185 #elif defined(__PLATFORM_LINUX__) && defined(__UNIX_JACK__)
186 api = RtAudio::UNIX_JACK;
187 #elif defined(__MACOSX_CORE__)
188 api = RtAudio::MACOSX_CORE;
189 #endif
190 }
191
192 return api;
193 }
194
195
196
197
198 //-----------------------------------------------------------------------------
199 // name: apiToDriverName()
200 // desc: get driver name from API
201 //-----------------------------------------------------------------------------
202 static const char * apiToDriverName( RtAudio::Api api )
203 {
204 static const char * const drivers[] = {
205 "(Unspecified)",
206 "ALSA",
207 "Pulse",
208 "OSS",
209 "Jack",
210 "CoreAudio",
211 "WASAPI",
212 "ASIO",
213 "DirectSound", // DirectSound
214 "(DUMMY)"
215 };
216
217 // cast and check
218 t_CKINT index = (t_CKINT)api;
219 if( index < 0 || index >= sizeof(drivers) / sizeof(const char *) ) return NULL;
220
221 // return
222 return drivers[index];
223 }
224
225
226
227
228 //-----------------------------------------------------------------------------
229 // name: print()
230 // desc: print info for an audio device
231 //-----------------------------------------------------------------------------
232 void print( const RtAudio::DeviceInfo & info )
233 {
234 EM_error2b( 0, "device name = \"%s\"", info.name.c_str() );
235 if (!info.probed)
236 EM_error2b( 0, "probe [failed]..." );
237 else
238 {
239 EM_error2b( 0, "probe [success]..." );
240 EM_error2b( 0, "# output channels = %d", info.outputChannels );
241 EM_error2b( 0, "# input channels = %d", info.inputChannels );
242 EM_error2b( 0, "# duplex Channels = %d", info.duplexChannels );
243 if( info.isDefaultOutput ) EM_error2b( 0, "default output = YES" );
244 else EM_error2b( 0, "default output = NO" );
245 if( info.isDefaultInput ) EM_error2b( 0, "default input = YES" );
246 else EM_error2b( 0, "default input = NO" );
247 if( info.nativeFormats == 0 ) EM_error2b( 0, "no natively supported data formats(?)!" );
248 else
249 {
250 EM_error2b( 0, "natively supported data formats:" );
251 if( info.nativeFormats & RTAUDIO_SINT8 ) EM_error2b( 0, " 8-bit int" );
252 if( info.nativeFormats & RTAUDIO_SINT16 ) EM_error2b( 0, " 16-bit int" );
253 if( info.nativeFormats & RTAUDIO_SINT24 ) EM_error2b( 0, " 24-bit int" );
254 if( info.nativeFormats & RTAUDIO_SINT32 ) EM_error2b( 0, " 32-bit int" );
255 if( info.nativeFormats & RTAUDIO_FLOAT32 ) EM_error2b( 0, " 32-bit float" );
256 if( info.nativeFormats & RTAUDIO_FLOAT64 ) EM_error2b( 0, " 64-bit float" );
257 }
258 if ( info.sampleRates.size() < 1 ) EM_error2b( 0,"no supported sample rates found!" );
259 else
260 {
261 EM_error2b( 0, "supported sample rates:" );
262 for( unsigned int j = 0; j < info.sampleRates.size(); j++ )
263 EM_error2b( 0, " %d Hz", info.sampleRates[j] );
264 }
265 }
266 }
267
268
269
270
271 //-----------------------------------------------------------------------------
272 // name: rtAudioErrorHandler()
273 // desc: the RtAudio error handler
274 //-----------------------------------------------------------------------------
275 static void rtAudioErrorHandler( RtAudioErrorType t, const std::string & errorText )
276 {
277 // check if empty string
278 if( errorText.empty() ) return;
279
280 // check if warning or not a warning
281 if( t == RTAUDIO_WARNING )
282 {
283 // output to warning log level
284 EM_log( CK_LOG_WARNING, "%s", errorText.c_str() );
285 }
286 else
287 {
288 // output as error
289 EM_error2( 0, "%s", errorText.c_str() );
290 // NOTE: problem finding audio devices, likely
291 }
292 }
293
294
295
296
297 //-----------------------------------------------------------------------------
298 // name: probe()
299 // desc: probe audio devices by driver
300 //-----------------------------------------------------------------------------
301 void ChuckAudio::probe( const char * driver )
302 {
303 // get the audio driver enum by name; handles driver == NULL case
304 RtAudio::Api api = driverNameToApi( driver );
305 // go back from driver enum to driver name
306 const char * dnm = apiToDriverName( api );
307 // rtaudio pointer
308 RtAudio * audio = NULL;
309 // device info struct
310 RtAudio::DeviceInfo info;
311
312 // allocate RtAudio
313 audio = new RtAudio( api, rtAudioErrorHandler );
314 if( !audio )
315 {
316 // error reported by our errorHandler
317 return;
318 }
319
320 // get count
321 int devices = audio->getDeviceCount();
322 EM_error2b( 0, "[%s] driver found %d audio device(s)...", TC::green(dnm,TRUE).c_str(), devices );
323 EM_error2b( 0, "" );
324
325 // reset -- what does this do
326 EM_reset_msg();
327
328 // loop over devices
329 for( int i = 0; i < devices; i++ )
330 {
331 info = audio->getDeviceInfo(i);
332 if (!info.probed) { // errorHandle reports issues above
333 EM_error2b(0, "");
334 EM_reset_msg();
335 continue;
336 }
337
338 // print
339 EM_print2blue( "------( audio device: %d )------", i+1 );
340 print( info );
341 // skip
342 if( i < devices ) EM_error2b( 0, "" );
343
344 // reset
345 EM_reset_msg();
346 }
347
348 // done
349 CK_SAFE_DELETE( audio );
350
351 return;
352 }
353
354
355
356
357 //-----------------------------------------------------------------------------
358 // name: device_named()
359 // desc: get device number by name; needs_dac/adc prompts further checks on
360 // requested device having > 0 channels
361 //-----------------------------------------------------------------------------
362 t_CKINT ChuckAudio::device_named( const char * driver,
363 const std::string & name,
364 t_CKBOOL needs_dac,
365 t_CKBOOL needs_adc )
366 {
367 // rtaudio pointer
368 RtAudio * audio = NULL;
369 // device info struct
370 RtAudio::DeviceInfo info;
371 RtAudio::Api api = driverNameToApi(driver); // handles driver=NULL case
372 // const char * dnm = apiToDriverName(api);
373
374 // allocate RtAudio
375 audio = new RtAudio(api, rtAudioErrorHandler);
376 if(!audio)
377 return -1; // reporting in errorHandler
378
379 // get count
380 int devices = audio->getDeviceCount();
381 int device_no = -1;
382
383 // loop
384 for( int i = 0; i < devices; i++ )
385 {
386 // get info
387 info = audio->getDeviceInfo(i);
388 if(!info.probed)
389 {
390 // reportError handles problem
391 break;
392 }
393
394 // compare name
395 if( info.name.compare(name) == 0 )
396 {
397 // found!
398 device_no = i+1;
399 break;
400 }
401 }
402
403 // not found, yet
404 if( device_no == -1 )
405 {
406 // no exact match found; try partial match
407 for( int i = 0; i < devices; i++ )
408 {
409 info = audio->getDeviceInfo(i);
410 if(!info.probed)
411 {
412 // errorHandler reports issues
413 break;
414 }
415
416 if( info.name.find(name) != std::string::npos )
417 {
418 // skip over ones with 0 channels, if needed
419 if( (needs_dac && info.outputChannels == 0) ||
420 (needs_adc && info.inputChannels == 0) )
421 continue;
422 // found
423 device_no = i+1;
424 break;
425 }
426 }
427 }
428
429 // clean up
430 CK_SAFE_DELETE( audio );
431
432 // done
433 return device_no;
434 }
435
436
437
438
439 //-----------------------------------------------------------------------------
440 // name: defaultDriverApi()
441 // desc: get default audio driver number, i.e., RtAudio::Api enum
442 //-----------------------------------------------------------------------------
443 RtAudio::Api ChuckAudio::defaultDriverApi()
444 {
445 return driverNameToApi( NULL );
446 }
447
448
449
450
451 //-----------------------------------------------------------------------------
452 // name: defaultDriverName()
453 // desc: get default audio driver name
454 //-----------------------------------------------------------------------------
455 const char * ChuckAudio::defaultDriverName()
456 {
457 return driverApiToName( defaultDriverApi() );
458 }
459
460
461
462
463 //-----------------------------------------------------------------------------
464 // name: driverNameToApi()
465 // desc: get API/driver enum
466 //-----------------------------------------------------------------------------
467 RtAudio::Api ChuckAudio::driverNameToApi( const char * driver )
468 {
469 // if empty string, make the pointer null, which will retrieve default
470 if( driver != NULL && driver[0] == '\0' ) driver = NULL;
471 // get the driver enum
472 return ::driverNameToApi( driver );
473 }
474
475
476
477
478 //-----------------------------------------------------------------------------
479 // name: driverApiToName()
480 // desc: get API/driver name
481 //-----------------------------------------------------------------------------
482 const char * ChuckAudio::driverApiToName( t_CKUINT num )
483 {
484 // pass it on
485 return apiToDriverName( (RtAudio::Api)num );
486 }
487
488
489
490
491 //-----------------------------------------------------------------------------
492 // name: numDrivers()
493 // desc: get number of compiled audio driver APIs
494 //-----------------------------------------------------------------------------
495 t_CKUINT ChuckAudio::numDrivers()
496 {
497 return (t_CKUINT)rtaudio_num_compiled_apis;
498 }
499
500
501
502
503 //-----------------------------------------------------------------------------
504 // name: getDriver()
505 // desc: get info on a particular driver
506 //-----------------------------------------------------------------------------
507 ChuckAudioDriverInfo ChuckAudio::getDriverInfo( t_CKUINT n )
508 {
509 // check
510 if( n >= numDrivers() ) return ChuckAudioDriverInfo();
511
512 ChuckAudioDriverInfo info;
513 info.driver = rtaudio_compiled_apis[n];
514 info.name = rtaudio_api_names[info.driver][0];
515 info.userFriendlyName = rtaudio_api_names[info.driver][1];
516
517 return info;
518 }
519
520
521
522
523 //-----------------------------------------------------------------------------
524 // name: get_current_time()
525 // desc: ...
526 //-----------------------------------------------------------------------------
527 static t_CKFLOAT get_current_time( t_CKBOOL fresh = TRUE )
528 {
529 #ifdef __PLATFORM_WINDOWS__
530 struct _timeb t;
531 _ftime(&t);
532 return t.time + t.millitm/1000.0;
533 #else
534 static struct timeval t;
535 if( fresh ) gettimeofday(&t,NULL);
536 return t.tv_sec + (t_CKFLOAT)t.tv_usec/1000000;
537 #endif
538 }
539
540
541
542
543 // watch dog globals
544 static CHUCK_THREAD g_tid_synthesis = 0;
545 static XThread * g_watchdog_thread = NULL;
546 static t_CKBOOL g_watchdog_state = FALSE;
547 static t_CKFLOAT g_watchdog_time = 0;
548
549
550
551
552 //-----------------------------------------------------------------------------
553 // name: watch_dog()
554 // desc: this sniff out possible non-time advancing infinite loops
555 //-----------------------------------------------------------------------------
556 #if !defined(__PLATFORM_WINDOWS__) || defined(__WINDOWS_PTHREAD__)
557 static void * watch_dog( void * )
558 #else
559 static unsigned int __stdcall watch_dog( void * )
560 #endif
561 {
562 // time
563 t_CKFLOAT time = 0;
564
565 // boost priority?
566 t_CKUINT priority = XThreadUtil::our_priority;
567
568 // log
569 EM_log( CK_LOG_HERALD, "starting real-time watch dog process..." );
570 // push log
571 EM_pushlog();
572 EM_log( CK_LOG_INFO, "watchdog timeout: %f::second", g_watchdog_timeout );
573 EM_log( CK_LOG_INFO, "watchdog thread priority: %d", priority );
574 EM_log( CK_LOG_INFO, "watchdog countermeasure priority: %d", g_watchdog_countermeasure_priority );
575 // pop log
576 EM_poplog();
577
578 // boost watchdog by same priority
579 if( XThreadUtil::our_priority != 0x7fffffff )
580 XThreadUtil::set_priority( priority );
581
582 // while going
583 while( g_do_watchdog )
584 {
585 // get
586 time = get_current_time( TRUE );
587 // CK_FPRINTF_STDERR( "last: %f now: %f\n", g_watchdog_time, time );
588
589 // resting
590 if( g_watchdog_state == FALSE )
591 {
592 // check time vs timeout
593 if( time - g_watchdog_time > g_watchdog_timeout )
594 {
595 // log
596 EM_log( CK_LOG_HERALD, "real-time watchdog counter-measure activating..." );
597 // lowering priority
598 if( g_tid_synthesis && XThreadUtil::our_priority != 0x7fffffff )
599 XThreadUtil::set_priority( g_tid_synthesis, g_watchdog_countermeasure_priority );
600 // set state
601 g_watchdog_state = TRUE;
602 }
603 }
604 else
605 {
606 // check time vs timeout
607 if( time - g_watchdog_time < g_watchdog_timeout )
608 {
609 // log
610 EM_log( CK_LOG_HERALD, "real-time watchdog resting..." );
611 // raise priority
612 if( g_tid_synthesis && XThreadUtil::our_priority != 0x7fffffff )
613 XThreadUtil::set_priority( g_tid_synthesis, XThreadUtil::our_priority );
614 // set state
615 g_watchdog_state = FALSE;
616 }
617 }
618
619 // advance time
620 ck_usleep( 40000 );
621 }
622
623 // log
624 EM_log( CK_LOG_HERALD, "stopping real-time watch dog process..." );
625
626 return 0;
627 }
628
629
630
631
632 //-----------------------------------------------------------------------------
633 // name: watchdog_start()
634 // desc: start watchdog on separate thread
635 //-----------------------------------------------------------------------------
636 t_CKBOOL ChuckAudio::watchdog_start()
637 {
638 // already
639 if( g_watchdog_thread )
640 return FALSE;
641
642 // flag
643 g_do_watchdog = TRUE;
644 // allocate it
645 g_watchdog_thread = new XThread;
646 // start it
647 g_watchdog_thread->start( watch_dog, NULL );
648
649 return TRUE;
650 }
651
652
653
654
655 //-----------------------------------------------------------------------------
656 // name: watchdog_stop()
657 // desc: stop watchdog thread
658 //-----------------------------------------------------------------------------
659 t_CKBOOL ChuckAudio::watchdog_stop()
660 {
661 // already
662 if( !g_watchdog_thread )
663 return FALSE;
664
665 // stop things
666 g_do_watchdog = FALSE;
667 // wait a bit | TODO: is this needed?
668 ck_usleep( 100000 );
669 // delete watchdog thread | TODO: is this safe?
670 CK_SAFE_DELETE( g_watchdog_thread );
671
672 return TRUE;
673 }
674
675
676
677
678 //-----------------------------------------------------------------------------
679 // name: supportSampleRate()
680 // desc: does a device (which can potentially support multiple sample rates)
681 // support a particular sample rate? 1.5.0.0 (ge) | added
682 //-----------------------------------------------------------------------------
683 static t_CKBOOL supportSampleRate( RtAudio::DeviceInfo & device_info, t_CKINT sample_rate )
684 {
685 // loop over supported sample rates for a device
686 for( t_CKINT i = 0; i < device_info.sampleRates.size(); i++ )
687 {
688 // look for a match
689 if( device_info.sampleRates[i] == sample_rate )
690 {
691 return TRUE;
692 }
693 }
694
695 // no match
696 return FALSE;
697 }
698
699
700
701
702 //-----------------------------------------------------------------------------
703 // name: findMatchingInputDevice()
704 // desc: find an input device with matching chans and sample rate
705 // 1.5.0.0 (ge) | added
706 //-----------------------------------------------------------------------------
707 static t_CKINT findMatchingInputDevice( RtAudio * rtaudio, t_CKINT numInputChans,
708 t_CKINT sample_rate, t_CKBOOL allowMoreChans )
709 {
710 // get number of devices
711 t_CKINT num_devices = rtaudio->getDeviceCount();
712 // struct to hold info for a device
713 RtAudio::DeviceInfo device_info;
714
715 // find first device with at least the requested channel count (and sample rate match)
716 for( t_CKUINT i = 0; i < num_devices; i++ )
717 {
718 // get device info
719 device_info = rtaudio->getDeviceInfo((unsigned int)i);
720 // check sample rate
721 if( supportSampleRate( device_info, sample_rate ) )
722 {
723 // check channels; the allowMoreChans toggles exact match or lenient match
724 if( (allowMoreChans == FALSE && device_info.inputChannels == numInputChans) ||
725 (allowMoreChans == TRUE && device_info.inputChannels >= numInputChans) )
726 {
727 // log
728 EM_log( CK_LOG_INFO, "found alternate input device: %d...", i );
729 // return device number
730 return i;
731 }
732 }
733 }
734
735 // no match
736 return -1;
737 }
738
739
740
741
742 //-----------------------------------------------------------------------------
743 // name: initialize()
744 // desc: ...
745 //-----------------------------------------------------------------------------
746 t_CKBOOL ChuckAudio::initialize( t_CKUINT dac_device,
747 t_CKUINT adc_device,
748 t_CKUINT num_dac_channels,
749 t_CKUINT num_adc_channels,
750 t_CKUINT sample_rate,
751 t_CKUINT buffer_size,
752 t_CKUINT num_buffers,
753 ck_f_audio_cb callback,
754 void * data,
755 t_CKBOOL force_srate,
756 const char * driver )
757 {
758 // check if already initialized
759 if( m_init ) return FALSE;
760
761 m_dac_n = dac_device;
762 m_adc_n = adc_device;
763 m_dac_name = "[no output device]";
764 m_adc_name = "[no input device]";
765 m_num_channels_out = num_dac_channels;
766 m_num_channels_in = num_adc_channels;
767 m_sample_rate = sample_rate;
768 m_buffer_size = buffer_size;
769 m_num_buffers = num_buffers;
770 m_start = 0;
771 m_go = 0;
772 m_silent = 0;
773
774 // remember callback
775 m_audio_cb = callback;
776 // remember user data to pass to callback
777 m_cb_user_data = data;
778
779 // audio device probe results
780 RtAudio::DeviceInfo dac_info;
781 RtAudio::DeviceInfo adc_info;
782
783 // variable to pass by reference into RtAudio
784 unsigned int bufsize = (unsigned int)m_buffer_size;
785 // check output device number; 0 means "default"
786 bool useDefaultOut = ( m_dac_n == 0 );
787 // check input device number; 0 means "default"
788 bool useDefaultIn = ( m_adc_n == 0 );
789 // total number of audio devices (input and output)
790 unsigned int num_devices = 0;
791
792 // log
793 EM_log( CK_LOG_FINE, "initializing RtAudio..." );
794 // push indent
795 EM_pushlog();
796
797 // allocate RtAudio
798 RtAudio::Api api = driverNameToApi(driver);
799 m_driver_name = apiToDriverName(api);
800 RtAudioErrorType code = RTAUDIO_NO_ERROR;
801 m_rtaudio = new RtAudio(api, rtAudioErrorHandler);
802 if(!m_rtaudio)
803 {
804 // error reported above
805 goto error; // to clean up
806 }
807
808 // get number of audio devices
809 num_devices = m_rtaudio->getDeviceCount();
810
811 // convert 1-based ordinal to 0-based ordinal (added 1.3.0.0)
812 // note: this is to preserve previous devices numbering after RtAudio change
813 if( m_num_channels_out > 0 )
814 {
815 // default (refactor 1.3.1.2)
816 if( useDefaultOut )
817 {
818 // get the default
819 // FYI: getDefaultInputDevice returns 0 either as a valid index OR if no default/any devices
820 m_dac_n = m_rtaudio->getDefaultOutputDevice();
821 }
822 else
823 {
824 m_dac_n -= 1;
825 }
826
827 // get device info
828 RtAudio::DeviceInfo device_info = m_rtaudio->getDeviceInfo((unsigned int)m_dac_n);
829
830 // ensure correct channel count if default device is requested
831 if( useDefaultOut )
832 {
833 // check for output (channels)
834 if( device_info.outputChannels < m_num_channels_out )
835 {
836 // find first device with at least the requested channel count
837 m_dac_n = -1;
838 for( int i = 0; i < num_devices; i++ )
839 {
840 device_info = m_rtaudio->getDeviceInfo(i);
841 if(device_info.outputChannels >= m_num_channels_out)
842 {
843 m_dac_n = i;
844 break;
845 }
846 }
847
848 // check for error
849 if( m_dac_n == -1 )
850 {
851 EM_error2( 0, "no audio output device with requested channel count (%i)...",
852 m_num_channels_out );
853 // clean up
854 goto error;
855 }
856 }
857 }
858
859 // index of closest sample rate
860 long closestIndex = -1;
861 // difference of closest so far
862 long closestDiff = LONG_MAX;
863 // the next highest
864 long nextHighest = -1;
865 // diff to next highest so far
866 long diffToNextHighest = LONG_MAX;
867 // check if request sample rate in support rates (added 1.3.1.2)
868 for( long i = 0; i < device_info.sampleRates.size(); i++ )
869 {
870 // difference
871 long diff = device_info.sampleRates[i] - sample_rate;
872 // check // ge: changed from abs to labs, 2015.11
873 if( ::labs(diff) < closestDiff )
874 {
875 // remember index
876 closestIndex = i;
877 // update diff
878 closestDiff = ::labs(diff);
879 }
880
881 // for next highest
882 if( diff > 0 && diff < diffToNextHighest )
883 {
884 // remember index
885 nextHighest = i;
886 // update diff
887 diffToNextHighest = diff;
888 }
889 }
890
891 // see if we found exact match (added 1.3.1.2)
892 if( closestDiff != 0 )
893 {
894 // check
895 if( force_srate )
896 {
897 // request sample rate not found, error out
898 EM_error2( 0, "unsupported sample rate (%d) requested...", sample_rate );
899 EM_error2( 0, "| (try --probe to enumerate available sample rates)" );
900 // clean up
901 goto error;
902 }
903
904 // use next highest if available
905 if( nextHighest >= 0 )
906 {
907 // log
908 EM_log( CK_LOG_HERALD, "new sample rate (next highest): %d -> %d",
909 sample_rate, device_info.sampleRates[nextHighest] );
910 // update sampling rate
911 m_sample_rate = sample_rate = device_info.sampleRates[nextHighest];
912 }
913 else if( closestIndex >= 0 ) // nothing higher
914 {
915 // log
916 EM_log( CK_LOG_HERALD, "new sample rate (closest): %d -> %d",
917 sample_rate, device_info.sampleRates[closestIndex] );
918 // update sampling rate
919 m_sample_rate = sample_rate = device_info.sampleRates[closestIndex];
920 }
921 else
922 {
923 // nothing to do (will fail and throw error message when opening)
924 }
925 }
926 }
927
928 // convert 1-based ordinal to 0-based ordinal
929 if( m_num_channels_in > 0 )
930 {
931 // if we are requesting the default input device
932 if( useDefaultIn )
933 {
934 // get default input device
935 // FYI getDefaultInputDevice returns 0 either as a valid index OR if no default/any devices
936 m_adc_n = m_rtaudio->getDefaultInputDevice();
937 // ensure correct channel count if default device is requested
938 RtAudio::DeviceInfo device_info = m_rtaudio->getDeviceInfo((unsigned int)m_adc_n);
939
940 // remember
941 t_CKUINT inChannelsRequested = m_num_channels_in;
942
943 // check if input channels > 0 || sample rate does not match
944 if( device_info.inputChannels < m_num_channels_in )
945 {
946 // 1.4.2.0 (ge) | added: a specific but possible common case
947 // for systems that have a 1-channel default input audio device -- e.g., some MacOS systems
948 if( m_num_channels_in == 2 && device_info.inputChannels == 1
949 && supportSampleRate( device_info, sample_rate ) ) // try to stay on device if possible
950 {
951 // nothing more for now here
952 // the code here to set the m_expand_in_mono2stereo flag has been moved below
953 }
954 else // need further matching
955 {
956 // special case | 1.5.0.0 (ge) -- in this case of default input device,
957 // first try to match using the current default input device channels.
958 // This is to handle the situation in macOS and using bluetooth earbuds
959 // or headphones and the highest supported input sample rate is lower than
960 // the desired chuck sample rate (e.g., some input devices only support 24K);
961 // in this case, look for devices with match sample rates AND inherit the
962 // default input devices's actual channel count. This heuristic is so that
963 // on most Apple laptops since macOS 11, this will end up choosing the
964 // the onboard laptop microphone. This will hopefully serve many students
965 // working in the above setup; of course, power users can explicitly choose
966 // the input and output devices using command-line flags or other settings
967 // -
968 // special case | 1.4.0.1 (ge) -- check if the sample rate is supported
969 // this is to catch the case where the default device has
970 // insufficient channels (e.g., 1 on MacOS), finds secondary device
971 // (e.g., ZoomAudioDevice on MacOS) that has enough channels
972 // but does not support the desired sample rate
973 // amended 1.4.2.0 -- the behavior is modified above, where chuck
974 // will first check if the default input device has only 1 channel
975 // while we are requesting 2 channels...
976 // -
977
978 // if non-zero input channels
979 if( device_info.inputChannels > 0 )
980 {
981 // find a device with *exactly* the current device input channels
982 m_adc_n = findMatchingInputDevice( m_rtaudio, device_info.inputChannels, sample_rate, FALSE );
983 }
984 else // if device input channel count is 0
985 {
986 // find a device with *exactly* the requested channel count
987 m_adc_n = findMatchingInputDevice( m_rtaudio, m_num_channels_in, sample_rate, FALSE);
988 }
989
990 // check if match
991 if( m_adc_n >= 0 )
992 {
993 // get updated device info (since m_adc_n may be updated by this point)
994 device_info = m_rtaudio->getDeviceInfo((unsigned int)m_adc_n);
995 // update the request input channel request
996 m_num_channels_in = device_info.inputChannels;
997 }
998 else
999 {
1000 // find a device with *at least* the requested channel count
1001 m_adc_n = findMatchingInputDevice(m_rtaudio, m_num_channels_in, sample_rate, TRUE );
1002
1003 // changed 1.3.1.2 (ge): for input, if no match found by this point, we just gonna try to open half-duplex
1004 if( m_adc_n < 0 )
1005 {
1006 // set to 0
1007 m_num_channels_in = 0;
1008 // log
1009 EM_log( CK_LOG_HERALD, "cannot find compatible audio input device..." );
1010 EM_pushlog();
1011 EM_log(CK_LOG_HERALD, "defaulting to half-duplex (no audio input)...");
1012 EM_poplog();
1013
1014 // problem finding audio devices, most likely
1015 // EM_error2( 0, "unable to find audio input device with requested channel count (%i)...",
1016 // m_num_channels_in);
1017 // clean up
1018 // goto error;
1019 }
1020 }
1021 }
1022 }
1023
1024 // if we ended up with a match
1025 if( m_dac_n >= 0 )
1026 {
1027 // get info for the input device we ended up using
1028 device_info = m_rtaudio->getDeviceInfo((unsigned int)m_adc_n);
1029 // check channel situation look for specific arrangement; we should have a sample rate match if we get here
1030 if( inChannelsRequested == 2 && device_info.inputChannels == 1 )
1031 {
1032 // flag this for expansion in the callback
1033 m_expand_in_mono2stereo = TRUE;
1034 // log
1035 EM_log( CK_LOG_INFO, "using 1-channel default input device (instead of requested 2-channel)..." );
1036 EM_log( CK_LOG_INFO, "simulating stereo input from mono audio device..." );
1037 }
1038 }
1039 }
1040 else
1041 {
1042 // offset to 0-index device number
1043 m_adc_n -= 1;
1044 }
1045 }
1046
1047 // the dac and adc devices we've chosen to initialize | 1.5.0.0 (ge)
1048 if( m_num_channels_out > 0 && m_dac_n < num_devices )
1049 {
1050 // get device info
1051 dac_info = m_rtaudio->getDeviceInfo((unsigned int)m_dac_n);
1052 // copy names (if valid)
1053 if( dac_info.probed ) m_dac_name = dac_info.name;
1054 }
1055 if( m_num_channels_in > 0 && m_adc_n < num_devices )
1056 {
1057 // get device info
1058 adc_info = m_rtaudio->getDeviceInfo((unsigned int)m_adc_n);
1059 if( adc_info.probed ) m_adc_name = adc_info.name;
1060 }
1061
1062 // open device
1063 { // was: try {
1064 // log
1065 EM_log( CK_LOG_FINE, "[%s] driver trying %d input %d output...",
1066 m_driver_name.c_str(), m_num_channels_in, m_num_channels_out );
1067
1068 RtAudio::StreamParameters output_parameters;
1069 output_parameters.deviceId = (unsigned int)m_dac_n;
1070 output_parameters.nChannels = (unsigned int)m_num_channels_out;
1071 output_parameters.firstChannel = 0;
1072
1073 RtAudio::StreamParameters input_parameters;
1074 input_parameters.deviceId = (unsigned int)m_adc_n;
1075 input_parameters.nChannels = (unsigned int)(m_expand_in_mono2stereo ? 1 : m_num_channels_in);
1076 input_parameters.firstChannel = 0;
1077
1078 RtAudio::StreamOptions stream_options;
1079 stream_options.flags = 0;
1080 stream_options.numberOfBuffers = (unsigned int)num_buffers;
1081 stream_options.streamName = "ChucK";
1082 stream_options.priority = 0;
1083
1084 // open audio stream
1085 code = m_rtaudio->openStream(
1086 m_num_channels_out > 0 ? &output_parameters : NULL,
1087 m_num_channels_in > 0 ? &input_parameters : NULL,
1088 CK_RTAUDIO_FORMAT, (unsigned int)sample_rate, &bufsize,
1089 cb, m_cb_user_data,
1090 &stream_options
1091 );
1092
1093 // check error code
1094 if( code > RTAUDIO_WARNING ) // was: } catch( RtAudioErrorType ) {
1095 {
1096 // RtAudio no longer throws, errors reported via errorHandler
1097 CK_SAFE_DELETE( m_rtaudio );
1098 // clean up
1099 goto error;
1100 }
1101 }
1102
1103 // check bufsize
1104 if( bufsize != (int)m_buffer_size )
1105 {
1106 EM_log( CK_LOG_HERALD, "new buffer size: %d -> %i", m_buffer_size, bufsize );
1107 m_buffer_size = bufsize;
1108 }
1109
1110 // pop indent
1111 EM_poplog();
1112
1113 // greater of dac/adc channels
1114 m_num_channels_max = num_dac_channels > num_adc_channels ?
1115 num_dac_channels : num_adc_channels;
1116 // log
1117 EM_log( CK_LOG_HERALD, "allocating buffers for %d x %d samples...",
1118 m_buffer_size, m_num_channels_max );
1119
1120 // allocate buffers
1121 m_buffer_in = new SAMPLE[m_buffer_size * m_num_channels_max];
1122 m_buffer_out = new SAMPLE[m_buffer_size * m_num_channels_max];
1123 memset( m_buffer_in, 0, m_buffer_size * sizeof(SAMPLE) * m_num_channels_max );
1124 memset( m_buffer_out, 0, m_buffer_size * sizeof(SAMPLE) * m_num_channels_max );
1125
1126 // set flag and return
1127 return m_init = TRUE;
1128
1129 // handle common error case (added 1.4.1.0)
1130 error:
1131 // pop log indent (added 1.4.1.0)
1132 EM_poplog();
1133 // set flag and return
1134 return m_init = FALSE;
1135 }
1136
1137
1138
1139
1140 //-----------------------------------------------------------------------------
1141 // name: cb2()
1142 // desc: ...
1143 //-----------------------------------------------------------------------------
1144 int ChuckAudio::cb( void * output_buffer, void * input_buffer, unsigned int buffer_size,
1145 double streamTime, RtAudioStreamStatus status, void * user_data )
1146 {
1147 // length, in bytes of output
1148 t_CKUINT len = buffer_size * sizeof(SAMPLE) * m_num_channels_out;
1149
1150 // priority boost
1151 if( !m_go && XThreadUtil::our_priority != 0x7fffffff )
1152 {
1153 #if !defined(__PLATFORM_WINDOWS__) || defined(__WINDOWS_PTHREAD__)
1154 g_tid_synthesis = pthread_self();
1155 #else
1156 // must duplicate for handle to be usable by other threads
1157 g_tid_synthesis = NULL;
1158 DuplicateHandle(
1159 GetCurrentProcess(),
1160 GetCurrentThread(),
1161 GetCurrentProcess(),
1162 &g_tid_synthesis,
1163 0,
1164 FALSE,
1165 DUPLICATE_SAME_ACCESS
1166 );
1167
1168 // TODO: close the duplicate handle?
1169 #endif
1170 XThreadUtil::set_priority( XThreadUtil::our_priority );
1171 memset( output_buffer, 0, len );
1172 m_go = TRUE;
1173
1174 // start watchdog
1175 if( g_do_watchdog )
1176 {
1177 // timestamp
1178 g_watchdog_time = get_current_time( TRUE );
1179 // start watchdog
1180 watchdog_start();
1181 }
1182
1183 // let it go the first time
1184 return 0;
1185 }
1186
1187 // copy input to local buffer
1188 if( m_num_channels_in )
1189 {
1190 // added 1.4.0.1 (ge) -- special case in=1; out=2
1191 if( m_expand_in_mono2stereo )
1192 {
1193 for( int i = 0; i < buffer_size; i++ )
1194 {
1195 // copy mono sample into stereo buffer
1196 m_buffer_in[i*2] = m_buffer_in[i*2+1] = ((SAMPLE *)input_buffer)[i];
1197 }
1198 }
1199 else
1200 {
1201 memcpy( m_buffer_in, input_buffer, len );
1202 }
1203 // copy to extern
1204 if( m_extern_in ) memcpy( m_extern_in, input_buffer, len );
1205 }
1206
1207 // timestamp
1208 if( g_do_watchdog ) g_watchdog_time = get_current_time( TRUE );
1209 // call the audio cb
1210 m_audio_cb( m_buffer_in, m_buffer_out, buffer_size,
1211 m_num_channels_in, m_num_channels_out, m_cb_user_data );
1212
1213 // copy local buffer to be rendered
1214 // REFACTOR-2017: TODO: m_end was the signal to end, what should it be now?
1215 if( m_start ) // REFACTOR-2017: now using m_start to gate this
1216 {
1217 memcpy( output_buffer, m_buffer_out, len );
1218 }
1219 // set all elements of local buffer to silence
1220 else
1221 {
1222 memset( output_buffer, 0, len );
1223 }
1224
1225 // copy to extern
1226 if( m_extern_out ) memcpy( m_extern_out, output_buffer, len );
1227
1228 return 0;
1229 }
1230
1231
1232
1233
1234 //-----------------------------------------------------------------------------
1235 // name: start()
1236 // desc: start host audio
1237 //-----------------------------------------------------------------------------
1238 t_CKBOOL ChuckAudio::start( )
1239 {
1240 try {
1241 if( !m_start )
1242 m_rtaudio->startStream();
1243 m_start = TRUE;
1244 }
1245 catch( RtAudioErrorType )
1246 {
1247 // RtAudio no longer throws, case shouldn't happen
1248 return FALSE;
1249 }
1250
1251 return m_start;
1252 }
1253
1254
1255
1256
1257 //-----------------------------------------------------------------------------
1258 // name: stop()
1259 // desc: stop host audio
1260 //-----------------------------------------------------------------------------
1261 t_CKBOOL ChuckAudio::stop( )
1262 {
1263 try {
1264 if( m_start )
1265 m_rtaudio->stopStream();
1266 m_start = FALSE;
1267 }
1268 catch( RtAudioErrorType)
1269 {
1270 // RtAudio no longer throws, case shouldn't happen
1271 return FALSE;
1272 }
1273
1274 // REFACTOR-2017: set end flag
1275 m_silent = TRUE;
1276
1277 return !m_start;
1278 }
1279
1280
1281
1282
1283 //-----------------------------------------------------------------------------
1284 // name: shutdown()
1285 // desc: ...
1286 //-----------------------------------------------------------------------------
1287 void ChuckAudio::shutdown( t_CKUINT msWait )
1288 {
1289 // check flag
1290 if( !m_init ) return;
1291
1292 // stop watchdog | REFACTOR-2017: moved this earlier to give watchdog
1293 // a head start in stopping, to avoid unneeded countermeasure deployment
1294 watchdog_stop();
1295
1296 // check if started
1297 if( m_start )
1298 {
1299 // m_rtaudio->cancelStreamCallback();
1300 // m_rtaudio->stopStream();
1301 stop();
1302
1303 // wait for thread to wrap up | 1.5.1.3 (ge) added
1304 if( msWait > 0 ) ck_usleep( msWait * 1000 );
1305 }
1306
1307 // close stream
1308 m_rtaudio->closeStream();
1309 // cleanup
1310 CK_SAFE_DELETE( m_rtaudio );
1311
1312 // deallocate | 1.5.0.0 (ge) added
1313 CK_SAFE_DELETE( m_buffer_in );
1314 CK_SAFE_DELETE( m_buffer_out );
1315
1316 // unflag
1317 m_init = FALSE;
1318 m_start = FALSE;
1319 }