LV2 support.
[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
28 #include <ardour/audioengine.h>
29 #include <ardour/io.h>
30 #include <ardour/audio_unit.h>
31 #include <ardour/session.h>
32 #include <ardour/utils.h>
33
34 #include <appleutility/CAAudioUnit.h>
35
36 #include <CoreServices/CoreServices.h>
37 #include <AudioUnit/AudioUnit.h>
38
39 #include "i18n.h"
40
41 using namespace std;
42 using namespace PBD;
43 using namespace ARDOUR;
44
45 static OSStatus 
46 _render_callback(void *userData,
47                  AudioUnitRenderActionFlags *ioActionFlags,
48                  const AudioTimeStamp    *inTimeStamp,
49                  UInt32       inBusNumber,
50                  UInt32       inNumberFrames,
51                  AudioBufferList*       ioData)
52 {
53         return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
54 }
55
56 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
57         :
58         Plugin (engine, session),
59         comp (_comp),
60         unit (new CAAudioUnit),
61         initialized (false),
62         buffers (0),
63         current_maxbuf (0),
64         current_offset (0),
65         current_buffers (0),
66         frames_processed (0)
67 {                       
68         OSErr err = CAAudioUnit::Open (*(comp.get()), *unit);
69
70         if (err != noErr) {
71                 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
72                 throw failed_constructor ();
73         }
74         
75         AURenderCallbackStruct renderCallbackInfo;
76
77         renderCallbackInfo.inputProc = _render_callback;
78         renderCallbackInfo.inputProcRefCon = this;
79
80         if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 
81                                          0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
82                 cerr << "cannot install render callback (err = " << err << ')' << endl;
83                 throw failed_constructor();
84         }
85
86         unit->GetElementCount (kAudioUnitScope_Input, input_elements);
87         unit->GetElementCount (kAudioUnitScope_Output, output_elements);
88
89         // set up the basic stream format. these fields do not change
90                             
91         streamFormat.mSampleRate = session.frame_rate();
92         streamFormat.mFormatID = kAudioFormatLinearPCM;
93         streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
94         streamFormat.mBitsPerChannel = 32;
95         streamFormat.mFramesPerPacket = 1;
96
97         // subject to later modification as we discover channel counts
98
99         streamFormat.mBytesPerPacket = 4;
100         streamFormat.mBytesPerFrame = 4;
101         streamFormat.mChannelsPerFrame = 1;
102
103         format_set = 0;
104
105         if (_set_block_size (_session.get_block_size())) {
106                 error << _("AUPlugin: cannot set processing block size") << endmsg;
107                 throw failed_constructor();
108         }
109 }
110
111 AUPlugin::~AUPlugin ()
112 {
113         if (unit) {
114                 unit->Uninitialize ();
115         }
116
117         if (buffers) {
118                 free (buffers);
119         }
120 }
121
122 string
123 AUPlugin::unique_id () const
124 {
125         return AUPluginInfo::stringify_descriptor (comp->Desc());
126 }
127
128 const char *
129 AUPlugin::label () const
130 {
131         return _info->name.c_str();
132 }
133
134 uint32_t
135 AUPlugin::parameter_count () const
136 {
137         return 0;
138 }
139
140 float
141 AUPlugin::default_value (uint32_t port)
142 {
143         // AudioUnits don't have default values.  Maybe presets though?
144         return 0;
145 }
146
147 nframes_t
148 AUPlugin::latency () const
149 {
150         return unit->Latency ();
151 }
152
153 void
154 AUPlugin::set_parameter (uint32_t which, float val)
155 {
156         // unit->SetParameter (parameter_map[which].first, parameter_map[which].second, 0, val);
157 }
158
159 float
160 AUPlugin::get_parameter (uint32_t which) const
161 {
162         float outValue = 0.0;
163         
164         // unit->GetParameter(parameter_map[which].first, parameter_map[which].second, 0, outValue);
165         
166         return outValue;
167 }
168
169 int
170 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor&) const
171 {
172         return 0;
173 }
174
175 uint32_t
176 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
177 {
178         return 0;
179 }
180
181 void
182 AUPlugin::activate ()
183 {
184         if (!initialized) {
185                 OSErr err;
186                 if ((err = unit->Initialize()) != noErr) {
187                         error << string_compose (_("AUPlugin: cannot initialize plugin (err = %1)"), err) << endmsg;
188                 } else {
189                         frames_processed = 0;
190                         initialized = true;
191                 }
192         }
193 }
194
195 void
196 AUPlugin::deactivate ()
197 {
198         unit->GlobalReset ();
199 }
200
201 void
202 AUPlugin::set_block_size (nframes_t nframes)
203 {
204         _set_block_size (nframes);
205 }
206
207 int
208 AUPlugin::_set_block_size (nframes_t nframes)
209 {
210         bool was_initialized = initialized;
211         UInt32 numFrames = nframes;
212         OSErr err;
213
214         if (initialized) {
215                 unit->Uninitialize ();
216         }
217
218         if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 
219                                       0, &numFrames, sizeof (numFrames))) != noErr) {
220                 cerr << "cannot set max frames (err = " << err << ')' << endl;
221                 return -1;
222         }
223
224         if (was_initialized) {
225                 activate ();
226         }
227
228         return 0;
229 }
230
231 int32_t 
232 AUPlugin::can_support_input_configuration (int32_t in)
233 {       
234         streamFormat.mChannelsPerFrame = in;
235         /* apple says that for non-interleaved data, these
236            values always refer to a single channel.
237         */
238         streamFormat.mBytesPerPacket = 4;
239         streamFormat.mBytesPerFrame = 4;
240
241         if (set_input_format () == 0) {
242                 return 1;
243         } else {
244                 return -1;
245         }
246 }
247
248 int
249 AUPlugin::set_input_format ()
250 {
251         return set_stream_format (kAudioUnitScope_Input, input_elements);
252 }
253
254 int
255 AUPlugin::set_output_format ()
256 {
257         return set_stream_format (kAudioUnitScope_Output, output_elements);
258 }
259
260 int
261 AUPlugin::set_stream_format (int scope, uint32_t cnt)
262 {
263         OSErr result;
264
265         for (uint32_t i = 0; i < cnt; ++i) {
266                 if ((result = unit->SetFormat (scope, i, streamFormat)) != 0) {
267                         error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
268                                                  (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
269                         return -1;
270                 }
271         }
272
273         if (scope == kAudioUnitScope_Input) {
274                 format_set |= 0x1;
275         } else {
276                 format_set |= 0x2;
277         }
278
279         return 0;
280 }
281
282 int32_t 
283 AUPlugin::compute_output_streams (int32_t nplugins)
284 {
285         /* we will never replicate AU plugins - either they can do the I/O we need
286            or not. thus, we can ignore nplugins entirely.
287         */
288         
289         if (set_output_format() == 0) {
290
291                 if (buffers) {
292                         free (buffers);
293                         buffers = 0;
294                 }
295
296                 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) + 
297                                                       streamFormat.mChannelsPerFrame * sizeof(AudioBuffer));
298
299                 Glib::Mutex::Lock em (_session.engine().process_lock());
300                 IO::MoreOutputs (streamFormat.mChannelsPerFrame);
301
302                 return streamFormat.mChannelsPerFrame;
303         } else {
304                 return -1;
305         }
306 }
307
308 uint32_t
309 AUPlugin::output_streams() const
310 {
311         if (!(format_set & 0x2)) {
312                 warning << _("AUPlugin: output_streams() called without any format set!") << endmsg;
313                 return 1;
314         }
315         return streamFormat.mChannelsPerFrame;
316 }
317
318
319 uint32_t
320 AUPlugin::input_streams() const
321 {
322         if (!(format_set & 0x1)) {
323                 warning << _("AUPlugin: input_streams() called without any format set!") << endmsg;
324                 return 1;
325         }
326         return streamFormat.mChannelsPerFrame;
327 }
328
329 OSStatus 
330 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
331                           const AudioTimeStamp    *inTimeStamp,
332                           UInt32       inBusNumber,
333                           UInt32       inNumberFrames,
334                           AudioBufferList*       ioData)
335 {
336         /* not much to do - the data is already in the buffers given to us in connect_and_run() */
337
338         if (current_maxbuf == 0) {
339                 error << _("AUPlugin: render callback called illegally!") << endmsg;
340                 return kAudioUnitErr_CannotDoInCurrentContext;
341         }
342
343         for (uint32_t i = 0; i < current_maxbuf; ++i) {
344                 ioData->mBuffers[i].mNumberChannels = 1;
345                 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
346                 ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
347         }
348
349         cb_offset += inNumberFrames;
350
351         return noErr;
352 }
353
354 int
355 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
356 {
357         AudioUnitRenderActionFlags flags = 0;
358         AudioTimeStamp ts;
359
360         current_buffers = &bufs;
361         current_maxbuf = maxbuf;
362         current_offset = offset;
363         cb_offset = 0;
364
365         buffers->mNumberBuffers = maxbuf;
366
367         for (uint32_t i = 0; i < maxbuf; ++i) {
368                 buffers->mBuffers[i].mNumberChannels = 1;
369                 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
370                 buffers->mBuffers[i].mData = 0;
371         }
372
373         ts.mSampleTime = frames_processed;
374         ts.mFlags = kAudioTimeStampSampleTimeValid;
375
376         if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
377
378                 current_maxbuf = 0;
379                 frames_processed += nframes;
380                 
381                 for (uint32_t i = 0; i < maxbuf; ++i) {
382                         if (bufs[i] + offset != buffers->mBuffers[i].mData) {
383                                 memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
384                         }
385                 }
386                 return 0;
387         }
388
389         return -1;
390 }
391
392 set<uint32_t>
393 AUPlugin::automatable() const
394 {
395         set<uint32_t> automates;
396         
397         return automates;
398 }
399
400 string
401 AUPlugin::describe_parameter (uint32_t)
402 {
403         return "";
404 }
405
406 void
407 AUPlugin::print_parameter (uint32_t, char*, uint32_t len) const
408 {
409         
410 }
411
412 bool
413 AUPlugin::parameter_is_audio (uint32_t) const
414 {
415         return false;
416 }
417
418 bool
419 AUPlugin::parameter_is_control (uint32_t) const
420 {
421         return false;
422 }
423
424 bool
425 AUPlugin::parameter_is_input (uint32_t) const
426 {
427         return false;
428 }
429
430 bool
431 AUPlugin::parameter_is_output (uint32_t) const
432 {
433         return false;
434 }
435
436 XMLNode&
437 AUPlugin::get_state()
438 {
439         XMLNode *root = new XMLNode (state_node_name());
440         LocaleGuard lg (X_("POSIX"));
441         return *root;
442 }
443
444 int
445 AUPlugin::set_state(const XMLNode& node)
446 {
447         return -1;
448 }
449
450 bool
451 AUPlugin::save_preset (string name)
452 {
453         return false;
454 }
455
456 bool
457 AUPlugin::load_preset (const string preset_label)
458 {
459         return false;
460 }
461
462 vector<string>
463 AUPlugin::get_presets ()
464 {
465         vector<string> presets;
466         
467         return presets;
468 }
469
470 bool
471 AUPlugin::has_editor () const
472 {
473         // even if the plugin doesn't have its own editor, the AU API can be used
474         // to create one that looks native.
475         return true;
476 }
477
478 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
479         : descriptor (d)
480 {
481
482 }
483
484 AUPluginInfo::~AUPluginInfo ()
485 {
486 }
487
488 PluginPtr
489 AUPluginInfo::load (Session& session)
490 {
491         try {
492                 PluginPtr plugin;
493
494                 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
495                 
496                 if (!comp->IsValid()) {
497                         error << ("AudioUnit: not a valid Component") << endmsg;
498                 } else {
499                         plugin.reset (new AUPlugin (session.engine(), session, comp));
500                 }
501                 
502                 plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
503                 return plugin;
504         }
505
506         catch (failed_constructor &err) {
507                 return PluginPtr ((Plugin*) 0);
508         }
509 }
510
511 PluginInfoList
512 AUPluginInfo::discover ()
513 {
514         PluginInfoList plugs;
515
516         discover_fx (plugs);
517         discover_music (plugs);
518
519         return plugs;
520 }
521
522 void
523 AUPluginInfo::discover_music (PluginInfoList& plugs)
524 {
525         CAComponentDescription desc;
526         desc.componentFlags = 0;
527         desc.componentFlagsMask = 0;
528         desc.componentSubType = 0;
529         desc.componentManufacturer = 0;
530         desc.componentType = kAudioUnitType_MusicEffect;
531
532         discover_by_description (plugs, desc);
533 }
534
535 void
536 AUPluginInfo::discover_fx (PluginInfoList& plugs)
537 {
538         CAComponentDescription desc;
539         desc.componentFlags = 0;
540         desc.componentFlagsMask = 0;
541         desc.componentSubType = 0;
542         desc.componentManufacturer = 0;
543         desc.componentType = kAudioUnitType_Effect;
544
545         discover_by_description (plugs, desc);
546 }
547
548 void
549 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
550 {
551         Component comp = 0;
552
553         comp = FindNextComponent (NULL, &desc);
554
555         while (comp != NULL) {
556                 CAComponentDescription temp;
557                 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
558
559                 AUPluginInfoPtr info (new AUPluginInfo 
560                                       (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
561
562                 /* no panners, format converters or i/o AU's for our purposes
563                  */
564
565                 switch (info->descriptor->Type()) {
566                 case kAudioUnitType_Panner:
567                 case kAudioUnitType_OfflineEffect:
568                 case kAudioUnitType_FormatConverter:
569                         continue;
570                 default:
571                         break;
572                 }
573
574                 switch (info->descriptor->SubType()) {
575                 case kAudioUnitSubType_DefaultOutput:
576                 case kAudioUnitSubType_SystemOutput:
577                 case kAudioUnitSubType_GenericOutput:
578                 case kAudioUnitSubType_AUConverter:
579                         continue;
580                         break;
581
582                 case kAudioUnitSubType_DLSSynth:
583                         info->category = "DLSSynth";
584                         break;
585
586                 case kAudioUnitType_MusicEffect:
587                         info->category = "MusicEffect";
588                         break;
589
590                 case kAudioUnitSubType_Varispeed:
591                         info->category = "Varispeed";
592                         break;
593
594                 case kAudioUnitSubType_Delay:
595                         info->category = "Delay";
596                         break;
597
598                 case kAudioUnitSubType_LowPassFilter:
599                         info->category = "LowPassFilter";
600                         break;
601
602                 case kAudioUnitSubType_HighPassFilter:
603                         info->category = "HighPassFilter";
604                         break;
605
606                 case kAudioUnitSubType_BandPassFilter:
607                         info->category = "BandPassFilter";
608                         break;
609
610                 case kAudioUnitSubType_HighShelfFilter:
611                         info->category = "HighShelfFilter";
612                         break;
613
614                 case kAudioUnitSubType_LowShelfFilter:
615                         info->category = "LowShelfFilter";
616                         break;
617
618                 case kAudioUnitSubType_ParametricEQ:
619                         info->category = "ParametricEQ";
620                         break;
621
622                 case kAudioUnitSubType_GraphicEQ:
623                         info->category = "GraphicEQ";
624                         break;
625
626                 case kAudioUnitSubType_PeakLimiter:
627                         info->category = "PeakLimiter";
628                         break;
629
630                 case kAudioUnitSubType_DynamicsProcessor:
631                         info->category = "DynamicsProcessor";
632                         break;
633
634                 case kAudioUnitSubType_MultiBandCompressor:
635                         info->category = "MultiBandCompressor";
636                         break;
637
638                 case kAudioUnitSubType_MatrixReverb:
639                         info->category = "MatrixReverb";
640                         break;
641
642                 case kAudioUnitType_Mixer:
643                         info->category = "Mixer";
644                         break;
645
646                 case kAudioUnitSubType_StereoMixer:
647                         info->category = "StereoMixer";
648                         break;
649
650                 case kAudioUnitSubType_3DMixer:
651                         info->category = "3DMixer";
652                         break;
653
654                 case kAudioUnitSubType_MatrixMixer:
655                         info->category = "MatrixMixer";
656                         break;
657
658                 default:
659                         info->category = "";
660                 }
661
662                 AUPluginInfo::get_names (temp, info->name, info->creator);
663
664                 info->type = ARDOUR::AudioUnit;
665                 info->unique_id = stringify_descriptor (*info->descriptor);
666
667                 /* mark the plugin as having flexible i/o */
668                 
669                 info->n_inputs = -1;
670                 info->n_outputs = -1;
671
672
673                 plugs.push_back (info);
674                 
675                 comp = FindNextComponent (comp, &desc);
676         }
677 }
678
679 void
680 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
681 {
682         CFStringRef itemName = NULL;
683
684         // Marc Poirier-style item name
685         CAComponent auComponent (comp_desc);
686         if (auComponent.IsValid()) {
687                 CAComponentDescription dummydesc;
688                 Handle nameHandle = NewHandle(sizeof(void*));
689                 if (nameHandle != NULL) {
690                         OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
691                         if (err == noErr) {
692                                 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
693                                 if (nameString != NULL) {
694                                         itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
695                                 }
696                         }
697                         DisposeHandle(nameHandle);
698                 }
699         }
700     
701         // if Marc-style fails, do the original way
702         if (itemName == NULL) {
703                 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
704                 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
705                 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
706     
707                 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"), 
708                         compTypeString, compManufacturerString, compSubTypeString);
709     
710                 if (compTypeString != NULL)
711                         CFRelease(compTypeString);
712                 if (compSubTypeString != NULL)
713                         CFRelease(compSubTypeString);
714                 if (compManufacturerString != NULL)
715                         CFRelease(compManufacturerString);
716         }
717         
718         string str = CFStringRefToStdString(itemName);
719         string::size_type colon = str.find (':');
720
721         if (colon) {
722                 name = str.substr (colon+1);
723                 maker = str.substr (0, colon);
724                 // strip_whitespace_edges (maker);
725                 // strip_whitespace_edges (name);
726         } else {
727                 name = str;
728                 maker = "unknown";
729         }
730 }
731
732 // from CAComponentDescription.cpp (in libs/appleutility in ardour source)
733 extern char *StringForOSType (OSType t, char *writeLocation);
734
735 std::string
736 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
737 {
738         char str[24];
739         stringstream s;
740
741         s << StringForOSType (desc.Type(), str);
742         s << " - ";
743                 
744         s << StringForOSType (desc.SubType(), str);
745         s << " - ";
746                 
747         s << StringForOSType (desc.Manu(), str);
748
749         return s.str();
750 }