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