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