lots and lots of work to correctly deduce AU IO configurations and related issues
[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::latency () const
289 {
290         return unit->Latency() * _session.frame_rate();
291 }
292
293 void
294 AUPlugin::set_parameter (uint32_t which, float val)
295 {
296         if (which < descriptors.size()) {
297                 const AUParameterDescriptor& d (descriptors[which]);
298                 unit->SetParameter (d.id, d.scope, d.element, val);
299         }
300 }
301
302 float
303 AUPlugin::get_parameter (uint32_t which) const
304 {
305         float val = 0.0;
306         if (which < descriptors.size()) {
307                 const AUParameterDescriptor& d (descriptors[which]);
308                 unit->GetParameter(d.id, d.scope, d.element, val);
309         }
310         return val;
311 }
312
313 int
314 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
315 {
316         if (which < descriptors.size()) {
317                 pd = descriptors[which];
318                 return 0;
319         } 
320         return -1;
321 }
322
323 uint32_t
324 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
325 {
326         if (which < descriptors.size()) {
327                 ok = true;
328                 return which;
329         }
330         ok = false;
331         return 0;
332 }
333
334 void
335 AUPlugin::activate ()
336 {
337         if (!initialized) {
338                 OSErr err;
339                 if ((err = unit->Initialize()) != noErr) {
340                         error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
341                 } else {
342                         frames_processed = 0;
343                         initialized = true;
344                 }
345         }
346 }
347
348 void
349 AUPlugin::deactivate ()
350 {
351         unit->GlobalReset ();
352 }
353
354 void
355 AUPlugin::set_block_size (nframes_t nframes)
356 {
357         _set_block_size (nframes);
358 }
359
360 int
361 AUPlugin::_set_block_size (nframes_t nframes)
362 {
363         bool was_initialized = initialized;
364         UInt32 numFrames = nframes;
365         OSErr err;
366
367         if (initialized) {
368                 unit->Uninitialize ();
369         }
370
371         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 
372                                       0, &numFrames, sizeof (numFrames))) != noErr) {
373                 cerr << "cannot set max frames (err = " << err << ')' << endl;
374                 return -1;
375         }
376
377         if (was_initialized) {
378                 activate ();
379         }
380
381         return 0;
382 }
383
384 int32_t
385 AUPlugin::configure_io (int32_t in, int32_t out)
386 {
387         AudioStreamBasicDescription streamFormat;
388
389         streamFormat.mSampleRate = _session.frame_rate();
390         streamFormat.mFormatID = kAudioFormatLinearPCM;
391         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
392
393 #ifdef __LITTLE_ENDIAN__
394         /* relax */
395 #else
396         streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
397 #endif
398
399         streamFormat.mBitsPerChannel = 32;
400         streamFormat.mFramesPerPacket = 1;
401
402         /* apple says that for non-interleaved data, these
403            values always refer to a single channel.
404         */
405         streamFormat.mBytesPerPacket = 4;
406         streamFormat.mBytesPerFrame = 4;
407
408         streamFormat.mChannelsPerFrame = in;
409
410         if (set_input_format (streamFormat) != 0) {
411                 return -1;
412         }
413
414         streamFormat.mChannelsPerFrame = out;
415
416         if (set_output_format (streamFormat) != 0) {
417                 return -1;
418         }
419
420         return Plugin::configure_io (in, out);
421 }
422
423 int32_t
424 AUPlugin::can_do (int32_t in, int32_t& out)
425 {
426         // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
427         // attempt to multiply-instantiate plugins to meet io configurations.
428
429         int32_t plugcnt = -1;
430         AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
431
432         out = -1;
433
434         vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
435
436         for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
437
438                 int32_t possible_in = i->first;
439                 int32_t possible_out = i->second;
440
441                 if (possible_out == 0) {
442                         warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
443                         continue;
444                 }
445
446                 if (possible_in == 0) {
447
448                         /* instrument plugin, always legal but throws away inputs ...
449                         */
450
451                         if (possible_out == -1) {
452                                 /* out much match in (UNLIKELY!!) */
453                                 out = in;
454                                 plugcnt = 1;
455                         } else if (possible_out == -2) {
456                                 /* any configuration possible, pick matching */
457                                 out = in;
458                                 plugcnt = 1;
459                         } else if (possible_out < -2) {
460                                 /* explicit variable number of outputs, pick maximum */
461                                 out = -possible_out;
462                                 plugcnt = 1;
463                         } else {
464                                 /* exact number of outputs */
465                                 out = possible_out;
466                                 plugcnt = 1;
467                         }
468                 }
469                 
470                 if (possible_in == -1) {
471
472                         /* wildcard for input */
473
474                         if (possible_out == -1) {
475                                 /* out much match in */
476                                 out = in;
477                                 plugcnt = 1;
478                         } else if (possible_out == -2) {
479                                 /* any configuration possible, pick matching */
480                                 out = in;
481                                 plugcnt = 1;
482                         } else if (possible_out < -2) {
483                                 /* explicit variable number of outputs, pick maximum */
484                                 out = -possible_out;
485                                 plugcnt = 1;
486                         } else {
487                                 /* exact number of outputs */
488                                 out = possible_out;
489                                 plugcnt = 1;
490                         }
491                 }       
492                         
493                 if (possible_in == -2) {
494
495                         if (possible_out == -1) {
496                                 /* any configuration possible, pick matching */
497                                 out = in;
498                                 plugcnt = 1;
499                         } else if (possible_out == -2) {
500                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
501                                       << endmsg;
502                                 plugcnt = -1;
503                         } else if (possible_out < -2) {
504                                 /* explicit variable number of outputs, pick maximum */
505                                 out = -possible_out;
506                                 plugcnt = 1;
507                         } else {
508                                 /* exact number of outputs */
509                                 out = possible_out;
510                                 plugcnt = 1;
511                         }
512                 }
513
514                 if (possible_in < -2) {
515
516                         /* explicit variable number of inputs */
517
518                         if (in > -possible_in) {
519                                 /* request is too large */
520                                 plugcnt = -1;
521                         }
522
523                         if (possible_out == -1) {
524                                 /* out must match in */
525                                 out = in;
526                                 plugcnt = 1;
527                         } else if (possible_out == -2) {
528                                 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
529                                       << endmsg;
530                                 plugcnt = -1;
531                         } else if (possible_out < -2) {
532                                 /* explicit variable number of outputs, pick maximum */
533                                 out = -possible_out;
534                                 plugcnt = 1;
535                         } else {
536                                 /* exact number of outputs */
537                                 out = possible_out;
538                                 plugcnt = 1;
539                         }
540                 }
541
542                 if (possible_in == in) {
543
544                         /* exact number of inputs ... must match obviously */
545                         
546                         if (possible_out == -1) {
547                                 /* out must match in */
548                                 out = in;
549                                 plugcnt = 1;
550                         } else if (possible_out == -2) {
551                                 /* any output configuration, pick matching */
552                                 out = in;
553                                 plugcnt = -1;
554                         } else if (possible_out < -2) {
555                                 /* explicit variable number of outputs, pick maximum */
556                                 out = -possible_out;
557                                 plugcnt = 1;
558                         } else {
559                                 /* exact number of outputs */
560                                 out = possible_out;
561                                 plugcnt = 1;
562                         }
563                 }
564
565         }
566
567         /* no fit */
568         return plugcnt;
569 }
570
571 int
572 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
573 {
574         return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
575 }
576
577 int
578 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
579 {
580         if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
581                 return -1;
582         }
583
584         if (buffers) {
585                 free (buffers);
586                 buffers = 0;
587         }
588         
589         buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) + 
590                                               fmt.mChannelsPerFrame * sizeof(AudioBuffer));
591
592         Glib::Mutex::Lock em (_session.engine().process_lock());
593         IO::MoreOutputs (fmt.mChannelsPerFrame);
594
595         return 0;
596 }
597
598 int
599 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
600 {
601         OSErr result;
602
603         for (uint32_t i = 0; i < cnt; ++i) {
604                 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
605                         error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
606                                                  (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
607                         return -1;
608                 }
609         }
610
611         if (scope == kAudioUnitScope_Input) {
612                 input_channels = fmt.mChannelsPerFrame;
613         } else {
614                 output_channels = fmt.mChannelsPerFrame;
615         }
616
617         return 0;
618 }
619
620 uint32_t
621 AUPlugin::input_streams() const
622 {
623         if (input_channels < 0) {
624                 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
625                 return 1;
626         }
627         return input_channels;
628 }
629
630
631 uint32_t
632 AUPlugin::output_streams() const
633 {
634         if (output_channels < 0) {
635                 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
636                 return 1;
637         }
638         return output_channels;
639 }
640
641 OSStatus 
642 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
643                           const AudioTimeStamp    *inTimeStamp,
644                           UInt32       inBusNumber,
645                           UInt32       inNumberFrames,
646                           AudioBufferList*       ioData)
647 {
648         /* not much to do - the data is already in the buffers given to us in connect_and_run() */
649
650         if (current_maxbuf == 0) {
651                 error << _("AUPlugin: render callback called illegally!") << endmsg;
652                 return kAudioUnitErr_CannotDoInCurrentContext;
653         }
654
655         for (uint32_t i = 0; i < current_maxbuf; ++i) {
656                 ioData->mBuffers[i].mNumberChannels = 1;
657                 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
658                 ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
659         }
660
661         cb_offset += inNumberFrames;
662
663         return noErr;
664 }
665
666 int
667 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
668 {
669         AudioUnitRenderActionFlags flags = 0;
670         AudioTimeStamp ts;
671
672         current_buffers = &bufs;
673         current_maxbuf = maxbuf;
674         current_offset = offset;
675         cb_offset = 0;
676
677         buffers->mNumberBuffers = maxbuf;
678
679         for (uint32_t i = 0; i < maxbuf; ++i) {
680                 buffers->mBuffers[i].mNumberChannels = 1;
681                 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
682                 buffers->mBuffers[i].mData = 0;
683         }
684
685         ts.mSampleTime = frames_processed;
686         ts.mFlags = kAudioTimeStampSampleTimeValid;
687
688         if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
689
690                 current_maxbuf = 0;
691                 frames_processed += nframes;
692                 
693                 for (uint32_t i = 0; i < maxbuf; ++i) {
694                         if (bufs[i] + offset != buffers->mBuffers[i].mData) {
695                                 memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
696                         }
697                 }
698                 return 0;
699         }
700
701         return -1;
702 }
703
704 set<uint32_t>
705 AUPlugin::automatable() const
706 {
707         set<uint32_t> automates;
708
709         for (uint32_t i = 0; i < descriptors.size(); ++i) {
710                 if (descriptors[i].automatable) {
711                         automates.insert (i);
712                 }
713         }
714
715         return automates;
716 }
717
718 string
719 AUPlugin::describe_parameter (uint32_t param)
720 {
721         return descriptors[param].label;
722 }
723
724 void
725 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
726 {
727         // NameValue stuff here
728 }
729
730 bool
731 AUPlugin::parameter_is_audio (uint32_t) const
732 {
733         return false;
734 }
735
736 bool
737 AUPlugin::parameter_is_control (uint32_t) const
738 {
739         return true;
740 }
741
742 bool
743 AUPlugin::parameter_is_input (uint32_t) const
744 {
745         return false;
746 }
747
748 bool
749 AUPlugin::parameter_is_output (uint32_t) const
750 {
751         return false;
752 }
753
754 XMLNode&
755 AUPlugin::get_state()
756 {
757         XMLNode *root = new XMLNode (state_node_name());
758         LocaleGuard lg (X_("POSIX"));
759         return *root;
760 }
761
762 int
763 AUPlugin::set_state(const XMLNode& node)
764 {
765         return -1;
766 }
767
768 bool
769 AUPlugin::save_preset (string name)
770 {
771         return false;
772 }
773
774 bool
775 AUPlugin::load_preset (const string preset_label)
776 {
777         return false;
778 }
779
780 vector<string>
781 AUPlugin::get_presets ()
782 {
783         vector<string> presets;
784         
785         return presets;
786 }
787
788 bool
789 AUPlugin::has_editor () const
790 {
791         // even if the plugin doesn't have its own editor, the AU API can be used
792         // to create one that looks native.
793         return true;
794 }
795
796 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
797         : descriptor (d)
798 {
799
800 }
801
802 AUPluginInfo::~AUPluginInfo ()
803 {
804 }
805
806 PluginPtr
807 AUPluginInfo::load (Session& session)
808 {
809         try {
810                 PluginPtr plugin;
811
812                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
813                 
814                 if (!comp->IsValid()) {
815                         error << ("AudioUnit: not a valid Component") << endmsg;
816                 } else {
817                         plugin.reset (new AUPlugin (session.engine(), session, comp));
818                 }
819                 
820                 plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
821                 return plugin;
822         }
823
824         catch (failed_constructor &err) {
825                 return PluginPtr ();
826         }
827 }
828
829 Glib::ustring
830 AUPluginInfo::au_cache_path ()
831 {
832         return Glib::build_filename (ARDOUR::get_user_ardour_path(), "au_cache");
833 }
834
835 PluginInfoList
836 AUPluginInfo::discover ()
837 {
838         XMLTree tree;
839
840         if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
841                 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
842         }
843
844         PluginInfoList plugs;
845         
846         discover_fx (plugs);
847         discover_music (plugs);
848
849         return plugs;
850 }
851
852 void
853 AUPluginInfo::discover_music (PluginInfoList& plugs)
854 {
855         CAComponentDescription desc;
856         desc.componentFlags = 0;
857         desc.componentFlagsMask = 0;
858         desc.componentSubType = 0;
859         desc.componentManufacturer = 0;
860         desc.componentType = kAudioUnitType_MusicEffect;
861
862         discover_by_description (plugs, desc);
863 }
864
865 void
866 AUPluginInfo::discover_fx (PluginInfoList& plugs)
867 {
868         CAComponentDescription desc;
869         desc.componentFlags = 0;
870         desc.componentFlagsMask = 0;
871         desc.componentSubType = 0;
872         desc.componentManufacturer = 0;
873         desc.componentType = kAudioUnitType_Effect;
874
875         discover_by_description (plugs, desc);
876 }
877
878 void
879 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
880 {
881         Component comp = 0;
882
883         comp = FindNextComponent (NULL, &desc);
884
885         while (comp != NULL) {
886                 CAComponentDescription temp;
887                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
888
889                 AUPluginInfoPtr info (new AUPluginInfo 
890                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
891
892                 /* no panners, format converters or i/o AU's for our purposes
893                  */
894
895                 switch (info->descriptor->Type()) {
896                 case kAudioUnitType_Panner:
897                 case kAudioUnitType_OfflineEffect:
898                 case kAudioUnitType_FormatConverter:
899                         continue;
900                 default:
901                         break;
902                 }
903
904                 switch (info->descriptor->SubType()) {
905                 case kAudioUnitSubType_DefaultOutput:
906                 case kAudioUnitSubType_SystemOutput:
907                 case kAudioUnitSubType_GenericOutput:
908                 case kAudioUnitSubType_AUConverter:
909                         continue;
910                         break;
911
912                 case kAudioUnitSubType_DLSSynth:
913                         info->category = "DLSSynth";
914                         break;
915
916                 case kAudioUnitType_MusicEffect:
917                         info->category = "MusicEffect";
918                         break;
919
920                 case kAudioUnitSubType_Varispeed:
921                         info->category = "Varispeed";
922                         break;
923
924                 case kAudioUnitSubType_Delay:
925                         info->category = "Delay";
926                         break;
927
928                 case kAudioUnitSubType_LowPassFilter:
929                         info->category = "LowPassFilter";
930                         break;
931
932                 case kAudioUnitSubType_HighPassFilter:
933                         info->category = "HighPassFilter";
934                         break;
935
936                 case kAudioUnitSubType_BandPassFilter:
937                         info->category = "BandPassFilter";
938                         break;
939
940                 case kAudioUnitSubType_HighShelfFilter:
941                         info->category = "HighShelfFilter";
942                         break;
943
944                 case kAudioUnitSubType_LowShelfFilter:
945                         info->category = "LowShelfFilter";
946                         break;
947
948                 case kAudioUnitSubType_ParametricEQ:
949                         info->category = "ParametricEQ";
950                         break;
951
952                 case kAudioUnitSubType_GraphicEQ:
953                         info->category = "GraphicEQ";
954                         break;
955
956                 case kAudioUnitSubType_PeakLimiter:
957                         info->category = "PeakLimiter";
958                         break;
959
960                 case kAudioUnitSubType_DynamicsProcessor:
961                         info->category = "DynamicsProcessor";
962                         break;
963
964                 case kAudioUnitSubType_MultiBandCompressor:
965                         info->category = "MultiBandCompressor";
966                         break;
967
968                 case kAudioUnitSubType_MatrixReverb:
969                         info->category = "MatrixReverb";
970                         break;
971
972                 case kAudioUnitType_Mixer:
973                         info->category = "Mixer";
974                         break;
975
976                 case kAudioUnitSubType_StereoMixer:
977                         info->category = "StereoMixer";
978                         break;
979
980                 case kAudioUnitSubType_3DMixer:
981                         info->category = "3DMixer";
982                         break;
983
984                 case kAudioUnitSubType_MatrixMixer:
985                         info->category = "MatrixMixer";
986                         break;
987
988                 default:
989                         info->category = "";
990                 }
991
992                 AUPluginInfo::get_names (temp, info->name, info->creator);
993
994                 info->type = ARDOUR::AudioUnit;
995                 info->unique_id = stringify_descriptor (*info->descriptor);
996
997                 /* XXX not sure of the best way to handle plugin versioning yet
998                  */
999
1000                 CAComponent cacomp (*info->descriptor);
1001
1002                 if (cacomp.GetResourceVersion (info->version) != noErr) {
1003                         info->version = 0;
1004                 }
1005                 
1006                 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
1007
1008                         /* here we have to map apple's wildcard system to a simple pair
1009                            of values.
1010                         */
1011
1012                         info->n_inputs = info->cache.io_configs.front().first;
1013                         info->n_outputs = info->cache.io_configs.front().second;
1014
1015                         if (info->cache.io_configs.size() > 1) {
1016                                 cerr << "ODD: variable IO config for " << info->unique_id << endl;
1017                         }
1018
1019                         plugs.push_back (info);
1020
1021                 } else {
1022                         error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
1023                 }
1024                 
1025                 comp = FindNextComponent (comp, &desc);
1026         }
1027 }
1028
1029 bool
1030 AUPluginInfo::cached_io_configuration (const std::string& unique_id, 
1031                                        UInt32 version,
1032                                        CAComponent& comp, 
1033                                        AUPluginCachedInfo& cinfo, 
1034                                        const std::string& name)
1035 {
1036         std::string id;
1037         char buf[32];
1038
1039         /* concatenate unique ID with version to provide a key for cached info lookup.
1040            this ensures we don't get stale information, or should if plugin developers
1041            follow Apple "guidelines".
1042          */
1043
1044         snprintf (buf, sizeof (buf), "%u", version);
1045         id = unique_id;
1046         id += '/';
1047         id += buf;
1048
1049         CachedInfoMap::iterator cim = cached_info.find (id);
1050
1051         if (cim != cached_info.end()) {
1052                 cinfo = cim->second;
1053                 return true;
1054         }
1055
1056         CAAudioUnit unit;
1057         AUChannelInfo* channel_info;
1058         UInt32 cnt;
1059         int ret;
1060         
1061         ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
1062         
1063         if (CAAudioUnit::Open (comp, unit) != noErr) {
1064                 return false;
1065         }
1066
1067         if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
1068                 return false;
1069         }
1070
1071         if (ret > 0) {
1072                 /* no explicit info available */
1073
1074                 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
1075
1076         } else {
1077                 
1078                 /* store each configuration */
1079                 
1080                 for (uint32_t n = 0; n < cnt; ++n) {
1081                         cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
1082                                                                    channel_info[n].outChannels));
1083                 }
1084
1085                 free (channel_info);
1086         }
1087
1088         add_cached_info (id, cinfo);
1089         save_cached_info ();
1090
1091         return true;
1092 }
1093
1094 void
1095 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
1096 {
1097         cached_info[id] = cinfo;
1098 }
1099
1100 void
1101 AUPluginInfo::save_cached_info ()
1102 {
1103         XMLNode* node;
1104
1105         node = new XMLNode (X_("AudioUnitPluginCache"));
1106         
1107         for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
1108                 XMLNode* parent = new XMLNode (X_("plugin"));
1109                 parent->add_property ("id", i->first);
1110                 node->add_child_nocopy (*parent);
1111
1112                 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
1113
1114                         XMLNode* child = new XMLNode (X_("io"));
1115                         char buf[32];
1116
1117                         snprintf (buf, sizeof (buf), "%d", j->first);
1118                         child->add_property (X_("in"), buf);
1119                         snprintf (buf, sizeof (buf), "%d", j->second);
1120                         child->add_property (X_("out"), buf);
1121                         parent->add_child_nocopy (*child);
1122                 }
1123
1124         }
1125
1126         Glib::ustring path = au_cache_path ();
1127         XMLTree tree;
1128
1129         tree.set_root (node);
1130
1131         if (!tree.write (path)) {
1132                 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
1133                 unlink (path.c_str());
1134         }
1135 }
1136
1137 int
1138 AUPluginInfo::load_cached_info ()
1139 {
1140         Glib::ustring path = au_cache_path ();
1141         XMLTree tree;
1142         
1143         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1144                 return 0;
1145         }
1146
1147         tree.read (path);
1148         const XMLNode* root (tree.root());
1149
1150         if (root->name() != X_("AudioUnitPluginCache")) {
1151                 return -1;
1152         }
1153
1154         cached_info.clear ();
1155
1156         const XMLNodeList children = root->children();
1157
1158         for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
1159                 
1160                 const XMLNode* child = *iter;
1161                 
1162                 if (child->name() == X_("plugin")) {
1163
1164                         const XMLNode* gchild;
1165                         const XMLNodeList gchildren = child->children();
1166                         const XMLProperty* prop = child->property (X_("id"));
1167
1168                         if (!prop) {
1169                                 continue;
1170                         }
1171
1172                         std::string id = prop->value();
1173                         
1174                         for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
1175
1176                                 gchild = *giter;
1177
1178                                 if (gchild->name() == X_("io")) {
1179
1180                                         int in;
1181                                         int out;
1182                                         const XMLProperty* iprop;
1183                                         const XMLProperty* oprop;
1184
1185                                         if (((iprop = gchild->property (X_("in"))) != 0) &&
1186                                             ((oprop = gchild->property (X_("out"))) != 0)) {
1187                                                 in = atoi (iprop->value());
1188                                                 out = atoi (iprop->value());
1189                                                 
1190                                                 AUPluginCachedInfo cinfo;
1191                                                 cinfo.io_configs.push_back (pair<int,int> (in, out));
1192                                                 add_cached_info (id, cinfo);
1193                                         }
1194                                 }
1195                         }
1196                 }
1197         }
1198
1199         return 0;
1200 }
1201
1202 void
1203 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
1204 {
1205         CFStringRef itemName = NULL;
1206
1207         // Marc Poirier-style item name
1208         CAComponent auComponent (comp_desc);
1209         if (auComponent.IsValid()) {
1210                 CAComponentDescription dummydesc;
1211                 Handle nameHandle = NewHandle(sizeof(void*));
1212                 if (nameHandle != NULL) {
1213                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
1214                         if (err == noErr) {
1215                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
1216                                 if (nameString != NULL) {
1217                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
1218                                 }
1219                         }
1220                         DisposeHandle(nameHandle);
1221                 }
1222         }
1223     
1224         // if Marc-style fails, do the original way
1225         if (itemName == NULL) {
1226                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
1227                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
1228                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
1229     
1230                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"), 
1231                         compTypeString, compManufacturerString, compSubTypeString);
1232     
1233                 if (compTypeString != NULL)
1234                         CFRelease(compTypeString);
1235                 if (compSubTypeString != NULL)
1236                         CFRelease(compSubTypeString);
1237                 if (compManufacturerString != NULL)
1238                         CFRelease(compManufacturerString);
1239         }
1240         
1241         string str = CFStringRefToStdString(itemName);
1242         string::size_type colon = str.find (':');
1243
1244         if (colon) {
1245                 name = str.substr (colon+1);
1246                 maker = str.substr (0, colon);
1247                 // strip_whitespace_edges (maker);
1248                 // strip_whitespace_edges (name);
1249         } else {
1250                 name = str;
1251                 maker = "unknown";
1252         }
1253 }
1254
1255 // from CAComponentDescription.cpp (in libs/appleutility in ardour source)
1256 extern char *StringForOSType (OSType t, char *writeLocation);
1257
1258 std::string
1259 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
1260 {
1261         char str[24];
1262         stringstream s;
1263
1264         s << StringForOSType (desc.Type(), str);
1265         s << " - ";
1266                 
1267         s << StringForOSType (desc.SubType(), str);
1268         s << " - ";
1269                 
1270         s << StringForOSType (desc.Manu(), str);
1271
1272         return s.str();
1273 }