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