make ardour3 build and link on OS X (tiger, at least)
[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 <errno.h>
23 #include <string.h>
24 #include <math.h>
25 #include <ctype.h>
26
27 #include "pbd/transmitter.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30 #include "pbd/whitespace.h"
31 #include "pbd/pathscanner.h"
32 #include "pbd/locale_guard.h"
33
34 #include <glibmm/thread.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
37
38 #include "ardour/ardour.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/filesystem_paths.h"
42 #include "ardour/io.h"
43 #include "ardour/audio_unit.h"
44 #include "ardour/session.h"
45 #include "ardour/tempo.h"
46 #include "ardour/utils.h"
47
48 #include "appleutility/CAAudioUnit.h"
49 #include "appleutility/CAAUParameter.h"
50
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreServices/CoreServices.h>
53 #include <AudioUnit/AudioUnit.h>
54 #include <AudioToolbox/AudioUnitUtilities.h>
55
56 #include "i18n.h"
57
58 using namespace std;
59 using namespace PBD;
60 using namespace ARDOUR;
61
62 //#define TRACE_AU_API
63 #ifdef TRACE_AU_API
64 #define TRACE_API(fmt,...) fprintf (stderr, fmt, ## __VA_ARGS__)
65 #else
66 #define TRACE_API(fmt,...)
67 #endif
68
69 #ifndef AU_STATE_SUPPORT
70 static bool seen_get_state_message = false;
71 static bool seen_set_state_message = false;
72 static bool seen_loading_message = false;
73 static bool seen_saving_message = false;
74 #endif
75
76 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
77
78 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
79 static string preset_suffix = ".aupreset";
80 static bool preset_search_path_initialized = false;
81 static bool debug_io_config = true;
82
83 static OSStatus 
84 _render_callback(void *userData,
85                  AudioUnitRenderActionFlags *ioActionFlags,
86                  const AudioTimeStamp    *inTimeStamp,
87                  UInt32       inBusNumber,
88                  UInt32       inNumberFrames,
89                  AudioBufferList*       ioData)
90 {
91         if (userData) {
92                 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
93         }
94         return paramErr;
95 }
96
97 static OSStatus 
98 _get_beat_and_tempo_callback (void*                userData,
99                               Float64*             outCurrentBeat, 
100                               Float64*             outCurrentTempo)
101 {
102         if (userData) {
103                 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
104         }
105     
106         return paramErr;
107 }
108
109 static OSStatus 
110 _get_musical_time_location_callback (void *     userData,
111                                      UInt32 *   outDeltaSampleOffsetToNextBeat,
112                                      Float32 *  outTimeSig_Numerator,
113                                      UInt32 *   outTimeSig_Denominator,
114                                      Float64 *  outCurrentMeasureDownBeat)
115 {
116         if (userData) {
117                 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
118                                                                                   outTimeSig_Numerator,
119                                                                                   outTimeSig_Denominator,
120                                                                                   outCurrentMeasureDownBeat);
121         }
122         return paramErr;
123 }
124
125 static OSStatus 
126 _get_transport_state_callback (void*     userData,
127                                Boolean*  outIsPlaying,
128                                Boolean*  outTransportStateChanged,
129                                Float64*  outCurrentSampleInTimeLine,
130                                Boolean*  outIsCycling,
131                                Float64*  outCycleStartBeat,
132                                Float64*  outCycleEndBeat)
133 {
134         if (userData) {
135                 return ((AUPlugin*)userData)->get_transport_state_callback (outIsPlaying, outTransportStateChanged,
136                                                                             outCurrentSampleInTimeLine, outIsCycling,
137                                                                             outCycleStartBeat, outCycleEndBeat);
138         }
139         return paramErr;
140 }
141
142
143 static int 
144 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
145
146 {
147         CFDataRef xmlData;
148         int fd;
149
150         // Convert the property list into XML data.
151         
152         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
153
154         if (!xmlData) {
155                 error << _("Could not create XML version of property list") << endmsg;
156                 return -1;
157         }
158
159         // Write the XML data to the file.
160
161         fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
162         while (fd < 0) {
163                 if (errno == EEXIST) {
164                         /* tell any UI's that this file already exists and ask them what to do */
165                         bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
166                         if (overwrite) {
167                                 fd = open (path.c_str(), O_WRONLY, 0664);
168                                 continue;
169                         } else {
170                                 return 0;
171                         }
172                 }
173                 error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
174                 CFRelease (xmlData);
175                 return -1;
176         }
177
178         size_t cnt = CFDataGetLength (xmlData);
179
180         if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
181                 CFRelease (xmlData);
182                 close (fd);
183                 return -1;
184         }
185
186         close (fd);
187         return 0;
188 }
189  
190
191 static CFPropertyListRef 
192 load_property_list (Glib::ustring path) 
193 {
194         int fd;
195         CFPropertyListRef propertyList = 0;
196         CFDataRef         xmlData;
197         CFStringRef       errorString;
198
199         // Read the XML file.
200         
201         if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
202                 return propertyList;
203
204         }
205         
206         off_t len = lseek (fd, 0, SEEK_END);
207         char* buf = new char[len];
208         lseek (fd, 0, SEEK_SET);
209
210         if (read (fd, buf, len) != len) {
211                 delete [] buf;
212                 close (fd);
213                 return propertyList;
214         }
215         
216         close (fd);
217
218         xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
219         
220         // Reconstitute the dictionary using the XML data.
221         
222         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
223                                                         xmlData,
224                                                         kCFPropertyListImmutable,
225                                                         &errorString);
226
227         CFRelease (xmlData);
228         delete [] buf;
229
230         return propertyList;
231 }
232
233 //-----------------------------------------------------------------------------
234 static void 
235 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
236 {
237         if (!plist) {
238                 return;
239         }
240         CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
241
242         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
243                 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
244         }
245         
246         CFRelease (pn);
247 }
248
249 //-----------------------------------------------------------------------------
250 static std::string
251 get_preset_name_in_plist (CFPropertyListRef plist)
252 {
253         std::string ret;
254
255         if (!plist) {
256                 return ret;
257         }
258
259         if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
260                 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
261                 if (p) {
262                         CFStringRef str = (CFStringRef) p;
263                         int len = CFStringGetLength(str);
264                         len =  (len * 2) + 1;
265                         char local_buffer[len];
266                         if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
267                                 ret = local_buffer;
268                         }
269                 } 
270         }
271         return ret;
272 }
273
274 //--------------------------------------------------------------------------
275 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
276 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
277 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
278 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
279 {
280         if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
281                 return FALSE;
282
283         if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType) 
284                         && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
285         {
286                 // only sub-type and manufacturer IDs need to be equal
287                 if (inIgnoreType)
288                         return TRUE;
289                 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
290                 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
291                         return TRUE;
292         }
293
294         return FALSE;
295 }
296
297 //--------------------------------------------------------------------------
298 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
299 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
300 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
301 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
302 {
303         OSErr status;
304         ComponentDescription desc;
305
306         if ( (inComponent == NULL) || (inComponentDescription == NULL) )
307                 return FALSE;
308
309         // get the ComponentDescription of the input Component
310         status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
311         if (status != noErr)
312                 return FALSE;
313
314         // check if the Component's ComponentDescription matches the input ComponentDescription
315         return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
316 }
317
318 //--------------------------------------------------------------------------
319 // determine if 2 ComponentDescriptions are basically equal
320 // (by that, I mean that the important identifying values are compared, 
321 // but not the ComponentDescription flags)
322 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
323 {
324         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
325 }
326
327 //--------------------------------------------------------------------------
328 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
329 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
330 {
331         return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
332 }
333
334 //--------------------------------------------------------------------------
335 // determine if a ComponentDescription basically matches that of a particular Component
336 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
337 {
338         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
339 }
340
341 //--------------------------------------------------------------------------
342 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
343 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
344 {
345         return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
346 }
347
348
349 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
350         : Plugin (engine, session)
351         , comp (_comp)
352         , unit (new CAAudioUnit)
353         , initialized (false)
354         , _current_block_size (0)
355         , _requires_fixed_size_buffers (false)
356         , buffers (0)
357         , current_maxbuf (0)
358         , current_offset (0)
359         , current_buffers (0)
360         , frames_processed (0)
361         , last_transport_rolling (false)
362         , last_transport_speed (0.0)
363 {                       
364         if (!preset_search_path_initialized) {
365                 Glib::ustring p = Glib::get_home_dir();
366                 p += "/Library/Audio/Presets:";
367                 p += preset_search_path;
368                 preset_search_path = p;
369                 preset_search_path_initialized = true;
370         }
371
372         init ();
373 }
374
375 AUPlugin::AUPlugin (const AUPlugin& other)
376         : Plugin (other)
377         , comp (other.get_comp())
378         , unit (new CAAudioUnit)
379         , initialized (false)
380         , _current_block_size (0)
381         , _last_nframes (0)
382         , _requires_fixed_size_buffers (false)
383         , buffers (0)
384         , current_maxbuf (0)
385         , current_offset (0)
386         , current_buffers (0)
387         , frames_processed (0)
388           
389 {
390         init ();
391 }
392
393 AUPlugin::~AUPlugin ()
394 {
395         if (unit) {
396                 TRACE_API ("about to call uninitialize in plugin destructor\n");
397                 unit->Uninitialize ();
398         }
399
400         if (buffers) {
401                 free (buffers);
402         }
403 }
404
405 void
406 AUPlugin::discover_factory_presets ()
407 {
408         CFArrayRef presets;
409         UInt32 dataSize = sizeof (presets);
410         OSStatus err;
411         
412         TRACE_API ("get property FactoryPresets in global scope\n");
413         if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
414                 cerr << "cannot get factory preset info: " << err << endl;
415                 return;
416         }
417
418         if (!presets) {
419                 return;
420         }
421
422         CFIndex cnt = CFArrayGetCount (presets);
423
424         for (CFIndex i = 0; i < cnt; ++i) {
425                 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
426
427                 string name = CFStringRefToStdString (preset->presetName);
428                 factory_preset_map[name] = preset->presetNumber;
429         }
430         
431         CFRelease (presets);
432 }
433
434 void
435 AUPlugin::init ()
436 {
437         OSErr err;
438
439         try {
440                 TRACE_API ("opening AudioUnit\n");
441                 err = CAAudioUnit::Open (*(comp.get()), *unit);
442         } catch (...) {
443                 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
444                 throw failed_constructor();
445         }
446
447         if (err != noErr) {
448                 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
449                 throw failed_constructor ();
450         }
451         
452         TRACE_API ("count global elements\n");
453         unit->GetElementCount (kAudioUnitScope_Global, global_elements);
454         TRACE_API ("count input elements\n");
455         unit->GetElementCount (kAudioUnitScope_Input, input_elements);
456         TRACE_API ("count output elements\n");
457         unit->GetElementCount (kAudioUnitScope_Output, output_elements);
458
459         if (input_elements > 0) {
460                 AURenderCallbackStruct renderCallbackInfo;
461                 
462                 renderCallbackInfo.inputProc = _render_callback;
463                 renderCallbackInfo.inputProcRefCon = this;
464                 
465                 TRACE_API ("set render callback in input scope\n");
466                 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 
467                                               0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
468                         cerr << "cannot install render callback (err = " << err << ')' << endl;
469                         throw failed_constructor();
470                 }
471         }
472
473         /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
474
475         HostCallbackInfo info;
476         memset (&info, 0, sizeof (HostCallbackInfo));
477         info.hostUserData = this;
478         info.beatAndTempoProc = _get_beat_and_tempo_callback;
479         info.musicalTimeLocationProc = _get_musical_time_location_callback;
480         info.transportStateProc = _get_transport_state_callback;
481         
482         //ignore result of this - don't care if the property isn't supported
483         TRACE_API ("set host callbacks in global scope\n");
484         unit->SetProperty (kAudioUnitProperty_HostCallbacks, 
485                            kAudioUnitScope_Global, 
486                            0, //elementID 
487                            &info,
488                            sizeof (HostCallbackInfo));
489
490         /* these keep track of *configured* channel set up,
491            not potential set ups.
492         */
493
494         input_channels = -1;
495         output_channels = -1;
496
497         if (set_block_size (_session.get_block_size())) {
498                 error << _("AUPlugin: cannot set processing block size") << endmsg;
499                 throw failed_constructor();
500         }
501
502         discover_parameters ();
503         discover_factory_presets ();
504
505         // Plugin::setup_controls ();
506 }
507
508 void
509 AUPlugin::discover_parameters ()
510 {
511         /* discover writable parameters */
512         
513         AudioUnitScope scopes[] = { 
514                 kAudioUnitScope_Global,
515                 kAudioUnitScope_Output,
516                 kAudioUnitScope_Input
517         };
518
519         descriptors.clear ();
520
521         for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
522
523                 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
524                 
525                 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
526
527                         AUParameterDescriptor d;
528
529                         d.id = param_info.ParamID (i);
530
531                         const CAAUParameter* param = param_info.GetParamInfo (d.id);
532                         const AudioUnitParameterInfo& info (param->ParamInfo());
533
534                         const int len = CFStringGetLength (param->GetName());;
535                         char local_buffer[len*2];
536                         Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
537                         if (!good) {
538                                 d.label = "???";
539                         } else {
540                                 d.label = local_buffer;
541                         }
542
543                         d.scope = param_info.GetScope ();
544                         d.element = param_info.GetElement ();
545
546                         /* info.units to consider */
547                         /*
548                           kAudioUnitParameterUnit_Generic             = 0
549                           kAudioUnitParameterUnit_Indexed             = 1
550                           kAudioUnitParameterUnit_Boolean             = 2
551                           kAudioUnitParameterUnit_Percent             = 3
552                           kAudioUnitParameterUnit_Seconds             = 4
553                           kAudioUnitParameterUnit_SampleFrames        = 5
554                           kAudioUnitParameterUnit_Phase               = 6
555                           kAudioUnitParameterUnit_Rate                = 7
556                           kAudioUnitParameterUnit_Hertz               = 8
557                           kAudioUnitParameterUnit_Cents               = 9
558                           kAudioUnitParameterUnit_RelativeSemiTones   = 10
559                           kAudioUnitParameterUnit_MIDINoteNumber      = 11
560                           kAudioUnitParameterUnit_MIDIController      = 12
561                           kAudioUnitParameterUnit_Decibels            = 13
562                           kAudioUnitParameterUnit_LinearGain          = 14
563                           kAudioUnitParameterUnit_Degrees             = 15
564                           kAudioUnitParameterUnit_EqualPowerCrossfade = 16
565                           kAudioUnitParameterUnit_MixerFaderCurve1    = 17
566                           kAudioUnitParameterUnit_Pan                 = 18
567                           kAudioUnitParameterUnit_Meters              = 19
568                           kAudioUnitParameterUnit_AbsoluteCents       = 20
569                           kAudioUnitParameterUnit_Octaves             = 21
570                           kAudioUnitParameterUnit_BPM                 = 22
571                           kAudioUnitParameterUnit_Beats               = 23
572                           kAudioUnitParameterUnit_Milliseconds        = 24
573                           kAudioUnitParameterUnit_Ratio               = 25
574                         */
575
576                         /* info.flags to consider */
577
578                         /*
579
580                           kAudioUnitParameterFlag_CFNameRelease       = (1L << 4)
581                           kAudioUnitParameterFlag_HasClump            = (1L << 20)
582                           kAudioUnitParameterFlag_HasName             = (1L << 21)
583                           kAudioUnitParameterFlag_DisplayLogarithmic  = (1L << 22)
584                           kAudioUnitParameterFlag_IsHighResolution    = (1L << 23)
585                           kAudioUnitParameterFlag_NonRealTime         = (1L << 24)
586                           kAudioUnitParameterFlag_CanRamp             = (1L << 25)
587                           kAudioUnitParameterFlag_ExpertMode          = (1L << 26)
588                           kAudioUnitParameterFlag_HasCFNameString     = (1L << 27)
589                           kAudioUnitParameterFlag_IsGlobalMeta        = (1L << 28)
590                           kAudioUnitParameterFlag_IsElementMeta       = (1L << 29)
591                           kAudioUnitParameterFlag_IsReadable          = (1L << 30)
592                           kAudioUnitParameterFlag_IsWritable          = (1L << 31)
593                         */
594
595                         d.lower = info.minValue;
596                         d.upper = info.maxValue;
597                         d.default_value = info.defaultValue;
598
599                         d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
600                         d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
601                                 (d.integer_step && ((d.upper - d.lower) == 1.0));
602                         d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
603                         d.automatable = !d.toggled && 
604                                 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
605                                 (info.flags & kAudioUnitParameterFlag_IsWritable);
606                         
607                         d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
608                         d.unit = info.unit;
609
610                         d.step = 1.0;
611                         d.smallstep = 0.1;
612                         d.largestep = 10.0;
613                         d.min_unbound = 0; // lower is bound
614                         d.max_unbound = 0; // upper is bound
615
616                         descriptors.push_back (d);
617                 }
618         }
619 }
620
621
622 static unsigned int
623 four_ints_to_four_byte_literal (unsigned char n[4])
624 {
625         /* this is actually implementation dependent. sigh. this is what gcc
626            and quite a few others do.
627          */
628         return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
629 }
630
631 std::string
632 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
633 {
634         if (isdigit (id[0])) {
635                 return id;
636         }
637
638         /* ID format is xxxx-xxxx-xxxx
639            where x maybe \xNN or a printable character.
640            
641            Split at the '-' and and process each part into an integer. 
642            Then put it back together.
643         */
644
645
646         unsigned char nascent[4];
647         const char* cstr = id.c_str();
648         const char* estr = cstr + id.size();
649         uint32_t n[3];
650         int in;
651         int next_int;
652         char short_buf[3];
653         stringstream s;
654
655         in = 0;
656         next_int = 0;
657         short_buf[2] = '\0';
658
659         while (*cstr && next_int < 4) {
660
661                 if (*cstr == '\\') {
662
663                         if (estr - cstr < 3) {
664
665                                 /* too close to the end for \xNN parsing: treat as literal characters */
666
667                                 cerr << "Parse " << cstr << " as a literal \\" << endl;
668                                 nascent[in] = *cstr;
669                                 ++cstr;
670                                 ++in;
671
672                         } else {
673                                 
674                                 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
675                                         
676                                         /* parse \xNN */
677                                         
678                                         memcpy (short_buf, &cstr[2], 2);
679                                         nascent[in] = strtol (short_buf, NULL, 16);
680                                         cstr += 4;
681                                         ++in;
682                                         
683                                 } else {
684
685                                         /* treat as literal characters */
686                                         cerr << "Parse " << cstr << " as a literal \\" << endl;
687                                         nascent[in] = *cstr;
688                                         ++cstr;
689                                         ++in;
690                                 }
691                         }
692
693                 } else {
694
695                         nascent[in] = *cstr;
696                         ++cstr;
697                         ++in;
698                 }
699
700                 if (in && (in % 4 == 0)) {
701                         /* nascent is ready */
702                         n[next_int] = four_ints_to_four_byte_literal (nascent);
703                         in = 0;
704                         next_int++;
705
706                         /* swallow space-hyphen-space */
707
708                         if (next_int < 3) {
709                                 ++cstr;
710                                 ++cstr;
711                                 ++cstr;
712                         }
713                 }
714         }
715
716         if (next_int != 3) {
717                 goto err;
718         }
719
720         s << n[0] << '-' << n[1] << '-' << n[2];
721         
722         return s.str();
723
724   err:
725         return string();
726 }
727
728 string
729 AUPlugin::unique_id () const
730 {
731         return AUPluginInfo::stringify_descriptor (comp->Desc());
732 }
733
734 const char *
735 AUPlugin::label () const
736 {
737         return _info->name.c_str();
738 }
739
740 uint32_t
741 AUPlugin::parameter_count () const
742 {
743         return descriptors.size();
744 }
745
746 float
747 AUPlugin::default_value (uint32_t port)
748 {
749         if (port < descriptors.size()) {
750                 return descriptors[port].default_value;
751         }
752
753         return 0;
754 }
755
756 nframes_t
757 AUPlugin::signal_latency () const
758 {
759         return unit->Latency() * _session.frame_rate();
760 }
761
762 void
763 AUPlugin::set_parameter (uint32_t which, float val)
764 {
765         if (which < descriptors.size()) {
766                 const AUParameterDescriptor& d (descriptors[which]);
767                 TRACE_API ("set parameter %d in scope %d element %d to %f\n", d.id, d.scope, d.element, val);
768                 unit->SetParameter (d.id, d.scope, d.element, val);
769
770                 /* tell the world what we did */
771
772                 AudioUnitEvent theEvent;
773                 
774                 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
775                 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
776                 theEvent.mArgument.mParameter.mParameterID = d.id;
777                 theEvent.mArgument.mParameter.mScope = d.scope;
778                 theEvent.mArgument.mParameter.mElement = d.element;
779
780                 TRACE_API ("notify about parameter change\n");
781                 AUEventListenerNotify (NULL, NULL, &theEvent);
782         }
783 }
784
785 float
786 AUPlugin::get_parameter (uint32_t which) const
787 {
788         float val = 0.0;
789         if (which < descriptors.size()) {
790                 const AUParameterDescriptor& d (descriptors[which]);
791                 TRACE_API ("get value of parameter %d in scope %d element %d\n", d.id, d.scope, d.element);
792                 unit->GetParameter(d.id, d.scope, d.element, val);
793         }
794         return val;
795 }
796
797 int
798 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
799 {
800         if (which < descriptors.size()) {
801                 pd = descriptors[which];
802                 return 0;
803         } 
804         return -1;
805 }
806
807 uint32_t
808 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
809 {
810         if (which < descriptors.size()) {
811                 ok = true;
812                 return which;
813         }
814         ok = false;
815         return 0;
816 }
817
818 void
819 AUPlugin::activate ()
820 {
821         if (!initialized) {
822                 OSErr err;
823                 TRACE_API ("call Initialize in activate()\n");
824                 if ((err = unit->Initialize()) != noErr) {
825                         error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
826                 } else {
827                         frames_processed = 0;
828                         initialized = true;
829                 }
830         }
831 }
832
833 void
834 AUPlugin::deactivate ()
835 {
836         TRACE_API ("call Uninitialize in deactivate()\n");
837         unit->Uninitialize ();
838         initialized = false;
839 }
840
841 void
842 AUPlugin::flush ()
843 {
844         TRACE_API ("call Reset in flush()\n");
845         unit->GlobalReset ();
846 }
847
848 bool
849 AUPlugin::requires_fixed_size_buffers() const
850 {
851         return _requires_fixed_size_buffers;
852 }
853
854
855 int
856 AUPlugin::set_block_size (nframes_t nframes)
857 {
858         bool was_initialized = initialized;
859         UInt32 numFrames = nframes;
860         OSErr err;
861
862         if (initialized) {
863                 deactivate ();
864         }
865
866         TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
867         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 
868                                       0, &numFrames, sizeof (numFrames))) != noErr) {
869                 cerr << "cannot set max frames (err = " << err << ')' << endl;
870                 return -1;
871         }
872
873         if (was_initialized) {
874                 activate ();
875         }
876
877         _current_block_size = nframes;
878
879         return 0;
880 }
881
882 bool
883 AUPlugin::configure_io (ChanCount in, ChanCount out)
884 {
885         AudioStreamBasicDescription streamFormat;
886         bool was_initialized = initialized;
887         int32_t audio_in = in.n_audio();
888         int32_t audio_out = out.n_audio();
889
890         if (initialized) {
891                 //if we are already running with the requested i/o config, bail out here
892                 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
893                         return 0;
894                 } else {
895                         deactivate ();
896                 }
897         }
898
899         streamFormat.mSampleRate = _session.frame_rate();
900         streamFormat.mFormatID = kAudioFormatLinearPCM;
901         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
902
903 #ifdef __LITTLE_ENDIAN__
904         /* relax */
905 #else
906         streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
907 #endif
908
909         streamFormat.mBitsPerChannel = 32;
910         streamFormat.mFramesPerPacket = 1;
911
912         /* apple says that for non-interleaved data, these
913            values always refer to a single channel.
914         */
915         streamFormat.mBytesPerPacket = 4;
916         streamFormat.mBytesPerFrame = 4;
917
918         streamFormat.mChannelsPerFrame = audio_in;
919
920         if (set_input_format (streamFormat) != 0) {
921                 return -1;
922         }
923
924         streamFormat.mChannelsPerFrame = audio_out;
925
926         if (set_output_format (streamFormat) != 0) {
927                 return -1;
928         }
929
930         if (was_initialized) {
931                 activate ();
932         }
933
934         return 0;
935 }
936
937 bool
938 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
939 {
940         // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
941         // attempt to multiply-instantiate plugins to meet io configurations.
942
943         int32_t audio_in = in.n_audio();
944         int32_t audio_out;
945         int32_t plugcnt = -1;
946         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
947
948         vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
949
950         if (debug_io_config) {
951                 cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
952         }
953
954         //Ardour expects the plugin to tell it the output configuration
955         //but AU plugins can have multiple I/O configurations
956         //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
957         //so first lets see if there's a configuration that keeps out==in
958
959         audio_out = audio_in;
960
961         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
962                 int32_t possible_in = i->first;
963                 int32_t possible_out = i->second;
964
965                 if (possible_in == audio_in && possible_out== audio_out) {
966                         cerr << "\tCHOSEN: in " << in << " out " << out << endl;
967                         return 1;
968                 }
969         }
970
971         /* now allow potentially "imprecise" matches */
972         audio_out = -1;
973         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
974
975                 int32_t possible_in = i->first;
976                 int32_t possible_out = i->second;
977
978                 if (debug_io_config) {
979                         cerr << "\tin " << possible_in << " out " << possible_out << endl;
980                 }
981
982                 if (possible_out == 0) {
983                         warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
984                         continue;
985                 }
986
987                 if (possible_in == 0) {
988
989                         /* instrument plugin, always legal but throws away inputs ...
990                         */
991
992                         if (possible_out == -1) {
993                                 /* out much match in (UNLIKELY!!) */
994                                 audio_out = audio_in;
995                                 plugcnt = 1;
996                         } else if (possible_out == -2) {
997                                 /* any configuration possible, pick matching */
998                                 audio_out = audio_in;
999                                 plugcnt = 1;
1000                         } else if (possible_out < -2) {
1001                                 /* explicit variable number of outputs, pick maximum */
1002                                 audio_out = -possible_out;
1003                                 plugcnt = 1;
1004                         } else {
1005                                 /* exact number of outputs */
1006                                 audio_out = possible_out;
1007                                 plugcnt = 1;
1008                         }
1009                 }
1010                 
1011                 if (possible_in == -1) {
1012
1013                         /* wildcard for input */
1014
1015                         if (possible_out == -1) {
1016                                 /* out much match in */
1017                                 audio_out = audio_in;
1018                                 plugcnt = 1;
1019                         } else if (possible_out == -2) {
1020                                 /* any configuration possible, pick matching */
1021                                 audio_out = audio_in;
1022                                 plugcnt = 1;
1023                         } else if (possible_out < -2) {
1024                                 /* explicit variable number of outputs, pick maximum */
1025                                 audio_out = -possible_out;
1026                                 plugcnt = 1;
1027                         } else {
1028                                 /* exact number of outputs */
1029                                 audio_out = possible_out;
1030                                 plugcnt = 1;
1031                         }
1032                 }       
1033                         
1034                 if (possible_in == -2) {
1035
1036                         if (possible_out == -1) {
1037                                 /* any configuration possible, pick matching */
1038                                 audio_out = audio_in;
1039                                 plugcnt = 1;
1040                         } else if (possible_out == -2) {
1041                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1042                                       << endmsg;
1043                                 plugcnt = -1;
1044                         } else if (possible_out < -2) {
1045                                 /* explicit variable number of outputs, pick maximum */
1046                                 audio_out = -possible_out;
1047                                 plugcnt = 1;
1048                         } else {
1049                                 /* exact number of outputs */
1050                                 audio_out = possible_out;
1051                                 plugcnt = 1;
1052                         }
1053                 }
1054
1055                 if (possible_in < -2) {
1056
1057                         /* explicit variable number of inputs */
1058
1059                         if (audio_in > -possible_in) {
1060                                 /* request is too large */
1061                                 plugcnt = -1;
1062                         }
1063
1064                         if (possible_out == -1) {
1065                                 /* out must match in */
1066                                 audio_out = audio_in;
1067                                 plugcnt = 1;
1068                         } else if (possible_out == -2) {
1069                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1070                                       << endmsg;
1071                                 plugcnt = -1;
1072                         } else if (possible_out < -2) {
1073                                 /* explicit variable number of outputs, pick maximum */
1074                                 audio_out = -possible_out;
1075                                 plugcnt = 1;
1076                         } else {
1077                                 /* exact number of outputs */
1078                                 audio_out = possible_out;
1079                                 plugcnt = 1;
1080                         }
1081                 }
1082
1083                 if (possible_in == audio_in) {
1084
1085                         /* exact number of inputs ... must match obviously */
1086                         
1087                         if (possible_out == -1) {
1088                                 /* out must match in */
1089                                 audio_out = audio_in;
1090                                 plugcnt = 1;
1091                         } else if (possible_out == -2) {
1092                                 /* any output configuration, pick matching */
1093                                 audio_out = audio_in;
1094                                 plugcnt = -1;
1095                         } else if (possible_out < -2) {
1096                                 /* explicit variable number of outputs, pick maximum */
1097                                 audio_out = -possible_out;
1098                                 plugcnt = 1;
1099                         } else {
1100                                 /* exact number of outputs */
1101                                 audio_out = possible_out;
1102                                 plugcnt = 1;
1103                         }
1104                 }
1105
1106                 if (plugcnt == 1) {
1107                         break;
1108                 }
1109
1110         }
1111
1112         if (debug_io_config) {
1113                 if (plugcnt > 0) {
1114                         cerr << "\tCHOSEN: in " << in << " out " << out << " plugcnt will be " << plugcnt << endl;
1115                 } else {
1116                         cerr << "\tFAIL: no configs match requested in " << in << endl;
1117                 }
1118         }
1119
1120         out.set (DataType::MIDI, 0);
1121         out.set (DataType::AUDIO, audio_out);
1122
1123         return plugcnt;
1124 }
1125
1126 int
1127 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1128 {
1129         return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1130 }
1131
1132 int
1133 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1134 {
1135         if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1136                 return -1;
1137         }
1138
1139         if (buffers) {
1140                 free (buffers);
1141                 buffers = 0;
1142         }
1143         
1144         buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) + 
1145                                               fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1146
1147         Glib::Mutex::Lock em (_session.engine().process_lock());
1148         IO::PortCountChanged (ChanCount(DataType::AUDIO, fmt.mChannelsPerFrame));
1149
1150         return 0;
1151 }
1152
1153 int
1154 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1155 {
1156         OSErr result;
1157
1158         for (uint32_t i = 0; i < cnt; ++i) {
1159                 TRACE_API ("set stream format for %s, scope = %d element %d\n",
1160                            (scope == kAudioUnitScope_Input ? "input" : "output"),
1161                            scope, cnt);
1162                 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1163                         error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1164                                                  (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1165                         return -1;
1166                 }
1167         }
1168
1169         if (scope == kAudioUnitScope_Input) {
1170                 input_channels = fmt.mChannelsPerFrame;
1171         } else {
1172                 output_channels = fmt.mChannelsPerFrame;
1173         }
1174
1175         return 0;
1176 }
1177
1178 OSStatus 
1179 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1180                           const AudioTimeStamp*,
1181                           UInt32,
1182                           UInt32       inNumberFrames,
1183                           AudioBufferList*       ioData)
1184 {
1185         /* not much to do - the data is already in the buffers given to us in connect_and_run() */
1186
1187         if (current_maxbuf == 0) {
1188                 error << _("AUPlugin: render callback called illegally!") << endmsg;
1189                 return kAudioUnitErr_CannotDoInCurrentContext;
1190         }
1191         uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
1192
1193         for (uint32_t i = 0; i < limit; ++i) {
1194                 ioData->mBuffers[i].mNumberChannels = 1;
1195                 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1196
1197                 /* we don't use the channel mapping because audiounits are
1198                    never replicated. one plugin instance uses all channels/buffers
1199                    passed to PluginInsert::connect_and_run()
1200                 */
1201
1202                 ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
1203         }
1204
1205         cb_offset += inNumberFrames;
1206
1207         return noErr;
1208 }
1209
1210 int
1211 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping, ChanMapping, nframes_t nframes, nframes_t offset)
1212 {
1213         AudioUnitRenderActionFlags flags = 0;
1214         AudioTimeStamp ts;
1215         OSErr err;
1216         uint32_t maxbuf = bufs.count().n_audio();
1217
1218         if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1219                 unit->GlobalReset();
1220                 _last_nframes = nframes;
1221         }
1222
1223         current_buffers = &bufs;
1224         current_maxbuf = maxbuf;
1225         current_offset = offset;
1226         cb_offset = 0;
1227
1228         buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
1229
1230         for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
1231                 buffers->mBuffers[i].mNumberChannels = 1;
1232                 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1233                 buffers->mBuffers[i].mData = 0;
1234         }
1235
1236         ts.mSampleTime = frames_processed;
1237         ts.mFlags = kAudioTimeStampSampleTimeValid;
1238
1239         if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1240
1241                 current_maxbuf = 0;
1242                 frames_processed += nframes;
1243                 
1244                 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1245                 uint32_t i;
1246
1247                 for (i = 0; i < limit; ++i) {
1248                         Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1249                         if (expected_buffer_address != buffers->mBuffers[i].mData) {
1250                                 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1251                                 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1252                         }
1253                 }
1254
1255                 /* now silence any buffers that were passed in but the that the plugin
1256                    did not fill/touch/use.
1257                 */
1258
1259                 for (;i < maxbuf; ++i) {
1260                         Sample* buffer_address= bufs.get_audio (i).data (offset);
1261                         memset (buffer_address, 0, nframes * sizeof (Sample));
1262                 }
1263
1264                 return 0;
1265         } 
1266
1267         cerr << name() << " render status " << err << endl;
1268         return -1;
1269 }
1270
1271 OSStatus 
1272 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat, 
1273                                        Float64* outCurrentTempo)
1274 {
1275         TempoMap& tmap (_session.tempo_map());
1276
1277         TRACE_API ("AU calls ardour beat&tempo callback\n");
1278
1279         /* more than 1 meter or more than 1 tempo means that a simplistic computation 
1280            (and interpretation) of a beat position will be incorrect. So refuse to 
1281            offer the value.
1282         */
1283
1284         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1285                 return kAudioUnitErr_CannotDoInCurrentContext;
1286         }
1287
1288         BBT_Time bbt;
1289         TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1290         tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1291
1292         if (outCurrentBeat) {
1293                 float beat;
1294                 beat = metric.meter().beats_per_bar() * bbt.bars;
1295                 beat += bbt.beats;
1296                 beat += bbt.ticks / Meter::ticks_per_beat;
1297                 *outCurrentBeat = beat;
1298         }
1299
1300         if (outCurrentTempo) {
1301                 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1302         }
1303
1304         return noErr;
1305
1306 }
1307
1308 OSStatus 
1309 AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
1310                                               Float32*  outTimeSig_Numerator,
1311                                               UInt32*   outTimeSig_Denominator,
1312                                               Float64*  outCurrentMeasureDownBeat)
1313 {
1314         TempoMap& tmap (_session.tempo_map());
1315
1316         TRACE_API ("AU calls ardour music time location callback\n");
1317
1318         /* more than 1 meter or more than 1 tempo means that a simplistic computation 
1319            (and interpretation) of a beat position will be incorrect. So refuse to 
1320            offer the value.
1321         */
1322
1323         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1324                 return kAudioUnitErr_CannotDoInCurrentContext;
1325         }
1326
1327         BBT_Time bbt;
1328         TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1329         tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1330
1331         if (outDeltaSampleOffsetToNextBeat) {
1332                 if (bbt.ticks == 0) {
1333                         /* on the beat */
1334                         *outDeltaSampleOffsetToNextBeat = 0;
1335                 } else {
1336                         *outDeltaSampleOffsetToNextBeat = (UInt32) floor (((Meter::ticks_per_beat - bbt.ticks)/Meter::ticks_per_beat) * // fraction of a beat to next beat
1337                                                                           metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1338                 }
1339         }
1340         
1341         if (outTimeSig_Numerator) {
1342                 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1343         }
1344         if (outTimeSig_Denominator) {
1345                 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1346         }
1347
1348         if (outCurrentMeasureDownBeat) {
1349
1350                 /* beat for the start of the bar. 
1351                    1|1|0 -> 1
1352                    2|1|0 -> 1 + beats_per_bar
1353                    3|1|0 -> 1 + (2 * beats_per_bar)
1354                    etc. 
1355                 */
1356
1357                 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1358         }
1359
1360         return noErr;
1361 }
1362
1363 OSStatus 
1364 AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
1365                                         Boolean*  outTransportStateChanged,
1366                                         Float64*  outCurrentSampleInTimeLine,
1367                                         Boolean*  outIsCycling,
1368                                         Float64*  outCycleStartBeat,
1369                                         Float64*  outCycleEndBeat)
1370 {
1371         bool rolling;
1372         float speed;
1373
1374         TRACE_API ("AU calls ardour transport state callback\n");
1375
1376         rolling = _session.transport_rolling();
1377         speed = _session.transport_speed ();
1378
1379         if (outIsPlaying) {
1380                 *outIsPlaying = _session.transport_rolling();
1381         }
1382
1383         if (outTransportStateChanged) {
1384                 if (rolling != last_transport_rolling) {
1385                         *outTransportStateChanged = true;
1386                 } else if (speed != last_transport_speed) {
1387                         *outTransportStateChanged = true;
1388                 } else {
1389                         *outTransportStateChanged = false;
1390                 }
1391         }
1392
1393         if (outCurrentSampleInTimeLine) {
1394                 /* this assumes that the AU can only call this host callback from render context,
1395                    where current_offset is valid.
1396                 */
1397                 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1398         }
1399
1400         if (outIsCycling) {
1401                 Location* loc = _session.locations()->auto_loop_location();
1402
1403                 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1404
1405                 if (*outIsCycling) {
1406
1407                         if (outCycleStartBeat || outCycleEndBeat) {
1408
1409                                 TempoMap& tmap (_session.tempo_map());
1410
1411                                 /* more than 1 meter means that a simplistic computation (and interpretation) of 
1412                                    a beat position will be incorrect. so refuse to offer the value.
1413                                 */
1414
1415                                 if (tmap.n_meters() > 1) {
1416                                         return kAudioUnitErr_CannotDoInCurrentContext;
1417                                 }
1418                                 
1419                                 BBT_Time bbt;
1420
1421                                 if (outCycleStartBeat) {
1422                                         TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
1423                                         _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1424
1425                                         float beat;
1426                                         beat = metric.meter().beats_per_bar() * bbt.bars;
1427                                         beat += bbt.beats;
1428                                         beat += bbt.ticks / Meter::ticks_per_beat;
1429                                         
1430                                         *outCycleStartBeat = beat;
1431                                 }
1432
1433                                 if (outCycleEndBeat) {
1434                                         TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
1435                                         _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1436                                         
1437                                         float beat;
1438                                         beat = metric.meter().beats_per_bar() * bbt.bars;
1439                                         beat += bbt.beats;
1440                                         beat += bbt.ticks / Meter::ticks_per_beat;
1441                                         
1442                                         *outCycleEndBeat = beat;
1443                                 }
1444                         }
1445                 }
1446         }
1447
1448         last_transport_rolling = rolling;
1449         last_transport_speed = speed;
1450
1451         return noErr;
1452 }
1453
1454 set<Evoral::Parameter>
1455 AUPlugin::automatable() const
1456 {
1457         set<Evoral::Parameter> automates;
1458
1459         for (uint32_t i = 0; i < descriptors.size(); ++i) {
1460                 if (descriptors[i].automatable) {
1461                         automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1462                 }
1463         }
1464
1465         return automates;
1466 }
1467
1468 string
1469 AUPlugin::describe_parameter (Evoral::Parameter param)
1470 {
1471         if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1472                 return descriptors[param.id()].label;
1473         } else {
1474                 return "??";
1475         }
1476 }
1477
1478 void
1479 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1480 {
1481         // NameValue stuff here
1482 }
1483
1484 bool
1485 AUPlugin::parameter_is_audio (uint32_t) const
1486 {
1487         return false;
1488 }
1489
1490 bool
1491 AUPlugin::parameter_is_control (uint32_t) const
1492 {
1493         return true;
1494 }
1495
1496 bool
1497 AUPlugin::parameter_is_input (uint32_t) const
1498 {
1499         return false;
1500 }
1501
1502 bool
1503 AUPlugin::parameter_is_output (uint32_t) const
1504 {
1505         return false;
1506 }
1507
1508 XMLNode&
1509 AUPlugin::get_state()
1510 {
1511         LocaleGuard lg (X_("POSIX"));
1512         XMLNode *root = new XMLNode (state_node_name());
1513
1514 #ifdef AU_STATE_SUPPORT
1515         CFDataRef xmlData;
1516         CFPropertyListRef propertyList;
1517
1518         TRACE_API ("get preset state\n");
1519         if (unit->GetAUPreset (propertyList) != noErr) {
1520                 return *root;
1521         }
1522
1523         // Convert the property list into XML data.
1524         
1525         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1526
1527         if (!xmlData) {
1528                 error << _("Could not create XML version of property list") << endmsg;
1529                 return *root;
1530         }
1531
1532         /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1533            our state node. GACK!
1534         */
1535
1536         XMLTree t;
1537
1538         if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1539                 if (t.root()) {
1540                         root->add_child_copy (*t.root());
1541                 }
1542         }
1543
1544         CFRelease (xmlData);
1545         CFRelease (propertyList);
1546 #else
1547         if (!seen_get_state_message) {
1548                 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1549                                         PROGRAM_NAME)
1550                      << endmsg;
1551                 seen_get_state_message = true;
1552         }
1553 #endif
1554         
1555         return *root;
1556 }
1557
1558 int
1559 AUPlugin::set_state(const XMLNode& node, int /* version*/)
1560 {
1561 #ifdef AU_STATE_SUPPORT
1562         int ret = -1;
1563         CFPropertyListRef propertyList;
1564         LocaleGuard lg (X_("POSIX"));
1565
1566         if (node.name() != state_node_name()) {
1567                 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1568                 return -1;
1569         }
1570         
1571         if (node.children().empty()) {
1572                 return -1;
1573         }
1574
1575         XMLNode* top = node.children().front();
1576         XMLNode* copy = new XMLNode (*top);
1577
1578         XMLTree t;
1579         t.set_root (copy);
1580
1581         const string& xml = t.write_buffer ();
1582         CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1583         CFStringRef errorString;
1584
1585         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1586                                                         xmlData,
1587                                                         kCFPropertyListImmutable,
1588                                                         &errorString);
1589
1590         CFRelease (xmlData);
1591         
1592         if (propertyList) {
1593                 TRACE_API ("set preset\n");
1594                 if (unit->SetAUPreset (propertyList) == noErr) {
1595                         ret = 0;
1596                         
1597                         /* tell the world */
1598
1599                         AudioUnitParameter changedUnit;
1600                         changedUnit.mAudioUnit = unit->AU();
1601                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1602                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1603                 } 
1604                 CFRelease (propertyList);
1605         }
1606         
1607         return ret;
1608 #else
1609         if (!seen_set_state_message) {
1610                 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1611                                         PROGRAM_NAME)
1612                      << endmsg;
1613         }
1614         return 0;
1615 #endif
1616 }
1617
1618 bool
1619 AUPlugin::load_preset (const string& preset_label)
1620 {
1621 #ifdef AU_STATE_SUPPORT
1622         bool ret = false;
1623         CFPropertyListRef propertyList;
1624         Glib::ustring path;
1625         UserPresetMap::iterator ux;
1626         FactoryPresetMap::iterator fx;
1627
1628         /* look first in "user" presets */
1629
1630         if ((ux = user_preset_map.find (preset_label)) != user_preset_map.end()) {
1631         
1632                 if ((propertyList = load_property_list (ux->second)) != 0) {
1633                         TRACE_API ("set preset from user presets\n");
1634                         if (unit->SetAUPreset (propertyList) == noErr) {
1635                                 ret = true;
1636
1637                                 /* tell the world */
1638                                 
1639                                 AudioUnitParameter changedUnit;
1640                                 changedUnit.mAudioUnit = unit->AU();
1641                                 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1642                                 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1643                         }
1644                         CFRelease(propertyList);
1645                 }
1646
1647         } else if ((fx = factory_preset_map.find (preset_label)) != factory_preset_map.end()) {
1648                 
1649                 AUPreset preset;
1650                 
1651                 preset.presetNumber = fx->second;
1652                 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1653                 
1654                 TRACE_API ("set preset from factory presets\n");
1655
1656                 if (unit->SetPresentPreset (preset) == 0) {
1657                         ret = true;
1658
1659                         /* tell the world */
1660
1661                         AudioUnitParameter changedUnit;
1662                         changedUnit.mAudioUnit = unit->AU();
1663                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1664                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1665                 }
1666         }
1667                 
1668         return ret;
1669 #else
1670         if (!seen_loading_message) {
1671                 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1672                                         PROGRAM_NAME)
1673                      << endmsg;
1674                 seen_loading_message = true;
1675         }
1676         return true;
1677 #endif
1678 }
1679
1680 bool
1681 AUPlugin::save_preset (string preset_name)
1682 {
1683 #ifdef AU_STATE_SUPPORT
1684         CFPropertyListRef propertyList;
1685         vector<Glib::ustring> v;
1686         Glib::ustring user_preset_path;
1687         bool ret = true;
1688
1689         std::string m = maker();
1690         std::string n = name();
1691         
1692         strip_whitespace_edges (m);
1693         strip_whitespace_edges (n);
1694
1695         v.push_back (Glib::get_home_dir());
1696         v.push_back ("Library");
1697         v.push_back ("Audio");
1698         v.push_back ("Presets");
1699         v.push_back (m);
1700         v.push_back (n);
1701         
1702         user_preset_path = Glib::build_filename (v);
1703
1704         if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1705                 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1706                 return false;
1707         }
1708
1709         TRACE_API ("get current preset\n");
1710         if (unit->GetAUPreset (propertyList) != noErr) {
1711                 return false;
1712         }
1713
1714         // add the actual preset name */
1715
1716         v.push_back (preset_name + preset_suffix);
1717                 
1718         // rebuild
1719
1720         user_preset_path = Glib::build_filename (v);
1721         
1722         set_preset_name_in_plist (propertyList, preset_name);
1723
1724         if (save_property_list (propertyList, user_preset_path)) {
1725                 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1726                 ret = false;
1727         }
1728
1729         CFRelease(propertyList);
1730
1731         return ret;
1732 #else
1733         if (!seen_saving_message) {
1734                 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1735                                         PROGRAM_NAME)
1736                      << endmsg;
1737                 seen_saving_message = true;
1738         }
1739         return false;
1740 #endif
1741 }
1742
1743 //-----------------------------------------------------------------------------
1744 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1745 static SInt32 
1746 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1747 {
1748         CFNumberRef cfNumber;
1749         SInt32 numberValue = 0;
1750         Boolean dummySuccess;
1751
1752         if (outSuccess == NULL)
1753                 outSuccess = &dummySuccess;
1754         if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1755         {
1756                 *outSuccess = FALSE;
1757                 return 0;
1758         }
1759
1760         cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1761         if (cfNumber == NULL)
1762         {
1763                 *outSuccess = FALSE;
1764                 return 0;
1765         }
1766         *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1767         if (*outSuccess)
1768                 return numberValue;
1769         else
1770                 return 0;
1771 }
1772
1773 static OSStatus 
1774 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1775 {
1776         CFDictionaryRef auStateDictionary;
1777         ComponentDescription tempDesc = {0,0,0,0,0};
1778         SInt32 versionValue;
1779         Boolean gotValue;
1780
1781         if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1782                 return paramErr;
1783         
1784         // the property list for AU state data must be of the dictionary type
1785         if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1786                 return kAudioUnitErr_InvalidPropertyValue;
1787         }
1788
1789         auStateDictionary = (CFDictionaryRef)inAUStateData;
1790
1791         // first check to make sure that the version of the AU state data is one that we know understand
1792         // XXX should I really do this?  later versions would probably still hold these ID keys, right?
1793         versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1794
1795         if (!gotValue) {
1796                 return kAudioUnitErr_InvalidPropertyValue;
1797         }
1798 #define kCurrentSavedStateVersion 0
1799         if (versionValue != kCurrentSavedStateVersion) {
1800                 return kAudioUnitErr_InvalidPropertyValue;
1801         }
1802
1803         // grab the ComponentDescription values from the AU state data
1804         tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1805         tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1806         tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1807         // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1808         if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1809                 return kAudioUnitErr_InvalidPropertyValue;
1810
1811         *outComponentDescription = tempDesc;
1812         return noErr;
1813 }
1814
1815
1816 static bool au_preset_filter (const string& str, void* arg)
1817 {
1818         /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1819
1820         bool ret;
1821         
1822         ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1823
1824         if (ret && arg) {
1825
1826                 /* check the preset file path name against this plugin
1827                    ID. The idea is that all preset files for this plugin
1828                    include "<manufacturer>/<plugin-name>" in their path.
1829                 */
1830
1831                 Plugin* p = (Plugin *) arg;
1832                 string match = p->maker();
1833                 match += '/';
1834                 match += p->name();
1835
1836                 ret = str.find (match) != string::npos;
1837
1838                 if (ret == false) {
1839                         string m = p->maker ();
1840                         string n = p->name ();
1841                         strip_whitespace_edges (m);
1842                         strip_whitespace_edges (n);
1843                         match = m;
1844                         match += '/';
1845                         match += n;
1846                         
1847                         ret = str.find (match) != string::npos;
1848                 }
1849         }
1850         
1851         return ret;
1852 }
1853
1854 bool 
1855 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1856 {
1857         OSStatus status;
1858         CFPropertyListRef plist;
1859         ComponentDescription presetDesc;
1860         bool ret = false;
1861                 
1862         plist = load_property_list (pathstr);
1863
1864         if (!plist) {
1865                 return ret;
1866         }
1867         
1868         // get the ComponentDescription from the AU preset file
1869         
1870         status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1871         
1872         if (status == noErr) {
1873                 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1874
1875                         /* try to get the preset name from the property list */
1876
1877                         if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1878
1879                                 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1880
1881                                 if (psk) {
1882
1883                                         const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1884
1885                                         if (!p) {
1886                                                 char buf[PATH_MAX+1];
1887
1888                                                 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1889                                                         preset_name = buf;
1890                                                 }
1891                                         }
1892                                 }
1893                         }
1894                 } 
1895         }
1896
1897         CFRelease (plist);
1898
1899         return true;
1900 }
1901
1902 std::string
1903 AUPlugin::current_preset() const
1904 {
1905         string preset_name;
1906         
1907 #ifdef AU_STATE_SUPPORT
1908         CFPropertyListRef propertyList;
1909
1910         TRACE_API ("get current preset for current_preset()\n");
1911         if (unit->GetAUPreset (propertyList) == noErr) {
1912                 preset_name = get_preset_name_in_plist (propertyList);
1913                 CFRelease(propertyList);
1914         }
1915 #endif
1916         return preset_name;
1917 }
1918
1919 vector<Plugin::PresetRecord>
1920 AUPlugin::get_presets ()
1921 {
1922         vector<Plugin::PresetRecord> presets;
1923
1924 #ifdef AU_STATE_SUPPORT
1925         vector<string*>* preset_files;
1926         PathScanner scanner;
1927
1928         user_preset_map.clear ();
1929
1930         preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1931         
1932         if (!preset_files) {
1933                 return presets;
1934         }
1935
1936         for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1937
1938                 string path = *(*x);
1939                 string preset_name;
1940
1941                 /* make an initial guess at the preset name using the path */
1942
1943                 preset_name = Glib::path_get_basename (path);
1944                 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1945
1946                 /* check that this preset file really matches this plugin
1947                    and potentially get the "real" preset name from
1948                    within the file.
1949                 */
1950
1951                 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
1952                         user_preset_map[preset_name] = path;
1953                 } 
1954
1955                 delete *x;
1956         }
1957
1958         delete preset_files;
1959
1960         /* now fill the vector<string> with the names we have */
1961
1962         for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
1963                 presets.push_back (Plugin::PresetRecord (i->second, i->first));
1964         }
1965
1966         /* add factory presets */
1967
1968         for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
1969                 presets.push_back (Plugin::PresetRecord ("", i->first));
1970         }
1971
1972 #endif
1973         
1974         return presets;
1975 }
1976
1977 bool
1978 AUPlugin::has_editor () const
1979 {
1980         // even if the plugin doesn't have its own editor, the AU API can be used
1981         // to create one that looks native.
1982         return true;
1983 }
1984
1985 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
1986         : descriptor (d)
1987 {
1988         type = ARDOUR::AudioUnit;
1989 }
1990
1991 AUPluginInfo::~AUPluginInfo ()
1992 {
1993         type = ARDOUR::AudioUnit;
1994 }
1995
1996 PluginPtr
1997 AUPluginInfo::load (Session& session)
1998 {
1999         try {
2000                 PluginPtr plugin;
2001
2002                 TRACE_API ("load AU as a component\n");
2003                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2004                 
2005                 if (!comp->IsValid()) {
2006                         error << ("AudioUnit: not a valid Component") << endmsg;
2007                 } else {
2008                         plugin.reset (new AUPlugin (session.engine(), session, comp));
2009                 }
2010                 
2011                 AUPluginInfo *aup = new AUPluginInfo (*this);
2012                 plugin->set_info (PluginInfoPtr (aup));
2013                 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2014                 return plugin;
2015         }
2016
2017         catch (failed_constructor &err) {
2018                 return PluginPtr ();
2019         }
2020 }
2021
2022 Glib::ustring
2023 AUPluginInfo::au_cache_path ()
2024 {
2025         return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2026 }
2027
2028 PluginInfoList*
2029 AUPluginInfo::discover ()
2030 {
2031         XMLTree tree;
2032
2033         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2034                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2035         }
2036
2037         PluginInfoList* plugs = new PluginInfoList;
2038         
2039         discover_fx (*plugs);
2040         discover_music (*plugs);
2041         discover_generators (*plugs);
2042
2043         return plugs;
2044 }
2045
2046 void
2047 AUPluginInfo::discover_music (PluginInfoList& plugs)
2048 {
2049         CAComponentDescription desc;
2050         desc.componentFlags = 0;
2051         desc.componentFlagsMask = 0;
2052         desc.componentSubType = 0;
2053         desc.componentManufacturer = 0;
2054         desc.componentType = kAudioUnitType_MusicEffect;
2055
2056         discover_by_description (plugs, desc);
2057 }
2058
2059 void
2060 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2061 {
2062         CAComponentDescription desc;
2063         desc.componentFlags = 0;
2064         desc.componentFlagsMask = 0;
2065         desc.componentSubType = 0;
2066         desc.componentManufacturer = 0;
2067         desc.componentType = kAudioUnitType_Effect;
2068
2069         discover_by_description (plugs, desc);
2070 }
2071
2072 void
2073 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2074 {
2075         CAComponentDescription desc;
2076         desc.componentFlags = 0;
2077         desc.componentFlagsMask = 0;
2078         desc.componentSubType = 0;
2079         desc.componentManufacturer = 0;
2080         desc.componentType = kAudioUnitType_Generator;
2081
2082         discover_by_description (plugs, desc);
2083 }
2084
2085 void
2086 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2087 {
2088         Component comp = 0;
2089
2090         comp = FindNextComponent (NULL, &desc);
2091
2092         while (comp != NULL) {
2093                 CAComponentDescription temp;
2094                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2095
2096                 AUPluginInfoPtr info (new AUPluginInfo 
2097                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2098
2099                 /* although apple designed the subtype field to be a "category" indicator,
2100                    its really turned into a plugin ID field for a given manufacturer. Hence
2101                    there are no categories for AudioUnits. However, to keep the plugins
2102                    showing up under "categories", we'll use the "type" as a high level
2103                    selector.
2104                    
2105                    NOTE: no panners, format converters or i/o AU's for our purposes
2106                  */
2107
2108                 switch (info->descriptor->Type()) {
2109                 case kAudioUnitType_Panner:
2110                 case kAudioUnitType_OfflineEffect:
2111                 case kAudioUnitType_FormatConverter:
2112                         continue;
2113
2114                 case kAudioUnitType_Output:
2115                         info->category = _("AudioUnit Outputs");
2116                         break;
2117                 case kAudioUnitType_MusicDevice:
2118                         info->category = _("AudioUnit Instruments");
2119                         break;
2120                 case kAudioUnitType_MusicEffect:
2121                         info->category = _("AudioUnit MusicEffects");
2122                         break;
2123                 case kAudioUnitType_Effect:
2124                         info->category = _("AudioUnit Effects");
2125                         break;
2126                 case kAudioUnitType_Mixer:
2127                         info->category = _("AudioUnit Mixers");
2128                         break;
2129                 case kAudioUnitType_Generator:
2130                         info->category = _("AudioUnit Generators");
2131                         break;
2132                 default:
2133                         info->category = _("AudioUnit (Unknown)");
2134                         break;
2135                 }
2136
2137                 AUPluginInfo::get_names (temp, info->name, info->creator);
2138                 
2139                 info->type = ARDOUR::AudioUnit;
2140                 info->unique_id = stringify_descriptor (*info->descriptor);
2141
2142                 /* XXX not sure of the best way to handle plugin versioning yet
2143                  */
2144
2145                 CAComponent cacomp (*info->descriptor);
2146
2147                 if (cacomp.GetResourceVersion (info->version) != noErr) {
2148                         info->version = 0;
2149                 }
2150                 
2151                 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2152
2153                         /* here we have to map apple's wildcard system to a simple pair
2154                            of values. in ::can_do() we use the whole system, but here
2155                            we need a single pair of values. XXX probably means we should
2156                            remove any use of these values.
2157                         */
2158
2159                         info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
2160                         info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
2161
2162                         cerr << "detected AU: " << info->name.c_str() << "  (" << info->cache.io_configs.size() << " i/o configurations) - " << info->unique_id << endl;
2163
2164                         plugs.push_back (info);
2165
2166                 } else {
2167                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2168                 }
2169                 
2170                 comp = FindNextComponent (comp, &desc);
2171         }
2172 }
2173
2174 bool
2175 AUPluginInfo::cached_io_configuration (const std::string& unique_id, 
2176                                        UInt32 version,
2177                                        CAComponent& comp, 
2178                                        AUPluginCachedInfo& cinfo, 
2179                                        const std::string& name)
2180 {
2181         std::string id;
2182         char buf[32];
2183
2184         /* concatenate unique ID with version to provide a key for cached info lookup.
2185            this ensures we don't get stale information, or should if plugin developers
2186            follow Apple "guidelines".
2187          */
2188
2189         snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2190         id = unique_id;
2191         id += '/';
2192         id += buf;
2193
2194         CachedInfoMap::iterator cim = cached_info.find (id);
2195
2196         if (cim != cached_info.end()) {
2197                 cinfo = cim->second;
2198                 return true;
2199         }
2200
2201         CAAudioUnit unit;
2202         AUChannelInfo* channel_info;
2203         UInt32 cnt;
2204         int ret;
2205         
2206         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2207         
2208         try {
2209
2210                 if (CAAudioUnit::Open (comp, unit) != noErr) {
2211                         return false;
2212                 }
2213
2214         } catch (...) {
2215
2216                 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2217                 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
2218                 return false;
2219
2220         }
2221                 
2222         TRACE_API ("get AU channel info\n");
2223         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2224                 return false;
2225         }
2226
2227         if (ret > 0) {
2228                 /* no explicit info available */
2229
2230                 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2231
2232         } else {
2233                 
2234                 /* store each configuration */
2235                 
2236                 for (uint32_t n = 0; n < cnt; ++n) {
2237                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2238                                                                    channel_info[n].outChannels));
2239                 }
2240
2241                 free (channel_info);
2242         }
2243
2244         add_cached_info (id, cinfo);
2245         save_cached_info ();
2246
2247         return true;
2248 }
2249
2250 void
2251 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2252 {
2253         cached_info[id] = cinfo;
2254 }
2255
2256 #define AU_CACHE_VERSION "2.0"
2257
2258 void
2259 AUPluginInfo::save_cached_info ()
2260 {
2261         XMLNode* node;
2262
2263         node = new XMLNode (X_("AudioUnitPluginCache"));
2264         node->add_property( "version", AU_CACHE_VERSION );
2265         
2266         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2267                 XMLNode* parent = new XMLNode (X_("plugin"));
2268                 parent->add_property ("id", i->first);
2269                 node->add_child_nocopy (*parent);
2270
2271                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2272
2273                         XMLNode* child = new XMLNode (X_("io"));
2274                         char buf[32];
2275
2276                         snprintf (buf, sizeof (buf), "%d", j->first);
2277                         child->add_property (X_("in"), buf);
2278                         snprintf (buf, sizeof (buf), "%d", j->second);
2279                         child->add_property (X_("out"), buf);
2280                         parent->add_child_nocopy (*child);
2281                 }
2282
2283         }
2284
2285         Glib::ustring path = au_cache_path ();
2286         XMLTree tree;
2287
2288         tree.set_root (node);
2289
2290         if (!tree.write (path)) {
2291                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2292                 unlink (path.c_str());
2293         }
2294 }
2295
2296 int
2297 AUPluginInfo::load_cached_info ()
2298 {
2299         Glib::ustring path = au_cache_path ();
2300         XMLTree tree;
2301         
2302         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2303                 return 0;
2304         }
2305
2306         if ( !tree.read (path) ) {
2307                 error << "au_cache is not a valid XML file.  AU plugins will be re-scanned" << endmsg;
2308                 return -1;
2309         }
2310         
2311         const XMLNode* root (tree.root());
2312
2313         if (root->name() != X_("AudioUnitPluginCache")) {
2314                 return -1;
2315         }
2316         
2317         //initial version has incorrectly stored i/o info, and/or garbage chars.
2318         const XMLProperty* version = root->property(X_("version"));
2319         if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2320                 error << "au_cache is not correct version.  AU plugins will be re-scanned" << endmsg;
2321                 return -1;
2322         }
2323         
2324         cached_info.clear ();
2325
2326         const XMLNodeList children = root->children();
2327
2328         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2329                 
2330                 const XMLNode* child = *iter;
2331                 
2332                 if (child->name() == X_("plugin")) {
2333
2334                         const XMLNode* gchild;
2335                         const XMLNodeList gchildren = child->children();
2336                         const XMLProperty* prop = child->property (X_("id"));
2337
2338                         if (!prop) {
2339                                 continue;
2340                         }
2341                         
2342                         string id = prop->value();
2343                         string fixed;
2344                         string version;
2345
2346                         string::size_type slash = id.find_last_of ('/');
2347
2348                         if (slash == string::npos) {
2349                                 continue;
2350                         }
2351
2352                         version = id.substr (slash);
2353                         id = id.substr (0, slash);
2354                         fixed = AUPlugin::maybe_fix_broken_au_id (id);
2355
2356                         if (fixed.empty()) {
2357                                 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2358                                 continue;
2359                         } 
2360
2361                         id = fixed;
2362                         id += version;
2363
2364                         AUPluginCachedInfo cinfo;
2365
2366                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2367
2368                                 gchild = *giter;
2369
2370                                 if (gchild->name() == X_("io")) {
2371
2372                                         int in;
2373                                         int out;
2374                                         const XMLProperty* iprop;
2375                                         const XMLProperty* oprop;
2376
2377                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
2378                                             ((oprop = gchild->property (X_("out"))) != 0)) {
2379                                                 in = atoi (iprop->value());
2380                                                 out = atoi (oprop->value());
2381                                                 
2382                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
2383                                         }
2384                                 }
2385                         }
2386
2387                         if (cinfo.io_configs.size()) {
2388                                 add_cached_info (id, cinfo);
2389                         }
2390                 }
2391         }
2392
2393         return 0;
2394 }
2395
2396 void
2397 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2398 {
2399         CFStringRef itemName = NULL;
2400
2401         // Marc Poirier-style item name
2402         CAComponent auComponent (comp_desc);
2403         if (auComponent.IsValid()) {
2404                 CAComponentDescription dummydesc;
2405                 Handle nameHandle = NewHandle(sizeof(void*));
2406                 if (nameHandle != NULL) {
2407                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2408                         if (err == noErr) {
2409                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2410                                 if (nameString != NULL) {
2411                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2412                                 }
2413                         }
2414                         DisposeHandle(nameHandle);
2415                 }
2416         }
2417     
2418         // if Marc-style fails, do the original way
2419         if (itemName == NULL) {
2420                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2421                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2422                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2423     
2424                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"), 
2425                         compTypeString, compManufacturerString, compSubTypeString);
2426     
2427                 if (compTypeString != NULL)
2428                         CFRelease(compTypeString);
2429                 if (compSubTypeString != NULL)
2430                         CFRelease(compSubTypeString);
2431                 if (compManufacturerString != NULL)
2432                         CFRelease(compManufacturerString);
2433         }
2434         
2435         string str = CFStringRefToStdString(itemName);
2436         string::size_type colon = str.find (':');
2437
2438         if (colon) {
2439                 name = str.substr (colon+1);
2440                 maker = str.substr (0, colon);
2441                 strip_whitespace_edges (maker);
2442                 strip_whitespace_edges (name);
2443         } else {
2444                 name = str;
2445                 maker = "unknown";
2446                 strip_whitespace_edges (name);
2447         }
2448 }
2449
2450 std::string
2451 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2452 {
2453         stringstream s;
2454
2455         /* note: OSType is a compiler-implemenation-defined value,
2456            historically a 32 bit integer created with a multi-character
2457            constant such as 'abcd'. It is, fundamentally, an abomination.
2458         */
2459
2460         s << desc.Type();
2461         s << '-';
2462         s << desc.SubType();
2463         s << '-';
2464         s << desc.Manu();
2465
2466         return s.str();
2467 }
2468