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