NOOP, remove trailing tabs/whitespace.
[ardour.git] / libs / ardour / audio_unit.cc
1 /*
2     Copyright (C) 2006-2009 Paul Davis
3     Some portions Copyright (C) Sophia Poirier.
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <sstream>
22 #include <fstream>
23 #include <errno.h>
24 #include <string.h>
25 #include <math.h>
26 #include <ctype.h>
27
28 #include "pbd/transmitter.h"
29 #include "pbd/xml++.h"
30 #include "pbd/convert.h"
31 #include "pbd/whitespace.h"
32 #include "pbd/file_utils.h"
33 #include "pbd/locale_guard.h"
34
35 #include <glibmm/threads.h>
36 #include <glibmm/fileutils.h>
37 #include <glibmm/miscutils.h>
38 #include <pbd/gstdio_compat.h>
39
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/debug.h"
44 #include "ardour/midi_buffer.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/audio_unit.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
52
53 #include "appleutility/CAAudioUnit.h"
54 #include "appleutility/CAAUParameter.h"
55
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
60 #ifdef WITH_CARBON
61 #include <Carbon/Carbon.h>
62 #endif
63
64 #include "i18n.h"
65
66 using namespace std;
67 using namespace PBD;
68 using namespace ARDOUR;
69
70 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
71
72 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
73 static string preset_suffix = ".aupreset";
74 static bool preset_search_path_initialized = false;
75 FILE * AUPluginInfo::_crashlog_fd = NULL;
76 bool AUPluginInfo::_scan_only = true;
77
78
79 static void au_blacklist (std::string id)
80 {
81         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
82         FILE * blacklist_fd = NULL;
83         if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
84                 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
85                 return;
86         }
87         assert(id.find("\n") == string::npos);
88         fprintf(blacklist_fd, "%s\n", id.c_str());
89         ::fclose(blacklist_fd);
90 }
91
92 static void au_unblacklist (std::string id)
93 {
94         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
95         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
96                 PBD::warning << "Expected Blacklist file does not exist.\n";
97                 return;
98         }
99
100         std::string bl;
101         {
102                 std::ifstream ifs(fn.c_str());
103                 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
104         }
105
106         ::g_unlink (fn.c_str());
107
108         assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
109         assert(id.find("\n") == string::npos);
110
111         id += "\n"; // add separator
112         const size_t rpl = bl.find(id);
113         if (rpl != string::npos) {
114                 bl.replace(rpl, id.size(), "");
115         }
116         if (bl.empty()) {
117                 return;
118         }
119
120         FILE * blacklist_fd = NULL;
121         if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
122                 PBD::error << "Cannot open AU blacklist.\n";
123                 return;
124         }
125         fprintf(blacklist_fd, "%s", bl.c_str());
126         ::fclose(blacklist_fd);
127 }
128
129 static bool is_blacklisted (std::string id)
130 {
131         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
132         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
133                 return false;
134         }
135         std::string bl;
136         std::ifstream ifs(fn.c_str());
137         bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
138
139         assert(id.find("\n") == string::npos);
140
141         id += "\n"; // add separator
142         const size_t rpl = bl.find(id);
143         if (rpl != string::npos) {
144                 return true;
145         }
146         return false;
147 }
148
149
150
151 static OSStatus
152 _render_callback(void *userData,
153                  AudioUnitRenderActionFlags *ioActionFlags,
154                  const AudioTimeStamp    *inTimeStamp,
155                  UInt32       inBusNumber,
156                  UInt32       inNumberFrames,
157                  AudioBufferList*       ioData)
158 {
159         if (userData) {
160                 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
161         }
162         return paramErr;
163 }
164
165 static OSStatus
166 _get_beat_and_tempo_callback (void*    userData,
167                               Float64* outCurrentBeat,
168                               Float64* outCurrentTempo)
169 {
170         if (userData) {
171                 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
172         }
173
174         return paramErr;
175 }
176
177 static OSStatus
178 _get_musical_time_location_callback (void *     userData,
179                                      UInt32 *   outDeltaSampleOffsetToNextBeat,
180                                      Float32 *  outTimeSig_Numerator,
181                                      UInt32 *   outTimeSig_Denominator,
182                                      Float64 *  outCurrentMeasureDownBeat)
183 {
184         if (userData) {
185                 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
186                                                                                   outTimeSig_Numerator,
187                                                                                   outTimeSig_Denominator,
188                                                                                   outCurrentMeasureDownBeat);
189         }
190         return paramErr;
191 }
192
193 static OSStatus
194 _get_transport_state_callback (void*     userData,
195                                Boolean*  outIsPlaying,
196                                Boolean*  outTransportStateChanged,
197                                Float64*  outCurrentSampleInTimeLine,
198                                Boolean*  outIsCycling,
199                                Float64*  outCycleStartBeat,
200                                Float64*  outCycleEndBeat)
201 {
202         if (userData) {
203                 return ((AUPlugin*)userData)->get_transport_state_callback (
204                         outIsPlaying, outTransportStateChanged,
205                         outCurrentSampleInTimeLine, outIsCycling,
206                         outCycleStartBeat, outCycleEndBeat);
207         }
208         return paramErr;
209 }
210
211
212 static int
213 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
214
215 {
216         CFDataRef xmlData;
217         int fd;
218
219         // Convert the property list into XML data.
220
221         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
222
223         if (!xmlData) {
224                 error << _("Could not create XML version of property list") << endmsg;
225                 return -1;
226         }
227
228         // Write the XML data to the file.
229
230         fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
231         while (fd < 0) {
232                 if (errno == EEXIST) {
233                         error << string_compose (_("Preset file %1 exists; not overwriting"),
234                                                  path) << endmsg;
235                 } else {
236                         error << string_compose (_("Cannot open preset file %1 (%2)"),
237                                                  path, strerror (errno)) << endmsg;
238                 }
239                 CFRelease (xmlData);
240                 return -1;
241         }
242
243         size_t cnt = CFDataGetLength (xmlData);
244
245         if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
246                 CFRelease (xmlData);
247                 close (fd);
248                 return -1;
249         }
250
251         close (fd);
252         return 0;
253 }
254
255
256 static CFPropertyListRef
257 load_property_list (Glib::ustring path)
258 {
259         int fd;
260         CFPropertyListRef propertyList = 0;
261         CFDataRef         xmlData;
262         CFStringRef       errorString;
263
264         // Read the XML file.
265
266         if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
267                 return propertyList;
268
269         }
270
271         off_t len = lseek (fd, 0, SEEK_END);
272         char* buf = new char[len];
273         lseek (fd, 0, SEEK_SET);
274
275         if (read (fd, buf, len) != len) {
276                 delete [] buf;
277                 close (fd);
278                 return propertyList;
279         }
280
281         close (fd);
282
283         xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
284
285         // Reconstitute the dictionary using the XML data.
286
287         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
288                                                         xmlData,
289                                                         kCFPropertyListImmutable,
290                                                         &errorString);
291
292         CFRelease (xmlData);
293         delete [] buf;
294
295         return propertyList;
296 }
297
298 //-----------------------------------------------------------------------------
299 static void
300 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
301 {
302         if (!plist) {
303                 return;
304         }
305         CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
306
307         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
308                 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
309         }
310
311         CFRelease (pn);
312 }
313
314 //-----------------------------------------------------------------------------
315 static std::string
316 get_preset_name_in_plist (CFPropertyListRef plist)
317 {
318         std::string ret;
319
320         if (!plist) {
321                 return ret;
322         }
323
324         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
325                 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
326                 if (p) {
327                         CFStringRef str = (CFStringRef) p;
328                         int len = CFStringGetLength(str);
329                         len =  (len * 2) + 1;
330                         char local_buffer[len];
331                         if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
332                                 ret = local_buffer;
333                         }
334                 }
335         }
336         return ret;
337 }
338
339 //--------------------------------------------------------------------------
340 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
341 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
342 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
343 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
344 {
345         if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
346                 return FALSE;
347
348         if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
349                         && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
350         {
351                 // only sub-type and manufacturer IDs need to be equal
352                 if (inIgnoreType)
353                         return TRUE;
354                 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
355                 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
356                         return TRUE;
357         }
358
359         return FALSE;
360 }
361
362 //--------------------------------------------------------------------------
363 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
364 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
365 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
366 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
367 {
368         OSErr status;
369         ComponentDescription desc;
370
371         if ( (inComponent == NULL) || (inComponentDescription == NULL) )
372                 return FALSE;
373
374         // get the ComponentDescription of the input Component
375         status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
376         if (status != noErr)
377                 return FALSE;
378
379         // check if the Component's ComponentDescription matches the input ComponentDescription
380         return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
381 }
382
383 //--------------------------------------------------------------------------
384 // determine if 2 ComponentDescriptions are basically equal
385 // (by that, I mean that the important identifying values are compared,
386 // but not the ComponentDescription flags)
387 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
388 {
389         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
390 }
391
392 //--------------------------------------------------------------------------
393 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
394 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
395 {
396         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
397 }
398
399 //--------------------------------------------------------------------------
400 // determine if a ComponentDescription basically matches that of a particular Component
401 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
402 {
403         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
404 }
405
406 //--------------------------------------------------------------------------
407 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
408 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
409 {
410         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
411 }
412
413
414 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
415         : Plugin (engine, session)
416         , comp (_comp)
417         , unit (new CAAudioUnit)
418         , initialized (false)
419         , _current_block_size (0)
420         , _requires_fixed_size_buffers (false)
421         , buffers (0)
422         , input_maxbuf (0)
423         , input_offset (0)
424         , input_buffers (0)
425         , frames_processed (0)
426         , audio_input_cnt (0)
427         , _parameter_listener (0)
428         , _parameter_listener_arg (0)
429         , last_transport_rolling (false)
430         , last_transport_speed (0.0)
431 {
432         if (!preset_search_path_initialized) {
433                 Glib::ustring p = Glib::get_home_dir();
434                 p += "/Library/Audio/Presets:";
435                 p += preset_search_path;
436                 preset_search_path = p;
437                 preset_search_path_initialized = true;
438                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
439         }
440
441         init ();
442 }
443
444
445 AUPlugin::AUPlugin (const AUPlugin& other)
446         : Plugin (other)
447         , comp (other.get_comp())
448         , unit (new CAAudioUnit)
449         , initialized (false)
450         , _current_block_size (0)
451         , _last_nframes (0)
452         , _requires_fixed_size_buffers (false)
453         , buffers (0)
454         , input_maxbuf (0)
455         , input_offset (0)
456         , input_buffers (0)
457         , frames_processed (0)
458         , _parameter_listener (0)
459         , _parameter_listener_arg (0)
460
461 {
462         init ();
463         for (size_t i = 0; i < descriptors.size(); ++i) {
464                 set_parameter (i, other.get_parameter (i));
465         }
466 }
467
468 AUPlugin::~AUPlugin ()
469 {
470         if (_parameter_listener) {
471                 AUListenerDispose (_parameter_listener);
472                 _parameter_listener = 0;
473         }
474
475         if (unit) {
476                 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
477                 unit->Uninitialize ();
478         }
479
480         if (buffers) {
481                 free (buffers);
482         }
483 }
484
485 void
486 AUPlugin::discover_factory_presets ()
487 {
488         CFArrayRef presets;
489         UInt32 dataSize;
490         Boolean isWritable;
491         OSStatus err;
492
493         if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
494                 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
495                 return;
496         }
497
498         assert (dataSize == sizeof (presets));
499
500         if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
501                 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
502                 return;
503         }
504
505         if (!presets) {
506                 return;
507         }
508
509         CFIndex cnt = CFArrayGetCount (presets);
510
511         for (CFIndex i = 0; i < cnt; ++i) {
512                 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
513
514                 string name = CFStringRefToStdString (preset->presetName);
515                 factory_preset_map[name] = preset->presetNumber;
516                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
517         }
518
519         CFRelease (presets);
520 }
521
522 void
523 AUPlugin::init ()
524 {
525         OSErr err;
526         CFStringRef itemName;
527
528         /* these keep track of *configured* channel set up,
529            not potential set ups.
530         */
531
532         input_channels = -1;
533         output_channels = -1;
534         {
535                 CAComponentDescription temp;
536                 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
537                 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
538                 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
539                 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
540                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
541                                 compTypeString, compManufacturerString, compSubTypeString);
542                 if (compTypeString != NULL) CFRelease(compTypeString);
543                 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
544                 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
545         }
546
547         au_blacklist(CFStringRefToStdString(itemName));
548
549         try {
550                 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
551                 err = CAAudioUnit::Open (*(comp.get()), *unit);
552         } catch (...) {
553                 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
554                 throw failed_constructor();
555         }
556
557         if (err != noErr) {
558                 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
559                 throw failed_constructor ();
560         }
561
562         DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
563         unit->GetElementCount (kAudioUnitScope_Global, global_elements);
564         DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
565         unit->GetElementCount (kAudioUnitScope_Input, input_elements);
566         DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
567         unit->GetElementCount (kAudioUnitScope_Output, output_elements);
568
569         if (input_elements > 0) {
570                 /* setup render callback: the plugin calls this to get input data
571                  */
572
573                 AURenderCallbackStruct renderCallbackInfo;
574
575                 renderCallbackInfo.inputProc = _render_callback;
576                 renderCallbackInfo.inputProcRefCon = this;
577
578                 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
579                 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
580                                               0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
581                         error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
582                         throw failed_constructor();
583                 }
584         }
585
586         /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
587
588         HostCallbackInfo info;
589         memset (&info, 0, sizeof (HostCallbackInfo));
590         info.hostUserData = this;
591         info.beatAndTempoProc = _get_beat_and_tempo_callback;
592         info.musicalTimeLocationProc = _get_musical_time_location_callback;
593         info.transportStateProc = _get_transport_state_callback;
594
595         //ignore result of this - don't care if the property isn't supported
596         DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
597         unit->SetProperty (kAudioUnitProperty_HostCallbacks,
598                            kAudioUnitScope_Global,
599                            0, //elementID
600                            &info,
601                            sizeof (HostCallbackInfo));
602
603         if (set_block_size (_session.get_block_size())) {
604                 error << _("AUPlugin: cannot set processing block size") << endmsg;
605                 throw failed_constructor();
606         }
607
608         create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
609         discover_parameters ();
610         discover_factory_presets ();
611
612         // Plugin::setup_controls ();
613
614         au_unblacklist(CFStringRefToStdString(itemName));
615         if (itemName != NULL) CFRelease(itemName);
616 }
617
618 void
619 AUPlugin::discover_parameters ()
620 {
621         /* discover writable parameters */
622
623         AudioUnitScope scopes[] = {
624                 kAudioUnitScope_Global,
625                 kAudioUnitScope_Output,
626                 kAudioUnitScope_Input
627         };
628
629         descriptors.clear ();
630
631         for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
632
633                 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
634
635                 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
636
637                         AUParameterDescriptor d;
638
639                         d.id = param_info.ParamID (i);
640
641                         const CAAUParameter* param = param_info.GetParamInfo (d.id);
642                         const AudioUnitParameterInfo& info (param->ParamInfo());
643
644                         const int len = CFStringGetLength (param->GetName());;
645                         char local_buffer[len*2];
646                         Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
647                         if (!good) {
648                                 d.label = "???";
649                         } else {
650                                 d.label = local_buffer;
651                         }
652
653                         d.scope = param_info.GetScope ();
654                         d.element = param_info.GetElement ();
655
656                         /* info.units to consider */
657                         /*
658                           kAudioUnitParameterUnit_Generic             = 0
659                           kAudioUnitParameterUnit_Indexed             = 1
660                           kAudioUnitParameterUnit_Boolean             = 2
661                           kAudioUnitParameterUnit_Percent             = 3
662                           kAudioUnitParameterUnit_Seconds             = 4
663                           kAudioUnitParameterUnit_SampleFrames        = 5
664                           kAudioUnitParameterUnit_Phase               = 6
665                           kAudioUnitParameterUnit_Rate                = 7
666                           kAudioUnitParameterUnit_Hertz               = 8
667                           kAudioUnitParameterUnit_Cents               = 9
668                           kAudioUnitParameterUnit_RelativeSemiTones   = 10
669                           kAudioUnitParameterUnit_MIDINoteNumber      = 11
670                           kAudioUnitParameterUnit_MIDIController      = 12
671                           kAudioUnitParameterUnit_Decibels            = 13
672                           kAudioUnitParameterUnit_LinearGain          = 14
673                           kAudioUnitParameterUnit_Degrees             = 15
674                           kAudioUnitParameterUnit_EqualPowerCrossfade = 16
675                           kAudioUnitParameterUnit_MixerFaderCurve1    = 17
676                           kAudioUnitParameterUnit_Pan                 = 18
677                           kAudioUnitParameterUnit_Meters              = 19
678                           kAudioUnitParameterUnit_AbsoluteCents       = 20
679                           kAudioUnitParameterUnit_Octaves             = 21
680                           kAudioUnitParameterUnit_BPM                 = 22
681                           kAudioUnitParameterUnit_Beats               = 23
682                           kAudioUnitParameterUnit_Milliseconds        = 24
683                           kAudioUnitParameterUnit_Ratio               = 25
684                         */
685
686                         /* info.flags to consider */
687
688                         /*
689
690                           kAudioUnitParameterFlag_CFNameRelease       = (1L << 4)
691                           kAudioUnitParameterFlag_HasClump            = (1L << 20)
692                           kAudioUnitParameterFlag_HasName             = (1L << 21)
693                           kAudioUnitParameterFlag_DisplayLogarithmic  = (1L << 22)
694                           kAudioUnitParameterFlag_IsHighResolution    = (1L << 23)
695                           kAudioUnitParameterFlag_NonRealTime         = (1L << 24)
696                           kAudioUnitParameterFlag_CanRamp             = (1L << 25)
697                           kAudioUnitParameterFlag_ExpertMode          = (1L << 26)
698                           kAudioUnitParameterFlag_HasCFNameString     = (1L << 27)
699                           kAudioUnitParameterFlag_IsGlobalMeta        = (1L << 28)
700                           kAudioUnitParameterFlag_IsElementMeta       = (1L << 29)
701                           kAudioUnitParameterFlag_IsReadable          = (1L << 30)
702                           kAudioUnitParameterFlag_IsWritable          = (1L << 31)
703                         */
704
705                         d.lower = info.minValue;
706                         d.upper = info.maxValue;
707                         d.normal = info.defaultValue;
708
709                         d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
710                         d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
711                                 (d.integer_step && ((d.upper - d.lower) == 1.0));
712                         d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
713                         d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
714                                 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
715                                 (info.flags & kAudioUnitParameterFlag_IsWritable);
716
717                         d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
718                         d.au_unit = info.unit;
719                         switch (info.unit) {
720                         case kAudioUnitParameterUnit_Decibels:
721                                 d.unit = ParameterDescriptor::DB;
722                                 break;
723                         case kAudioUnitParameterUnit_MIDINoteNumber:
724                                 d.unit = ParameterDescriptor::MIDI_NOTE;
725                                 break;
726                         case kAudioUnitParameterUnit_Hertz:
727                                 d.unit = ParameterDescriptor::HZ;
728                                 break;
729                         }
730
731                         d.min_unbound = 0; // lower is bound
732                         d.max_unbound = 0; // upper is bound
733                         d.update_steps();
734
735                         descriptors.push_back (d);
736
737                         uint32_t last_param = descriptors.size() - 1;
738                         parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
739                         listen_to_parameter (last_param);
740                 }
741         }
742 }
743
744
745 static unsigned int
746 four_ints_to_four_byte_literal (unsigned char n[4])
747 {
748         /* this is actually implementation dependent. sigh. this is what gcc
749            and quite a few others do.
750          */
751         return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
752 }
753
754 std::string
755 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
756 {
757         if (isdigit (id[0])) {
758                 return id;
759         }
760
761         /* ID format is xxxx-xxxx-xxxx
762            where x maybe \xNN or a printable character.
763
764            Split at the '-' and and process each part into an integer.
765            Then put it back together.
766         */
767
768
769         unsigned char nascent[4];
770         const char* cstr = id.c_str();
771         const char* estr = cstr + id.size();
772         uint32_t n[3];
773         int in;
774         int next_int;
775         char short_buf[3];
776         stringstream s;
777
778         in = 0;
779         next_int = 0;
780         short_buf[2] = '\0';
781
782         while (*cstr && next_int < 4) {
783
784                 if (*cstr == '\\') {
785
786                         if (estr - cstr < 3) {
787
788                                 /* too close to the end for \xNN parsing: treat as literal characters */
789
790                                 nascent[in] = *cstr;
791                                 ++cstr;
792                                 ++in;
793
794                         } else {
795
796                                 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
797
798                                         /* parse \xNN */
799
800                                         memcpy (short_buf, &cstr[2], 2);
801                                         nascent[in] = strtol (short_buf, NULL, 16);
802                                         cstr += 4;
803                                         ++in;
804
805                                 } else {
806
807                                         /* treat as literal characters */
808                                         nascent[in] = *cstr;
809                                         ++cstr;
810                                         ++in;
811                                 }
812                         }
813
814                 } else {
815
816                         nascent[in] = *cstr;
817                         ++cstr;
818                         ++in;
819                 }
820
821                 if (in && (in % 4 == 0)) {
822                         /* nascent is ready */
823                         n[next_int] = four_ints_to_four_byte_literal (nascent);
824                         in = 0;
825                         next_int++;
826
827                         /* swallow space-hyphen-space */
828
829                         if (next_int < 3) {
830                                 ++cstr;
831                                 ++cstr;
832                                 ++cstr;
833                         }
834                 }
835         }
836
837         if (next_int != 3) {
838                 goto err;
839         }
840
841         s << n[0] << '-' << n[1] << '-' << n[2];
842
843         return s.str();
844
845   err:
846         return string();
847 }
848
849 string
850 AUPlugin::unique_id () const
851 {
852         return AUPluginInfo::stringify_descriptor (comp->Desc());
853 }
854
855 const char *
856 AUPlugin::label () const
857 {
858         return _info->name.c_str();
859 }
860
861 uint32_t
862 AUPlugin::parameter_count () const
863 {
864         return descriptors.size();
865 }
866
867 float
868 AUPlugin::default_value (uint32_t port)
869 {
870         if (port < descriptors.size()) {
871                 return descriptors[port].normal;
872         }
873
874         return 0;
875 }
876
877 framecnt_t
878 AUPlugin::signal_latency () const
879 {
880         return unit->Latency() * _session.frame_rate();
881 }
882
883 void
884 AUPlugin::set_parameter (uint32_t which, float val)
885 {
886         if (which >= descriptors.size()) {
887                 return;
888         }
889
890         if (get_parameter(which) == val) {
891                 return;
892         }
893
894         const AUParameterDescriptor& d (descriptors[which]);
895         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
896         unit->SetParameter (d.id, d.scope, d.element, val);
897
898         /* tell the world what we did */
899
900         AudioUnitEvent theEvent;
901
902         theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
903         theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
904         theEvent.mArgument.mParameter.mParameterID = d.id;
905         theEvent.mArgument.mParameter.mScope = d.scope;
906         theEvent.mArgument.mParameter.mElement = d.element;
907
908         DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
909         AUEventListenerNotify (NULL, NULL, &theEvent);
910
911         Plugin::set_parameter (which, val);
912 }
913
914 float
915 AUPlugin::get_parameter (uint32_t which) const
916 {
917         float val = 0.0;
918         if (which < descriptors.size()) {
919                 const AUParameterDescriptor& d (descriptors[which]);
920                 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
921                 unit->GetParameter(d.id, d.scope, d.element, val);
922         }
923         return val;
924 }
925
926 int
927 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
928 {
929         if (which < descriptors.size()) {
930                 pd = descriptors[which];
931                 return 0;
932         }
933         return -1;
934 }
935
936 uint32_t
937 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
938 {
939         if (which < descriptors.size()) {
940                 ok = true;
941                 return which;
942         }
943         ok = false;
944         return 0;
945 }
946
947 void
948 AUPlugin::activate ()
949 {
950         if (!initialized) {
951                 OSErr err;
952                 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
953                 if ((err = unit->Initialize()) != noErr) {
954                         error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
955                 } else {
956                         frames_processed = 0;
957                         initialized = true;
958                 }
959         }
960 }
961
962 void
963 AUPlugin::deactivate ()
964 {
965         DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
966         unit->Uninitialize ();
967         initialized = false;
968 }
969
970 void
971 AUPlugin::flush ()
972 {
973         DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
974         unit->GlobalReset ();
975 }
976
977 bool
978 AUPlugin::requires_fixed_size_buffers() const
979 {
980         return _requires_fixed_size_buffers;
981 }
982
983
984 int
985 AUPlugin::set_block_size (pframes_t nframes)
986 {
987         bool was_initialized = initialized;
988         UInt32 numFrames = nframes;
989         OSErr err;
990
991         if (initialized) {
992                 deactivate ();
993         }
994
995         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
996         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
997                                       0, &numFrames, sizeof (numFrames))) != noErr) {
998                 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
999                 return -1;
1000         }
1001
1002         if (was_initialized) {
1003                 activate ();
1004         }
1005
1006         _current_block_size = nframes;
1007
1008         return 0;
1009 }
1010
1011 bool
1012 AUPlugin::configure_io (ChanCount in, ChanCount out)
1013 {
1014         AudioStreamBasicDescription streamFormat;
1015         bool was_initialized = initialized;
1016         int32_t audio_out = out.n_audio();
1017         if (audio_input_cnt > 0) {
1018                 in.set (DataType::AUDIO, audio_input_cnt);
1019         }
1020         int32_t audio_in = in.n_audio();
1021
1022         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1023
1024         if (initialized) {
1025                 //if we are already running with the requested i/o config, bail out here
1026                 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1027                         return 0;
1028                 } else {
1029                         deactivate ();
1030                 }
1031         }
1032
1033         streamFormat.mSampleRate = _session.frame_rate();
1034         streamFormat.mFormatID = kAudioFormatLinearPCM;
1035         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1036
1037 #ifdef __LITTLE_ENDIAN__
1038         /* relax */
1039 #else
1040         streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1041 #endif
1042
1043         streamFormat.mBitsPerChannel = 32;
1044         streamFormat.mFramesPerPacket = 1;
1045
1046         /* apple says that for non-interleaved data, these
1047            values always refer to a single channel.
1048         */
1049         streamFormat.mBytesPerPacket = 4;
1050         streamFormat.mBytesPerFrame = 4;
1051
1052         streamFormat.mChannelsPerFrame = audio_in;
1053
1054         if (set_input_format (streamFormat) != 0) {
1055                 return -1;
1056         }
1057
1058         streamFormat.mChannelsPerFrame = audio_out;
1059
1060         if (set_output_format (streamFormat) != 0) {
1061                 return -1;
1062         }
1063
1064         /* reset plugin info to show currently configured state */
1065
1066         _info->n_inputs = in;
1067         _info->n_outputs = out;
1068
1069         if (was_initialized) {
1070                 activate ();
1071         }
1072
1073         return 0;
1074 }
1075
1076 ChanCount
1077 AUPlugin::input_streams() const
1078 {
1079         ChanCount c;
1080
1081
1082         if (input_channels < 0) {
1083                 // force PluginIoReConfigure -- see also commit msg e38eb06
1084                 c.set (DataType::AUDIO, 0);
1085                 c.set (DataType::MIDI, 0);
1086         } else {
1087                 c.set (DataType::AUDIO, input_channels);
1088                 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1089         }
1090
1091         return c;
1092 }
1093
1094
1095 ChanCount
1096 AUPlugin::output_streams() const
1097 {
1098         ChanCount c;
1099
1100         if (output_channels < 0) {
1101                 // force PluginIoReConfigure - see also commit msg e38eb06
1102                 c.set (DataType::AUDIO, 0);
1103                 c.set (DataType::MIDI, 0);
1104         } else {
1105                 c.set (DataType::AUDIO, output_channels);
1106                 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1107         }
1108
1109         return c;
1110 }
1111
1112 bool
1113 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1114 {
1115         // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1116
1117         int32_t audio_in = in.n_audio();
1118         int32_t audio_out;
1119         bool found = false;
1120         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1121
1122         /* lets check MIDI first */
1123
1124         if (in.n_midi() > 0) {
1125                 if (!_has_midi_input) {
1126                         return false;
1127                 }
1128         }
1129
1130         vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1131
1132         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1133                                                         name(), io_configs.size(), in, out));
1134
1135         //Ardour expects the plugin to tell it the output
1136         //configuration but AU plugins can have multiple I/O
1137         //configurations in most cases. so first lets see
1138         //if there's a configuration that keeps out==in
1139
1140         if (in.n_midi() > 0 && audio_in == 0) {
1141                 audio_out = 2; // prefer stereo version if available.
1142         } else {
1143                 audio_out = audio_in;
1144         }
1145
1146         /* kAudioUnitProperty_SupportedNumChannels
1147          * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1148          *
1149          * - both fields are -1
1150          *   e.g. inChannels = -1 outChannels = -1
1151          *    This is the default case. Any number of input and output channels, as long as the numbers match
1152          *
1153          * - one field is -1, the other field is positive
1154          *   e.g. inChannels = -1 outChannels = 2
1155          *    Any number of input channels, exactly two output channels
1156          *
1157          * - one field is -1, the other field is -2
1158          *   e.g. inChannels = -1 outChannels = -2
1159          *    Any number of input channels, any number of output channels
1160          *
1161          * - both fields have non-negative values
1162          *   e.g. inChannels = 2 outChannels = 6
1163          *    Exactly two input channels, exactly six output channels
1164          *   e.g. inChannels = 0 outChannels = 2
1165          *    No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1166          *
1167          * - both fields have negative values, neither of which is â€“1 or â€“2
1168          *   e.g. inChannels = -4 outChannels = -8
1169          *    Up to four input channels and up to eight output channels
1170          */
1171
1172         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1173
1174                 int32_t possible_in = i->first;
1175                 int32_t possible_out = i->second;
1176
1177                 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1178                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1179                                                                         possible_in, possible_out,
1180                                                                         in, out));
1181
1182                         out.set (DataType::MIDI, 0);
1183                         out.set (DataType::AUDIO, audio_out);
1184
1185                         return 1;
1186                 }
1187         }
1188
1189         /* now allow potentially "imprecise" matches */
1190
1191         audio_out = -1;
1192
1193         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1194
1195                 int32_t possible_in = i->first;
1196                 int32_t possible_out = i->second;
1197
1198                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1199
1200                 if (possible_out == 0) {
1201                         warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1202                         /* XXX surely this is just a send? (e.g. AUNetSend) */
1203                         continue;
1204                 }
1205
1206                 if (possible_in == 0) {
1207
1208                         /* instrument plugin, always legal but throws away inputs ...
1209                         */
1210
1211                         if (possible_out == -1) {
1212                                 /* any configuration possible, provide stereo output */
1213                                 audio_out = 2;
1214                                 found = true;
1215                         } else if (possible_out == -2) {
1216                                 /* plugins shouldn't really use (0,-2) but might.
1217                                    any configuration possible, provide stereo output
1218                                 */
1219                                 audio_out = 2;
1220                                 found = true;
1221                         } else if (possible_out < -2) {
1222                                 /* explicitly variable number of outputs.
1223                                  *
1224                                  * We really need to ask the user in this case.
1225                                  * stereo will be correct in 99.9% of all cases.
1226                                  */
1227                                 audio_out = 2;
1228                                 found = true;
1229                         } else {
1230                                 /* exact number of outputs */
1231                                 audio_out = possible_out;
1232                                 found = true;
1233                         }
1234                 }
1235
1236                 if (possible_in == -1) {
1237
1238                         /* wildcard for input */
1239
1240                         if (possible_out == -1) {
1241                                 /* out much match in */
1242                                 audio_out = audio_in;
1243                                 found = true;
1244                         } else if (possible_out == -2) {
1245                                 /* any configuration possible, pick matching */
1246                                 audio_out = audio_in;
1247                                 found = true;
1248                         } else if (possible_out < -2) {
1249                                 /* explicitly variable number of outputs, pick maximum */
1250                                 audio_out = -possible_out;
1251                                 found = true;
1252                         } else {
1253                                 /* exact number of outputs */
1254                                 audio_out = possible_out;
1255                                 found = true;
1256                         }
1257                 }
1258
1259                 if (possible_in == -2) {
1260
1261                         if (possible_out == -1) {
1262                                 /* any configuration possible, pick matching */
1263                                 audio_out = audio_in;
1264                                 found = true;
1265                         } else if (possible_out == -2) {
1266                                 /* plugins shouldn't really use (-2,-2) but might.
1267                                    interpret as (-1,-1).
1268                                 */
1269                                 audio_out = audio_in;
1270                                 found = true;
1271                         } else if (possible_out < -2) {
1272                                 /* explicitly variable number of outputs, pick maximum */
1273                                 audio_out = -possible_out;
1274                                 found = true;
1275                         } else {
1276                                 /* exact number of outputs */
1277                                 audio_out = possible_out;
1278                                 found = true;
1279                         }
1280                 }
1281
1282                 if (possible_in < -2) {
1283
1284                         /* explicit variable number of inputs */
1285
1286                         if (audio_in > -possible_in) {
1287                                 /* request is too large */
1288                         }
1289
1290
1291                         if (possible_out == -1) {
1292                                 /* any output configuration possible, provide stereo out */
1293                                 audio_out = 2;
1294                                 found = true;
1295                         } else if (possible_out == -2) {
1296                                 /* plugins shouldn't really use (<-2,-2) but might.
1297                                    interpret as (<-2,-1): any configuration possible, provide stereo output
1298                                 */
1299                                 audio_out = 2;
1300                                 found = true;
1301                         } else if (possible_out < -2) {
1302                                 /* explicitly variable number of outputs.
1303                                  *
1304                                  * We really need to ask the user in this case.
1305                                  * stereo will be correct in 99.9% of all cases.
1306                                  */
1307                                 audio_out = 2;
1308                                 found = true;
1309                         } else {
1310                                 /* exact number of outputs */
1311                                 audio_out = possible_out;
1312                                 found = true;
1313                         }
1314                 }
1315
1316                 if (possible_in && (possible_in == audio_in)) {
1317
1318                         /* exact number of inputs ... must match obviously */
1319
1320                         if (possible_out == -1) {
1321                                 /* any output configuration possible, provide stereo output */
1322                                 audio_out = 2;
1323                                 found = true;
1324                         } else if (possible_out == -2) {
1325                                 /* plugins shouldn't really use (>0,-2) but might.
1326                                    interpret as (>0,-1):
1327                                    any output configuration possible, provide stereo output
1328                                 */
1329                                 audio_out = 2;
1330                                 found = true;
1331                         } else if (possible_out < -2) {
1332                                 /* explicitly variable number of outputs, pick maximum */
1333                                 audio_out = -possible_out;
1334                                 found = true;
1335                         } else {
1336                                 /* exact number of outputs */
1337                                 audio_out = possible_out;
1338                                 found = true;
1339                         }
1340                 }
1341
1342                 if (found) {
1343                         if (possible_in < -2 && audio_in == 0) {
1344                                 // input-port count cannot be zero, use as many ports
1345                                 // as outputs, but at most abs(possible_in)
1346                                 audio_input_cnt = max (1, min (audio_out, -possible_in));
1347                         }
1348                         break;
1349                 }
1350
1351         }
1352
1353         if (found) {
1354                 out.set (DataType::MIDI, 0); /// XXX
1355                 out.set (DataType::AUDIO, audio_out);
1356                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1357         } else {
1358                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1359                 return false;
1360         }
1361
1362         return true;
1363 }
1364
1365 int
1366 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1367 {
1368         return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1369 }
1370
1371 int
1372 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1373 {
1374         if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1375                 return -1;
1376         }
1377
1378         if (buffers) {
1379                 free (buffers);
1380                 buffers = 0;
1381         }
1382
1383         buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1384                                               fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1385
1386         return 0;
1387 }
1388
1389 int
1390 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1391 {
1392         OSErr result;
1393
1394         for (uint32_t i = 0; i < cnt; ++i) {
1395                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1396                                                                 (scope == kAudioUnitScope_Input ? "input" : "output"),
1397                                                                 scope, cnt));
1398                 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1399                         error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1400                                                  (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1401                         return -1;
1402                 }
1403         }
1404
1405         if (scope == kAudioUnitScope_Input) {
1406                 input_channels = fmt.mChannelsPerFrame;
1407         } else {
1408                 output_channels = fmt.mChannelsPerFrame;
1409         }
1410
1411         return 0;
1412 }
1413
1414 OSStatus
1415 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1416                           const AudioTimeStamp*,
1417                           UInt32,
1418                           UInt32       inNumberFrames,
1419                           AudioBufferList*       ioData)
1420 {
1421         /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1422
1423         // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1424         // name(), inNumberFrames, ioData->mNumberBuffers));
1425
1426         if (input_maxbuf == 0) {
1427                 error << _("AUPlugin: render callback called illegally!") << endmsg;
1428                 return kAudioUnitErr_CannotDoInCurrentContext;
1429         }
1430         uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1431
1432         for (uint32_t i = 0; i < limit; ++i) {
1433                 ioData->mBuffers[i].mNumberChannels = 1;
1434                 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1435
1436                 /* we don't use the channel mapping because audiounits are
1437                    never replicated. one plugin instance uses all channels/buffers
1438                    passed to PluginInsert::connect_and_run()
1439                 */
1440
1441                 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1442         }
1443
1444         cb_offset += inNumberFrames;
1445
1446         return noErr;
1447 }
1448
1449 int
1450 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1451 {
1452         Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1453
1454         AudioUnitRenderActionFlags flags = 0;
1455         AudioTimeStamp ts;
1456         OSErr err;
1457
1458         if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1459                 unit->GlobalReset();
1460                 _last_nframes = nframes;
1461         }
1462
1463         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1464                                                         name(), input_channels, output_channels, _has_midi_input,
1465                                                         bufs.count(), bufs.available()));
1466
1467         /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1468            has the capacity to handle our outputs.
1469         */
1470
1471         assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1472
1473         input_buffers = &bufs;
1474         input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1475         input_offset = offset;
1476         cb_offset = 0;
1477
1478         buffers->mNumberBuffers = output_channels;
1479
1480         for (int32_t i = 0; i < output_channels; ++i) {
1481                 buffers->mBuffers[i].mNumberChannels = 1;
1482                 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1483                 /* setting this to 0 indicates to the AU that it can provide buffers here
1484                    if necessary. if it can process in-place, it will use the buffers provided
1485                    as input by ::render_callback() above.
1486
1487                    a non-null values tells the plugin to render into the buffer pointed
1488                    at by the value.
1489                 */
1490                 buffers->mBuffers[i].mData = 0;
1491         }
1492
1493         if (_has_midi_input) {
1494
1495                 uint32_t nmidi = bufs.count().n_midi();
1496
1497                 for (uint32_t i = 0; i < nmidi; ++i) {
1498
1499                         /* one MIDI port/buffer only */
1500
1501                         MidiBuffer& m = bufs.get_midi (i);
1502
1503                         for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1504                                 Evoral::MIDIEvent<framepos_t> ev (*i);
1505
1506                                 if (ev.is_channel_event()) {
1507                                         const uint8_t* b = ev.buffer();
1508                                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1509                                         unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1510                                 }
1511
1512                                 /* XXX need to handle sysex and other message types */
1513                         }
1514                 }
1515         }
1516
1517         /* does this really mean anything ?
1518          */
1519
1520         ts.mSampleTime = frames_processed;
1521         ts.mFlags = kAudioTimeStampSampleTimeValid;
1522
1523         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1524                                                         name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1525
1526         if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1527
1528                 input_maxbuf = 0;
1529                 frames_processed += nframes;
1530
1531                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1532                                                                 name(), buffers->mNumberBuffers, output_channels));
1533
1534                 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1535                 int32_t i;
1536
1537                 for (i = 0; i < limit; ++i) {
1538                         Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1539                         if (expected_buffer_address != buffers->mBuffers[i].mData) {
1540                                 /* plugin provided its own buffer for output so copy it back to where we want it
1541                                  */
1542                                 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1543                         }
1544                 }
1545
1546                 /* now silence any buffers that were passed in but the that the plugin
1547                    did not fill/touch/use.
1548                 */
1549
1550                 for (;i < output_channels; ++i) {
1551                         memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1552                 }
1553
1554                 return 0;
1555         }
1556
1557         error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1558         return -1;
1559 }
1560
1561 OSStatus
1562 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1563                                        Float64* outCurrentTempo)
1564 {
1565         TempoMap& tmap (_session.tempo_map());
1566
1567         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1568
1569         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1570            (and interpretation) of a beat position will be incorrect. So refuse to
1571            offer the value.
1572         */
1573
1574         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1575                 return kAudioUnitErr_CannotDoInCurrentContext;
1576         }
1577
1578         Timecode::BBT_Time bbt;
1579         TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1580         tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1581
1582         if (outCurrentBeat) {
1583                 float beat;
1584                 beat = metric.meter().divisions_per_bar() * bbt.bars;
1585                 beat += bbt.beats;
1586                 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1587                 *outCurrentBeat = beat;
1588         }
1589
1590         if (outCurrentTempo) {
1591                 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1592         }
1593
1594         return noErr;
1595
1596 }
1597
1598 OSStatus
1599 AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
1600                                               Float32*  outTimeSig_Numerator,
1601                                               UInt32*   outTimeSig_Denominator,
1602                                               Float64*  outCurrentMeasureDownBeat)
1603 {
1604         TempoMap& tmap (_session.tempo_map());
1605
1606         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1607
1608         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1609            (and interpretation) of a beat position will be incorrect. So refuse to
1610            offer the value.
1611         */
1612
1613         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1614                 return kAudioUnitErr_CannotDoInCurrentContext;
1615         }
1616
1617         Timecode::BBT_Time bbt;
1618         TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1619         tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1620
1621         if (outDeltaSampleOffsetToNextBeat) {
1622                 if (bbt.ticks == 0) {
1623                         /* on the beat */
1624                         *outDeltaSampleOffsetToNextBeat = 0;
1625                 } else {
1626                         *outDeltaSampleOffsetToNextBeat = (UInt32)
1627                                 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1628                                        metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1629                 }
1630         }
1631
1632         if (outTimeSig_Numerator) {
1633                 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1634         }
1635         if (outTimeSig_Denominator) {
1636                 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1637         }
1638
1639         if (outCurrentMeasureDownBeat) {
1640
1641                 /* beat for the start of the bar.
1642                    1|1|0 -> 1
1643                    2|1|0 -> 1 + divisions_per_bar
1644                    3|1|0 -> 1 + (2 * divisions_per_bar)
1645                    etc.
1646                 */
1647
1648                 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1649         }
1650
1651         return noErr;
1652 }
1653
1654 OSStatus
1655 AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
1656                                         Boolean*  outTransportStateChanged,
1657                                         Float64*  outCurrentSampleInTimeLine,
1658                                         Boolean*  outIsCycling,
1659                                         Float64*  outCycleStartBeat,
1660                                         Float64*  outCycleEndBeat)
1661 {
1662         bool rolling;
1663         float speed;
1664
1665         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1666
1667         rolling = _session.transport_rolling();
1668         speed = _session.transport_speed ();
1669
1670         if (outIsPlaying) {
1671                 *outIsPlaying = _session.transport_rolling();
1672         }
1673
1674         if (outTransportStateChanged) {
1675                 if (rolling != last_transport_rolling) {
1676                         *outTransportStateChanged = true;
1677                 } else if (speed != last_transport_speed) {
1678                         *outTransportStateChanged = true;
1679                 } else {
1680                         *outTransportStateChanged = false;
1681                 }
1682         }
1683
1684         if (outCurrentSampleInTimeLine) {
1685                 /* this assumes that the AU can only call this host callback from render context,
1686                    where input_offset is valid.
1687                 */
1688                 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1689         }
1690
1691         if (outIsCycling) {
1692                 Location* loc = _session.locations()->auto_loop_location();
1693
1694                 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1695
1696                 if (*outIsCycling) {
1697
1698                         if (outCycleStartBeat || outCycleEndBeat) {
1699
1700                                 TempoMap& tmap (_session.tempo_map());
1701
1702                                 /* more than 1 meter means that a simplistic computation (and interpretation) of
1703                                    a beat position will be incorrect. so refuse to offer the value.
1704                                 */
1705
1706                                 if (tmap.n_meters() > 1) {
1707                                         return kAudioUnitErr_CannotDoInCurrentContext;
1708                                 }
1709
1710                                 Timecode::BBT_Time bbt;
1711
1712                                 if (outCycleStartBeat) {
1713                                         TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1714                                         _session.tempo_map().bbt_time (loc->start(), bbt);
1715
1716                                         float beat;
1717                                         beat = metric.meter().divisions_per_bar() * bbt.bars;
1718                                         beat += bbt.beats;
1719                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1720
1721                                         *outCycleStartBeat = beat;
1722                                 }
1723
1724                                 if (outCycleEndBeat) {
1725                                         TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1726                                         _session.tempo_map().bbt_time (loc->end(), bbt);
1727
1728                                         float beat;
1729                                         beat = metric.meter().divisions_per_bar() * bbt.bars;
1730                                         beat += bbt.beats;
1731                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1732
1733                                         *outCycleEndBeat = beat;
1734                                 }
1735                         }
1736                 }
1737         }
1738
1739         last_transport_rolling = rolling;
1740         last_transport_speed = speed;
1741
1742         return noErr;
1743 }
1744
1745 set<Evoral::Parameter>
1746 AUPlugin::automatable() const
1747 {
1748         set<Evoral::Parameter> automates;
1749
1750         for (uint32_t i = 0; i < descriptors.size(); ++i) {
1751                 if (descriptors[i].automatable) {
1752                         automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1753                 }
1754         }
1755
1756         return automates;
1757 }
1758
1759 string
1760 AUPlugin::describe_parameter (Evoral::Parameter param)
1761 {
1762         if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1763                 return descriptors[param.id()].label;
1764         } else {
1765                 return "??";
1766         }
1767 }
1768
1769 void
1770 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1771 {
1772         // NameValue stuff here
1773 }
1774
1775 bool
1776 AUPlugin::parameter_is_audio (uint32_t) const
1777 {
1778         return false;
1779 }
1780
1781 bool
1782 AUPlugin::parameter_is_control (uint32_t param) const
1783 {
1784         assert(param < descriptors.size());
1785         if (descriptors[param].automatable) {
1786                 /* corrently ardour expects all controls to be automatable
1787                  * IOW ardour GUI elements mandate an Evoral::Parameter
1788                  * for all input+control ports.
1789                  */
1790                 return true;
1791         }
1792         return false;
1793 }
1794
1795 bool
1796 AUPlugin::parameter_is_input (uint32_t param) const
1797 {
1798         /* AU params that are both readable and writeable,
1799          * are listed in kAudioUnitScope_Global
1800          */
1801         return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1802 }
1803
1804 bool
1805 AUPlugin::parameter_is_output (uint32_t param) const
1806 {
1807         assert(param < descriptors.size());
1808         // TODO check if ardour properly handles ports
1809         // that report is_input + is_output == true
1810         // -> add || descriptors[param].scope == kAudioUnitScope_Global
1811         return (descriptors[param].scope == kAudioUnitScope_Output);
1812 }
1813
1814 void
1815 AUPlugin::add_state (XMLNode* root) const
1816 {
1817         LocaleGuard lg (X_("C"));
1818         CFDataRef xmlData;
1819         CFPropertyListRef propertyList;
1820
1821         DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1822         if (unit->GetAUPreset (propertyList) != noErr) {
1823                 return;
1824         }
1825
1826         // Convert the property list into XML data.
1827
1828         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1829
1830         if (!xmlData) {
1831                 error << _("Could not create XML version of property list") << endmsg;
1832                 return;
1833         }
1834
1835         /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1836            our state node. GACK!
1837         */
1838
1839         XMLTree t;
1840
1841         if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1842                 if (t.root()) {
1843                         root->add_child_copy (*t.root());
1844                 }
1845         }
1846
1847         CFRelease (xmlData);
1848         CFRelease (propertyList);
1849 }
1850
1851 int
1852 AUPlugin::set_state(const XMLNode& node, int version)
1853 {
1854         int ret = -1;
1855         CFPropertyListRef propertyList;
1856         LocaleGuard lg (X_("C"));
1857
1858         if (node.name() != state_node_name()) {
1859                 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1860                 return -1;
1861         }
1862
1863 #ifndef NO_PLUGIN_STATE
1864         if (node.children().empty()) {
1865                 return -1;
1866         }
1867
1868         XMLNode* top = node.children().front();
1869         XMLNode* copy = new XMLNode (*top);
1870
1871         XMLTree t;
1872         t.set_root (copy);
1873
1874         const string& xml = t.write_buffer ();
1875         CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1876         CFStringRef errorString;
1877
1878         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1879                                                         xmlData,
1880                                                         kCFPropertyListImmutable,
1881                                                         &errorString);
1882
1883         CFRelease (xmlData);
1884
1885         if (propertyList) {
1886                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1887                 if (unit->SetAUPreset (propertyList) == noErr) {
1888                         ret = 0;
1889
1890                         /* tell the world */
1891
1892                         AudioUnitParameter changedUnit;
1893                         changedUnit.mAudioUnit = unit->AU();
1894                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1895                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1896                 }
1897                 CFRelease (propertyList);
1898         }
1899 #endif
1900
1901         Plugin::set_state (node, version);
1902         return ret;
1903 }
1904
1905 bool
1906 AUPlugin::load_preset (PresetRecord r)
1907 {
1908         Plugin::load_preset (r);
1909
1910         bool ret = false;
1911         CFPropertyListRef propertyList;
1912         Glib::ustring path;
1913         UserPresetMap::iterator ux;
1914         FactoryPresetMap::iterator fx;
1915
1916         /* look first in "user" presets */
1917
1918         if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1919
1920                 if ((propertyList = load_property_list (ux->second)) != 0) {
1921                         DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1922                         if (unit->SetAUPreset (propertyList) == noErr) {
1923                                 ret = true;
1924
1925                                 /* tell the world */
1926
1927                                 AudioUnitParameter changedUnit;
1928                                 changedUnit.mAudioUnit = unit->AU();
1929                                 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1930                                 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1931                         }
1932                         CFRelease(propertyList);
1933                 }
1934
1935         } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1936
1937                 AUPreset preset;
1938
1939                 preset.presetNumber = fx->second;
1940                 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1941
1942                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1943
1944                 if (unit->SetPresentPreset (preset) == 0) {
1945                         ret = true;
1946
1947                         /* tell the world */
1948
1949                         AudioUnitParameter changedUnit;
1950                         changedUnit.mAudioUnit = unit->AU();
1951                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1952                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1953                 }
1954         }
1955
1956         return ret;
1957 }
1958
1959 void
1960 AUPlugin::do_remove_preset (std::string)
1961 {
1962 }
1963
1964 string
1965 AUPlugin::do_save_preset (string preset_name)
1966 {
1967         CFPropertyListRef propertyList;
1968         vector<Glib::ustring> v;
1969         Glib::ustring user_preset_path;
1970
1971         std::string m = maker();
1972         std::string n = name();
1973
1974         strip_whitespace_edges (m);
1975         strip_whitespace_edges (n);
1976
1977         v.push_back (Glib::get_home_dir());
1978         v.push_back ("Library");
1979         v.push_back ("Audio");
1980         v.push_back ("Presets");
1981         v.push_back (m);
1982         v.push_back (n);
1983
1984         user_preset_path = Glib::build_filename (v);
1985
1986         if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1987                 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1988                 return string();
1989         }
1990
1991         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1992         if (unit->GetAUPreset (propertyList) != noErr) {
1993                 return string();
1994         }
1995
1996         // add the actual preset name */
1997
1998         v.push_back (preset_name + preset_suffix);
1999
2000         // rebuild
2001
2002         user_preset_path = Glib::build_filename (v);
2003
2004         set_preset_name_in_plist (propertyList, preset_name);
2005
2006         if (save_property_list (propertyList, user_preset_path)) {
2007                 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2008                 return string();
2009         }
2010
2011         CFRelease(propertyList);
2012
2013         user_preset_map[preset_name] = user_preset_path;;
2014
2015         DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2016
2017         return string ("file:///") + user_preset_path;
2018 }
2019
2020 //-----------------------------------------------------------------------------
2021 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2022 static SInt32
2023 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2024 {
2025         CFNumberRef cfNumber;
2026         SInt32 numberValue = 0;
2027         Boolean dummySuccess;
2028
2029         if (outSuccess == NULL)
2030                 outSuccess = &dummySuccess;
2031         if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2032         {
2033                 *outSuccess = FALSE;
2034                 return 0;
2035         }
2036
2037         cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2038         if (cfNumber == NULL)
2039         {
2040                 *outSuccess = FALSE;
2041                 return 0;
2042         }
2043         *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2044         if (*outSuccess)
2045                 return numberValue;
2046         else
2047                 return 0;
2048 }
2049
2050 static OSStatus
2051 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
2052 {
2053         CFDictionaryRef auStateDictionary;
2054         ComponentDescription tempDesc = {0,0,0,0,0};
2055         SInt32 versionValue;
2056         Boolean gotValue;
2057
2058         if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2059                 return paramErr;
2060
2061         // the property list for AU state data must be of the dictionary type
2062         if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2063                 return kAudioUnitErr_InvalidPropertyValue;
2064         }
2065
2066         auStateDictionary = (CFDictionaryRef)inAUStateData;
2067
2068         // first check to make sure that the version of the AU state data is one that we know understand
2069         // XXX should I really do this?  later versions would probably still hold these ID keys, right?
2070         versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2071
2072         if (!gotValue) {
2073                 return kAudioUnitErr_InvalidPropertyValue;
2074         }
2075 #define kCurrentSavedStateVersion 0
2076         if (versionValue != kCurrentSavedStateVersion) {
2077                 return kAudioUnitErr_InvalidPropertyValue;
2078         }
2079
2080         // grab the ComponentDescription values from the AU state data
2081         tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2082         tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2083         tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2084         // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2085         if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2086                 return kAudioUnitErr_InvalidPropertyValue;
2087
2088         *outComponentDescription = tempDesc;
2089         return noErr;
2090 }
2091
2092
2093 static bool au_preset_filter (const string& str, void* arg)
2094 {
2095         /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2096
2097         bool ret;
2098
2099         ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2100
2101         if (ret && arg) {
2102
2103                 /* check the preset file path name against this plugin
2104                    ID. The idea is that all preset files for this plugin
2105                    include "<manufacturer>/<plugin-name>" in their path.
2106                 */
2107
2108                 Plugin* p = (Plugin *) arg;
2109                 string match = p->maker();
2110                 match += '/';
2111                 match += p->name();
2112
2113                 ret = str.find (match) != string::npos;
2114
2115                 if (ret == false) {
2116                         string m = p->maker ();
2117                         string n = p->name ();
2118                         strip_whitespace_edges (m);
2119                         strip_whitespace_edges (n);
2120                         match = m;
2121                         match += '/';
2122                         match += n;
2123
2124                         ret = str.find (match) != string::npos;
2125                 }
2126         }
2127
2128         return ret;
2129 }
2130
2131 bool
2132 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2133 {
2134         OSStatus status;
2135         CFPropertyListRef plist;
2136         ComponentDescription presetDesc;
2137         bool ret = false;
2138
2139         plist = load_property_list (pathstr);
2140
2141         if (!plist) {
2142                 return ret;
2143         }
2144
2145         // get the ComponentDescription from the AU preset file
2146
2147         status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2148
2149         if (status == noErr) {
2150                 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2151
2152                         /* try to get the preset name from the property list */
2153
2154                         if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2155
2156                                 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2157
2158                                 if (psk) {
2159
2160                                         const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2161
2162                                         if (!p) {
2163                                                 char buf[PATH_MAX+1];
2164
2165                                                 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2166                                                         preset_name = buf;
2167                                                 }
2168                                         }
2169                                 }
2170                         }
2171                 }
2172         }
2173
2174         CFRelease (plist);
2175
2176         return true;
2177 }
2178
2179 std::string
2180 AUPlugin::current_preset() const
2181 {
2182         string preset_name;
2183
2184         CFPropertyListRef propertyList;
2185
2186         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2187         if (unit->GetAUPreset (propertyList) == noErr) {
2188                 preset_name = get_preset_name_in_plist (propertyList);
2189                 CFRelease(propertyList);
2190         }
2191
2192         return preset_name;
2193 }
2194
2195 void
2196 AUPlugin::find_presets ()
2197 {
2198         vector<string> preset_files;
2199
2200         user_preset_map.clear ();
2201
2202         find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2203
2204         if (preset_files.empty()) {
2205                 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2206                 return;
2207         }
2208
2209         for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2210
2211                 string path = *x;
2212                 string preset_name;
2213
2214                 /* make an initial guess at the preset name using the path */
2215
2216                 preset_name = Glib::path_get_basename (path);
2217                 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2218
2219                 /* check that this preset file really matches this plugin
2220                    and potentially get the "real" preset name from
2221                    within the file.
2222                 */
2223
2224                 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2225                         user_preset_map[preset_name] = path;
2226                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2227                 } else {
2228                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2229                 }
2230
2231         }
2232
2233         /* now fill the vector<string> with the names we have */
2234
2235         for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2236                 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2237                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2238         }
2239
2240         /* add factory presets */
2241
2242         for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2243                 /* XXX: dubious */
2244                 string const uri = string_compose ("%1", _presets.size ());
2245                 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2246                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2247         }
2248 }
2249
2250 bool
2251 AUPlugin::has_editor () const
2252 {
2253         // even if the plugin doesn't have its own editor, the AU API can be used
2254         // to create one that looks native.
2255         return true;
2256 }
2257
2258 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2259         : descriptor (d)
2260         , version (0)
2261 {
2262         type = ARDOUR::AudioUnit;
2263 }
2264
2265 AUPluginInfo::~AUPluginInfo ()
2266 {
2267         type = ARDOUR::AudioUnit;
2268 }
2269
2270 PluginPtr
2271 AUPluginInfo::load (Session& session)
2272 {
2273         try {
2274                 PluginPtr plugin;
2275
2276                 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2277                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2278
2279                 if (!comp->IsValid()) {
2280                         error << ("AudioUnit: not a valid Component") << endmsg;
2281                 } else {
2282                         plugin.reset (new AUPlugin (session.engine(), session, comp));
2283                 }
2284
2285                 AUPluginInfo *aup = new AUPluginInfo (*this);
2286                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2287                 plugin->set_info (PluginInfoPtr (aup));
2288                 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2289                 return plugin;
2290         }
2291
2292         catch (failed_constructor &err) {
2293                 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2294                 return PluginPtr ();
2295         }
2296 }
2297
2298 Glib::ustring
2299 AUPluginInfo::au_cache_path ()
2300 {
2301         return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2302 }
2303
2304 PluginInfoList*
2305 AUPluginInfo::discover (bool scan_only)
2306 {
2307         XMLTree tree;
2308
2309         /* AU require a CAComponentDescription pointer provided by the OS.
2310          * Ardour only caches port and i/o config. It can't just 'scan' without
2311          * 'discovering' (like we do for VST).
2312          *
2313          * "Scan Only" means
2314          * "Iterate over all plugins. skip the ones where there's no io-cache".
2315          */
2316         _scan_only = scan_only;
2317
2318         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2319                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2320         }
2321         // create crash log file
2322         au_start_crashlog ();
2323
2324         PluginInfoList* plugs = new PluginInfoList;
2325
2326         discover_fx (*plugs);
2327         discover_music (*plugs);
2328         discover_generators (*plugs);
2329         discover_instruments (*plugs);
2330
2331         // all fine if we get here
2332         au_remove_crashlog ();
2333
2334         DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2335
2336         return plugs;
2337 }
2338
2339 void
2340 AUPluginInfo::discover_music (PluginInfoList& plugs)
2341 {
2342         CAComponentDescription desc;
2343         desc.componentFlags = 0;
2344         desc.componentFlagsMask = 0;
2345         desc.componentSubType = 0;
2346         desc.componentManufacturer = 0;
2347         desc.componentType = kAudioUnitType_MusicEffect;
2348
2349         discover_by_description (plugs, desc);
2350 }
2351
2352 void
2353 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2354 {
2355         CAComponentDescription desc;
2356         desc.componentFlags = 0;
2357         desc.componentFlagsMask = 0;
2358         desc.componentSubType = 0;
2359         desc.componentManufacturer = 0;
2360         desc.componentType = kAudioUnitType_Effect;
2361
2362         discover_by_description (plugs, desc);
2363 }
2364
2365 void
2366 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2367 {
2368         CAComponentDescription desc;
2369         desc.componentFlags = 0;
2370         desc.componentFlagsMask = 0;
2371         desc.componentSubType = 0;
2372         desc.componentManufacturer = 0;
2373         desc.componentType = kAudioUnitType_Generator;
2374
2375         discover_by_description (plugs, desc);
2376 }
2377
2378 void
2379 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2380 {
2381         CAComponentDescription desc;
2382         desc.componentFlags = 0;
2383         desc.componentFlagsMask = 0;
2384         desc.componentSubType = 0;
2385         desc.componentManufacturer = 0;
2386         desc.componentType = kAudioUnitType_MusicDevice;
2387
2388         discover_by_description (plugs, desc);
2389 }
2390
2391
2392 bool
2393 AUPluginInfo::au_get_crashlog (std::string &msg)
2394 {
2395         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2396         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2397                 return false;
2398         }
2399         std::ifstream ifs(fn.c_str());
2400         msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2401         au_remove_crashlog ();
2402         return true;
2403 }
2404
2405 void
2406 AUPluginInfo::au_start_crashlog ()
2407 {
2408         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2409         assert(!_crashlog_fd);
2410         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2411         if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2412                 PBD::error << "Cannot create AU error-log" << fn << "\n";
2413                 cerr << "Cannot create AU error-log" << fn << "\n";
2414         }
2415 }
2416
2417 void
2418 AUPluginInfo::au_remove_crashlog ()
2419 {
2420         if (_crashlog_fd) {
2421                 ::fclose(_crashlog_fd);
2422                 _crashlog_fd = NULL;
2423         }
2424         string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2425         ::g_unlink(fn.c_str());
2426         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2427 }
2428
2429
2430 void
2431 AUPluginInfo::au_crashlog (std::string msg)
2432 {
2433         if (!_crashlog_fd) {
2434                 fprintf(stderr, "AU: %s\n", msg.c_str());
2435         } else {
2436                 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2437                 ::fflush(_crashlog_fd);
2438         }
2439 }
2440
2441 void
2442 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2443 {
2444         Component comp = 0;
2445         au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2446
2447         comp = FindNextComponent (NULL, &desc);
2448
2449         while (comp != NULL) {
2450                 CAComponentDescription temp;
2451                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2452                 CFStringRef itemName = NULL;
2453
2454                 {
2455                         if (itemName != NULL) CFRelease(itemName);
2456                         CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2457                         CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2458                         CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2459                         itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2460                                         compTypeString, compManufacturerString, compSubTypeString);
2461                         au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2462                         if (compTypeString != NULL)
2463                                 CFRelease(compTypeString);
2464                         if (compSubTypeString != NULL)
2465                                 CFRelease(compSubTypeString);
2466                         if (compManufacturerString != NULL)
2467                                 CFRelease(compManufacturerString);
2468                 }
2469
2470                 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2471                         info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2472                         comp = FindNextComponent (comp, &desc);
2473                         continue;
2474                 }
2475
2476                 AUPluginInfoPtr info (new AUPluginInfo
2477                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2478
2479                 /* although apple designed the subtype field to be a "category" indicator,
2480                    its really turned into a plugin ID field for a given manufacturer. Hence
2481                    there are no categories for AudioUnits. However, to keep the plugins
2482                    showing up under "categories", we'll use the "type" as a high level
2483                    selector.
2484
2485                    NOTE: no panners, format converters or i/o AU's for our purposes
2486                  */
2487
2488                 switch (info->descriptor->Type()) {
2489                 case kAudioUnitType_Panner:
2490                 case kAudioUnitType_OfflineEffect:
2491                 case kAudioUnitType_FormatConverter:
2492                         comp = FindNextComponent (comp, &desc);
2493                         continue;
2494
2495                 case kAudioUnitType_Output:
2496                         info->category = _("AudioUnit Outputs");
2497                         break;
2498                 case kAudioUnitType_MusicDevice:
2499                         info->category = _("AudioUnit Instruments");
2500                         break;
2501                 case kAudioUnitType_MusicEffect:
2502                         info->category = _("AudioUnit MusicEffects");
2503                         break;
2504                 case kAudioUnitType_Effect:
2505                         info->category = _("AudioUnit Effects");
2506                         break;
2507                 case kAudioUnitType_Mixer:
2508                         info->category = _("AudioUnit Mixers");
2509                         break;
2510                 case kAudioUnitType_Generator:
2511                         info->category = _("AudioUnit Generators");
2512                         break;
2513                 default:
2514                         info->category = _("AudioUnit (Unknown)");
2515                         break;
2516                 }
2517
2518                 au_blacklist(CFStringRefToStdString(itemName));
2519                 AUPluginInfo::get_names (temp, info->name, info->creator);
2520                 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2521                 au_crashlog(string_compose("Plugin: %1", info->name));
2522
2523                 info->type = ARDOUR::AudioUnit;
2524                 info->unique_id = stringify_descriptor (*info->descriptor);
2525
2526                 /* XXX not sure of the best way to handle plugin versioning yet
2527                  */
2528
2529                 CAComponent cacomp (*info->descriptor);
2530
2531                 if (cacomp.GetResourceVersion (info->version) != noErr) {
2532                         info->version = 0;
2533                 }
2534
2535                 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2536
2537                 if (rv == 0) {
2538                         /* here we have to map apple's wildcard system to a simple pair
2539                            of values. in ::can_do() we use the whole system, but here
2540                            we need a single pair of values. XXX probably means we should
2541                            remove any use of these values.
2542
2543                            for now, if the plugin provides a wildcard, treat it as 1. we really
2544                            don't care much, because whether we can handle an i/o configuration
2545                            depends upon ::can_support_io_configuration(), not these counts.
2546
2547                            they exist because other parts of ardour try to present i/o configuration
2548                            info to the user, which should perhaps be revisited.
2549                         */
2550
2551                         int32_t possible_in = info->cache.io_configs.front().first;
2552                         int32_t possible_out = info->cache.io_configs.front().second;
2553
2554                         if (possible_in > 0) {
2555                                 info->n_inputs.set (DataType::AUDIO, possible_in);
2556                         } else {
2557                                 info->n_inputs.set (DataType::AUDIO, 1);
2558                         }
2559
2560                         if (possible_out > 0) {
2561                                 info->n_outputs.set (DataType::AUDIO, possible_out);
2562                         } else {
2563                                 info->n_outputs.set (DataType::AUDIO, 1);
2564                         }
2565
2566                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2567                                                                         info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2568
2569                         plugs.push_back (info);
2570
2571                 }
2572                 else if (rv == -1) {
2573                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2574                 }
2575
2576                 au_unblacklist(CFStringRefToStdString(itemName));
2577                 au_crashlog("Success.");
2578                 comp = FindNextComponent (comp, &desc);
2579                 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2580         }
2581         au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2582 }
2583
2584 int
2585 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2586                                        UInt32 version,
2587                                        CAComponent& comp,
2588                                        AUPluginCachedInfo& cinfo,
2589                                        const std::string& name)
2590 {
2591         std::string id;
2592         char buf[32];
2593
2594         /* concatenate unique ID with version to provide a key for cached info lookup.
2595            this ensures we don't get stale information, or should if plugin developers
2596            follow Apple "guidelines".
2597          */
2598
2599         snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2600         id = unique_id;
2601         id += '/';
2602         id += buf;
2603
2604         CachedInfoMap::iterator cim = cached_info.find (id);
2605
2606         if (cim != cached_info.end()) {
2607                 cinfo = cim->second;
2608                 return 0;
2609         }
2610
2611         if (_scan_only) {
2612                 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
2613                 return 1;
2614         }
2615
2616         CAAudioUnit unit;
2617         AUChannelInfo* channel_info;
2618         UInt32 cnt;
2619         int ret;
2620
2621         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2622
2623         try {
2624
2625                 if (CAAudioUnit::Open (comp, unit) != noErr) {
2626                         return -1;
2627                 }
2628
2629         } catch (...) {
2630
2631                 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2632                 return -1;
2633
2634         }
2635
2636         DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2637         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2638                 return -1;
2639         }
2640
2641         if (ret > 0) {
2642
2643                 /* no explicit info available, so default to 1in/1out */
2644
2645                 /* XXX this is wrong. we should be indicating wildcard values */
2646
2647                 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2648
2649         } else {
2650
2651                 /* store each configuration */
2652
2653                 for (uint32_t n = 0; n < cnt; ++n) {
2654                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2655                                                                    channel_info[n].outChannels));
2656                 }
2657
2658                 free (channel_info);
2659         }
2660
2661         add_cached_info (id, cinfo);
2662         save_cached_info ();
2663
2664         return 0;
2665 }
2666
2667 void
2668 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2669 {
2670         cached_info[id] = cinfo;
2671 }
2672
2673 #define AU_CACHE_VERSION "2.0"
2674
2675 void
2676 AUPluginInfo::save_cached_info ()
2677 {
2678         XMLNode* node;
2679
2680         node = new XMLNode (X_("AudioUnitPluginCache"));
2681         node->add_property( "version", AU_CACHE_VERSION );
2682
2683         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2684                 XMLNode* parent = new XMLNode (X_("plugin"));
2685                 parent->add_property ("id", i->first);
2686                 node->add_child_nocopy (*parent);
2687
2688                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2689
2690                         XMLNode* child = new XMLNode (X_("io"));
2691                         char buf[32];
2692
2693                         snprintf (buf, sizeof (buf), "%d", j->first);
2694                         child->add_property (X_("in"), buf);
2695                         snprintf (buf, sizeof (buf), "%d", j->second);
2696                         child->add_property (X_("out"), buf);
2697                         parent->add_child_nocopy (*child);
2698                 }
2699
2700         }
2701
2702         Glib::ustring path = au_cache_path ();
2703         XMLTree tree;
2704
2705         tree.set_root (node);
2706
2707         if (!tree.write (path)) {
2708                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2709                 g_unlink (path.c_str());
2710         }
2711 }
2712
2713 int
2714 AUPluginInfo::load_cached_info ()
2715 {
2716         Glib::ustring path = au_cache_path ();
2717         XMLTree tree;
2718
2719         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2720                 return 0;
2721         }
2722
2723         if ( !tree.read (path) ) {
2724                 error << "au_cache is not a valid XML file.  AU plugins will be re-scanned" << endmsg;
2725                 return -1;
2726         }
2727
2728         const XMLNode* root (tree.root());
2729
2730         if (root->name() != X_("AudioUnitPluginCache")) {
2731                 return -1;
2732         }
2733
2734         //initial version has incorrectly stored i/o info, and/or garbage chars.
2735         const XMLProperty* version = root->property(X_("version"));
2736         if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2737                 error << "au_cache is not correct version.  AU plugins will be re-scanned" << endmsg;
2738                 return -1;
2739         }
2740
2741         cached_info.clear ();
2742
2743         const XMLNodeList children = root->children();
2744
2745         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2746
2747                 const XMLNode* child = *iter;
2748
2749                 if (child->name() == X_("plugin")) {
2750
2751                         const XMLNode* gchild;
2752                         const XMLNodeList gchildren = child->children();
2753                         const XMLProperty* prop = child->property (X_("id"));
2754
2755                         if (!prop) {
2756                                 continue;
2757                         }
2758
2759                         string id = prop->value();
2760                         string fixed;
2761                         string version;
2762
2763                         string::size_type slash = id.find_last_of ('/');
2764
2765                         if (slash == string::npos) {
2766                                 continue;
2767                         }
2768
2769                         version = id.substr (slash);
2770                         id = id.substr (0, slash);
2771                         fixed = AUPlugin::maybe_fix_broken_au_id (id);
2772
2773                         if (fixed.empty()) {
2774                                 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2775                                 continue;
2776                         }
2777
2778                         id = fixed;
2779                         id += version;
2780
2781                         AUPluginCachedInfo cinfo;
2782
2783                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2784
2785                                 gchild = *giter;
2786
2787                                 if (gchild->name() == X_("io")) {
2788
2789                                         int in;
2790                                         int out;
2791                                         const XMLProperty* iprop;
2792                                         const XMLProperty* oprop;
2793
2794                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
2795                                             ((oprop = gchild->property (X_("out"))) != 0)) {
2796                                                 in = atoi (iprop->value());
2797                                                 out = atoi (oprop->value());
2798
2799                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
2800                                         }
2801                                 }
2802                         }
2803
2804                         if (cinfo.io_configs.size()) {
2805                                 add_cached_info (id, cinfo);
2806                         }
2807                 }
2808         }
2809
2810         return 0;
2811 }
2812
2813 void
2814 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2815 {
2816         CFStringRef itemName = NULL;
2817
2818         // Marc Poirier-style item name
2819         CAComponent auComponent (comp_desc);
2820         if (auComponent.IsValid()) {
2821                 CAComponentDescription dummydesc;
2822                 Handle nameHandle = NewHandle(sizeof(void*));
2823                 if (nameHandle != NULL) {
2824                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2825                         if (err == noErr) {
2826                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2827                                 if (nameString != NULL) {
2828                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2829                                 }
2830                         }
2831                         DisposeHandle(nameHandle);
2832                 }
2833         }
2834
2835         // if Marc-style fails, do the original way
2836         if (itemName == NULL) {
2837                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2838                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2839                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2840
2841                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2842                         compTypeString, compManufacturerString, compSubTypeString);
2843
2844                 if (compTypeString != NULL)
2845                         CFRelease(compTypeString);
2846                 if (compSubTypeString != NULL)
2847                         CFRelease(compSubTypeString);
2848                 if (compManufacturerString != NULL)
2849                         CFRelease(compManufacturerString);
2850         }
2851
2852         string str = CFStringRefToStdString(itemName);
2853         string::size_type colon = str.find (':');
2854
2855         if (colon) {
2856                 name = str.substr (colon+1);
2857                 maker = str.substr (0, colon);
2858                 strip_whitespace_edges (maker);
2859                 strip_whitespace_edges (name);
2860         } else {
2861                 name = str;
2862                 maker = "unknown";
2863                 strip_whitespace_edges (name);
2864         }
2865 }
2866
2867 std::string
2868 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2869 {
2870         stringstream s;
2871
2872         /* note: OSType is a compiler-implemenation-defined value,
2873            historically a 32 bit integer created with a multi-character
2874            constant such as 'abcd'. It is, fundamentally, an abomination.
2875         */
2876
2877         s << desc.Type();
2878         s << '-';
2879         s << desc.SubType();
2880         s << '-';
2881         s << desc.Manu();
2882
2883         return s.str();
2884 }
2885
2886 bool
2887 AUPluginInfo::needs_midi_input ()
2888 {
2889         return is_effect_with_midi_input () || is_instrument ();
2890 }
2891
2892 bool
2893 AUPluginInfo::is_effect () const
2894 {
2895         return is_effect_without_midi_input() || is_effect_with_midi_input();
2896 }
2897
2898 bool
2899 AUPluginInfo::is_effect_without_midi_input () const
2900 {
2901         return descriptor->IsAUFX();
2902 }
2903
2904 bool
2905 AUPluginInfo::is_effect_with_midi_input () const
2906 {
2907         return descriptor->IsAUFM();
2908 }
2909
2910 bool
2911 AUPluginInfo::is_instrument () const
2912 {
2913         return descriptor->IsMusicDevice();
2914 }
2915
2916 void
2917 AUPlugin::set_info (PluginInfoPtr info)
2918 {
2919         Plugin::set_info (info);
2920
2921         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2922         _has_midi_input = pinfo->needs_midi_input ();
2923         _has_midi_output = false;
2924 }
2925
2926 int
2927 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2928 {
2929 #ifdef WITH_CARBON
2930         CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2931 #else
2932         CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2933 #endif
2934         CFStringRef  loop_mode = kCFRunLoopDefaultMode;
2935
2936         if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2937                 return -1;
2938         }
2939
2940         _parameter_listener_arg = arg;
2941
2942         return 0;
2943 }
2944
2945 int
2946 AUPlugin::listen_to_parameter (uint32_t param_id)
2947 {
2948         AudioUnitEvent      event;
2949
2950         if (!_parameter_listener || param_id >= descriptors.size()) {
2951                 return -2;
2952         }
2953
2954         event.mEventType = kAudioUnitEvent_ParameterValueChange;
2955         event.mArgument.mParameter.mAudioUnit = unit->AU();
2956         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2957         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2958         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2959
2960         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2961                 return -1;
2962         }
2963
2964         event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2965         event.mArgument.mParameter.mAudioUnit = unit->AU();
2966         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2967         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2968         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2969
2970         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2971                 return -1;
2972         }
2973
2974         event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2975         event.mArgument.mParameter.mAudioUnit = unit->AU();
2976         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2977         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2978         event.mArgument.mParameter.mElement = descriptors[param_id].element;
2979
2980         if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2981                 return -1;
2982         }
2983
2984         return 0;
2985 }
2986
2987 int
2988 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2989 {
2990         AudioUnitEvent      event;
2991
2992         if (!_parameter_listener || param_id >= descriptors.size()) {
2993                 return -2;
2994         }
2995
2996         event.mEventType = kAudioUnitEvent_ParameterValueChange;
2997         event.mArgument.mParameter.mAudioUnit = unit->AU();
2998         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2999         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3000         event.mArgument.mParameter.mElement = descriptors[param_id].element;
3001
3002         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3003                 return -1;
3004         }
3005
3006         event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3007         event.mArgument.mParameter.mAudioUnit = unit->AU();
3008         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3009         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3010         event.mArgument.mParameter.mElement = descriptors[param_id].element;
3011
3012         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3013                 return -1;
3014         }
3015
3016         event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3017         event.mArgument.mParameter.mAudioUnit = unit->AU();
3018         event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3019         event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3020         event.mArgument.mParameter.mElement = descriptors[param_id].element;
3021
3022         if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3023                 return -1;
3024         }
3025
3026         return 0;
3027 }
3028
3029 void
3030 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3031 {
3032         ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3033 }
3034
3035 void
3036 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3037 {
3038         ParameterMap::iterator i;
3039
3040         if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3041                 return;
3042         }
3043
3044         switch (event->mEventType) {
3045         case kAudioUnitEvent_BeginParameterChangeGesture:
3046                 StartTouch (i->second);
3047                 break;
3048         case kAudioUnitEvent_EndParameterChangeGesture:
3049                 EndTouch (i->second);
3050                 break;
3051         case kAudioUnitEvent_ParameterValueChange:
3052                 ParameterChanged (i->second, new_value);
3053                 break;
3054         default:
3055                 break;
3056         }
3057 }