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