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