2 Copyright (C) 2006 Paul Davis
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.
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.
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.
22 #include <pbd/transmitter.h>
23 #include <pbd/xml++.h>
24 #include <pbd/whitespace.h>
26 #include <glibmm/thread.h>
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>
34 #include <appleutility/CAAudioUnit.h>
35 #include <appleutility/CAAUParameter.h>
37 #include <CoreServices/CoreServices.h>
38 #include <AudioUnit/AudioUnit.h>
44 using namespace ARDOUR;
47 _render_callback(void *userData,
48 AudioUnitRenderActionFlags *ioActionFlags,
49 const AudioTimeStamp *inTimeStamp,
51 UInt32 inNumberFrames,
52 AudioBufferList* ioData)
54 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
57 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
59 Plugin (engine, session),
61 unit (new CAAudioUnit),
69 OSErr err = CAAudioUnit::Open (*(comp.get()), *unit);
72 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
73 throw failed_constructor ();
76 AURenderCallbackStruct renderCallbackInfo;
78 renderCallbackInfo.inputProc = _render_callback;
79 renderCallbackInfo.inputProcRefCon = this;
81 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
82 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
83 cerr << "cannot install render callback (err = " << err << ')' << endl;
84 throw failed_constructor();
87 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
88 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
89 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
91 // set up the basic stream format. these fields do not change
93 streamFormat.mSampleRate = session.frame_rate();
94 streamFormat.mFormatID = kAudioFormatLinearPCM;
95 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
96 streamFormat.mBitsPerChannel = 32;
97 streamFormat.mFramesPerPacket = 1;
99 // subject to later modification as we discover channel counts
101 streamFormat.mBytesPerPacket = 4;
102 streamFormat.mBytesPerFrame = 4;
103 streamFormat.mChannelsPerFrame = 1;
107 if (_set_block_size (_session.get_block_size())) {
108 error << _("AUPlugin: cannot set processing block size") << endmsg;
109 throw failed_constructor();
112 discover_parameters ();
114 Plugin::setup_controls ();
117 AUPlugin::~AUPlugin ()
120 unit->Uninitialize ();
129 AUPlugin::discover_parameters ()
131 /* discover writable parameters */
133 cerr << "get param info, there are " << global_elements << " global elements\n";
135 AudioUnitScope scopes[] = {
136 kAudioUnitScope_Global,
137 kAudioUnitScope_Output,
138 kAudioUnitScope_Input
141 descriptors.clear ();
143 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
145 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
147 cerr << "discovered " << param_info.NumParams() << " parameters in scope " << i << endl;
149 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
151 AUParameterDescriptor d;
153 d.id = param_info.ParamID (i);
155 const CAAUParameter* param = param_info.GetParamInfo (d.id);
156 const AudioUnitParameterInfo& info (param->ParamInfo());
158 const int len = CFStringGetLength (param->GetName());;
159 char local_buffer[len*2];
160 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
164 d.label = local_buffer;
167 d.scope = param_info.GetScope ();
168 d.element = param_info.GetElement ();
170 /* info.units to consider */
172 kAudioUnitParameterUnit_Generic = 0
173 kAudioUnitParameterUnit_Indexed = 1
174 kAudioUnitParameterUnit_Boolean = 2
175 kAudioUnitParameterUnit_Percent = 3
176 kAudioUnitParameterUnit_Seconds = 4
177 kAudioUnitParameterUnit_SampleFrames = 5
178 kAudioUnitParameterUnit_Phase = 6
179 kAudioUnitParameterUnit_Rate = 7
180 kAudioUnitParameterUnit_Hertz = 8
181 kAudioUnitParameterUnit_Cents = 9
182 kAudioUnitParameterUnit_RelativeSemiTones = 10
183 kAudioUnitParameterUnit_MIDINoteNumber = 11
184 kAudioUnitParameterUnit_MIDIController = 12
185 kAudioUnitParameterUnit_Decibels = 13
186 kAudioUnitParameterUnit_LinearGain = 14
187 kAudioUnitParameterUnit_Degrees = 15
188 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
189 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
190 kAudioUnitParameterUnit_Pan = 18
191 kAudioUnitParameterUnit_Meters = 19
192 kAudioUnitParameterUnit_AbsoluteCents = 20
193 kAudioUnitParameterUnit_Octaves = 21
194 kAudioUnitParameterUnit_BPM = 22
195 kAudioUnitParameterUnit_Beats = 23
196 kAudioUnitParameterUnit_Milliseconds = 24
197 kAudioUnitParameterUnit_Ratio = 25
200 /* info.flags to consider */
204 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
205 kAudioUnitParameterFlag_HasClump = (1L << 20)
206 kAudioUnitParameterFlag_HasName = (1L << 21)
207 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
208 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
209 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
210 kAudioUnitParameterFlag_CanRamp = (1L << 25)
211 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
212 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
213 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
214 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
215 kAudioUnitParameterFlag_IsReadable = (1L << 30)
216 kAudioUnitParameterFlag_IsWritable = (1L << 31)
219 d.integer_step = (info.unit & kAudioUnitParameterUnit_Indexed);
220 d.toggled = (info.unit & kAudioUnitParameterUnit_Boolean);
221 d.sr_dependent = (info.unit & kAudioUnitParameterUnit_SampleFrames);
222 d.automatable = !d.toggled &&
223 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
224 (info.flags & kAudioUnitParameterFlag_IsWritable);
226 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
229 d.lower = info.minValue;
230 d.upper = info.maxValue;
231 d.default_value = info.defaultValue;
235 d.min_unbound = 0; // lower is bound
236 d.max_unbound = 0; // upper is bound
238 descriptors.push_back (d);
245 AUPlugin::unique_id () const
247 return AUPluginInfo::stringify_descriptor (comp->Desc());
251 AUPlugin::label () const
253 return _info->name.c_str();
257 AUPlugin::parameter_count () const
259 return descriptors.size();
263 AUPlugin::default_value (uint32_t port)
265 if (port < descriptors.size()) {
266 return descriptors[port].default_value;
273 AUPlugin::latency () const
275 return unit->Latency ();
279 AUPlugin::set_parameter (uint32_t which, float val)
281 // unit->SetParameter (id, 0, val);
285 AUPlugin::get_parameter (uint32_t which) const
287 float outValue = 0.0;
289 // unit->GetParameter(parameter_map[which].first, parameter_map[which].second, 0, outValue);
295 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
297 if (which < descriptors.size()) {
298 pd = descriptors[which];
305 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
307 if (which < descriptors.size()) {
316 AUPlugin::activate ()
320 if ((err = unit->Initialize()) != noErr) {
321 error << string_compose (_("AUPlugin: cannot initialize plugin (err = %1)"), err) << endmsg;
323 frames_processed = 0;
330 AUPlugin::deactivate ()
332 unit->GlobalReset ();
336 AUPlugin::set_block_size (nframes_t nframes)
338 _set_block_size (nframes);
342 AUPlugin::_set_block_size (nframes_t nframes)
344 bool was_initialized = initialized;
345 UInt32 numFrames = nframes;
349 unit->Uninitialize ();
352 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
353 0, &numFrames, sizeof (numFrames))) != noErr) {
354 cerr << "cannot set max frames (err = " << err << ')' << endl;
358 if (was_initialized) {
366 AUPlugin::can_support_input_configuration (int32_t in)
368 streamFormat.mChannelsPerFrame = in;
369 /* apple says that for non-interleaved data, these
370 values always refer to a single channel.
372 streamFormat.mBytesPerPacket = 4;
373 streamFormat.mBytesPerFrame = 4;
375 if (set_input_format () == 0) {
383 AUPlugin::set_input_format ()
385 return set_stream_format (kAudioUnitScope_Input, input_elements);
389 AUPlugin::set_output_format ()
391 return set_stream_format (kAudioUnitScope_Output, output_elements);
395 AUPlugin::set_stream_format (int scope, uint32_t cnt)
399 for (uint32_t i = 0; i < cnt; ++i) {
400 if ((result = unit->SetFormat (scope, i, streamFormat)) != 0) {
401 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
402 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
407 if (scope == kAudioUnitScope_Input) {
417 AUPlugin::compute_output_streams (int32_t nplugins)
419 /* we will never replicate AU plugins - either they can do the I/O we need
420 or not. thus, we can ignore nplugins entirely.
423 if (set_output_format() == 0) {
430 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
431 streamFormat.mChannelsPerFrame * sizeof(AudioBuffer));
433 Glib::Mutex::Lock em (_session.engine().process_lock());
434 IO::MoreOutputs (streamFormat.mChannelsPerFrame);
436 return streamFormat.mChannelsPerFrame;
443 AUPlugin::output_streams() const
445 if (!(format_set & 0x2)) {
446 warning << _("AUPlugin: output_streams() called without any format set!") << endmsg;
449 return streamFormat.mChannelsPerFrame;
454 AUPlugin::input_streams() const
456 if (!(format_set & 0x1)) {
457 warning << _("AUPlugin: input_streams() called without any format set!") << endmsg;
460 return streamFormat.mChannelsPerFrame;
464 AUPlugin::render_callback(AudioUnitRenderActionFlags *ioActionFlags,
465 const AudioTimeStamp *inTimeStamp,
467 UInt32 inNumberFrames,
468 AudioBufferList* ioData)
470 /* not much to do - the data is already in the buffers given to us in connect_and_run() */
472 if (current_maxbuf == 0) {
473 error << _("AUPlugin: render callback called illegally!") << endmsg;
474 return kAudioUnitErr_CannotDoInCurrentContext;
477 for (uint32_t i = 0; i < current_maxbuf; ++i) {
478 ioData->mBuffers[i].mNumberChannels = 1;
479 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
480 ioData->mBuffers[i].mData = (*current_buffers)[i] + cb_offset + current_offset;
483 cb_offset += inNumberFrames;
489 AUPlugin::connect_and_run (vector<Sample*>& bufs, uint32_t maxbuf, int32_t& in, int32_t& out, nframes_t nframes, nframes_t offset)
491 AudioUnitRenderActionFlags flags = 0;
494 current_buffers = &bufs;
495 current_maxbuf = maxbuf;
496 current_offset = offset;
499 buffers->mNumberBuffers = maxbuf;
501 for (uint32_t i = 0; i < maxbuf; ++i) {
502 buffers->mBuffers[i].mNumberChannels = 1;
503 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
504 buffers->mBuffers[i].mData = 0;
507 ts.mSampleTime = frames_processed;
508 ts.mFlags = kAudioTimeStampSampleTimeValid;
510 if (unit->Render (&flags, &ts, 0, nframes, buffers) == noErr) {
513 frames_processed += nframes;
515 for (uint32_t i = 0; i < maxbuf; ++i) {
516 if (bufs[i] + offset != buffers->mBuffers[i].mData) {
517 memcpy (bufs[i]+offset, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
527 AUPlugin::automatable() const
529 set<uint32_t> automates;
531 for (uint32_t i = 0; i < descriptors.size(); ++i) {
532 if (descriptors[i].automatable) {
533 automates.insert (i);
541 AUPlugin::describe_parameter (uint32_t param)
543 return descriptors[param].label;
547 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
549 // NameValue stuff here
553 AUPlugin::parameter_is_audio (uint32_t) const
559 AUPlugin::parameter_is_control (uint32_t) const
565 AUPlugin::parameter_is_input (uint32_t) const
571 AUPlugin::parameter_is_output (uint32_t) const
577 AUPlugin::get_state()
579 XMLNode *root = new XMLNode (state_node_name());
580 LocaleGuard lg (X_("POSIX"));
585 AUPlugin::set_state(const XMLNode& node)
591 AUPlugin::save_preset (string name)
597 AUPlugin::load_preset (const string preset_label)
603 AUPlugin::get_presets ()
605 vector<string> presets;
611 AUPlugin::has_editor () const
613 // even if the plugin doesn't have its own editor, the AU API can be used
614 // to create one that looks native.
618 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
624 AUPluginInfo::~AUPluginInfo ()
629 AUPluginInfo::load (Session& session)
634 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
636 if (!comp->IsValid()) {
637 error << ("AudioUnit: not a valid Component") << endmsg;
639 plugin.reset (new AUPlugin (session.engine(), session, comp));
642 plugin->set_info (PluginInfoPtr (new AUPluginInfo (*this)));
646 catch (failed_constructor &err) {
647 return PluginPtr ((Plugin*) 0);
652 AUPluginInfo::discover ()
654 PluginInfoList plugs;
657 discover_music (plugs);
663 AUPluginInfo::discover_music (PluginInfoList& plugs)
665 CAComponentDescription desc;
666 desc.componentFlags = 0;
667 desc.componentFlagsMask = 0;
668 desc.componentSubType = 0;
669 desc.componentManufacturer = 0;
670 desc.componentType = kAudioUnitType_MusicEffect;
672 discover_by_description (plugs, desc);
676 AUPluginInfo::discover_fx (PluginInfoList& plugs)
678 CAComponentDescription desc;
679 desc.componentFlags = 0;
680 desc.componentFlagsMask = 0;
681 desc.componentSubType = 0;
682 desc.componentManufacturer = 0;
683 desc.componentType = kAudioUnitType_Effect;
685 discover_by_description (plugs, desc);
689 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
693 comp = FindNextComponent (NULL, &desc);
695 while (comp != NULL) {
696 CAComponentDescription temp;
697 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
699 AUPluginInfoPtr info (new AUPluginInfo
700 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
702 /* no panners, format converters or i/o AU's for our purposes
705 switch (info->descriptor->Type()) {
706 case kAudioUnitType_Panner:
707 case kAudioUnitType_OfflineEffect:
708 case kAudioUnitType_FormatConverter:
714 switch (info->descriptor->SubType()) {
715 case kAudioUnitSubType_DefaultOutput:
716 case kAudioUnitSubType_SystemOutput:
717 case kAudioUnitSubType_GenericOutput:
718 case kAudioUnitSubType_AUConverter:
722 case kAudioUnitSubType_DLSSynth:
723 info->category = "DLSSynth";
726 case kAudioUnitType_MusicEffect:
727 info->category = "MusicEffect";
730 case kAudioUnitSubType_Varispeed:
731 info->category = "Varispeed";
734 case kAudioUnitSubType_Delay:
735 info->category = "Delay";
738 case kAudioUnitSubType_LowPassFilter:
739 info->category = "LowPassFilter";
742 case kAudioUnitSubType_HighPassFilter:
743 info->category = "HighPassFilter";
746 case kAudioUnitSubType_BandPassFilter:
747 info->category = "BandPassFilter";
750 case kAudioUnitSubType_HighShelfFilter:
751 info->category = "HighShelfFilter";
754 case kAudioUnitSubType_LowShelfFilter:
755 info->category = "LowShelfFilter";
758 case kAudioUnitSubType_ParametricEQ:
759 info->category = "ParametricEQ";
762 case kAudioUnitSubType_GraphicEQ:
763 info->category = "GraphicEQ";
766 case kAudioUnitSubType_PeakLimiter:
767 info->category = "PeakLimiter";
770 case kAudioUnitSubType_DynamicsProcessor:
771 info->category = "DynamicsProcessor";
774 case kAudioUnitSubType_MultiBandCompressor:
775 info->category = "MultiBandCompressor";
778 case kAudioUnitSubType_MatrixReverb:
779 info->category = "MatrixReverb";
782 case kAudioUnitType_Mixer:
783 info->category = "Mixer";
786 case kAudioUnitSubType_StereoMixer:
787 info->category = "StereoMixer";
790 case kAudioUnitSubType_3DMixer:
791 info->category = "3DMixer";
794 case kAudioUnitSubType_MatrixMixer:
795 info->category = "MatrixMixer";
802 AUPluginInfo::get_names (temp, info->name, info->creator);
804 info->type = ARDOUR::AudioUnit;
805 info->unique_id = stringify_descriptor (*info->descriptor);
807 /* mark the plugin as having flexible i/o */
810 info->n_outputs = -1;
813 plugs.push_back (info);
815 comp = FindNextComponent (comp, &desc);
820 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, Glib::ustring& maker)
822 CFStringRef itemName = NULL;
824 // Marc Poirier-style item name
825 CAComponent auComponent (comp_desc);
826 if (auComponent.IsValid()) {
827 CAComponentDescription dummydesc;
828 Handle nameHandle = NewHandle(sizeof(void*));
829 if (nameHandle != NULL) {
830 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
832 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
833 if (nameString != NULL) {
834 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
837 DisposeHandle(nameHandle);
841 // if Marc-style fails, do the original way
842 if (itemName == NULL) {
843 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
844 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
845 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
847 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
848 compTypeString, compManufacturerString, compSubTypeString);
850 if (compTypeString != NULL)
851 CFRelease(compTypeString);
852 if (compSubTypeString != NULL)
853 CFRelease(compSubTypeString);
854 if (compManufacturerString != NULL)
855 CFRelease(compManufacturerString);
858 string str = CFStringRefToStdString(itemName);
859 string::size_type colon = str.find (':');
862 name = str.substr (colon+1);
863 maker = str.substr (0, colon);
864 // strip_whitespace_edges (maker);
865 // strip_whitespace_edges (name);
872 // from CAComponentDescription.cpp (in libs/appleutility in ardour source)
873 extern char *StringForOSType (OSType t, char *writeLocation);
876 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
881 s << StringForOSType (desc.Type(), str);
884 s << StringForOSType (desc.SubType(), str);
887 s << StringForOSType (desc.Manu(), str);