2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "pbd/transmitter.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30 #include "pbd/whitespace.h"
31 #include "pbd/pathscanner.h"
32 #include "pbd/locale_guard.h"
34 #include <glibmm/thread.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
38 #include "ardour/ardour.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/midi_buffer.h"
42 #include "ardour/filesystem_paths.h"
43 #include "ardour/io.h"
44 #include "ardour/audio_unit.h"
45 #include "ardour/session.h"
46 #include "ardour/tempo.h"
47 #include "ardour/utils.h"
49 #include "appleutility/CAAudioUnit.h"
50 #include "appleutility/CAAUParameter.h"
52 #include <CoreFoundation/CoreFoundation.h>
53 #include <CoreServices/CoreServices.h>
54 #include <AudioUnit/AudioUnit.h>
55 #include <AudioToolbox/AudioUnitUtilities.h>
61 using namespace ARDOUR;
63 //#define TRACE_AU_API
65 #define TRACE_API(fmt,...) fprintf (stderr, fmt, ## __VA_ARGS__)
67 #define TRACE_API(fmt,...)
70 #ifndef AU_STATE_SUPPORT
71 static bool seen_get_state_message = false;
72 static bool seen_set_state_message = false;
73 static bool seen_loading_message = false;
74 static bool seen_saving_message = false;
77 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
79 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
80 static string preset_suffix = ".aupreset";
81 static bool preset_search_path_initialized = false;
82 static bool debug_io_config = true;
85 _render_callback(void *userData,
86 AudioUnitRenderActionFlags *ioActionFlags,
87 const AudioTimeStamp *inTimeStamp,
89 UInt32 inNumberFrames,
90 AudioBufferList* ioData)
93 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
99 _get_beat_and_tempo_callback (void* userData,
100 Float64* outCurrentBeat,
101 Float64* outCurrentTempo)
104 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
111 _get_musical_time_location_callback (void * userData,
112 UInt32 * outDeltaSampleOffsetToNextBeat,
113 Float32 * outTimeSig_Numerator,
114 UInt32 * outTimeSig_Denominator,
115 Float64 * outCurrentMeasureDownBeat)
118 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
119 outTimeSig_Numerator,
120 outTimeSig_Denominator,
121 outCurrentMeasureDownBeat);
127 _get_transport_state_callback (void* userData,
128 Boolean* outIsPlaying,
129 Boolean* outTransportStateChanged,
130 Float64* outCurrentSampleInTimeLine,
131 Boolean* outIsCycling,
132 Float64* outCycleStartBeat,
133 Float64* outCycleEndBeat)
136 return ((AUPlugin*)userData)->get_transport_state_callback (outIsPlaying, outTransportStateChanged,
137 outCurrentSampleInTimeLine, outIsCycling,
138 outCycleStartBeat, outCycleEndBeat);
145 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
151 // Convert the property list into XML data.
153 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
156 error << _("Could not create XML version of property list") << endmsg;
160 // Write the XML data to the file.
162 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
164 if (errno == EEXIST) {
165 /* tell any UI's that this file already exists and ask them what to do */
166 bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
168 fd = open (path.c_str(), O_WRONLY, 0664);
174 error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
179 size_t cnt = CFDataGetLength (xmlData);
181 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
192 static CFPropertyListRef
193 load_property_list (Glib::ustring path)
196 CFPropertyListRef propertyList = 0;
198 CFStringRef errorString;
200 // Read the XML file.
202 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
207 off_t len = lseek (fd, 0, SEEK_END);
208 char* buf = new char[len];
209 lseek (fd, 0, SEEK_SET);
211 if (read (fd, buf, len) != len) {
219 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
221 // Reconstitute the dictionary using the XML data.
223 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
225 kCFPropertyListImmutable,
234 //-----------------------------------------------------------------------------
236 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
241 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
243 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
244 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
250 //-----------------------------------------------------------------------------
252 get_preset_name_in_plist (CFPropertyListRef plist)
260 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
261 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
263 CFStringRef str = (CFStringRef) p;
264 int len = CFStringGetLength(str);
266 char local_buffer[len];
267 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
275 //--------------------------------------------------------------------------
276 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
277 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
278 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
279 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
281 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
284 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
285 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
287 // only sub-type and manufacturer IDs need to be equal
290 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
291 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
298 //--------------------------------------------------------------------------
299 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
300 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
301 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
302 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
305 ComponentDescription desc;
307 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
310 // get the ComponentDescription of the input Component
311 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
315 // check if the Component's ComponentDescription matches the input ComponentDescription
316 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
319 //--------------------------------------------------------------------------
320 // determine if 2 ComponentDescriptions are basically equal
321 // (by that, I mean that the important identifying values are compared,
322 // but not the ComponentDescription flags)
323 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
325 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
328 //--------------------------------------------------------------------------
329 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
330 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
332 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
335 //--------------------------------------------------------------------------
336 // determine if a ComponentDescription basically matches that of a particular Component
337 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
339 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
342 //--------------------------------------------------------------------------
343 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
344 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
346 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
350 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
351 : Plugin (engine, session)
353 , unit (new CAAudioUnit)
354 , initialized (false)
355 , _current_block_size (0)
356 , _requires_fixed_size_buffers (false)
360 , current_buffers (0)
361 , frames_processed (0)
362 , last_transport_rolling (false)
363 , last_transport_speed (0.0)
365 if (!preset_search_path_initialized) {
366 Glib::ustring p = Glib::get_home_dir();
367 p += "/Library/Audio/Presets:";
368 p += preset_search_path;
369 preset_search_path = p;
370 preset_search_path_initialized = true;
376 AUPlugin::AUPlugin (const AUPlugin& other)
378 , comp (other.get_comp())
379 , unit (new CAAudioUnit)
380 , initialized (false)
381 , _current_block_size (0)
383 , _requires_fixed_size_buffers (false)
387 , current_buffers (0)
388 , frames_processed (0)
394 AUPlugin::~AUPlugin ()
397 TRACE_API ("about to call uninitialize in plugin destructor\n");
398 unit->Uninitialize ();
407 AUPlugin::discover_factory_presets ()
410 UInt32 dataSize = sizeof (presets);
413 TRACE_API ("get property FactoryPresets in global scope\n");
414 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
415 cerr << "cannot get factory preset info: " << err << endl;
423 CFIndex cnt = CFArrayGetCount (presets);
425 for (CFIndex i = 0; i < cnt; ++i) {
426 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
428 string name = CFStringRefToStdString (preset->presetName);
429 factory_preset_map[name] = preset->presetNumber;
441 TRACE_API ("opening AudioUnit\n");
442 err = CAAudioUnit::Open (*(comp.get()), *unit);
444 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
445 throw failed_constructor();
449 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
450 throw failed_constructor ();
453 TRACE_API ("count global elements\n");
454 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
455 TRACE_API ("count input elements\n");
456 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
457 TRACE_API ("count output elements\n");
458 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
460 if (input_elements > 0) {
461 AURenderCallbackStruct renderCallbackInfo;
463 renderCallbackInfo.inputProc = _render_callback;
464 renderCallbackInfo.inputProcRefCon = this;
466 TRACE_API ("set render callback in input scope\n");
467 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
468 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
469 cerr << "cannot install render callback (err = " << err << ')' << endl;
470 throw failed_constructor();
474 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
476 HostCallbackInfo info;
477 memset (&info, 0, sizeof (HostCallbackInfo));
478 info.hostUserData = this;
479 info.beatAndTempoProc = _get_beat_and_tempo_callback;
480 info.musicalTimeLocationProc = _get_musical_time_location_callback;
481 info.transportStateProc = _get_transport_state_callback;
483 //ignore result of this - don't care if the property isn't supported
484 TRACE_API ("set host callbacks in global scope\n");
485 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
486 kAudioUnitScope_Global,
489 sizeof (HostCallbackInfo));
491 /* these keep track of *configured* channel set up,
492 not potential set ups.
496 output_channels = -1;
498 if (set_block_size (_session.get_block_size())) {
499 error << _("AUPlugin: cannot set processing block size") << endmsg;
500 throw failed_constructor();
503 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
504 _has_midi_input = pinfo->needs_midi_input ();
505 _has_midi_output = false;
507 discover_parameters ();
508 discover_factory_presets ();
510 // Plugin::setup_controls ();
514 AUPlugin::discover_parameters ()
516 /* discover writable parameters */
518 AudioUnitScope scopes[] = {
519 kAudioUnitScope_Global,
520 kAudioUnitScope_Output,
521 kAudioUnitScope_Input
524 descriptors.clear ();
526 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
528 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
530 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
532 AUParameterDescriptor d;
534 d.id = param_info.ParamID (i);
536 const CAAUParameter* param = param_info.GetParamInfo (d.id);
537 const AudioUnitParameterInfo& info (param->ParamInfo());
539 const int len = CFStringGetLength (param->GetName());;
540 char local_buffer[len*2];
541 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
545 d.label = local_buffer;
548 d.scope = param_info.GetScope ();
549 d.element = param_info.GetElement ();
551 /* info.units to consider */
553 kAudioUnitParameterUnit_Generic = 0
554 kAudioUnitParameterUnit_Indexed = 1
555 kAudioUnitParameterUnit_Boolean = 2
556 kAudioUnitParameterUnit_Percent = 3
557 kAudioUnitParameterUnit_Seconds = 4
558 kAudioUnitParameterUnit_SampleFrames = 5
559 kAudioUnitParameterUnit_Phase = 6
560 kAudioUnitParameterUnit_Rate = 7
561 kAudioUnitParameterUnit_Hertz = 8
562 kAudioUnitParameterUnit_Cents = 9
563 kAudioUnitParameterUnit_RelativeSemiTones = 10
564 kAudioUnitParameterUnit_MIDINoteNumber = 11
565 kAudioUnitParameterUnit_MIDIController = 12
566 kAudioUnitParameterUnit_Decibels = 13
567 kAudioUnitParameterUnit_LinearGain = 14
568 kAudioUnitParameterUnit_Degrees = 15
569 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
570 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
571 kAudioUnitParameterUnit_Pan = 18
572 kAudioUnitParameterUnit_Meters = 19
573 kAudioUnitParameterUnit_AbsoluteCents = 20
574 kAudioUnitParameterUnit_Octaves = 21
575 kAudioUnitParameterUnit_BPM = 22
576 kAudioUnitParameterUnit_Beats = 23
577 kAudioUnitParameterUnit_Milliseconds = 24
578 kAudioUnitParameterUnit_Ratio = 25
581 /* info.flags to consider */
585 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
586 kAudioUnitParameterFlag_HasClump = (1L << 20)
587 kAudioUnitParameterFlag_HasName = (1L << 21)
588 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
589 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
590 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
591 kAudioUnitParameterFlag_CanRamp = (1L << 25)
592 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
593 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
594 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
595 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
596 kAudioUnitParameterFlag_IsReadable = (1L << 30)
597 kAudioUnitParameterFlag_IsWritable = (1L << 31)
600 d.lower = info.minValue;
601 d.upper = info.maxValue;
602 d.default_value = info.defaultValue;
604 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
605 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
606 (d.integer_step && ((d.upper - d.lower) == 1.0));
607 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
608 d.automatable = !d.toggled &&
609 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
610 (info.flags & kAudioUnitParameterFlag_IsWritable);
612 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
618 d.min_unbound = 0; // lower is bound
619 d.max_unbound = 0; // upper is bound
621 descriptors.push_back (d);
628 four_ints_to_four_byte_literal (unsigned char n[4])
630 /* this is actually implementation dependent. sigh. this is what gcc
631 and quite a few others do.
633 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
637 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
639 if (isdigit (id[0])) {
643 /* ID format is xxxx-xxxx-xxxx
644 where x maybe \xNN or a printable character.
646 Split at the '-' and and process each part into an integer.
647 Then put it back together.
651 unsigned char nascent[4];
652 const char* cstr = id.c_str();
653 const char* estr = cstr + id.size();
664 while (*cstr && next_int < 4) {
668 if (estr - cstr < 3) {
670 /* too close to the end for \xNN parsing: treat as literal characters */
672 cerr << "Parse " << cstr << " as a literal \\" << endl;
679 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
683 memcpy (short_buf, &cstr[2], 2);
684 nascent[in] = strtol (short_buf, NULL, 16);
690 /* treat as literal characters */
691 cerr << "Parse " << cstr << " as a literal \\" << endl;
705 if (in && (in % 4 == 0)) {
706 /* nascent is ready */
707 n[next_int] = four_ints_to_four_byte_literal (nascent);
711 /* swallow space-hyphen-space */
725 s << n[0] << '-' << n[1] << '-' << n[2];
734 AUPlugin::unique_id () const
736 return AUPluginInfo::stringify_descriptor (comp->Desc());
740 AUPlugin::label () const
742 return _info->name.c_str();
746 AUPlugin::parameter_count () const
748 return descriptors.size();
752 AUPlugin::default_value (uint32_t port)
754 if (port < descriptors.size()) {
755 return descriptors[port].default_value;
762 AUPlugin::signal_latency () const
764 return unit->Latency() * _session.frame_rate();
768 AUPlugin::set_parameter (uint32_t which, float val)
770 if (which < descriptors.size()) {
771 const AUParameterDescriptor& d (descriptors[which]);
772 TRACE_API ("set parameter %d in scope %d element %d to %f\n", d.id, d.scope, d.element, val);
773 unit->SetParameter (d.id, d.scope, d.element, val);
775 /* tell the world what we did */
777 AudioUnitEvent theEvent;
779 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
780 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
781 theEvent.mArgument.mParameter.mParameterID = d.id;
782 theEvent.mArgument.mParameter.mScope = d.scope;
783 theEvent.mArgument.mParameter.mElement = d.element;
785 TRACE_API ("notify about parameter change\n");
786 AUEventListenerNotify (NULL, NULL, &theEvent);
791 AUPlugin::get_parameter (uint32_t which) const
794 if (which < descriptors.size()) {
795 const AUParameterDescriptor& d (descriptors[which]);
796 TRACE_API ("get value of parameter %d in scope %d element %d\n", d.id, d.scope, d.element);
797 unit->GetParameter(d.id, d.scope, d.element, val);
803 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
805 if (which < descriptors.size()) {
806 pd = descriptors[which];
813 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
815 if (which < descriptors.size()) {
824 AUPlugin::activate ()
828 TRACE_API ("call Initialize in activate()\n");
829 if ((err = unit->Initialize()) != noErr) {
830 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
832 frames_processed = 0;
839 AUPlugin::deactivate ()
841 TRACE_API ("call Uninitialize in deactivate()\n");
842 unit->Uninitialize ();
849 TRACE_API ("call Reset in flush()\n");
850 unit->GlobalReset ();
854 AUPlugin::requires_fixed_size_buffers() const
856 return _requires_fixed_size_buffers;
861 AUPlugin::set_block_size (pframes_t nframes)
863 bool was_initialized = initialized;
864 UInt32 numFrames = nframes;
871 TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
872 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
873 0, &numFrames, sizeof (numFrames))) != noErr) {
874 cerr << "cannot set max frames (err = " << err << ')' << endl;
878 if (was_initialized) {
882 _current_block_size = nframes;
888 AUPlugin::configure_io (ChanCount in, ChanCount out)
890 AudioStreamBasicDescription streamFormat;
891 bool was_initialized = initialized;
892 int32_t audio_in = in.n_audio();
893 int32_t audio_out = out.n_audio();
896 //if we are already running with the requested i/o config, bail out here
897 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
904 streamFormat.mSampleRate = _session.frame_rate();
905 streamFormat.mFormatID = kAudioFormatLinearPCM;
906 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
908 #ifdef __LITTLE_ENDIAN__
911 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
914 streamFormat.mBitsPerChannel = 32;
915 streamFormat.mFramesPerPacket = 1;
917 /* apple says that for non-interleaved data, these
918 values always refer to a single channel.
920 streamFormat.mBytesPerPacket = 4;
921 streamFormat.mBytesPerFrame = 4;
923 streamFormat.mChannelsPerFrame = audio_in;
925 if (set_input_format (streamFormat) != 0) {
929 streamFormat.mChannelsPerFrame = audio_out;
931 if (set_output_format (streamFormat) != 0) {
935 if (was_initialized) {
943 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
945 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
946 // attempt to multiply-instantiate plugins to meet io configurations.
948 int32_t audio_in = in.n_audio();
950 int32_t plugcnt = -1;
951 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
953 /* lets check MIDI first */
955 if (in.n_midi() > 0) {
956 if (!_has_midi_input) {
961 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
963 if (debug_io_config) {
964 cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
967 //Ardour expects the plugin to tell it the output configuration
968 //but AU plugins can have multiple I/O configurations
969 //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
970 //so first lets see if there's a configuration that keeps out==in
972 audio_out = audio_in;
974 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
975 int32_t possible_in = i->first;
976 int32_t possible_out = i->second;
978 if (possible_in == audio_in && possible_out== audio_out) {
979 cerr << "\tCHOSEN: in " << in << " out " << out << endl;
984 /* now allow potentially "imprecise" matches */
986 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
988 int32_t possible_in = i->first;
989 int32_t possible_out = i->second;
991 if (debug_io_config) {
992 cerr << "\tin " << possible_in << " out " << possible_out << endl;
995 if (possible_out == 0) {
996 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1000 if (possible_in == 0) {
1002 /* instrument plugin, always legal but throws away inputs ...
1005 if (possible_out == -1) {
1006 /* out much match in (UNLIKELY!!) */
1007 audio_out = audio_in;
1009 } else if (possible_out == -2) {
1010 /* any configuration possible, pick matching */
1011 audio_out = audio_in;
1013 } else if (possible_out < -2) {
1014 /* explicit variable number of outputs, pick maximum */
1015 audio_out = -possible_out;
1018 /* exact number of outputs */
1019 audio_out = possible_out;
1024 if (possible_in == -1) {
1026 /* wildcard for input */
1028 if (possible_out == -1) {
1029 /* out much match in */
1030 audio_out = audio_in;
1032 } else if (possible_out == -2) {
1033 /* any configuration possible, pick matching */
1034 audio_out = audio_in;
1036 } else if (possible_out < -2) {
1037 /* explicit variable number of outputs, pick maximum */
1038 audio_out = -possible_out;
1041 /* exact number of outputs */
1042 audio_out = possible_out;
1047 if (possible_in == -2) {
1049 if (possible_out == -1) {
1050 /* any configuration possible, pick matching */
1051 audio_out = audio_in;
1053 } else if (possible_out == -2) {
1054 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1057 } else if (possible_out < -2) {
1058 /* explicit variable number of outputs, pick maximum */
1059 audio_out = -possible_out;
1062 /* exact number of outputs */
1063 audio_out = possible_out;
1068 if (possible_in < -2) {
1070 /* explicit variable number of inputs */
1072 if (audio_in > -possible_in) {
1073 /* request is too large */
1077 if (possible_out == -1) {
1078 /* out must match in */
1079 audio_out = audio_in;
1081 } else if (possible_out == -2) {
1082 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1085 } else if (possible_out < -2) {
1086 /* explicit variable number of outputs, pick maximum */
1087 audio_out = -possible_out;
1090 /* exact number of outputs */
1091 audio_out = possible_out;
1096 if (possible_in == audio_in) {
1098 /* exact number of inputs ... must match obviously */
1100 if (possible_out == -1) {
1101 /* out must match in */
1102 audio_out = audio_in;
1104 } else if (possible_out == -2) {
1105 /* any output configuration, pick matching */
1106 audio_out = audio_in;
1108 } else if (possible_out < -2) {
1109 /* explicit variable number of outputs, pick maximum */
1110 audio_out = -possible_out;
1113 /* exact number of outputs */
1114 audio_out = possible_out;
1125 if (debug_io_config) {
1127 cerr << "\tCHOSEN: in " << in << " out " << out << " plugcnt will be " << plugcnt << endl;
1129 cerr << "\tFAIL: no configs match requested in " << in << endl;
1133 out.set (DataType::MIDI, 0);
1134 out.set (DataType::AUDIO, audio_out);
1140 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1142 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1146 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1148 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1157 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1158 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1160 Glib::Mutex::Lock em (_session.engine().process_lock());
1161 IO::PortCountChanged (ChanCount(DataType::AUDIO, fmt.mChannelsPerFrame));
1167 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1171 for (uint32_t i = 0; i < cnt; ++i) {
1172 TRACE_API ("set stream format for %s, scope = %d element %d\n",
1173 (scope == kAudioUnitScope_Input ? "input" : "output"),
1175 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1176 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1177 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1182 if (scope == kAudioUnitScope_Input) {
1183 input_channels = fmt.mChannelsPerFrame;
1185 output_channels = fmt.mChannelsPerFrame;
1192 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1193 const AudioTimeStamp*,
1195 UInt32 inNumberFrames,
1196 AudioBufferList* ioData)
1198 if (_has_midi_input) {
1199 assert (current_buffers->count().n_midi() > 0);
1201 /* deliver the first (and assumed only) MIDI buffer's data
1205 MidiBuffer& mb (current_buffers->get_midi(0));
1207 for (MidiBuffer::iterator i = mb.begin(); i != mb.end(); ++i) {
1208 Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *i;
1209 switch (ev.type()) {
1210 case MIDI_CMD_NOTE_ON:
1211 case MIDI_CMD_NOTE_OFF:
1212 case MIDI_CMD_CONTROL:
1213 case MIDI_CMD_BENDER:
1214 case MIDI_CMD_PGM_CHANGE:
1215 case MIDI_CMD_CHANNEL_PRESSURE:
1217 const uint8_t* b = ev.buffer();
1218 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1223 /* plugins do not get other stuff by default */
1229 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1231 if (current_maxbuf == 0) {
1232 error << _("AUPlugin: render callback called illegally!") << endmsg;
1233 return kAudioUnitErr_CannotDoInCurrentContext;
1235 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
1237 for (uint32_t i = 0; i < limit; ++i) {
1238 ioData->mBuffers[i].mNumberChannels = 1;
1239 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1241 /* we don't use the channel mapping because audiounits are
1242 never replicated. one plugin instance uses all channels/buffers
1243 passed to PluginInsert::connect_and_run()
1246 ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
1249 cb_offset += inNumberFrames;
1255 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1257 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1259 AudioUnitRenderActionFlags flags = 0;
1262 uint32_t maxbuf = bufs.count().n_audio();
1264 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1265 unit->GlobalReset();
1266 _last_nframes = nframes;
1269 current_buffers = &bufs;
1270 current_maxbuf = maxbuf;
1271 current_offset = offset;
1274 buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
1276 for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
1277 buffers->mBuffers[i].mNumberChannels = 1;
1278 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1279 buffers->mBuffers[i].mData = 0;
1282 ts.mSampleTime = frames_processed;
1283 ts.mFlags = kAudioTimeStampSampleTimeValid;
1285 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1288 frames_processed += nframes;
1290 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1293 for (i = 0; i < limit; ++i) {
1294 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1295 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1296 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1297 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1301 /* now silence any buffers that were passed in but the that the plugin
1302 did not fill/touch/use.
1305 for (;i < maxbuf; ++i) {
1306 Sample* buffer_address= bufs.get_audio (i).data (offset);
1307 memset (buffer_address, 0, nframes * sizeof (Sample));
1313 cerr << name() << " render status " << err << endl;
1318 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1319 Float64* outCurrentTempo)
1321 TempoMap& tmap (_session.tempo_map());
1323 TRACE_API ("AU calls ardour beat&tempo callback\n");
1325 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1326 (and interpretation) of a beat position will be incorrect. So refuse to
1330 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1331 return kAudioUnitErr_CannotDoInCurrentContext;
1334 Timecode::BBT_Time bbt;
1335 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1336 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1338 if (outCurrentBeat) {
1340 beat = metric.meter().beats_per_bar() * bbt.bars;
1342 beat += bbt.ticks / BBT_Time::ticks_per_beat;
1343 *outCurrentBeat = beat;
1346 if (outCurrentTempo) {
1347 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1355 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1356 Float32* outTimeSig_Numerator,
1357 UInt32* outTimeSig_Denominator,
1358 Float64* outCurrentMeasureDownBeat)
1360 TempoMap& tmap (_session.tempo_map());
1362 TRACE_API ("AU calls ardour music time location callback\n");
1364 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1365 (and interpretation) of a beat position will be incorrect. So refuse to
1369 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1370 return kAudioUnitErr_CannotDoInCurrentContext;
1373 Timecode::BBT_Time bbt;
1374 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1375 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1377 if (outDeltaSampleOffsetToNextBeat) {
1378 if (bbt.ticks == 0) {
1380 *outDeltaSampleOffsetToNextBeat = 0;
1382 *outDeltaSampleOffsetToNextBeat = (UInt32) floor (((BBT_Time::ticks_per_beat - bbt.ticks)/BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1383 metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1387 if (outTimeSig_Numerator) {
1388 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1390 if (outTimeSig_Denominator) {
1391 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1394 if (outCurrentMeasureDownBeat) {
1396 /* beat for the start of the bar.
1398 2|1|0 -> 1 + beats_per_bar
1399 3|1|0 -> 1 + (2 * beats_per_bar)
1403 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1410 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1411 Boolean* outTransportStateChanged,
1412 Float64* outCurrentSampleInTimeLine,
1413 Boolean* outIsCycling,
1414 Float64* outCycleStartBeat,
1415 Float64* outCycleEndBeat)
1420 TRACE_API ("AU calls ardour transport state callback\n");
1422 rolling = _session.transport_rolling();
1423 speed = _session.transport_speed ();
1426 *outIsPlaying = _session.transport_rolling();
1429 if (outTransportStateChanged) {
1430 if (rolling != last_transport_rolling) {
1431 *outTransportStateChanged = true;
1432 } else if (speed != last_transport_speed) {
1433 *outTransportStateChanged = true;
1435 *outTransportStateChanged = false;
1439 if (outCurrentSampleInTimeLine) {
1440 /* this assumes that the AU can only call this host callback from render context,
1441 where current_offset is valid.
1443 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1447 Location* loc = _session.locations()->auto_loop_location();
1449 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1451 if (*outIsCycling) {
1453 if (outCycleStartBeat || outCycleEndBeat) {
1455 TempoMap& tmap (_session.tempo_map());
1457 /* more than 1 meter means that a simplistic computation (and interpretation) of
1458 a beat position will be incorrect. so refuse to offer the value.
1461 if (tmap.n_meters() > 1) {
1462 return kAudioUnitErr_CannotDoInCurrentContext;
1465 Timecode::BBT_Time bbt;
1467 if (outCycleStartBeat) {
1468 TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
1469 _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1472 beat = metric.meter().beats_per_bar() * bbt.bars;
1474 beat += bbt.ticks / BBT_Time::ticks_per_beat;
1476 *outCycleStartBeat = beat;
1479 if (outCycleEndBeat) {
1480 TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
1481 _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1484 beat = metric.meter().beats_per_bar() * bbt.bars;
1486 beat += bbt.ticks / BBT_Time::ticks_per_beat;
1488 *outCycleEndBeat = beat;
1494 last_transport_rolling = rolling;
1495 last_transport_speed = speed;
1500 set<Evoral::Parameter>
1501 AUPlugin::automatable() const
1503 set<Evoral::Parameter> automates;
1505 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1506 if (descriptors[i].automatable) {
1507 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1515 AUPlugin::describe_parameter (Evoral::Parameter param)
1517 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1518 return descriptors[param.id()].label;
1525 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1527 // NameValue stuff here
1531 AUPlugin::parameter_is_audio (uint32_t) const
1537 AUPlugin::parameter_is_control (uint32_t) const
1543 AUPlugin::parameter_is_input (uint32_t) const
1549 AUPlugin::parameter_is_output (uint32_t) const
1555 AUPlugin::get_state()
1557 LocaleGuard lg (X_("POSIX"));
1558 XMLNode *root = new XMLNode (state_node_name());
1560 #ifdef AU_STATE_SUPPORT
1562 CFPropertyListRef propertyList;
1564 TRACE_API ("get preset state\n");
1565 if (unit->GetAUPreset (propertyList) != noErr) {
1569 // Convert the property list into XML data.
1571 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1574 error << _("Could not create XML version of property list") << endmsg;
1578 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1579 our state node. GACK!
1584 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1586 root->add_child_copy (*t.root());
1590 CFRelease (xmlData);
1591 CFRelease (propertyList);
1593 if (!seen_get_state_message) {
1594 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1597 seen_get_state_message = true;
1605 AUPlugin::set_state(const XMLNode& node, int /* version*/)
1607 #ifdef AU_STATE_SUPPORT
1609 CFPropertyListRef propertyList;
1610 LocaleGuard lg (X_("POSIX"));
1612 if (node.name() != state_node_name()) {
1613 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1617 if (node.children().empty()) {
1621 XMLNode* top = node.children().front();
1622 XMLNode* copy = new XMLNode (*top);
1627 const string& xml = t.write_buffer ();
1628 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1629 CFStringRef errorString;
1631 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1633 kCFPropertyListImmutable,
1636 CFRelease (xmlData);
1639 TRACE_API ("set preset\n");
1640 if (unit->SetAUPreset (propertyList) == noErr) {
1643 /* tell the world */
1645 AudioUnitParameter changedUnit;
1646 changedUnit.mAudioUnit = unit->AU();
1647 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1648 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1650 CFRelease (propertyList);
1655 if (!seen_set_state_message) {
1656 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1665 AUPlugin::load_preset (const string& preset_label)
1667 #ifdef AU_STATE_SUPPORT
1669 CFPropertyListRef propertyList;
1671 UserPresetMap::iterator ux;
1672 FactoryPresetMap::iterator fx;
1674 /* look first in "user" presets */
1676 if ((ux = user_preset_map.find (preset_label)) != user_preset_map.end()) {
1678 if ((propertyList = load_property_list (ux->second)) != 0) {
1679 TRACE_API ("set preset from user presets\n");
1680 if (unit->SetAUPreset (propertyList) == noErr) {
1683 /* tell the world */
1685 AudioUnitParameter changedUnit;
1686 changedUnit.mAudioUnit = unit->AU();
1687 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1688 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1690 CFRelease(propertyList);
1693 } else if ((fx = factory_preset_map.find (preset_label)) != factory_preset_map.end()) {
1697 preset.presetNumber = fx->second;
1698 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1700 TRACE_API ("set preset from factory presets\n");
1702 if (unit->SetPresentPreset (preset) == 0) {
1705 /* tell the world */
1707 AudioUnitParameter changedUnit;
1708 changedUnit.mAudioUnit = unit->AU();
1709 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1710 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1716 if (!seen_loading_message) {
1717 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1720 seen_loading_message = true;
1727 AUPlugin::save_preset (string preset_name)
1729 #ifdef AU_STATE_SUPPORT
1730 CFPropertyListRef propertyList;
1731 vector<Glib::ustring> v;
1732 Glib::ustring user_preset_path;
1735 std::string m = maker();
1736 std::string n = name();
1738 strip_whitespace_edges (m);
1739 strip_whitespace_edges (n);
1741 v.push_back (Glib::get_home_dir());
1742 v.push_back ("Library");
1743 v.push_back ("Audio");
1744 v.push_back ("Presets");
1748 user_preset_path = Glib::build_filename (v);
1750 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1751 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1755 TRACE_API ("get current preset\n");
1756 if (unit->GetAUPreset (propertyList) != noErr) {
1760 // add the actual preset name */
1762 v.push_back (preset_name + preset_suffix);
1766 user_preset_path = Glib::build_filename (v);
1768 set_preset_name_in_plist (propertyList, preset_name);
1770 if (save_property_list (propertyList, user_preset_path)) {
1771 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1775 CFRelease(propertyList);
1779 if (!seen_saving_message) {
1780 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1783 seen_saving_message = true;
1789 //-----------------------------------------------------------------------------
1790 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1792 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1794 CFNumberRef cfNumber;
1795 SInt32 numberValue = 0;
1796 Boolean dummySuccess;
1798 if (outSuccess == NULL)
1799 outSuccess = &dummySuccess;
1800 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1802 *outSuccess = FALSE;
1806 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1807 if (cfNumber == NULL)
1809 *outSuccess = FALSE;
1812 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1820 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1822 CFDictionaryRef auStateDictionary;
1823 ComponentDescription tempDesc = {0,0,0,0,0};
1824 SInt32 versionValue;
1827 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1830 // the property list for AU state data must be of the dictionary type
1831 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1832 return kAudioUnitErr_InvalidPropertyValue;
1835 auStateDictionary = (CFDictionaryRef)inAUStateData;
1837 // first check to make sure that the version of the AU state data is one that we know understand
1838 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1839 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1842 return kAudioUnitErr_InvalidPropertyValue;
1844 #define kCurrentSavedStateVersion 0
1845 if (versionValue != kCurrentSavedStateVersion) {
1846 return kAudioUnitErr_InvalidPropertyValue;
1849 // grab the ComponentDescription values from the AU state data
1850 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1851 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1852 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1853 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1854 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1855 return kAudioUnitErr_InvalidPropertyValue;
1857 *outComponentDescription = tempDesc;
1862 static bool au_preset_filter (const string& str, void* arg)
1864 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1868 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1872 /* check the preset file path name against this plugin
1873 ID. The idea is that all preset files for this plugin
1874 include "<manufacturer>/<plugin-name>" in their path.
1877 Plugin* p = (Plugin *) arg;
1878 string match = p->maker();
1882 ret = str.find (match) != string::npos;
1885 string m = p->maker ();
1886 string n = p->name ();
1887 strip_whitespace_edges (m);
1888 strip_whitespace_edges (n);
1893 ret = str.find (match) != string::npos;
1901 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1904 CFPropertyListRef plist;
1905 ComponentDescription presetDesc;
1908 plist = load_property_list (pathstr);
1914 // get the ComponentDescription from the AU preset file
1916 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1918 if (status == noErr) {
1919 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1921 /* try to get the preset name from the property list */
1923 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1925 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1929 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1932 char buf[PATH_MAX+1];
1934 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1949 AUPlugin::current_preset() const
1953 #ifdef AU_STATE_SUPPORT
1954 CFPropertyListRef propertyList;
1956 TRACE_API ("get current preset for current_preset()\n");
1957 if (unit->GetAUPreset (propertyList) == noErr) {
1958 preset_name = get_preset_name_in_plist (propertyList);
1959 CFRelease(propertyList);
1965 vector<Plugin::PresetRecord>
1966 AUPlugin::get_presets ()
1968 vector<Plugin::PresetRecord> presets;
1970 #ifdef AU_STATE_SUPPORT
1971 vector<string*>* preset_files;
1972 PathScanner scanner;
1974 user_preset_map.clear ();
1976 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1978 if (!preset_files) {
1982 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1984 string path = *(*x);
1987 /* make an initial guess at the preset name using the path */
1989 preset_name = Glib::path_get_basename (path);
1990 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1992 /* check that this preset file really matches this plugin
1993 and potentially get the "real" preset name from
1997 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
1998 user_preset_map[preset_name] = path;
2004 delete preset_files;
2006 /* now fill the vector<string> with the names we have */
2008 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2009 presets.push_back (Plugin::PresetRecord (i->second, i->first));
2012 /* add factory presets */
2014 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2015 presets.push_back (Plugin::PresetRecord ("", i->first));
2024 AUPlugin::has_editor () const
2026 // even if the plugin doesn't have its own editor, the AU API can be used
2027 // to create one that looks native.
2031 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2034 type = ARDOUR::AudioUnit;
2037 AUPluginInfo::~AUPluginInfo ()
2039 type = ARDOUR::AudioUnit;
2043 AUPluginInfo::load (Session& session)
2048 TRACE_API ("load AU as a component\n");
2049 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2051 if (!comp->IsValid()) {
2052 error << ("AudioUnit: not a valid Component") << endmsg;
2054 plugin.reset (new AUPlugin (session.engine(), session, comp));
2057 AUPluginInfo *aup = new AUPluginInfo (*this);
2058 plugin->set_info (PluginInfoPtr (aup));
2059 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2063 catch (failed_constructor &err) {
2064 return PluginPtr ();
2069 AUPluginInfo::au_cache_path ()
2071 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2075 AUPluginInfo::discover ()
2079 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2080 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2083 PluginInfoList* plugs = new PluginInfoList;
2085 discover_fx (*plugs);
2086 discover_music (*plugs);
2087 discover_generators (*plugs);
2088 discover_instruments (*plugs);
2094 AUPluginInfo::discover_music (PluginInfoList& plugs)
2096 CAComponentDescription desc;
2097 desc.componentFlags = 0;
2098 desc.componentFlagsMask = 0;
2099 desc.componentSubType = 0;
2100 desc.componentManufacturer = 0;
2101 desc.componentType = kAudioUnitType_MusicEffect;
2103 discover_by_description (plugs, desc);
2107 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2109 CAComponentDescription desc;
2110 desc.componentFlags = 0;
2111 desc.componentFlagsMask = 0;
2112 desc.componentSubType = 0;
2113 desc.componentManufacturer = 0;
2114 desc.componentType = kAudioUnitType_Effect;
2116 discover_by_description (plugs, desc);
2120 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2122 CAComponentDescription desc;
2123 desc.componentFlags = 0;
2124 desc.componentFlagsMask = 0;
2125 desc.componentSubType = 0;
2126 desc.componentManufacturer = 0;
2127 desc.componentType = kAudioUnitType_Generator;
2129 discover_by_description (plugs, desc);
2133 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2135 CAComponentDescription desc;
2136 desc.componentFlags = 0;
2137 desc.componentFlagsMask = 0;
2138 desc.componentSubType = 0;
2139 desc.componentManufacturer = 0;
2140 desc.componentType = kAudioUnitType_MusicDevice;
2142 discover_by_description (plugs, desc);
2146 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2150 comp = FindNextComponent (NULL, &desc);
2152 while (comp != NULL) {
2153 CAComponentDescription temp;
2154 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2156 AUPluginInfoPtr info (new AUPluginInfo
2157 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2159 /* although apple designed the subtype field to be a "category" indicator,
2160 its really turned into a plugin ID field for a given manufacturer. Hence
2161 there are no categories for AudioUnits. However, to keep the plugins
2162 showing up under "categories", we'll use the "type" as a high level
2165 NOTE: no panners, format converters or i/o AU's for our purposes
2168 switch (info->descriptor->Type()) {
2169 case kAudioUnitType_Panner:
2170 case kAudioUnitType_OfflineEffect:
2171 case kAudioUnitType_FormatConverter:
2174 case kAudioUnitType_Output:
2175 info->category = _("AudioUnit Outputs");
2177 case kAudioUnitType_MusicDevice:
2178 info->category = _("AudioUnit Instruments");
2180 case kAudioUnitType_MusicEffect:
2181 info->category = _("AudioUnit MusicEffects");
2183 case kAudioUnitType_Effect:
2184 info->category = _("AudioUnit Effects");
2186 case kAudioUnitType_Mixer:
2187 info->category = _("AudioUnit Mixers");
2189 case kAudioUnitType_Generator:
2190 info->category = _("AudioUnit Generators");
2193 info->category = _("AudioUnit (Unknown)");
2197 AUPluginInfo::get_names (temp, info->name, info->creator);
2199 info->type = ARDOUR::AudioUnit;
2200 info->unique_id = stringify_descriptor (*info->descriptor);
2202 /* XXX not sure of the best way to handle plugin versioning yet
2205 CAComponent cacomp (*info->descriptor);
2207 if (cacomp.GetResourceVersion (info->version) != noErr) {
2211 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2213 /* here we have to map apple's wildcard system to a simple pair
2214 of values. in ::can_do() we use the whole system, but here
2215 we need a single pair of values. XXX probably means we should
2216 remove any use of these values.
2219 info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
2220 info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
2222 cerr << "detected AU: " << info->name.c_str() << " (" << info->cache.io_configs.size() << " i/o configurations) - " << info->unique_id << endl;
2224 plugs.push_back (info);
2227 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2230 comp = FindNextComponent (comp, &desc);
2235 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2238 AUPluginCachedInfo& cinfo,
2239 const std::string& name)
2244 /* concatenate unique ID with version to provide a key for cached info lookup.
2245 this ensures we don't get stale information, or should if plugin developers
2246 follow Apple "guidelines".
2249 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2254 CachedInfoMap::iterator cim = cached_info.find (id);
2256 if (cim != cached_info.end()) {
2257 cinfo = cim->second;
2262 AUChannelInfo* channel_info;
2266 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2270 if (CAAudioUnit::Open (comp, unit) != noErr) {
2276 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2277 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
2282 TRACE_API ("get AU channel info\n");
2283 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2288 /* no explicit info available */
2290 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2294 /* store each configuration */
2296 for (uint32_t n = 0; n < cnt; ++n) {
2297 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2298 channel_info[n].outChannels));
2301 free (channel_info);
2304 add_cached_info (id, cinfo);
2305 save_cached_info ();
2311 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2313 cached_info[id] = cinfo;
2316 #define AU_CACHE_VERSION "2.0"
2319 AUPluginInfo::save_cached_info ()
2323 node = new XMLNode (X_("AudioUnitPluginCache"));
2324 node->add_property( "version", AU_CACHE_VERSION );
2326 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2327 XMLNode* parent = new XMLNode (X_("plugin"));
2328 parent->add_property ("id", i->first);
2329 node->add_child_nocopy (*parent);
2331 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2333 XMLNode* child = new XMLNode (X_("io"));
2336 snprintf (buf, sizeof (buf), "%d", j->first);
2337 child->add_property (X_("in"), buf);
2338 snprintf (buf, sizeof (buf), "%d", j->second);
2339 child->add_property (X_("out"), buf);
2340 parent->add_child_nocopy (*child);
2345 Glib::ustring path = au_cache_path ();
2348 tree.set_root (node);
2350 if (!tree.write (path)) {
2351 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2352 unlink (path.c_str());
2357 AUPluginInfo::load_cached_info ()
2359 Glib::ustring path = au_cache_path ();
2362 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2366 if ( !tree.read (path) ) {
2367 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2371 const XMLNode* root (tree.root());
2373 if (root->name() != X_("AudioUnitPluginCache")) {
2377 //initial version has incorrectly stored i/o info, and/or garbage chars.
2378 const XMLProperty* version = root->property(X_("version"));
2379 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2380 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2384 cached_info.clear ();
2386 const XMLNodeList children = root->children();
2388 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2390 const XMLNode* child = *iter;
2392 if (child->name() == X_("plugin")) {
2394 const XMLNode* gchild;
2395 const XMLNodeList gchildren = child->children();
2396 const XMLProperty* prop = child->property (X_("id"));
2402 string id = prop->value();
2406 string::size_type slash = id.find_last_of ('/');
2408 if (slash == string::npos) {
2412 version = id.substr (slash);
2413 id = id.substr (0, slash);
2414 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2416 if (fixed.empty()) {
2417 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2424 AUPluginCachedInfo cinfo;
2426 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2430 if (gchild->name() == X_("io")) {
2434 const XMLProperty* iprop;
2435 const XMLProperty* oprop;
2437 if (((iprop = gchild->property (X_("in"))) != 0) &&
2438 ((oprop = gchild->property (X_("out"))) != 0)) {
2439 in = atoi (iprop->value());
2440 out = atoi (oprop->value());
2442 cinfo.io_configs.push_back (pair<int,int> (in, out));
2447 if (cinfo.io_configs.size()) {
2448 add_cached_info (id, cinfo);
2457 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2459 CFStringRef itemName = NULL;
2461 // Marc Poirier-style item name
2462 CAComponent auComponent (comp_desc);
2463 if (auComponent.IsValid()) {
2464 CAComponentDescription dummydesc;
2465 Handle nameHandle = NewHandle(sizeof(void*));
2466 if (nameHandle != NULL) {
2467 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2469 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2470 if (nameString != NULL) {
2471 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2474 DisposeHandle(nameHandle);
2478 // if Marc-style fails, do the original way
2479 if (itemName == NULL) {
2480 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2481 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2482 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2484 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2485 compTypeString, compManufacturerString, compSubTypeString);
2487 if (compTypeString != NULL)
2488 CFRelease(compTypeString);
2489 if (compSubTypeString != NULL)
2490 CFRelease(compSubTypeString);
2491 if (compManufacturerString != NULL)
2492 CFRelease(compManufacturerString);
2495 string str = CFStringRefToStdString(itemName);
2496 string::size_type colon = str.find (':');
2499 name = str.substr (colon+1);
2500 maker = str.substr (0, colon);
2501 strip_whitespace_edges (maker);
2502 strip_whitespace_edges (name);
2506 strip_whitespace_edges (name);
2511 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2515 /* note: OSType is a compiler-implemenation-defined value,
2516 historically a 32 bit integer created with a multi-character
2517 constant such as 'abcd'. It is, fundamentally, an abomination.
2522 s << desc.SubType();
2530 AUPluginInfo::needs_midi_input ()
2532 return is_effect_with_midi_input () || is_instrument ();
2536 AUPluginInfo::is_effect () const
2538 return is_effect_without_midi_input() || is_effect_with_midi_input();
2542 AUPluginInfo::is_effect_without_midi_input () const
2544 return descriptor->IsAUFX();
2548 AUPluginInfo::is_effect_with_midi_input () const
2550 return descriptor->IsAUFM();
2554 AUPluginInfo::is_instrument () const
2556 return descriptor->IsMusicDevice();