deliver MIDI events to AU plugins that want them
[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         if (_has_midi_input) {
1309
1310                 for (uint32_t i = 0; i < bufs.count().n_midi(); ++i) {
1311                         
1312                         /* one MIDI port/buffer only */
1313                         
1314                         MidiBuffer& m = bufs.get_midi (i);
1315                         
1316                         for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1317                                 Evoral::MIDIEvent<framepos_t> ev (*i);
1318                                 
1319                                 if (ev.is_channel_event()) {
1320                                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n",
1321                                                                                         name(), ev));
1322                                         unit->MIDIEvent (ev.type() << 8 | ev.channel(),
1323                                                          ev.buffer()[1],
1324                                                          ev.buffer()[2],
1325                                                          ev.time());
1326                                 }
1327
1328                                 /* XXX need to handle sysex and other message types */
1329                         }
1330                 }
1331         }
1332
1333         ts.mSampleTime = frames_processed;
1334         ts.mFlags = kAudioTimeStampSampleTimeValid;
1335
1336         if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1337
1338                 current_maxbuf = 0;
1339                 frames_processed += nframes;
1340
1341                 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1342                 uint32_t i;
1343
1344                 for (i = 0; i < limit; ++i) {
1345                         Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1346                         if (expected_buffer_address != buffers->mBuffers[i].mData) {
1347                                 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1348                                 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1349                         }
1350                 }
1351
1352                 /* now silence any buffers that were passed in but the that the plugin
1353                    did not fill/touch/use.
1354                 */
1355
1356                 for (;i < maxbuf; ++i) {
1357                         Sample* buffer_address= bufs.get_audio (i).data (offset);
1358                         memset (buffer_address, 0, nframes * sizeof (Sample));
1359                 }
1360
1361                 return 0;
1362         }
1363
1364         cerr << name() << " render status " << err << endl;
1365         return -1;
1366 }
1367
1368 OSStatus
1369 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1370                                        Float64* outCurrentTempo)
1371 {
1372         TempoMap& tmap (_session.tempo_map());
1373
1374         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1375
1376         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1377            (and interpretation) of a beat position will be incorrect. So refuse to
1378            offer the value.
1379         */
1380
1381         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1382                 return kAudioUnitErr_CannotDoInCurrentContext;
1383         }
1384
1385         Timecode::BBT_Time bbt;
1386         TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1387         tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1388
1389         if (outCurrentBeat) {
1390                 float beat;
1391                 beat = metric.meter().beats_per_bar() * bbt.bars;
1392                 beat += bbt.beats;
1393                 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1394                 *outCurrentBeat = beat;
1395         }
1396
1397         if (outCurrentTempo) {
1398                 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1399         }
1400
1401         return noErr;
1402
1403 }
1404
1405 OSStatus
1406 AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNextBeat,
1407                                               Float32*  outTimeSig_Numerator,
1408                                               UInt32*   outTimeSig_Denominator,
1409                                               Float64*  outCurrentMeasureDownBeat)
1410 {
1411         TempoMap& tmap (_session.tempo_map());
1412
1413         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1414
1415         /* more than 1 meter or more than 1 tempo means that a simplistic computation
1416            (and interpretation) of a beat position will be incorrect. So refuse to
1417            offer the value.
1418         */
1419
1420         if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1421                 return kAudioUnitErr_CannotDoInCurrentContext;
1422         }
1423
1424         Timecode::BBT_Time bbt;
1425         TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1426         tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1427
1428         if (outDeltaSampleOffsetToNextBeat) {
1429                 if (bbt.ticks == 0) {
1430                         /* on the beat */
1431                         *outDeltaSampleOffsetToNextBeat = 0;
1432                 } else {
1433                         *outDeltaSampleOffsetToNextBeat = (UInt32) 
1434                                 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1435                                        metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1436                 }
1437         }
1438
1439         if (outTimeSig_Numerator) {
1440                 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1441         }
1442         if (outTimeSig_Denominator) {
1443                 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1444         }
1445
1446         if (outCurrentMeasureDownBeat) {
1447
1448                 /* beat for the start of the bar.
1449                    1|1|0 -> 1
1450                    2|1|0 -> 1 + beats_per_bar
1451                    3|1|0 -> 1 + (2 * beats_per_bar)
1452                    etc.
1453                 */
1454
1455                 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1456         }
1457
1458         return noErr;
1459 }
1460
1461 OSStatus
1462 AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
1463                                         Boolean*  outTransportStateChanged,
1464                                         Float64*  outCurrentSampleInTimeLine,
1465                                         Boolean*  outIsCycling,
1466                                         Float64*  outCycleStartBeat,
1467                                         Float64*  outCycleEndBeat)
1468 {
1469         bool rolling;
1470         float speed;
1471
1472         DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1473
1474         rolling = _session.transport_rolling();
1475         speed = _session.transport_speed ();
1476
1477         if (outIsPlaying) {
1478                 *outIsPlaying = _session.transport_rolling();
1479         }
1480
1481         if (outTransportStateChanged) {
1482                 if (rolling != last_transport_rolling) {
1483                         *outTransportStateChanged = true;
1484                 } else if (speed != last_transport_speed) {
1485                         *outTransportStateChanged = true;
1486                 } else {
1487                         *outTransportStateChanged = false;
1488                 }
1489         }
1490
1491         if (outCurrentSampleInTimeLine) {
1492                 /* this assumes that the AU can only call this host callback from render context,
1493                    where current_offset is valid.
1494                 */
1495                 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1496         }
1497
1498         if (outIsCycling) {
1499                 Location* loc = _session.locations()->auto_loop_location();
1500
1501                 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1502
1503                 if (*outIsCycling) {
1504
1505                         if (outCycleStartBeat || outCycleEndBeat) {
1506
1507                                 TempoMap& tmap (_session.tempo_map());
1508
1509                                 /* more than 1 meter means that a simplistic computation (and interpretation) of
1510                                    a beat position will be incorrect. so refuse to offer the value.
1511                                 */
1512
1513                                 if (tmap.n_meters() > 1) {
1514                                         return kAudioUnitErr_CannotDoInCurrentContext;
1515                                 }
1516
1517                                 Timecode::BBT_Time bbt;
1518
1519                                 if (outCycleStartBeat) {
1520                                         TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
1521                                         _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1522
1523                                         float beat;
1524                                         beat = metric.meter().beats_per_bar() * bbt.bars;
1525                                         beat += bbt.beats;
1526                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1527
1528                                         *outCycleStartBeat = beat;
1529                                 }
1530
1531                                 if (outCycleEndBeat) {
1532                                         TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
1533                                         _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1534
1535                                         float beat;
1536                                         beat = metric.meter().beats_per_bar() * bbt.bars;
1537                                         beat += bbt.beats;
1538                                         beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1539
1540                                         *outCycleEndBeat = beat;
1541                                 }
1542                         }
1543                 }
1544         }
1545
1546         last_transport_rolling = rolling;
1547         last_transport_speed = speed;
1548
1549         return noErr;
1550 }
1551
1552 set<Evoral::Parameter>
1553 AUPlugin::automatable() const
1554 {
1555         set<Evoral::Parameter> automates;
1556
1557         for (uint32_t i = 0; i < descriptors.size(); ++i) {
1558                 if (descriptors[i].automatable) {
1559                         automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1560                 }
1561         }
1562
1563         return automates;
1564 }
1565
1566 string
1567 AUPlugin::describe_parameter (Evoral::Parameter param)
1568 {
1569         if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1570                 return descriptors[param.id()].label;
1571         } else {
1572                 return "??";
1573         }
1574 }
1575
1576 void
1577 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1578 {
1579         // NameValue stuff here
1580 }
1581
1582 bool
1583 AUPlugin::parameter_is_audio (uint32_t) const
1584 {
1585         return false;
1586 }
1587
1588 bool
1589 AUPlugin::parameter_is_control (uint32_t) const
1590 {
1591         return true;
1592 }
1593
1594 bool
1595 AUPlugin::parameter_is_input (uint32_t) const
1596 {
1597         return false;
1598 }
1599
1600 bool
1601 AUPlugin::parameter_is_output (uint32_t) const
1602 {
1603         return false;
1604 }
1605
1606 void
1607 AUPlugin::add_state (XMLNode* root) const
1608 {
1609         LocaleGuard lg (X_("POSIX"));
1610
1611 #ifdef AU_STATE_SUPPORT
1612         CFDataRef xmlData;
1613         CFPropertyListRef propertyList;
1614
1615         DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1616         if (unit->GetAUPreset (propertyList) != noErr) {
1617                 return;
1618         }
1619
1620         // Convert the property list into XML data.
1621
1622         xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1623
1624         if (!xmlData) {
1625                 error << _("Could not create XML version of property list") << endmsg;
1626                 return;
1627         }
1628
1629         /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1630            our state node. GACK!
1631         */
1632
1633         XMLTree t;
1634
1635         if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1636                 if (t.root()) {
1637                         root->add_child_copy (*t.root());
1638                 }
1639         }
1640
1641         CFRelease (xmlData);
1642         CFRelease (propertyList);
1643 #else
1644         if (!seen_get_state_message) {
1645                 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1646                                         PROGRAM_NAME)
1647                      << endmsg;
1648                 seen_get_state_message = true;
1649         }
1650 #endif
1651 }
1652
1653 int
1654 AUPlugin::set_state(const XMLNode& node, int version)
1655 {
1656 #ifdef AU_STATE_SUPPORT
1657         int ret = -1;
1658         CFPropertyListRef propertyList;
1659         LocaleGuard lg (X_("POSIX"));
1660
1661         if (node.name() != state_node_name()) {
1662                 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1663                 return -1;
1664         }
1665
1666         if (node.children().empty()) {
1667                 return -1;
1668         }
1669
1670         XMLNode* top = node.children().front();
1671         XMLNode* copy = new XMLNode (*top);
1672
1673         XMLTree t;
1674         t.set_root (copy);
1675
1676         const string& xml = t.write_buffer ();
1677         CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1678         CFStringRef errorString;
1679
1680         propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1681                                                         xmlData,
1682                                                         kCFPropertyListImmutable,
1683                                                         &errorString);
1684
1685         CFRelease (xmlData);
1686
1687         if (propertyList) {
1688                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1689                 if (unit->SetAUPreset (propertyList) == noErr) {
1690                         ret = 0;
1691
1692                         /* tell the world */
1693
1694                         AudioUnitParameter changedUnit;
1695                         changedUnit.mAudioUnit = unit->AU();
1696                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1697                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1698                 }
1699                 CFRelease (propertyList);
1700         }
1701
1702         Plugin::set_state (node, version);
1703         return ret;
1704 #else
1705         if (!seen_set_state_message) {
1706                 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1707                                         PROGRAM_NAME)
1708                      << endmsg;
1709         }
1710         return Plugin::set_state (node, version);
1711 #endif
1712 }
1713
1714 bool
1715 AUPlugin::load_preset (PresetRecord r)
1716 {
1717         Plugin::load_preset (r);
1718
1719 #ifdef AU_STATE_SUPPORT
1720         bool ret = false;
1721         CFPropertyListRef propertyList;
1722         Glib::ustring path;
1723         UserPresetMap::iterator ux;
1724         FactoryPresetMap::iterator fx;
1725
1726         /* look first in "user" presets */
1727
1728         if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1729
1730                 if ((propertyList = load_property_list (ux->second)) != 0) {
1731                         DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1732                         if (unit->SetAUPreset (propertyList) == noErr) {
1733                                 ret = true;
1734
1735                                 /* tell the world */
1736
1737                                 AudioUnitParameter changedUnit;
1738                                 changedUnit.mAudioUnit = unit->AU();
1739                                 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1740                                 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1741                         }
1742                         CFRelease(propertyList);
1743                 }
1744
1745         } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1746
1747                 AUPreset preset;
1748
1749                 preset.presetNumber = fx->second;
1750                 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1751
1752                 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1753
1754                 if (unit->SetPresentPreset (preset) == 0) {
1755                         ret = true;
1756
1757                         /* tell the world */
1758
1759                         AudioUnitParameter changedUnit;
1760                         changedUnit.mAudioUnit = unit->AU();
1761                         changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1762                         AUParameterListenerNotify (NULL, NULL, &changedUnit);
1763                 }
1764         }
1765
1766         return ret;
1767 #else
1768         if (!seen_loading_message) {
1769                 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1770                                         PROGRAM_NAME)
1771                      << endmsg;
1772                 seen_loading_message = true;
1773         }
1774         return true;
1775 #endif
1776 }
1777
1778 void
1779 AUPlugin::do_remove_preset (std::string) 
1780 {
1781 }
1782
1783 string
1784 AUPlugin::do_save_preset (string preset_name)
1785 {
1786 #ifdef AU_STATE_SUPPORT
1787         CFPropertyListRef propertyList;
1788         vector<Glib::ustring> v;
1789         Glib::ustring user_preset_path;
1790         bool ret = true;
1791
1792         std::string m = maker();
1793         std::string n = name();
1794
1795         strip_whitespace_edges (m);
1796         strip_whitespace_edges (n);
1797
1798         v.push_back (Glib::get_home_dir());
1799         v.push_back ("Library");
1800         v.push_back ("Audio");
1801         v.push_back ("Presets");
1802         v.push_back (m);
1803         v.push_back (n);
1804
1805         user_preset_path = Glib::build_filename (v);
1806
1807         if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1808                 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1809                 return false;
1810         }
1811
1812         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1813         if (unit->GetAUPreset (propertyList) != noErr) {
1814                 return false;
1815         }
1816
1817         // add the actual preset name */
1818
1819         v.push_back (preset_name + preset_suffix);
1820
1821         // rebuild
1822
1823         user_preset_path = Glib::build_filename (v);
1824
1825         set_preset_name_in_plist (propertyList, preset_name);
1826
1827         if (save_property_list (propertyList, user_preset_path)) {
1828                 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1829                 ret = false;
1830         }
1831
1832         CFRelease(propertyList);
1833
1834         return string ("file:///") + user_preset_path;
1835 #else
1836         if (!seen_saving_message) {
1837                 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1838                                         PROGRAM_NAME)
1839                      << endmsg;
1840                 seen_saving_message = true;
1841         }
1842         return string();
1843 #endif
1844 }
1845
1846 //-----------------------------------------------------------------------------
1847 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1848 static SInt32
1849 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1850 {
1851         CFNumberRef cfNumber;
1852         SInt32 numberValue = 0;
1853         Boolean dummySuccess;
1854
1855         if (outSuccess == NULL)
1856                 outSuccess = &dummySuccess;
1857         if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1858         {
1859                 *outSuccess = FALSE;
1860                 return 0;
1861         }
1862
1863         cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1864         if (cfNumber == NULL)
1865         {
1866                 *outSuccess = FALSE;
1867                 return 0;
1868         }
1869         *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1870         if (*outSuccess)
1871                 return numberValue;
1872         else
1873                 return 0;
1874 }
1875
1876 static OSStatus
1877 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1878 {
1879         CFDictionaryRef auStateDictionary;
1880         ComponentDescription tempDesc = {0,0,0,0,0};
1881         SInt32 versionValue;
1882         Boolean gotValue;
1883
1884         if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1885                 return paramErr;
1886
1887         // the property list for AU state data must be of the dictionary type
1888         if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1889                 return kAudioUnitErr_InvalidPropertyValue;
1890         }
1891
1892         auStateDictionary = (CFDictionaryRef)inAUStateData;
1893
1894         // first check to make sure that the version of the AU state data is one that we know understand
1895         // XXX should I really do this?  later versions would probably still hold these ID keys, right?
1896         versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1897
1898         if (!gotValue) {
1899                 return kAudioUnitErr_InvalidPropertyValue;
1900         }
1901 #define kCurrentSavedStateVersion 0
1902         if (versionValue != kCurrentSavedStateVersion) {
1903                 return kAudioUnitErr_InvalidPropertyValue;
1904         }
1905
1906         // grab the ComponentDescription values from the AU state data
1907         tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1908         tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1909         tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1910         // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1911         if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1912                 return kAudioUnitErr_InvalidPropertyValue;
1913
1914         *outComponentDescription = tempDesc;
1915         return noErr;
1916 }
1917
1918
1919 static bool au_preset_filter (const string& str, void* arg)
1920 {
1921         /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1922
1923         bool ret;
1924
1925         ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1926
1927         if (ret && arg) {
1928
1929                 /* check the preset file path name against this plugin
1930                    ID. The idea is that all preset files for this plugin
1931                    include "<manufacturer>/<plugin-name>" in their path.
1932                 */
1933
1934                 Plugin* p = (Plugin *) arg;
1935                 string match = p->maker();
1936                 match += '/';
1937                 match += p->name();
1938
1939                 ret = str.find (match) != string::npos;
1940
1941                 if (ret == false) {
1942                         string m = p->maker ();
1943                         string n = p->name ();
1944                         strip_whitespace_edges (m);
1945                         strip_whitespace_edges (n);
1946                         match = m;
1947                         match += '/';
1948                         match += n;
1949
1950                         ret = str.find (match) != string::npos;
1951                 }
1952         }
1953
1954         return ret;
1955 }
1956
1957 bool
1958 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1959 {
1960         OSStatus status;
1961         CFPropertyListRef plist;
1962         ComponentDescription presetDesc;
1963         bool ret = false;
1964
1965         plist = load_property_list (pathstr);
1966
1967         if (!plist) {
1968                 return ret;
1969         }
1970
1971         // get the ComponentDescription from the AU preset file
1972
1973         status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1974
1975         if (status == noErr) {
1976                 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1977
1978                         /* try to get the preset name from the property list */
1979
1980                         if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1981
1982                                 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1983
1984                                 if (psk) {
1985
1986                                         const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1987
1988                                         if (!p) {
1989                                                 char buf[PATH_MAX+1];
1990
1991                                                 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1992                                                         preset_name = buf;
1993                                                 }
1994                                         }
1995                                 }
1996                         }
1997                 }
1998         }
1999
2000         CFRelease (plist);
2001
2002         return true;
2003 }
2004
2005 std::string
2006 AUPlugin::current_preset() const
2007 {
2008         string preset_name;
2009
2010 #ifdef AU_STATE_SUPPORT
2011         CFPropertyListRef propertyList;
2012
2013         DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2014         if (unit->GetAUPreset (propertyList) == noErr) {
2015                 preset_name = get_preset_name_in_plist (propertyList);
2016                 CFRelease(propertyList);
2017         }
2018 #endif
2019         return preset_name;
2020 }
2021
2022 void
2023 AUPlugin::find_presets ()
2024 {
2025 #ifdef AU_STATE_SUPPORT
2026         vector<string*>* preset_files;
2027         PathScanner scanner;
2028
2029         user_preset_map.clear ();
2030
2031         preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2032
2033         if (!preset_files) {
2034                 return;
2035         }
2036
2037         for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2038
2039                 string path = *(*x);
2040                 string preset_name;
2041
2042                 /* make an initial guess at the preset name using the path */
2043
2044                 preset_name = Glib::path_get_basename (path);
2045                 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2046
2047                 /* check that this preset file really matches this plugin
2048                    and potentially get the "real" preset name from
2049                    within the file.
2050                 */
2051
2052                 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2053                         user_preset_map[preset_name] = path;
2054                 }
2055
2056                 delete *x;
2057         }
2058
2059         delete preset_files;
2060
2061         /* now fill the vector<string> with the names we have */
2062
2063         for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2064                 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2065         }
2066
2067         /* add factory presets */
2068
2069         for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2070                 /* XXX: dubious */
2071                 string const uri = string_compose ("%1", _presets.size ());
2072                 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first)));
2073         }
2074
2075 #endif
2076 }
2077
2078 bool
2079 AUPlugin::has_editor () const
2080 {
2081         // even if the plugin doesn't have its own editor, the AU API can be used
2082         // to create one that looks native.
2083         return true;
2084 }
2085
2086 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2087         : descriptor (d)
2088 {
2089         type = ARDOUR::AudioUnit;
2090 }
2091
2092 AUPluginInfo::~AUPluginInfo ()
2093 {
2094         type = ARDOUR::AudioUnit;
2095 }
2096
2097 PluginPtr
2098 AUPluginInfo::load (Session& session)
2099 {
2100         try {
2101                 PluginPtr plugin;
2102
2103                 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2104                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2105
2106                 if (!comp->IsValid()) {
2107                         error << ("AudioUnit: not a valid Component") << endmsg;
2108                 } else {
2109                         plugin.reset (new AUPlugin (session.engine(), session, comp));
2110                 }
2111
2112                 AUPluginInfo *aup = new AUPluginInfo (*this);
2113                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2114                 plugin->set_info (PluginInfoPtr (aup));
2115                 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2116                 return plugin;
2117         }
2118
2119         catch (failed_constructor &err) {
2120                 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2121                 return PluginPtr ();
2122         }
2123 }
2124
2125 Glib::ustring
2126 AUPluginInfo::au_cache_path ()
2127 {
2128         return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2129 }
2130
2131 PluginInfoList*
2132 AUPluginInfo::discover ()
2133 {
2134         XMLTree tree;
2135
2136         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2137                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2138         }
2139
2140         PluginInfoList* plugs = new PluginInfoList;
2141
2142         discover_fx (*plugs);
2143         discover_music (*plugs);
2144         discover_generators (*plugs);
2145         discover_instruments (*plugs);
2146
2147         DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2148
2149         return plugs;
2150 }
2151
2152 void
2153 AUPluginInfo::discover_music (PluginInfoList& plugs)
2154 {
2155         CAComponentDescription desc;
2156         desc.componentFlags = 0;
2157         desc.componentFlagsMask = 0;
2158         desc.componentSubType = 0;
2159         desc.componentManufacturer = 0;
2160         desc.componentType = kAudioUnitType_MusicEffect;
2161
2162         discover_by_description (plugs, desc);
2163 }
2164
2165 void
2166 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2167 {
2168         CAComponentDescription desc;
2169         desc.componentFlags = 0;
2170         desc.componentFlagsMask = 0;
2171         desc.componentSubType = 0;
2172         desc.componentManufacturer = 0;
2173         desc.componentType = kAudioUnitType_Effect;
2174
2175         discover_by_description (plugs, desc);
2176 }
2177
2178 void
2179 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2180 {
2181         CAComponentDescription desc;
2182         desc.componentFlags = 0;
2183         desc.componentFlagsMask = 0;
2184         desc.componentSubType = 0;
2185         desc.componentManufacturer = 0;
2186         desc.componentType = kAudioUnitType_Generator;
2187
2188         discover_by_description (plugs, desc);
2189 }
2190
2191 void
2192 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2193 {
2194         CAComponentDescription desc;
2195         desc.componentFlags = 0;
2196         desc.componentFlagsMask = 0;
2197         desc.componentSubType = 0;
2198         desc.componentManufacturer = 0;
2199         desc.componentType = kAudioUnitType_MusicDevice;
2200
2201         discover_by_description (plugs, desc);
2202 }
2203
2204 void
2205 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2206 {
2207         Component comp = 0;
2208
2209         comp = FindNextComponent (NULL, &desc);
2210
2211         while (comp != NULL) {
2212                 CAComponentDescription temp;
2213                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2214
2215                 AUPluginInfoPtr info (new AUPluginInfo
2216                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2217
2218                 /* although apple designed the subtype field to be a "category" indicator,
2219                    its really turned into a plugin ID field for a given manufacturer. Hence
2220                    there are no categories for AudioUnits. However, to keep the plugins
2221                    showing up under "categories", we'll use the "type" as a high level
2222                    selector.
2223
2224                    NOTE: no panners, format converters or i/o AU's for our purposes
2225                  */
2226
2227                 switch (info->descriptor->Type()) {
2228                 case kAudioUnitType_Panner:
2229                 case kAudioUnitType_OfflineEffect:
2230                 case kAudioUnitType_FormatConverter:
2231                         continue;
2232
2233                 case kAudioUnitType_Output:
2234                         info->category = _("AudioUnit Outputs");
2235                         break;
2236                 case kAudioUnitType_MusicDevice:
2237                         info->category = _("AudioUnit Instruments");
2238                         break;
2239                 case kAudioUnitType_MusicEffect:
2240                         info->category = _("AudioUnit MusicEffects");
2241                         break;
2242                 case kAudioUnitType_Effect:
2243                         info->category = _("AudioUnit Effects");
2244                         break;
2245                 case kAudioUnitType_Mixer:
2246                         info->category = _("AudioUnit Mixers");
2247                         break;
2248                 case kAudioUnitType_Generator:
2249                         info->category = _("AudioUnit Generators");
2250                         break;
2251                 default:
2252                         info->category = _("AudioUnit (Unknown)");
2253                         break;
2254                 }
2255
2256                 AUPluginInfo::get_names (temp, info->name, info->creator);
2257
2258                 info->type = ARDOUR::AudioUnit;
2259                 info->unique_id = stringify_descriptor (*info->descriptor);
2260
2261                 /* XXX not sure of the best way to handle plugin versioning yet
2262                  */
2263
2264                 CAComponent cacomp (*info->descriptor);
2265
2266                 if (cacomp.GetResourceVersion (info->version) != noErr) {
2267                         info->version = 0;
2268                 }
2269
2270                 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2271
2272                         /* here we have to map apple's wildcard system to a simple pair
2273                            of values. in ::can_do() we use the whole system, but here
2274                            we need a single pair of values. XXX probably means we should
2275                            remove any use of these values.
2276                         */
2277
2278                         info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
2279                         info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
2280
2281                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2282                                                                         info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2283
2284                         plugs.push_back (info);
2285
2286                 } else {
2287                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2288                 }
2289
2290                 comp = FindNextComponent (comp, &desc);
2291         }
2292 }
2293
2294 bool
2295 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2296                                        UInt32 version,
2297                                        CAComponent& comp,
2298                                        AUPluginCachedInfo& cinfo,
2299                                        const std::string& name)
2300 {
2301         std::string id;
2302         char buf[32];
2303
2304         /* concatenate unique ID with version to provide a key for cached info lookup.
2305            this ensures we don't get stale information, or should if plugin developers
2306            follow Apple "guidelines".
2307          */
2308
2309         snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2310         id = unique_id;
2311         id += '/';
2312         id += buf;
2313
2314         CachedInfoMap::iterator cim = cached_info.find (id);
2315
2316         if (cim != cached_info.end()) {
2317                 cinfo = cim->second;
2318                 return true;
2319         }
2320
2321         CAAudioUnit unit;
2322         AUChannelInfo* channel_info;
2323         UInt32 cnt;
2324         int ret;
2325
2326         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2327
2328         try {
2329
2330                 if (CAAudioUnit::Open (comp, unit) != noErr) {
2331                         return false;
2332                 }
2333
2334         } catch (...) {
2335
2336                 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2337                 return false;
2338
2339         }
2340
2341         DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2342         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2343                 return false;
2344         }
2345
2346         if (ret > 0) {
2347
2348                 /* no explicit info available, so default to 1in/1out */
2349
2350                 cinfo.io_configs.push_back (pair<int,int> (1, 1));
2351
2352         } else {
2353
2354                 /* store each configuration */
2355
2356                 for (uint32_t n = 0; n < cnt; ++n) {
2357                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2358                                                                    channel_info[n].outChannels));
2359                 }
2360
2361                 free (channel_info);
2362         }
2363
2364         add_cached_info (id, cinfo);
2365         save_cached_info ();
2366
2367         return true;
2368 }
2369
2370 void
2371 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2372 {
2373         cached_info[id] = cinfo;
2374 }
2375
2376 #define AU_CACHE_VERSION "2.0"
2377
2378 void
2379 AUPluginInfo::save_cached_info ()
2380 {
2381         XMLNode* node;
2382
2383         node = new XMLNode (X_("AudioUnitPluginCache"));
2384         node->add_property( "version", AU_CACHE_VERSION );
2385
2386         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2387                 XMLNode* parent = new XMLNode (X_("plugin"));
2388                 parent->add_property ("id", i->first);
2389                 node->add_child_nocopy (*parent);
2390
2391                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2392
2393                         XMLNode* child = new XMLNode (X_("io"));
2394                         char buf[32];
2395
2396                         snprintf (buf, sizeof (buf), "%d", j->first);
2397                         child->add_property (X_("in"), buf);
2398                         snprintf (buf, sizeof (buf), "%d", j->second);
2399                         child->add_property (X_("out"), buf);
2400                         parent->add_child_nocopy (*child);
2401                 }
2402
2403         }
2404
2405         Glib::ustring path = au_cache_path ();
2406         XMLTree tree;
2407
2408         tree.set_root (node);
2409
2410         if (!tree.write (path)) {
2411                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2412                 unlink (path.c_str());
2413         }
2414 }
2415
2416 int
2417 AUPluginInfo::load_cached_info ()
2418 {
2419         Glib::ustring path = au_cache_path ();
2420         XMLTree tree;
2421
2422         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2423                 return 0;
2424         }
2425
2426         if ( !tree.read (path) ) {
2427                 error << "au_cache is not a valid XML file.  AU plugins will be re-scanned" << endmsg;
2428                 return -1;
2429         }
2430
2431         const XMLNode* root (tree.root());
2432
2433         if (root->name() != X_("AudioUnitPluginCache")) {
2434                 return -1;
2435         }
2436
2437         //initial version has incorrectly stored i/o info, and/or garbage chars.
2438         const XMLProperty* version = root->property(X_("version"));
2439         if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2440                 error << "au_cache is not correct version.  AU plugins will be re-scanned" << endmsg;
2441                 return -1;
2442         }
2443
2444         cached_info.clear ();
2445
2446         const XMLNodeList children = root->children();
2447
2448         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2449
2450                 const XMLNode* child = *iter;
2451
2452                 if (child->name() == X_("plugin")) {
2453
2454                         const XMLNode* gchild;
2455                         const XMLNodeList gchildren = child->children();
2456                         const XMLProperty* prop = child->property (X_("id"));
2457
2458                         if (!prop) {
2459                                 continue;
2460                         }
2461
2462                         string id = prop->value();
2463                         string fixed;
2464                         string version;
2465
2466                         string::size_type slash = id.find_last_of ('/');
2467
2468                         if (slash == string::npos) {
2469                                 continue;
2470                         }
2471
2472                         version = id.substr (slash);
2473                         id = id.substr (0, slash);
2474                         fixed = AUPlugin::maybe_fix_broken_au_id (id);
2475
2476                         if (fixed.empty()) {
2477                                 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2478                                 continue;
2479                         }
2480
2481                         id = fixed;
2482                         id += version;
2483
2484                         AUPluginCachedInfo cinfo;
2485
2486                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2487
2488                                 gchild = *giter;
2489
2490                                 if (gchild->name() == X_("io")) {
2491
2492                                         int in;
2493                                         int out;
2494                                         const XMLProperty* iprop;
2495                                         const XMLProperty* oprop;
2496
2497                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
2498                                             ((oprop = gchild->property (X_("out"))) != 0)) {
2499                                                 in = atoi (iprop->value());
2500                                                 out = atoi (oprop->value());
2501
2502                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
2503                                         }
2504                                 }
2505                         }
2506
2507                         if (cinfo.io_configs.size()) {
2508                                 add_cached_info (id, cinfo);
2509                         }
2510                 }
2511         }
2512
2513         return 0;
2514 }
2515
2516 void
2517 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2518 {
2519         CFStringRef itemName = NULL;
2520
2521         // Marc Poirier-style item name
2522         CAComponent auComponent (comp_desc);
2523         if (auComponent.IsValid()) {
2524                 CAComponentDescription dummydesc;
2525                 Handle nameHandle = NewHandle(sizeof(void*));
2526                 if (nameHandle != NULL) {
2527                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2528                         if (err == noErr) {
2529                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2530                                 if (nameString != NULL) {
2531                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2532                                 }
2533                         }
2534                         DisposeHandle(nameHandle);
2535                 }
2536         }
2537
2538         // if Marc-style fails, do the original way
2539         if (itemName == NULL) {
2540                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2541                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2542                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2543
2544                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2545                         compTypeString, compManufacturerString, compSubTypeString);
2546
2547                 if (compTypeString != NULL)
2548                         CFRelease(compTypeString);
2549                 if (compSubTypeString != NULL)
2550                         CFRelease(compSubTypeString);
2551                 if (compManufacturerString != NULL)
2552                         CFRelease(compManufacturerString);
2553         }
2554
2555         string str = CFStringRefToStdString(itemName);
2556         string::size_type colon = str.find (':');
2557
2558         if (colon) {
2559                 name = str.substr (colon+1);
2560                 maker = str.substr (0, colon);
2561                 strip_whitespace_edges (maker);
2562                 strip_whitespace_edges (name);
2563         } else {
2564                 name = str;
2565                 maker = "unknown";
2566                 strip_whitespace_edges (name);
2567         }
2568 }
2569
2570 std::string
2571 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2572 {
2573         stringstream s;
2574
2575         /* note: OSType is a compiler-implemenation-defined value,
2576            historically a 32 bit integer created with a multi-character
2577            constant such as 'abcd'. It is, fundamentally, an abomination.
2578         */
2579
2580         s << desc.Type();
2581         s << '-';
2582         s << desc.SubType();
2583         s << '-';
2584         s << desc.Manu();
2585
2586         return s.str();
2587 }
2588
2589 bool
2590 AUPluginInfo::needs_midi_input ()
2591 {
2592         return is_effect_with_midi_input () || is_instrument ();
2593 }
2594
2595 bool
2596 AUPluginInfo::is_effect () const
2597 {
2598         return is_effect_without_midi_input() || is_effect_with_midi_input();
2599 }
2600
2601 bool
2602 AUPluginInfo::is_effect_without_midi_input () const
2603 {
2604         return descriptor->IsAUFX();
2605 }
2606
2607 bool
2608 AUPluginInfo::is_effect_with_midi_input () const
2609 {
2610         return descriptor->IsAUFM();
2611 }
2612
2613 bool
2614 AUPluginInfo::is_instrument () const
2615 {
2616         return descriptor->IsMusicDevice();
2617 }
2618
2619 void
2620 AUPlugin::set_info (PluginInfoPtr info)
2621 {
2622         Plugin::set_info (info);
2623
2624         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2625
2626         _has_midi_input = pinfo->needs_midi_input ();
2627         _has_midi_output = false;
2628 }