-
Notifications
You must be signed in to change notification settings - Fork 716
/
Copy pathaudio_unit.cc
2711 lines (2251 loc) · 79.6 KB
/
audio_unit.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2006-2016 David Robillard <[email protected]>
* Copyright (C) 2007-2017 Paul Davis <[email protected]>
* Copyright (C) 2010 Carl Hetherington <[email protected]>
* Copyright (C) 2013-2023 Robin Gareus <[email protected]>
* Copyright (C) 2014-2017 Tim Mayberry <[email protected]>
* Copyright (C) 2015-2016 Nick Mainsbridge <[email protected]>
* Copyright (C) 2018 Julien "_FrnchFrgg_" RIVAUD <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <sstream>
#include <fstream>
#include <errno.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <boost/algorithm/string.hpp>
#include "pbd/gstdio_compat.h"
#include "pbd/transmitter.h"
#include "pbd/xml++.h"
#include "pbd/convert.h"
#include "pbd/whitespace.h"
#include "pbd/file_utils.h"
#include "pbd/locale_guard.h"
#include <glibmm/threads.h>
#include <glibmm/fileutils.h>
#include <glibmm/miscutils.h>
#include "ardour/ardour.h"
#include "ardour/audio_unit.h"
#include "ardour/audioengine.h"
#include "ardour/audio_buffer.h"
#include "ardour/auv2_scan.h"
#include "ardour/debug.h"
#include "ardour/filesystem_paths.h"
#include "ardour/io.h"
#include "ardour/midi_buffer.h"
#include "ardour/route.h"
#include "ardour/session.h"
#include "ardour/tempo.h"
#include "ardour/utils.h"
#include "CAAudioUnit.h"
#include "CAAUParameter.h"
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioUnitUtilities.h>
#ifdef WITH_CARBON
#include <Carbon/Carbon.h>
#endif
#include "pbd/i18n.h"
using namespace std;
using namespace PBD;
using namespace ARDOUR;
static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
static string preset_suffix = ".aupreset";
static bool preset_search_path_initialized = false;
static OSStatus
_render_callback(void *userData,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberSamples,
AudioBufferList* ioData)
{
if (userData) {
return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberSamples, ioData);
}
return paramErr;
}
static OSStatus
_get_beat_and_tempo_callback (void* userData,
Float64* outCurrentBeat,
Float64* outCurrentTempo)
{
if (userData) {
return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
}
return paramErr;
}
static OSStatus
_get_musical_time_location_callback (void * userData,
UInt32 * outDeltaSampleOffsetToNextBeat,
Float32 * outTimeSig_Numerator,
UInt32 * outTimeSig_Denominator,
Float64 * outCurrentMeasureDownBeat)
{
if (userData) {
return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
outTimeSig_Numerator,
outTimeSig_Denominator,
outCurrentMeasureDownBeat);
}
return paramErr;
}
static OSStatus
_get_transport_state_callback (void* userData,
Boolean* outIsPlaying,
Boolean* outTransportStateChanged,
Float64* outCurrentSampleInTimeLine,
Boolean* outIsCycling,
Float64* outCycleStartBeat,
Float64* outCycleEndBeat)
{
if (userData) {
return ((AUPlugin*)userData)->get_transport_state_callback (
outIsPlaying, outTransportStateChanged,
outCurrentSampleInTimeLine, outIsCycling,
outCycleStartBeat, outCycleEndBeat);
}
return paramErr;
}
static int
save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
{
CFDataRef xmlData;
int fd;
// Convert the property list into XML data.
xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
if (!xmlData) {
error << _("Could not create XML version of property list") << endmsg;
return -1;
}
// Write the XML data to the file.
fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
while (fd < 0) {
if (errno == EEXIST) {
error << string_compose (_("Preset file %1 exists; not overwriting"),
path) << endmsg;
} else {
error << string_compose (_("Cannot open preset file %1 (%2)"),
path, strerror (errno)) << endmsg;
}
CFRelease (xmlData);
return -1;
}
size_t cnt = CFDataGetLength (xmlData);
if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
CFRelease (xmlData);
close (fd);
return -1;
}
close (fd);
return 0;
}
static CFPropertyListRef
load_property_list (Glib::ustring path)
{
int fd;
CFPropertyListRef propertyList = 0;
CFDataRef xmlData;
CFStringRef errorString;
// Read the XML file.
if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
return propertyList;
}
off_t len = lseek (fd, 0, SEEK_END);
char* buf = new char[len];
lseek (fd, 0, SEEK_SET);
if (read (fd, buf, len) != len) {
delete [] buf;
close (fd);
return propertyList;
}
close (fd);
xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
// Reconstitute the dictionary using the XML data.
propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
xmlData,
kCFPropertyListImmutable,
&errorString);
CFRelease (xmlData);
delete [] buf;
return propertyList;
}
//-----------------------------------------------------------------------------
static void
set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
{
if (!plist) {
return;
}
CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
}
CFRelease (pn);
}
//-----------------------------------------------------------------------------
static std::string
get_preset_name_in_plist (CFPropertyListRef plist)
{
std::string ret;
if (!plist) {
return ret;
}
if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
if (p) {
CFStringRef str = (CFStringRef) p;
int len = CFStringGetLength(str);
len = (len * 2) + 1;
char local_buffer[len];
if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
ret = local_buffer;
}
}
}
return ret;
}
//--------------------------------------------------------------------------
// general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
// if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
Boolean ComponentDescriptionsMatch_General(const AudioComponentDescription * inComponentDescription1, const AudioComponentDescription * inComponentDescription2, Boolean inIgnoreType)
{
if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
return FALSE;
if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
&& (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
{
// only sub-type and manufacturer IDs need to be equal
if (inIgnoreType)
return TRUE;
// type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
return TRUE;
}
return FALSE;
}
//--------------------------------------------------------------------------
// general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
// if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
Boolean ComponentAndDescriptionMatch_General(AudioComponent inComponent, const AudioComponentDescription * inComponentDescription, Boolean inIgnoreType)
{
OSErr status;
AudioComponentDescription desc;
if ( (inComponent == NULL) || (inComponentDescription == NULL) )
return FALSE;
// get the ComponentDescription of the input Component
status = AudioComponentGetDescription (inComponent, &desc);
if (status != noErr)
return FALSE;
// check if the Component's ComponentDescription matches the input ComponentDescription
return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
}
//--------------------------------------------------------------------------
// determine if 2 ComponentDescriptions are basically equal
// (by that, I mean that the important identifying values are compared,
// but not the ComponentDescription flags)
Boolean ComponentDescriptionsMatch(const AudioComponentDescription * inComponentDescription1, const AudioComponentDescription * inComponentDescription2)
{
return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
}
//--------------------------------------------------------------------------
// determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
Boolean ComponentDescriptionsMatch_Loose(const AudioComponentDescription * inComponentDescription1, const AudioComponentDescription * inComponentDescription2)
{
return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
}
//--------------------------------------------------------------------------
// determine if a ComponentDescription basically matches that of a particular Component
Boolean ComponentAndDescriptionMatch(AudioComponent inComponent, const AudioComponentDescription * inComponentDescription)
{
return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
}
//--------------------------------------------------------------------------
// determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
Boolean ComponentAndDescriptionMatch_Loosely(AudioComponent inComponent, const AudioComponentDescription * inComponentDescription)
{
return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
}
AUPlugin::AUPlugin (AudioEngine& engine, Session& session, std::shared_ptr<CAComponent> _comp)
: Plugin (engine, session)
, comp (_comp)
, unit (new CAAudioUnit)
, initialized (false)
, process_offline (false)
, _last_nframes (0)
, _requires_fixed_size_buffers (false)
, buffers (0)
, variable_inputs (false)
, variable_outputs (false)
, configured_input_busses (0)
, configured_output_busses (0)
, bus_inputs (0)
, bus_inused (0)
, bus_outputs (0)
, input_maxbuf (0)
, input_offset (0)
, cb_offsets (0)
, input_buffers (0)
, input_map (0)
, samples_processed (0)
, _parameter_listener (0)
, _parameter_listener_arg (0)
, transport_sample (0)
, transport_speed (0)
, last_transport_speed (0.0)
, preset_holdoff (0)
{
if (!preset_search_path_initialized) {
Glib::ustring p = Glib::get_home_dir();
p += "/Library/Audio/Presets:";
p += preset_search_path;
preset_search_path = p;
preset_search_path_initialized = true;
DEBUG_TRACE (DEBUG::AudioUnitConfig, string_compose("AU Preset Path: %1\n", preset_search_path));
}
init ();
}
AUPlugin::AUPlugin (const AUPlugin& other)
: Plugin (other)
, comp (other.get_comp())
, unit (new CAAudioUnit)
, initialized (false)
, process_offline (false)
, _last_nframes (0)
, _requires_fixed_size_buffers (false)
, buffers (0)
, variable_inputs (false)
, variable_outputs (false)
, configured_input_busses (0)
, configured_output_busses (0)
, bus_inputs (0)
, bus_inused (0)
, bus_outputs (0)
, input_maxbuf (0)
, input_offset (0)
, cb_offsets (0)
, input_buffers (0)
, input_map (0)
, samples_processed (0)
, _parameter_listener (0)
, _parameter_listener_arg (0)
, transport_sample (0)
, transport_speed (0)
, last_transport_speed (0.0)
, preset_holdoff (0)
{
init ();
XMLNode root (other.state_node_name ());
other.add_state (&root);
set_state (root, Stateful::loading_state_version);
for (size_t i = 0; i < descriptors.size(); ++i) {
set_parameter (i, other.get_parameter (i), 0);
}
}
AUPlugin::~AUPlugin ()
{
if (_parameter_listener) {
AUListenerDispose (_parameter_listener);
_parameter_listener = 0;
}
if (unit) {
DEBUG_TRACE (DEBUG::AudioUnitConfig, "about to call uninitialize in plugin destructor\n");
unit->Uninitialize ();
}
free (buffers);
free (bus_inputs);
free (bus_inused);
free (bus_outputs);
free (cb_offsets);
}
void
AUPlugin::discover_factory_presets ()
{
CFArrayRef presets;
UInt32 dataSize;
Boolean isWritable;
OSStatus err;
if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
DEBUG_TRACE (DEBUG::AudioUnitConfig, "no factory presets for AU\n");
return;
}
assert (dataSize == sizeof (presets));
if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
return;
}
if (!presets) {
return;
}
CFIndex cnt = CFArrayGetCount (presets);
for (CFIndex i = 0; i < cnt; ++i) {
AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
string name = CFStringRefToStdString (preset->presetName);
factory_preset_map[name] = preset->presetNumber;
DEBUG_TRACE (DEBUG::AudioUnitConfig, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
}
CFRelease (presets);
}
void
AUPlugin::init ()
{
_current_latency.store (UINT_MAX);
OSErr err;
/* these keep track of *configured* channel set up,
* not potential set ups.
*/
input_channels = -1;
output_channels = -1;
try {
DEBUG_TRACE (DEBUG::AudioUnitConfig, "opening AudioUnit\n");
err = CAAudioUnit::Open (*(comp.get()), *unit);
} catch (...) {
error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
throw failed_constructor();
}
if (err != noErr) {
error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
throw failed_constructor ();
}
DEBUG_TRACE (DEBUG::AudioUnitConfig, "count global elements\n");
unit->GetElementCount (kAudioUnitScope_Global, global_elements);
DEBUG_TRACE (DEBUG::AudioUnitConfig, "count input elements\n");
unit->GetElementCount (kAudioUnitScope_Input, input_elements);
DEBUG_TRACE (DEBUG::AudioUnitConfig, "count output elements\n");
unit->GetElementCount (kAudioUnitScope_Output, output_elements);
if (input_elements > 0) {
cb_offsets = (samplecnt_t*) calloc (input_elements, sizeof(samplecnt_t));
bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
bus_inused = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
}
if (output_elements > 0) {
bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
}
for (size_t i = 0; i < output_elements; ++i) {
unit->Reset (kAudioUnitScope_Output, i);
AudioStreamBasicDescription fmt;
err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
if (err == noErr) {
bus_outputs[i] = fmt.mChannelsPerFrame;
}
CFStringRef name;
UInt32 sz = sizeof (CFStringRef);
if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
i, &name, &sz) == noErr
&& sz > 0) {
_bus_name_out.push_back (CFStringRefToStdString (name));
CFRelease(name);
} else {
_bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
}
}
for (size_t i = 0; i < input_elements; ++i) {
unit->Reset (kAudioUnitScope_Input, i);
AudioStreamBasicDescription fmt;
err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
if (err == noErr) {
bus_inputs[i] = fmt.mChannelsPerFrame;
bus_inused[i] = bus_inputs[i];
}
CFStringRef name;
UInt32 sz = sizeof (CFStringRef);
if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
i, &name, &sz) == noErr
&& sz > 0) {
_bus_name_in.push_back (CFStringRefToStdString (name));
CFRelease(name);
} else {
_bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
}
}
/* tell the plugin about tempo/meter/transport callbacks in case it wants them */
HostCallbackInfo info;
memset (&info, 0, sizeof (HostCallbackInfo));
info.hostUserData = this;
info.beatAndTempoProc = _get_beat_and_tempo_callback;
info.musicalTimeLocationProc = _get_musical_time_location_callback;
info.transportStateProc = _get_transport_state_callback;
//ignore result of this - don't care if the property isn't supported
DEBUG_TRACE (DEBUG::AudioUnitConfig, "set host callbacks in global scope\n");
unit->SetProperty (kAudioUnitProperty_HostCallbacks,
kAudioUnitScope_Global,
0, //elementID
&info,
sizeof (HostCallbackInfo));
if (set_block_size (_session.get_block_size())) {
error << _("AUPlugin: cannot set processing block size") << endmsg;
throw failed_constructor();
}
create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
discover_parameters ();
discover_factory_presets ();
// Plugin::setup_controls ();
}
void
AUPlugin::discover_parameters ()
{
/* discover writable parameters */
AudioUnitScope scopes[] = {
kAudioUnitScope_Global,
kAudioUnitScope_Output,
kAudioUnitScope_Input
};
descriptors.clear ();
for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
AUParameterDescriptor d;
d.id = param_info.ParamID (i);
const CAAUParameter* param = param_info.GetParamInfo (d.id);
const AudioUnitParameterInfo& info (param->ParamInfo());
const int len = CFStringGetLength (param->GetName());
char local_buffer[len*2];
Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
if (!good) {
d.label = "???";
} else {
d.label = local_buffer;
}
d.scope = param_info.GetScope ();
d.element = param_info.GetElement ();
/* info.units to consider */
/*
kAudioUnitParameterUnit_Generic = 0
kAudioUnitParameterUnit_Indexed = 1
kAudioUnitParameterUnit_Boolean = 2
kAudioUnitParameterUnit_Percent = 3
kAudioUnitParameterUnit_Seconds = 4
kAudioUnitParameterUnit_SampleFrames = 5
kAudioUnitParameterUnit_Phase = 6
kAudioUnitParameterUnit_Rate = 7
kAudioUnitParameterUnit_Hertz = 8
kAudioUnitParameterUnit_Cents = 9
kAudioUnitParameterUnit_RelativeSemiTones = 10
kAudioUnitParameterUnit_MIDINoteNumber = 11
kAudioUnitParameterUnit_MIDIController = 12
kAudioUnitParameterUnit_Decibels = 13
kAudioUnitParameterUnit_LinearGain = 14
kAudioUnitParameterUnit_Degrees = 15
kAudioUnitParameterUnit_EqualPowerCrossfade = 16
kAudioUnitParameterUnit_MixerFaderCurve1 = 17
kAudioUnitParameterUnit_Pan = 18
kAudioUnitParameterUnit_Meters = 19
kAudioUnitParameterUnit_AbsoluteCents = 20
kAudioUnitParameterUnit_Octaves = 21
kAudioUnitParameterUnit_BPM = 22
kAudioUnitParameterUnit_Beats = 23
kAudioUnitParameterUnit_Milliseconds = 24
kAudioUnitParameterUnit_Ratio = 25
*/
/* info.flags to consider */
/*
kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
kAudioUnitParameterFlag_HasClump = (1L << 20)
kAudioUnitParameterFlag_HasName = (1L << 21)
kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
kAudioUnitParameterFlag_NonRealTime = (1L << 24)
kAudioUnitParameterFlag_CanRamp = (1L << 25)
kAudioUnitParameterFlag_ExpertMode = (1L << 26)
kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
kAudioUnitParameterFlag_IsReadable = (1L << 30)
kAudioUnitParameterFlag_IsWritable = (1L << 31)
*/
d.lower = info.minValue;
d.upper = info.maxValue;
d.normal = info.defaultValue;
d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
(d.integer_step && ((d.upper - d.lower) == 1.0));
d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
!(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
(info.flags & kAudioUnitParameterFlag_IsWritable);
d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
d.au_unit = info.unit;
switch (info.unit) {
case kAudioUnitParameterUnit_Decibels:
d.unit = ParameterDescriptor::DB;
break;
case kAudioUnitParameterUnit_MIDINoteNumber:
d.unit = ParameterDescriptor::MIDI_NOTE;
break;
case kAudioUnitParameterUnit_Hertz:
d.unit = ParameterDescriptor::HZ;
break;
}
d.update_steps();
descriptors.push_back (d);
uint32_t last_param = descriptors.size() - 1;
parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
listen_to_parameter (last_param);
}
}
}
string
AUPlugin::unique_id () const
{
assert (_info->unique_id == auv2_stringify_descriptor (comp->Desc()));
return auv2_stringify_descriptor (comp->Desc());
}
const char *
AUPlugin::label () const
{
return _info->name.c_str();
}
uint32_t
AUPlugin::parameter_count () const
{
return descriptors.size();
}
float
AUPlugin::default_value (uint32_t port)
{
if (port < descriptors.size()) {
return descriptors[port].normal;
}
return 0;
}
samplecnt_t
AUPlugin::plugin_latency () const
{
guint lat = _current_latency.load ();;
if (lat == UINT_MAX) {
lat = unit->Latency() * _session.sample_rate();
_current_latency.store (lat);
}
return lat;
}
void
AUPlugin::set_parameter (uint32_t which, float val, sampleoffset_t when)
{
if (which >= descriptors.size()) {
return;
}
if (get_parameter(which) == val) {
return;
}
const AUParameterDescriptor& d (descriptors[which]);
DEBUG_TRACE (DEBUG::AudioUnitProcess, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
unit->SetParameter (d.id, d.scope, d.element, val);
/* tell the world what we did */
AudioUnitEvent theEvent;
theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
theEvent.mArgument.mParameter.mParameterID = d.id;
theEvent.mArgument.mParameter.mScope = d.scope;
theEvent.mArgument.mParameter.mElement = d.element;
DEBUG_TRACE (DEBUG::AudioUnitProcess, "notify about parameter change\n");
/* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
Plugin::set_parameter (which, val, when);
}
float
AUPlugin::get_parameter (uint32_t which) const
{
float val = 0.0;
if (which < descriptors.size()) {
const AUParameterDescriptor& d (descriptors[which]);
DEBUG_TRACE (DEBUG::AudioUnitProcess, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
unit->GetParameter(d.id, d.scope, d.element, val);
}
return val;
}
int
AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
{
if (which < descriptors.size()) {
pd = descriptors[which];
return 0;
}
return -1;
}
uint32_t
AUPlugin::nth_parameter (uint32_t which, bool& ok) const
{
if (which < descriptors.size()) {
ok = true;
return which;
}
ok = false;
return 0;
}
void
AUPlugin::activate ()
{
if (!initialized) {
OSErr err;
DEBUG_TRACE (DEBUG::AudioUnitConfig, "call Initialize in activate()\n");
if ((err = unit->Initialize()) != noErr) {
error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
} else {
samples_processed = 0;
initialized = true;
}
}
}
void
AUPlugin::deactivate ()
{
DEBUG_TRACE (DEBUG::AudioUnitConfig, "call Uninitialize in deactivate()\n");
unit->Uninitialize ();
initialized = false;
}
void
AUPlugin::flush ()
{
DEBUG_TRACE (DEBUG::AudioUnitConfig, "call Reset in flush()\n");
unit->GlobalReset ();
}
bool
AUPlugin::requires_fixed_size_buffers() const
{
return _requires_fixed_size_buffers;
}
void
AUPlugin::set_non_realtime (bool yn)
{
if (process_offline == yn) {
return;
}
process_offline = yn;
bool was_initialized = initialized;
if (initialized) {
deactivate ();
}
OSErr err;
UInt32 isOffline = yn ? 1 : 0;
if ((err = unit->SetProperty (/*kAudioUnitProperty_OfflineRender*/ 37, kAudioUnitScope_Global, 0, &isOffline, sizeof (isOffline))) != noErr) {
info << string_compose (_("AU: cannot set offline rendering(err = %1)"), err) << endmsg;
}
if (yn) {
UInt32 numSamples = _session.get_block_size();
unit->SetProperty (/*kAudioUnitOfflineProperty_InputSize*/ 3020, kAudioUnitScope_Global, 0, &numSamples, sizeof(numSamples));
}
if (was_initialized) {
activate ();
}
}
int
AUPlugin::set_block_size (pframes_t nframes)
{
bool was_initialized = initialized;
UInt32 numSamples = nframes;
OSErr err;
if (initialized) {
deactivate ();
}
DEBUG_TRACE (DEBUG::AudioUnitConfig, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numSamples));
if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
0, &numSamples, sizeof (numSamples))) != noErr) {
error << string_compose (_("AU: cannot set max samples (err = %1)"), err) << endmsg;
return -1;
}
if (process_offline) {
unit->SetProperty (/*kAudioUnitOfflineProperty_InputSize*/ 3020, kAudioUnitScope_Global, 0, &numSamples, sizeof(numSamples));
}
if (was_initialized) {
activate ();
}
return 0;
}
bool
AUPlugin::reconfigure_io (ChanCount in, ChanCount aux_in, ChanCount out)
{
AudioStreamBasicDescription streamFormat;
bool was_initialized = initialized;
DEBUG_TRACE (DEBUG::AudioUnitConfig, string_compose ("AUPlugin::reconfigure_io %1 for in: %2 aux-in %3 out: %4 out\n", name(), in, aux_in, out));
//TODO handle cases of no-input, only sidechain
// (needs special-casing of configured_input_busses)
if (input_elements == 1 || in.n_audio () == 0) {
in += aux_in;
aux_in.reset ();
}
const int32_t audio_in = in.n_audio();
const int32_t audio_out = out.n_audio();
if (initialized) {
/* if we are already running with the requested i/o config, bail out here */
if ((audio_in + aux_in.n_audio () == input_channels) && (audio_out == output_channels)) {
return true;
} else {
deactivate ();
}
}
streamFormat.mSampleRate = _session.sample_rate();
streamFormat.mFormatID = kAudioFormatLinearPCM;
streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
#ifdef __LITTLE_ENDIAN__
/* relax */
#else
streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
#endif
streamFormat.mBitsPerChannel = 32;
streamFormat.mFramesPerPacket = 1;
/* apple says that for non-interleaved data, these
* values always refer to a single channel.
*/
streamFormat.mBytesPerPacket = 4;
streamFormat.mBytesPerFrame = 4;
configured_input_busses = 0;
configured_output_busses = 0;
/* reset busses */
for (size_t i = 0; i < output_elements; ++i) {
unit->Reset (kAudioUnitScope_Output, i);
}
for (size_t i = 0; i < input_elements; ++i) {
bus_inused[i] = 0;
unit->Reset (kAudioUnitScope_Input, i);
/* remove any input callbacks */
AURenderCallbackStruct renderCallbackInfo;
renderCallbackInfo.inputProc = 0;
renderCallbackInfo.inputProcRefCon = 0;
unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo));
}
/* now assign the channels to available busses */
uint32_t used_in = 0;
uint32_t used_out = 0;
if (input_elements == 0 || audio_in == 0) {
configured_input_busses = 0;
} else if (variable_inputs || input_elements == 1 || audio_in < bus_inputs[0]) {
/* we only ever use the first bus and configure it to match */
if (variable_inputs && input_elements > 1) {
info << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
}
streamFormat.mChannelsPerFrame = audio_in;
if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
warning << string_compose (_("AU %1 failed to reconfigure input: %2"), name(), audio_in) << endmsg;
return false;
}
bus_inused[0] = audio_in;
configured_input_busses = 1;
used_in = audio_in;
} else {
/* more inputs than the first bus' channel-count: distribute sequentially */
configured_input_busses = 0;
uint32_t remain = audio_in + aux_in.n_audio ();