merge 2.0-ongoing into 3.0 @ 3581 - 3710
[ardour.git] / libs / ardour / audio_unit.cc
1 /*
2     Copyright (C) 2006 Paul Davis 
3         
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <sstream>
21
22 #include <pbd/transmitter.h>
23 #include <pbd/xml++.h>
24 #include <pbd/whitespace.h>
25
26 #include <glibmm/thread.h>
27 #include <glibmm/fileutils.h>
28 #include <glibmm/miscutils.h>
29
30 #include <ardour/ardour.h>
31 #include <ardour/audioengine.h>
32 #include <ardour/io.h>
33 #include <ardour/audio_unit.h>
34 #include <ardour/session.h>
35 #include <ardour/utils.h>
36
37 #include <appleutility/CAAudioUnit.h>
38 #include <appleutility/CAAUParameter.h>
39
40 #include <CoreServices/CoreServices.h>
41 #include <AudioUnit/AudioUnit.h>
42
43 #include "i18n.h"
44
45 using namespace std;
46 using namespace PBD;
47 using namespace ARDOUR;
48
49 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
50
51 static OSStatus 
52 _render_callback(void *userData,
53                  AudioUnitRenderActionFlags *ioActionFlags,
54                  const AudioTimeStamp    *inTimeStamp,
55                  UInt32       inBusNumber,
56                  UInt32       inNumberFrames,
57                  AudioBufferList*       ioData)
58 {
59         return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
60 }
61
62 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
63         : Plugin (engine, session),
64           comp (_comp),
65           unit (new CAAudioUnit),
66           initialized (false),
67           buffers (0),
68           current_maxbuf (0),
69           current_offset (0),
70           current_buffers (0),
71         frames_processed (0)
72 {                       
73         init ();
74 }
75
76 AUPlugin::AUPlugin (const AUPlugin& other)
77         : Plugin (other)
78         , comp (other.get_comp())
79         , unit (new CAAudioUnit)
80         , initialized (false)
81         , buffers (0)
82         , current_maxbuf (0)
83         , current_offset (0)
84         , current_buffers (0)
85         , frames_processed (0)
86           
87 {
88         init ();
89 }
90
91 AUPlugin::~AUPlugin ()
92 {
93         if (unit) {
94                 unit->Uninitialize ();
95         }
96
97         if (buffers) {
98                 free (buffers);
99         }
100 }
101
102
103 void
104 AUPlugin::init ()
105 {
106         OSErr err = CAAudioUnit::Open (*(comp.get()), *unit);
107
108         if (err != noErr) {
109                 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
110                 throw failed_constructor ();
111         }
112         
113         AURenderCallbackStruct renderCallbackInfo;
114
115         renderCallbackInfo.inputProc = _render_callback;
116         renderCallbackInfo.inputProcRefCon = this;
117
118         if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 
119                                          0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
120                 cerr << "cannot install render callback (err = " << err << ')' << endl;
121                 throw failed_constructor();
122         }
123
124         unit->GetElementCount (kAudioUnitScope_Global, global_elements);
125         unit->GetElementCount (kAudioUnitScope_Input, input_elements);
126         unit->GetElementCount (kAudioUnitScope_Output, output_elements);
127
128         /* these keep track of *configured* channel set up,
129            not potential set ups.
130         */
131
132         input_channels = -1;
133         output_channels = -1;
134
135         if (_set_block_size (_session.get_block_size())) {
136                 error << _("AUPlugin: cannot set processing block size") << endmsg;
137                 throw failed_constructor();
138         }
139
140         discover_parameters ();
141
142         Plugin::setup_controls ();
143 }
144
145 void
146 AUPlugin::discover_parameters ()
147 {
148         /* discover writable parameters */
149         
150         AudioUnitScope scopes[] = { 
151                 kAudioUnitScope_Global,
152                 kAudioUnitScope_Output,
153                 kAudioUnitScope_Input
154         };
155
156         descriptors.clear ();
157
158         for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
159
160                 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
161                 
162                 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
163
164                         AUParameterDescriptor d;
165
166                         d.id = param_info.ParamID (i);
167
168                         const CAAUParameter* param = param_info.GetParamInfo (d.id);
169                         const AudioUnitParameterInfo& info (param->ParamInfo());
170
171                         const int len = CFStringGetLength (param->GetName());;
172                         char local_buffer[len*2];
173                         Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
174                         if (!good) {
175                                 d.label = "???";
176                         } else {
177                                 d.label = local_buffer;
178                         }
179
180                         d.scope = param_info.GetScope ();
181                         d.element = param_info.GetElement ();
182
183                         /* info.units to consider */
184                         /*
185                           kAudioUnitParameterUnit_Generic             = 0
186                           kAudioUnitParameterUnit_Indexed             = 1
187                           kAudioUnitParameterUnit_Boolean             = 2
188                           kAudioUnitParameterUnit_Percent             = 3
189                           kAudioUnitParameterUnit_Seconds             = 4
190                           kAudioUnitParameterUnit_SampleFrames        = 5
191                           kAudioUnitParameterUnit_Phase               = 6
192                           kAudioUnitParameterUnit_Rate                = 7
193                           kAudioUnitParameterUnit_Hertz               = 8
194                           kAudioUnitParameterUnit_Cents               = 9
195                           kAudioUnitParameterUnit_RelativeSemiTones   = 10
196                           kAudioUnitParameterUnit_MIDINoteNumber      = 11
197                           kAudioUnitParameterUnit_MIDIController      = 12
198                           kAudioUnitParameterUnit_Decibels            = 13
199                           kAudioUnitParameterUnit_LinearGain          = 14
200                           kAudioUnitParameterUnit_Degrees             = 15
201                           kAudioUnitParameterUnit_EqualPowerCrossfade = 16
202                           kAudioUnitParameterUnit_MixerFaderCurve1    = 17
203                           kAudioUnitParameterUnit_Pan                 = 18
204                           kAudioUnitParameterUnit_Meters              = 19
205                           kAudioUnitParameterUnit_AbsoluteCents       = 20
206                           kAudioUnitParameterUnit_Octaves             = 21
207                           kAudioUnitParameterUnit_BPM                 = 22
208                           kAudioUnitParameterUnit_Beats               = 23
209                           kAudioUnitParameterUnit_Milliseconds        = 24
210                           kAudioUnitParameterUnit_Ratio               = 25
211                         */
212
213                         /* info.flags to consider */
214
215                         /*
216
217                           kAudioUnitParameterFlag_CFNameRelease       = (1L << 4)
218                           kAudioUnitParameterFlag_HasClump            = (1L << 20)
219                           kAudioUnitParameterFlag_HasName             = (1L << 21)
220                           kAudioUnitParameterFlag_DisplayLogarithmic  = (1L << 22)
221                           kAudioUnitParameterFlag_IsHighResolution    = (1L << 23)
222                           kAudioUnitParameterFlag_NonRealTime         = (1L << 24)
223                           kAudioUnitParameterFlag_CanRamp             = (1L << 25)
224                           kAudioUnitParameterFlag_ExpertMode          = (1L << 26)
225                           kAudioUnitParameterFlag_HasCFNameString     = (1L << 27)
226                           kAudioUnitParameterFlag_IsGlobalMeta        = (1L << 28)
227                           kAudioUnitParameterFlag_IsElementMeta       = (1L << 29)
228                           kAudioUnitParameterFlag_IsReadable          = (1L << 30)
229                           kAudioUnitParameterFlag_IsWritable          = (1L << 31)
230                         */
231
232                         d.lower = info.minValue;
233                         d.upper = info.maxValue;
234                         d.default_value = info.defaultValue;
235
236                         d.integer_step = (info.unit & kAudioUnitParameterUnit_Indexed);
237                         d.toggled = (info.unit & kAudioUnitParameterUnit_Boolean) ||
238                                 (d.integer_step && ((d.upper - d.lower) == 1.0));
239                         d.sr_dependent = (info.unit & kAudioUnitParameterUnit_SampleFrames);
240                         d.automatable = !d.toggled && 
241                                 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
242                                 (info.flags & kAudioUnitParameterFlag_IsWritable);
243                         
244                         d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
245                         d.unit = info.unit;
246
247                         d.step = 1.0;
248                         d.smallstep = 0.1;
249                         d.largestep = 10.0;
250                         d.min_unbound = 0; // lower is bound
251                         d.max_unbound = 0; // upper is bound
252
253                         descriptors.push_back (d);
254                 }
255         }
256 }
257
258
259 string
260 AUPlugin::unique_id () const
261 {
262         return AUPluginInfo::stringify_descriptor (comp->Desc());
263 }
264
265 const char *
266 AUPlugin::label () const
267 {
268         return _info->name.c_str();
269 }
270
271 uint32_t
272 AUPlugin::parameter_count () const
273 {
274         return descriptors.size();
275 }
276
277 float
278 AUPlugin::default_value (uint32_t port)
279 {
280         if (port < descriptors.size()) {
281                 return descriptors[port].default_value;
282         }
283
284         return 0;
285 }
286
287 nframes_t
288 AUPlugin::signal_latency () const
289 {
290         if (_user_latency) {
291                 return _user_latency;
292         }
293
294         return unit->Latency() * _session.frame_rate();
295 }
296
297 void
298 AUPlugin::set_parameter (uint32_t which, float val)
299 {
300         if (which < descriptors.size()) {
301                 const AUParameterDescriptor& d (descriptors[which]);
302                 unit->SetParameter (d.id, d.scope, d.element, val);
303         }
304 }
305
306 float
307 AUPlugin::get_parameter (uint32_t which) const
308 {
309         float val = 0.0;
310         if (which < descriptors.size()) {
311                 const AUParameterDescriptor& d (descriptors[which]);
312                 unit->GetParameter(d.id, d.scope, d.element, val);
313         }
314         return val;
315 }
316
317 int
318 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
319 {
320         if (which < descriptors.size()) {
321                 pd = descriptors[which];
322                 return 0;
323         } 
324         return -1;
325 }
326
327 uint32_t
328 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
329 {
330         if (which < descriptors.size()) {
331                 ok = true;
332                 return which;
333         }
334         ok = false;
335         return 0;
336 }
337
338 void
339 AUPlugin::activate ()
340 {
341         if (!initialized) {
342                 OSErr err;
343                 if ((err = unit->Initialize()) != noErr) {
344                         error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
345                 } else {
346                         frames_processed = 0;
347                         initialized = true;
348                 }
349         }
350 }
351
352 void
353 AUPlugin::deactivate ()
354 {
355         unit->GlobalReset ();
356 }
357
358 void
359 AUPlugin::set_block_size (nframes_t nframes)
360 {
361         _set_block_size (nframes);
362 }
363
364 int
365 AUPlugin::_set_block_size (nframes_t nframes)
366 {
367         bool was_initialized = initialized;
368         UInt32 numFrames = nframes;
369         OSErr err;
370
371         if (initialized) {
372                 unit->Uninitialize ();
373         }
374
375         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 
376                                       0, &numFrames, sizeof (numFrames))) != noErr) {
377                 cerr << "cannot set max frames (err = " << err << ')' << endl;
378                 return -1;
379         }
380
381         if (was_initialized) {
382                 activate ();
383         }
384
385         return 0;
386 }
387
388 int32_t
389 AUPlugin::configure_io (ChanCount in, ChanCount out)
390 {
391         AudioStreamBasicDescription streamFormat;
392
393         streamFormat.mSampleRate = _session.frame_rate();
394         streamFormat.mFormatID = kAudioFormatLinearPCM;
395         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
396
397 #ifdef __LITTLE_ENDIAN__
398         /* relax */
399 #else
400         streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
401 #endif
402
403         streamFormat.mBitsPerChannel = 32;
404         streamFormat.mFramesPerPacket = 1;
405
406         /* apple says that for non-interleaved data, these
407            values always refer to a single channel.
408         */
409         streamFormat.mBytesPerPacket = 4;
410         streamFormat.mBytesPerFrame = 4;
411
412         streamFormat.mChannelsPerFrame = in.n_audio();
413
414         if (set_input_format (streamFormat) != 0) {
415                 return -1;
416         }
417
418         streamFormat.mChannelsPerFrame = out.n_audio();
419
420         if (set_output_format (streamFormat) != 0) {
421                 return -1;
422         }
423
424         return Plugin::configure_io (in, out);
425 }
426
427 bool
428 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
429 {
430         int32_t ret = count_for_configuration (in, out);
431         return ret >= 0;
432 }
433
434 int32_t
435 AUPlugin::count_for_configuration(ChanCount cin, ChanCount& out) const
436 {
437         // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
438         // attempt to multiply-instantiate plugins to meet io configurations.
439
440         int32_t plugcnt = -1;
441         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
442         int32_t in = cin.n_audio(); /* XXX handle MIDI one day ??? */
443
444         vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
445
446         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
447
448                 int32_t possible_in = i->first;
449                 int32_t possible_out = i->second;
450
451                 if (possible_out == 0) {
452                         warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
453                         continue;
454                 }
455
456                 if (possible_in == 0) {
457
458                         /* instrument plugin, always legal but throws away inputs ...
459                         */
460
461                         if (possible_out == -1) {
462                                 /* out much match in (UNLIKELY!!) */
463                                 out.set (DataType::AUDIO, in);
464                                 plugcnt = 1;
465                         } else if (possible_out == -2) {
466                                 /* any configuration possible, pick matching */
467                                 out.set (DataType::AUDIO, in);
468                                 plugcnt = 1;
469                         } else if (possible_out < -2) {
470                                 /* explicit variable number of outputs, pick maximum */
471                                 out.set (DataType::AUDIO, -possible_out);
472                                 plugcnt = 1;
473                         } else {
474                                 /* exact number of outputs */
475                                 out.set (DataType::AUDIO, possible_out);
476                                 plugcnt = 1;
477                         }
478                 }
479                 
480                 if (possible_in == -1) {
481
482                         /* wildcard for input */
483
484                         if (possible_out == -1) {
485                                 /* out much match in */
486                                 out.set (DataType::AUDIO, in);
487                                 plugcnt = 1;
488                         } else if (possible_out == -2) {
489                                 /* any configuration possible, pick matching */
490                                 out.set (DataType::AUDIO, in);
491                                 plugcnt = 1;
492                         } else if (possible_out < -2) {
493                                 /* explicit variable number of outputs, pick maximum */
494                                 out.set (DataType::AUDIO, -possible_out);
495                                 plugcnt = 1;
496                         } else {
497                                 /* exact number of outputs */
498                                 out.set (DataType::AUDIO, possible_out);
499                                 plugcnt = 1;
500                         }
501                 }       
502                         
503                 if (possible_in == -2) {
504
505                         if (possible_out == -1) {
506                                 /* any configuration possible, pick matching */
507                                 out.set (DataType::AUDIO, in);
508                                 plugcnt = 1;
509                         } else if (possible_out == -2) {
510                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
511                                       << endmsg;
512                                 plugcnt = -1;
513                         } else if (possible_out < -2) {
514                                 /* explicit variable number of outputs, pick maximum */
515                                 out.set (DataType::AUDIO, -possible_out);
516                                 plugcnt = 1;
517                         } else {
518                                 /* exact number of outputs */
519                                 out.set (DataType::AUDIO, possible_out);
520                                 plugcnt = 1;
521                         }
522                 }
523
524                 if (possible_in < -2) {
525
526                         /* explicit variable number of inputs */
527
528                         if (in > -possible_in) {
529                                 /* request is too large */
530                                 plugcnt = -1;
531                         }
532
533                         if (possible_out == -1) {
534                                 /* out must match in */
535                                 out.set (DataType::AUDIO, in);
536                                 plugcnt = 1;
537                         } else if (possible_out == -2) {
538                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
539                                       << endmsg;
540                                 plugcnt = -1;
541                         } else if (possible_out < -2) {
542                                 /* explicit variable number of outputs, pick maximum */
543                                 out.set (DataType::AUDIO, -possible_out);
544                                 plugcnt = 1;
545                         } else {
546                                 /* exact number of outputs */
547                                 out.set (DataType::AUDIO, possible_out);
548                                 plugcnt = 1;
549                         }
550                 }
551
552                 if (possible_in == in) {
553
554                         /* exact number of inputs ... must match obviously */
555                         
556                         if (possible_out == -1) {
557                                 /* out must match in */
558                                 out.set (DataType::AUDIO, in);
559                                 plugcnt = 1;
560                         } else if (possible_out == -2) {
561                                 /* any output configuration, pick matching */
562                                 out.set (DataType::AUDIO, in);
563                                 plugcnt = -1;
564                         } else if (possible_out < -2) {
565                                 /* explicit variable number of outputs, pick maximum */
566                                 out.set (DataType::AUDIO, -possible_out);
567                                 plugcnt = 1;
568                         } else {
569                                 /* exact number of outputs */
570                                 out.set (DataType::AUDIO, possible_out);
571                                 plugcnt = 1;
572                         }
573                 }
574
575         }
576
577         /* no fit */
578         return plugcnt;
579 }
580
581 int
582 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
583 {
584         return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
585 }
586
587 int
588 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
589 {
590         if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
591                 return -1;
592         }
593
594         if (buffers) {
595                 free (buffers);
596                 buffers = 0;
597         }
598         
599         buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) + 
600                                               fmt.mChannelsPerFrame * sizeof(AudioBuffer));
601
602         Glib::Mutex::Lock em (_session.engine().process_lock());
603         IO::PortCountChanged (ChanCount (DataType::AUDIO, fmt.mChannelsPerFrame));
604
605         return 0;
606 }
607
608 int
609 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
610 {
611         OSErr result;
612
613         for (uint32_t i = 0; i < cnt; ++i) {
614                 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
615                         error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
616                                                  (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
617                         return -1;
618                 }
619         }
620
621         if (scope == kAudioUnitScope_Input) {
622                 input_channels = fmt.mChannelsPerFrame;
623         } else {
624                 output_channels = fmt.mChannelsPerFrame;
625         }
626
627         return 0;
628 }
629
630
631 ChanCount
632 AUPlugin::input_streams() const
633 {
634         ChanCount in;
635
636         if (input_channels < 0) {
637                 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
638                 in.set_audio (1);
639         } else {
640                 in.set_audio (input_channels);
641         }
642
643         return in;
644 }
645
646
647 ChanCount
648 AUPlugin::output_streams() const
649 {
650         ChanCount out;
651
652         if (output_channels < 0) {
653                 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
654                 out.set_audio (1);
655         } else {
656                 out.set_audio (output_channels);
657         }
658
659         return out;
660 }
661
662 OSStatus 
663 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
664                           const AudioTimeStamp    *inTimeStamp,
665                           UInt32       inBusNumber,
666                           UInt32       inNumberFrames,
667                           AudioBufferList*       ioData)
668 {
669         /* not much to do - the data is already in the buffers given to us in connect_and_run() */
670
671         if (current_maxbuf == 0) {
672                 error << _("AUPlugin: render callback called illegally!") << endmsg;
673                 return kAudioUnitErr_CannotDoInCurrentContext;
674         }
675
676         for (uint32_t i = 0; i < current_maxbuf; ++i) {
677                 ioData->mBuffers[i].mNumberChannels = 1;
678                 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
679                 ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
680         }
681
682         cb_offset += inNumberFrames;
683
684         return noErr;
685 }
686
687 int
688 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
689 {
690         AudioUnitRenderActionFlags flags = 0;
691         AudioTimeStamp ts;
692
693         current_buffers = &bufs;
694         current_maxbuf = maxbuf;
695         current_offset = offset;
696         cb_offset = 0;
697
698         buffers->mNumberBuffers = maxbuf;
699
700         for (uint32_t i = 0; i < maxbuf; ++i) {
701                 buffers->mBuffers[i].mNumberChannels = 1;
702                 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
703                 buffers->mBuffers[i].mData = 0;
704         }
705
706         ts.mSampleTime = frames_processed;
707         ts.mFlags = kAudioTimeStampSampleTimeValid;
708
709         if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
710
711                 current_maxbuf = 0;
712                 frames_processed += nframes;
713                 
714                 for (uint32_t i = 0; i < maxbuf; ++i) {
715                         if (bufs[i] + offset != buffers->mBuffers[i].mData) {
716                                 memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
717                         }
718                 }
719                 return 0;
720         }
721
722         return -1;
723 }
724
725 set<uint32_t>
726 AUPlugin::automatable() const
727 {
728         set<uint32_t> automates;
729
730         for (uint32_t i = 0; i < descriptors.size(); ++i) {
731                 if (descriptors[i].automatable) {
732                         automates.insert (i);
733                 }
734         }
735
736         return automates;
737 }
738
739 string
740 AUPlugin::describe_parameter (uint32_t param)
741 {
742         return descriptors[param].label;
743 }
744
745 void
746 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
747 {
748         // NameValue stuff here
749 }
750
751 bool
752 AUPlugin::parameter_is_audio (uint32_t) const
753 {
754         return false;
755 }
756
757 bool
758 AUPlugin::parameter_is_control (uint32_t) const
759 {
760         return true;
761 }
762
763 bool
764 AUPlugin::parameter_is_input (uint32_t) const
765 {
766         return false;
767 }
768
769 bool
770 AUPlugin::parameter_is_output (uint32_t) const
771 {
772         return false;
773 }
774
775 XMLNode&
776 AUPlugin::get_state()
777 {
778         XMLNode *root = new XMLNode (state_node_name());
779         LocaleGuard lg (X_("POSIX"));
780         return *root;
781 }
782
783 int
784 AUPlugin::set_state(const XMLNode& node)
785 {
786         return -1;
787 }
788
789 bool
790 AUPlugin::save_preset (string name)
791 {
792         return false;
793 }
794
795 bool
796 AUPlugin::load_preset (const string preset_label)
797 {
798         return false;
799 }
800
801 vector<string>
802 AUPlugin::get_presets ()
803 {
804         vector<string> presets;
805         
806         return presets;
807 }
808
809 bool
810 AUPlugin::has_editor () const
811 {
812         // even if the plugin doesn't have its own editor, the AU API can be used
813         // to create one that looks native.
814         return true;
815 }
816
817 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
818         : descriptor (d)
819 {
820
821 }
822
823 AUPluginInfo::~AUPluginInfo ()
824 {
825 }
826
827 PluginPtr
828 AUPluginInfo::load (Session& session)
829 {
830         try {
831                 PluginPtr plugin;
832
833                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
834                 
835                 if (!comp->IsValid()) {
836                         error << ("AudioUnit: not a valid Component") << endmsg;
837                 } else {
838                         plugin.reset (new AUPlugin (session.engine(), session, comp));
839                 }
840                 
841                 plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
842                 return plugin;
843         }
844
845         catch (failed_constructor &err) {
846                 return PluginPtr ();
847         }
848 }
849
850 Glib::ustring
851 AUPluginInfo::au_cache_path ()
852 {
853         return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
854 }
855
856 PluginInfoList
857 AUPluginInfo::discover ()
858 {
859         XMLTree tree;
860
861         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
862                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
863         }
864
865         PluginInfoList plugs;
866         
867         discover_fx (plugs);
868         discover_music (plugs);
869
870         return plugs;
871 }
872
873 void
874 AUPluginInfo::discover_music (PluginInfoList& plugs)
875 {
876         CAComponentDescription desc;
877         desc.componentFlags = 0;
878         desc.componentFlagsMask = 0;
879         desc.componentSubType = 0;
880         desc.componentManufacturer = 0;
881         desc.componentType = kAudioUnitType_MusicEffect;
882
883         discover_by_description (plugs, desc);
884 }
885
886 void
887 AUPluginInfo::discover_fx (PluginInfoList& plugs)
888 {
889         CAComponentDescription desc;
890         desc.componentFlags = 0;
891         desc.componentFlagsMask = 0;
892         desc.componentSubType = 0;
893         desc.componentManufacturer = 0;
894         desc.componentType = kAudioUnitType_Effect;
895
896         discover_by_description (plugs, desc);
897 }
898
899 void
900 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
901 {
902         Component comp = 0;
903
904         comp = FindNextComponent (NULL, &desc);
905
906         while (comp != NULL) {
907                 CAComponentDescription temp;
908                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
909
910                 AUPluginInfoPtr info (new AUPluginInfo 
911                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
912
913                 /* no panners, format converters or i/o AU's for our purposes
914                  */
915
916                 switch (info->descriptor->Type()) {
917                 case kAudioUnitType_Panner:
918                 case kAudioUnitType_OfflineEffect:
919                 case kAudioUnitType_FormatConverter:
920                         continue;
921                 default:
922                         break;
923                 }
924
925                 switch (info->descriptor->SubType()) {
926                 case kAudioUnitSubType_DefaultOutput:
927                 case kAudioUnitSubType_SystemOutput:
928                 case kAudioUnitSubType_GenericOutput:
929                 case kAudioUnitSubType_AUConverter:
930                         continue;
931                         break;
932
933                 case kAudioUnitSubType_DLSSynth:
934                         info->category = "DLSSynth";
935                         break;
936
937                 case kAudioUnitType_MusicEffect:
938                         info->category = "MusicEffect";
939                         break;
940
941                 case kAudioUnitSubType_Varispeed:
942                         info->category = "Varispeed";
943                         break;
944
945                 case kAudioUnitSubType_Delay:
946                         info->category = "Delay";
947                         break;
948
949                 case kAudioUnitSubType_LowPassFilter:
950                         info->category = "LowPassFilter";
951                         break;
952
953                 case kAudioUnitSubType_HighPassFilter:
954                         info->category = "HighPassFilter";
955                         break;
956
957                 case kAudioUnitSubType_BandPassFilter:
958                         info->category = "BandPassFilter";
959                         break;
960
961                 case kAudioUnitSubType_HighShelfFilter:
962                         info->category = "HighShelfFilter";
963                         break;
964
965                 case kAudioUnitSubType_LowShelfFilter:
966                         info->category = "LowShelfFilter";
967                         break;
968
969                 case kAudioUnitSubType_ParametricEQ:
970                         info->category = "ParametricEQ";
971                         break;
972
973                 case kAudioUnitSubType_GraphicEQ:
974                         info->category = "GraphicEQ";
975                         break;
976
977                 case kAudioUnitSubType_PeakLimiter:
978                         info->category = "PeakLimiter";
979                         break;
980
981                 case kAudioUnitSubType_DynamicsProcessor:
982                         info->category = "DynamicsProcessor";
983                         break;
984
985                 case kAudioUnitSubType_MultiBandCompressor:
986                         info->category = "MultiBandCompressor";
987                         break;
988
989                 case kAudioUnitSubType_MatrixReverb:
990                         info->category = "MatrixReverb";
991                         break;
992
993                 case kAudioUnitType_Mixer:
994                         info->category = "Mixer";
995                         break;
996
997                 case kAudioUnitSubType_StereoMixer:
998                         info->category = "StereoMixer";
999                         break;
1000
1001                 case kAudioUnitSubType_3DMixer:
1002                         info->category = "3DMixer";
1003                         break;
1004
1005                 case kAudioUnitSubType_MatrixMixer:
1006                         info->category = "MatrixMixer";
1007                         break;
1008
1009                 default:
1010                         info->category = "";
1011                 }
1012
1013                 AUPluginInfo::get_names (temp, info->name, info->creator);
1014
1015                 info->type = ARDOUR::AudioUnit;
1016                 info->unique_id = stringify_descriptor (*info->descriptor);
1017
1018                 /* XXX not sure of the best way to handle plugin versioning yet
1019                  */
1020
1021                 CAComponent cacomp (*info->descriptor);
1022
1023                 if (cacomp.GetResourceVersion (info->version) != noErr) {
1024                         info->version = 0;
1025                 }
1026                 
1027                 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
1028
1029                         /* here we have to map apple's wildcard system to a simple pair
1030                            of values.
1031                         */
1032
1033                         info->n_inputs = ChanCount (DataType::AUDIO, info->cache.io_configs.front().first);
1034                         info->n_outputs = ChanCount (DataType::AUDIO, info->cache.io_configs.front().second);
1035
1036                         if (info->cache.io_configs.size() > 1) {
1037                                 cerr << "ODD: variable IO config for " << info->unique_id << endl;
1038                         }
1039
1040                         plugs.push_back (info);
1041
1042                 } else {
1043                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
1044                 }
1045                 
1046                 comp = FindNextComponent (comp, &desc);
1047         }
1048 }
1049
1050 bool
1051 AUPluginInfo::cached_io_configuration (const std::string& unique_id, 
1052                                        UInt32 version,
1053                                        CAComponent& comp, 
1054                                        AUPluginCachedInfo& cinfo, 
1055                                        const std::string& name)
1056 {
1057         std::string id;
1058         char buf[32];
1059
1060         /* concatenate unique ID with version to provide a key for cached info lookup.
1061            this ensures we don't get stale information, or should if plugin developers
1062            follow Apple "guidelines".
1063          */
1064
1065         snprintf (buf, sizeof (buf), "%u", version);
1066         id = unique_id;
1067         id += '/';
1068         id += buf;
1069
1070         CachedInfoMap::iterator cim = cached_info.find (id);
1071
1072         if (cim != cached_info.end()) {
1073                 cinfo = cim->second;
1074                 return true;
1075         }
1076
1077         CAAudioUnit unit;
1078         AUChannelInfo* channel_info;
1079         UInt32 cnt;
1080         int ret;
1081         
1082         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
1083         
1084         try {
1085
1086                 if (CAAudioUnit::Open (comp, unit) != noErr) {
1087                         return false;
1088                 }
1089
1090         } catch (...) {
1091
1092                 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
1093                 return false;
1094
1095         }
1096                 
1097         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
1098                 return false;
1099         }
1100
1101         if (ret > 0) {
1102                 /* no explicit info available */
1103
1104                 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
1105
1106         } else {
1107                 
1108                 /* store each configuration */
1109                 
1110                 for (uint32_t n = 0; n < cnt; ++n) {
1111                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
1112                                                                    channel_info[n].outChannels));
1113                 }
1114
1115                 free (channel_info);
1116         }
1117
1118         add_cached_info (id, cinfo);
1119         save_cached_info ();
1120
1121         return true;
1122 }
1123
1124 void
1125 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
1126 {
1127         cached_info[id] = cinfo;
1128 }
1129
1130 void
1131 AUPluginInfo::save_cached_info ()
1132 {
1133         XMLNode* node;
1134
1135         node = new XMLNode (X_("AudioUnitPluginCache"));
1136         
1137         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
1138                 XMLNode* parent = new XMLNode (X_("plugin"));
1139                 parent->add_property ("id", i->first);
1140                 node->add_child_nocopy (*parent);
1141
1142                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
1143
1144                         XMLNode* child = new XMLNode (X_("io"));
1145                         char buf[32];
1146
1147                         snprintf (buf, sizeof (buf), "%d", j->first);
1148                         child->add_property (X_("in"), buf);
1149                         snprintf (buf, sizeof (buf), "%d", j->second);
1150                         child->add_property (X_("out"), buf);
1151                         parent->add_child_nocopy (*child);
1152                 }
1153
1154         }
1155
1156         Glib::ustring path = au_cache_path ();
1157         XMLTree tree;
1158
1159         tree.set_root (node);
1160
1161         if (!tree.write (path)) {
1162                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
1163                 unlink (path.c_str());
1164         }
1165 }
1166
1167 int
1168 AUPluginInfo::load_cached_info ()
1169 {
1170         Glib::ustring path = au_cache_path ();
1171         XMLTree tree;
1172         
1173         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1174                 return 0;
1175         }
1176
1177         tree.read (path);
1178         const XMLNode* root (tree.root());
1179
1180         if (root->name() != X_("AudioUnitPluginCache")) {
1181                 return -1;
1182         }
1183
1184         cached_info.clear ();
1185
1186         const XMLNodeList children = root->children();
1187
1188         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
1189                 
1190                 const XMLNode* child = *iter;
1191                 
1192                 if (child->name() == X_("plugin")) {
1193
1194                         const XMLNode* gchild;
1195                         const XMLNodeList gchildren = child->children();
1196                         const XMLProperty* prop = child->property (X_("id"));
1197
1198                         if (!prop) {
1199                                 continue;
1200                         }
1201
1202                         std::string id = prop->value();
1203                         
1204                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
1205
1206                                 gchild = *giter;
1207
1208                                 if (gchild->name() == X_("io")) {
1209
1210                                         int in;
1211                                         int out;
1212                                         const XMLProperty* iprop;
1213                                         const XMLProperty* oprop;
1214
1215                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
1216                                             ((oprop = gchild->property (X_("out"))) != 0)) {
1217                                                 in = atoi (iprop->value());
1218                                                 out = atoi (iprop->value());
1219                                                 
1220                                                 AUPluginCachedInfo cinfo;
1221                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
1222                                                 add_cached_info (id, cinfo);
1223                                         }
1224                                 }
1225                         }
1226                 }
1227         }
1228
1229         return 0;
1230 }
1231
1232 void
1233 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
1234 {
1235         CFStringRef itemName = NULL;
1236
1237         // Marc Poirier-style item name
1238         CAComponent auComponent (comp_desc);
1239         if (auComponent.IsValid()) {
1240                 CAComponentDescription dummydesc;
1241                 Handle nameHandle = NewHandle(sizeof(void*));
1242                 if (nameHandle != NULL) {
1243                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
1244                         if (err == noErr) {
1245                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
1246                                 if (nameString != NULL) {
1247                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
1248                                 }
1249                         }
1250                         DisposeHandle(nameHandle);
1251                 }
1252         }
1253     
1254         // if Marc-style fails, do the original way
1255         if (itemName == NULL) {
1256                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
1257                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
1258                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
1259     
1260                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"), 
1261                         compTypeString, compManufacturerString, compSubTypeString);
1262     
1263                 if (compTypeString != NULL)
1264                         CFRelease(compTypeString);
1265                 if (compSubTypeString != NULL)
1266                         CFRelease(compSubTypeString);
1267                 if (compManufacturerString != NULL)
1268                         CFRelease(compManufacturerString);
1269         }
1270         
1271         string str = CFStringRefToStdString(itemName);
1272         string::size_type colon = str.find (':');
1273
1274         if (colon) {
1275                 name = str.substr (colon+1);
1276                 maker = str.substr (0, colon);
1277                 // strip_whitespace_edges (maker);
1278                 // strip_whitespace_edges (name);
1279         } else {
1280                 name = str;
1281                 maker = "unknown";
1282         }
1283 }
1284
1285 // from CAComponentDescription.cpp (in libs/appleutility in ardour source)
1286 extern char *StringForOSType (OSType t, char *writeLocation);
1287
1288 std::string
1289 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
1290 {
1291         char str[24];
1292         stringstream s;
1293
1294         s << StringForOSType (desc.Type(), str);
1295         s << " - ";
1296                 
1297         s << StringForOSType (desc.SubType(), str);
1298         s << " - ";
1299                 
1300         s << StringForOSType (desc.Manu(), str);
1301
1302         return s.str();
1303 }