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