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 (
137 outIsPlaying, outTransportStateChanged,
138 outCurrentSampleInTimeLine, outIsCycling,
139 outCycleStartBeat, outCycleEndBeat);
146 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
152 // Convert the property list into XML data.
154 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
157 error << _("Could not create XML version of property list") << endmsg;
161 // Write the XML data to the file.
163 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
165 if (errno == EEXIST) {
166 error << string_compose (_("Preset file %1 exists; not overwriting"),
169 error << string_compose (_("Cannot open preset file %1 (%2)"),
170 path, strerror (errno)) << endmsg;
176 size_t cnt = CFDataGetLength (xmlData);
178 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
189 static CFPropertyListRef
190 load_property_list (Glib::ustring path)
193 CFPropertyListRef propertyList = 0;
195 CFStringRef errorString;
197 // Read the XML file.
199 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
204 off_t len = lseek (fd, 0, SEEK_END);
205 char* buf = new char[len];
206 lseek (fd, 0, SEEK_SET);
208 if (read (fd, buf, len) != len) {
216 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
218 // Reconstitute the dictionary using the XML data.
220 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
222 kCFPropertyListImmutable,
231 //-----------------------------------------------------------------------------
233 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
238 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
240 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
241 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
247 //-----------------------------------------------------------------------------
249 get_preset_name_in_plist (CFPropertyListRef plist)
257 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
258 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
260 CFStringRef str = (CFStringRef) p;
261 int len = CFStringGetLength(str);
263 char local_buffer[len];
264 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
272 //--------------------------------------------------------------------------
273 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
274 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
275 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
276 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
278 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
281 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
282 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
284 // only sub-type and manufacturer IDs need to be equal
287 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
288 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
295 //--------------------------------------------------------------------------
296 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
297 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
298 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
299 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
302 ComponentDescription desc;
304 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
307 // get the ComponentDescription of the input Component
308 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
312 // check if the Component's ComponentDescription matches the input ComponentDescription
313 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
316 //--------------------------------------------------------------------------
317 // determine if 2 ComponentDescriptions are basically equal
318 // (by that, I mean that the important identifying values are compared,
319 // but not the ComponentDescription flags)
320 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
322 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
325 //--------------------------------------------------------------------------
326 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
327 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
329 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
332 //--------------------------------------------------------------------------
333 // determine if a ComponentDescription basically matches that of a particular Component
334 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
336 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
339 //--------------------------------------------------------------------------
340 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
341 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
343 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
347 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
348 : Plugin (engine, session)
350 , unit (new CAAudioUnit)
351 , initialized (false)
352 , _current_block_size (0)
353 , _requires_fixed_size_buffers (false)
357 , current_buffers (0)
358 , frames_processed (0)
359 , last_transport_rolling (false)
360 , last_transport_speed (0.0)
362 if (!preset_search_path_initialized) {
363 Glib::ustring p = Glib::get_home_dir();
364 p += "/Library/Audio/Presets:";
365 p += preset_search_path;
366 preset_search_path = p;
367 preset_search_path_initialized = true;
374 AUPlugin::AUPlugin (const AUPlugin& other)
376 , comp (other.get_comp())
377 , unit (new CAAudioUnit)
378 , initialized (false)
379 , _current_block_size (0)
381 , _requires_fixed_size_buffers (false)
385 , current_buffers (0)
386 , frames_processed (0)
392 AUPlugin::~AUPlugin ()
395 TRACE_API ("about to call uninitialize in plugin destructor\n");
396 unit->Uninitialize ();
405 AUPlugin::discover_factory_presets ()
408 UInt32 dataSize = sizeof (presets);
411 TRACE_API ("get property FactoryPresets in global scope\n");
412 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
413 cerr << "cannot get factory preset info: " << err << endl;
421 CFIndex cnt = CFArrayGetCount (presets);
423 for (CFIndex i = 0; i < cnt; ++i) {
424 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
426 string name = CFStringRefToStdString (preset->presetName);
427 factory_preset_map[name] = preset->presetNumber;
439 TRACE_API ("opening AudioUnit\n");
440 err = CAAudioUnit::Open (*(comp.get()), *unit);
442 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
443 throw failed_constructor();
447 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
448 throw failed_constructor ();
451 TRACE_API ("count global elements\n");
452 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
453 TRACE_API ("count input elements\n");
454 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
455 TRACE_API ("count output elements\n");
456 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
458 if (input_elements > 0) {
459 AURenderCallbackStruct renderCallbackInfo;
461 renderCallbackInfo.inputProc = _render_callback;
462 renderCallbackInfo.inputProcRefCon = this;
464 TRACE_API ("set render callback in input scope\n");
465 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
466 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
467 cerr << "cannot install render callback (err = " << err << ')' << endl;
468 throw failed_constructor();
472 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
474 HostCallbackInfo info;
475 memset (&info, 0, sizeof (HostCallbackInfo));
476 info.hostUserData = this;
477 info.beatAndTempoProc = _get_beat_and_tempo_callback;
478 info.musicalTimeLocationProc = _get_musical_time_location_callback;
479 info.transportStateProc = _get_transport_state_callback;
481 //ignore result of this - don't care if the property isn't supported
482 TRACE_API ("set host callbacks in global scope\n");
483 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
484 kAudioUnitScope_Global,
487 sizeof (HostCallbackInfo));
489 /* these keep track of *configured* channel set up,
490 not potential set ups.
494 output_channels = -1;
496 if (set_block_size (_session.get_block_size())) {
497 error << _("AUPlugin: cannot set processing block size") << endmsg;
498 throw failed_constructor();
501 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
502 _has_midi_input = pinfo->needs_midi_input ();
503 _has_midi_output = false;
505 discover_parameters ();
506 discover_factory_presets ();
508 // Plugin::setup_controls ();
512 AUPlugin::discover_parameters ()
514 /* discover writable parameters */
516 AudioUnitScope scopes[] = {
517 kAudioUnitScope_Global,
518 kAudioUnitScope_Output,
519 kAudioUnitScope_Input
522 descriptors.clear ();
524 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
526 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
528 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
530 AUParameterDescriptor d;
532 d.id = param_info.ParamID (i);
534 const CAAUParameter* param = param_info.GetParamInfo (d.id);
535 const AudioUnitParameterInfo& info (param->ParamInfo());
537 const int len = CFStringGetLength (param->GetName());;
538 char local_buffer[len*2];
539 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
543 d.label = local_buffer;
546 d.scope = param_info.GetScope ();
547 d.element = param_info.GetElement ();
549 /* info.units to consider */
551 kAudioUnitParameterUnit_Generic = 0
552 kAudioUnitParameterUnit_Indexed = 1
553 kAudioUnitParameterUnit_Boolean = 2
554 kAudioUnitParameterUnit_Percent = 3
555 kAudioUnitParameterUnit_Seconds = 4
556 kAudioUnitParameterUnit_SampleFrames = 5
557 kAudioUnitParameterUnit_Phase = 6
558 kAudioUnitParameterUnit_Rate = 7
559 kAudioUnitParameterUnit_Hertz = 8
560 kAudioUnitParameterUnit_Cents = 9
561 kAudioUnitParameterUnit_RelativeSemiTones = 10
562 kAudioUnitParameterUnit_MIDINoteNumber = 11
563 kAudioUnitParameterUnit_MIDIController = 12
564 kAudioUnitParameterUnit_Decibels = 13
565 kAudioUnitParameterUnit_LinearGain = 14
566 kAudioUnitParameterUnit_Degrees = 15
567 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
568 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
569 kAudioUnitParameterUnit_Pan = 18
570 kAudioUnitParameterUnit_Meters = 19
571 kAudioUnitParameterUnit_AbsoluteCents = 20
572 kAudioUnitParameterUnit_Octaves = 21
573 kAudioUnitParameterUnit_BPM = 22
574 kAudioUnitParameterUnit_Beats = 23
575 kAudioUnitParameterUnit_Milliseconds = 24
576 kAudioUnitParameterUnit_Ratio = 25
579 /* info.flags to consider */
583 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
584 kAudioUnitParameterFlag_HasClump = (1L << 20)
585 kAudioUnitParameterFlag_HasName = (1L << 21)
586 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
587 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
588 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
589 kAudioUnitParameterFlag_CanRamp = (1L << 25)
590 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
591 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
592 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
593 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
594 kAudioUnitParameterFlag_IsReadable = (1L << 30)
595 kAudioUnitParameterFlag_IsWritable = (1L << 31)
598 d.lower = info.minValue;
599 d.upper = info.maxValue;
600 d.default_value = info.defaultValue;
602 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
603 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
604 (d.integer_step && ((d.upper - d.lower) == 1.0));
605 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
606 d.automatable = !d.toggled &&
607 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
608 (info.flags & kAudioUnitParameterFlag_IsWritable);
610 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
616 d.min_unbound = 0; // lower is bound
617 d.max_unbound = 0; // upper is bound
619 descriptors.push_back (d);
626 four_ints_to_four_byte_literal (unsigned char n[4])
628 /* this is actually implementation dependent. sigh. this is what gcc
629 and quite a few others do.
631 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
635 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
637 if (isdigit (id[0])) {
641 /* ID format is xxxx-xxxx-xxxx
642 where x maybe \xNN or a printable character.
644 Split at the '-' and and process each part into an integer.
645 Then put it back together.
649 unsigned char nascent[4];
650 const char* cstr = id.c_str();
651 const char* estr = cstr + id.size();
662 while (*cstr && next_int < 4) {
666 if (estr - cstr < 3) {
668 /* too close to the end for \xNN parsing: treat as literal characters */
670 cerr << "Parse " << cstr << " as a literal \\" << endl;
677 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
681 memcpy (short_buf, &cstr[2], 2);
682 nascent[in] = strtol (short_buf, NULL, 16);
688 /* treat as literal characters */
689 cerr << "Parse " << cstr << " as a literal \\" << endl;
703 if (in && (in % 4 == 0)) {
704 /* nascent is ready */
705 n[next_int] = four_ints_to_four_byte_literal (nascent);
709 /* swallow space-hyphen-space */
723 s << n[0] << '-' << n[1] << '-' << n[2];
732 AUPlugin::unique_id () const
734 return AUPluginInfo::stringify_descriptor (comp->Desc());
738 AUPlugin::label () const
740 return _info->name.c_str();
744 AUPlugin::parameter_count () const
746 return descriptors.size();
750 AUPlugin::default_value (uint32_t port)
752 if (port < descriptors.size()) {
753 return descriptors[port].default_value;
760 AUPlugin::signal_latency () const
762 return unit->Latency() * _session.frame_rate();
766 AUPlugin::set_parameter (uint32_t which, float val)
768 if (which >= descriptors.size()) {
772 const AUParameterDescriptor& d (descriptors[which]);
773 TRACE_API ("set parameter %d in scope %d element %d to %f\n", d.id, d.scope, d.element, val);
774 unit->SetParameter (d.id, d.scope, d.element, val);
776 /* tell the world what we did */
778 AudioUnitEvent theEvent;
780 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
781 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
782 theEvent.mArgument.mParameter.mParameterID = d.id;
783 theEvent.mArgument.mParameter.mScope = d.scope;
784 theEvent.mArgument.mParameter.mElement = d.element;
786 TRACE_API ("notify about parameter change\n");
787 AUEventListenerNotify (NULL, NULL, &theEvent);
789 Plugin::set_parameter (which, val);
793 AUPlugin::get_parameter (uint32_t which) const
796 if (which < descriptors.size()) {
797 const AUParameterDescriptor& d (descriptors[which]);
798 TRACE_API ("get value of parameter %d in scope %d element %d\n", d.id, d.scope, d.element);
799 unit->GetParameter(d.id, d.scope, d.element, val);
805 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
807 if (which < descriptors.size()) {
808 pd = descriptors[which];
815 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
817 if (which < descriptors.size()) {
826 AUPlugin::activate ()
830 TRACE_API ("call Initialize in activate()\n");
831 if ((err = unit->Initialize()) != noErr) {
832 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
834 frames_processed = 0;
841 AUPlugin::deactivate ()
843 TRACE_API ("call Uninitialize in deactivate()\n");
844 unit->Uninitialize ();
851 TRACE_API ("call Reset in flush()\n");
852 unit->GlobalReset ();
856 AUPlugin::requires_fixed_size_buffers() const
858 return _requires_fixed_size_buffers;
863 AUPlugin::set_block_size (pframes_t nframes)
865 bool was_initialized = initialized;
866 UInt32 numFrames = nframes;
873 TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
874 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
875 0, &numFrames, sizeof (numFrames))) != noErr) {
876 cerr << "cannot set max frames (err = " << err << ')' << endl;
880 if (was_initialized) {
884 _current_block_size = nframes;
890 AUPlugin::configure_io (ChanCount in, ChanCount out)
892 AudioStreamBasicDescription streamFormat;
893 bool was_initialized = initialized;
894 int32_t audio_in = in.n_audio();
895 int32_t audio_out = out.n_audio();
898 //if we are already running with the requested i/o config, bail out here
899 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
906 streamFormat.mSampleRate = _session.frame_rate();
907 streamFormat.mFormatID = kAudioFormatLinearPCM;
908 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
910 #ifdef __LITTLE_ENDIAN__
913 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
916 streamFormat.mBitsPerChannel = 32;
917 streamFormat.mFramesPerPacket = 1;
919 /* apple says that for non-interleaved data, these
920 values always refer to a single channel.
922 streamFormat.mBytesPerPacket = 4;
923 streamFormat.mBytesPerFrame = 4;
925 streamFormat.mChannelsPerFrame = audio_in;
927 if (set_input_format (streamFormat) != 0) {
931 streamFormat.mChannelsPerFrame = audio_out;
933 if (set_output_format (streamFormat) != 0) {
937 if (was_initialized) {
945 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
947 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
948 // attempt to multiply-instantiate plugins to meet io configurations.
950 int32_t audio_in = in.n_audio();
952 int32_t plugcnt = -1;
953 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
955 /* lets check MIDI first */
957 if (in.n_midi() > 0) {
958 if (!_has_midi_input) {
963 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
965 if (debug_io_config) {
966 cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
969 //Ardour expects the plugin to tell it the output configuration
970 //but AU plugins can have multiple I/O configurations
971 //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
972 //so first lets see if there's a configuration that keeps out==in
974 audio_out = audio_in;
976 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
977 int32_t possible_in = i->first;
978 int32_t possible_out = i->second;
980 if (possible_in == audio_in && possible_out== audio_out) {
981 cerr << "\tCHOSEN: in " << in << " out " << out << endl;
986 /* now allow potentially "imprecise" matches */
988 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
990 int32_t possible_in = i->first;
991 int32_t possible_out = i->second;
993 if (debug_io_config) {
994 cerr << "\tin " << possible_in << " out " << possible_out << endl;
997 if (possible_out == 0) {
998 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1002 if (possible_in == 0) {
1004 /* instrument plugin, always legal but throws away inputs ...
1007 if (possible_out == -1) {
1008 /* out much match in (UNLIKELY!!) */
1009 audio_out = audio_in;
1011 } else if (possible_out == -2) {
1012 /* any configuration possible, pick matching */
1013 audio_out = audio_in;
1015 } else if (possible_out < -2) {
1016 /* explicit variable number of outputs, pick maximum */
1017 audio_out = -possible_out;
1020 /* exact number of outputs */
1021 audio_out = possible_out;
1026 if (possible_in == -1) {
1028 /* wildcard for input */
1030 if (possible_out == -1) {
1031 /* out much match in */
1032 audio_out = audio_in;
1034 } else if (possible_out == -2) {
1035 /* any configuration possible, pick matching */
1036 audio_out = audio_in;
1038 } else if (possible_out < -2) {
1039 /* explicit variable number of outputs, pick maximum */
1040 audio_out = -possible_out;
1043 /* exact number of outputs */
1044 audio_out = possible_out;
1049 if (possible_in == -2) {
1051 if (possible_out == -1) {
1052 /* any configuration possible, pick matching */
1053 audio_out = audio_in;
1055 } else if (possible_out == -2) {
1056 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1059 } else if (possible_out < -2) {
1060 /* explicit variable number of outputs, pick maximum */
1061 audio_out = -possible_out;
1064 /* exact number of outputs */
1065 audio_out = possible_out;
1070 if (possible_in < -2) {
1072 /* explicit variable number of inputs */
1074 if (audio_in > -possible_in) {
1075 /* request is too large */
1079 if (possible_out == -1) {
1080 /* out must match in */
1081 audio_out = audio_in;
1083 } else if (possible_out == -2) {
1084 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1087 } else if (possible_out < -2) {
1088 /* explicit variable number of outputs, pick maximum */
1089 audio_out = -possible_out;
1092 /* exact number of outputs */
1093 audio_out = possible_out;
1098 if (possible_in == audio_in) {
1100 /* exact number of inputs ... must match obviously */
1102 if (possible_out == -1) {
1103 /* out must match in */
1104 audio_out = audio_in;
1106 } else if (possible_out == -2) {
1107 /* any output configuration, pick matching */
1108 audio_out = audio_in;
1110 } else if (possible_out < -2) {
1111 /* explicit variable number of outputs, pick maximum */
1112 audio_out = -possible_out;
1115 /* exact number of outputs */
1116 audio_out = possible_out;
1127 if (debug_io_config) {
1129 cerr << "\tCHOSEN: in " << in << " out " << out << " plugcnt will be " << plugcnt << endl;
1131 cerr << "\tFAIL: no configs match requested in " << in << endl;
1135 out.set (DataType::MIDI, 0);
1136 out.set (DataType::AUDIO, audio_out);
1142 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1144 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1148 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1150 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1159 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1160 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1162 Glib::Mutex::Lock em (_session.engine().process_lock());
1163 IO::PortCountChanged (ChanCount(DataType::AUDIO, fmt.mChannelsPerFrame));
1169 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1173 for (uint32_t i = 0; i < cnt; ++i) {
1174 TRACE_API ("set stream format for %s, scope = %d element %d\n",
1175 (scope == kAudioUnitScope_Input ? "input" : "output"),
1177 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1178 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1179 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1184 if (scope == kAudioUnitScope_Input) {
1185 input_channels = fmt.mChannelsPerFrame;
1187 output_channels = fmt.mChannelsPerFrame;
1194 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1195 const AudioTimeStamp*,
1197 UInt32 inNumberFrames,
1198 AudioBufferList* ioData)
1200 if (_has_midi_input) {
1201 assert (current_buffers->count().n_midi() > 0);
1203 /* deliver the first (and assumed only) MIDI buffer's data
1207 MidiBuffer& mb (current_buffers->get_midi(0));
1209 for (MidiBuffer::iterator i = mb.begin(); i != mb.end(); ++i) {
1210 Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *i;
1211 switch (ev.type()) {
1212 case MIDI_CMD_NOTE_ON:
1213 case MIDI_CMD_NOTE_OFF:
1214 case MIDI_CMD_CONTROL:
1215 case MIDI_CMD_BENDER:
1216 case MIDI_CMD_PGM_CHANGE:
1217 case MIDI_CMD_CHANNEL_PRESSURE:
1219 const uint8_t* b = ev.buffer();
1220 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1225 /* plugins do not get other stuff by default */
1231 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1233 if (current_maxbuf == 0) {
1234 error << _("AUPlugin: render callback called illegally!") << endmsg;
1235 return kAudioUnitErr_CannotDoInCurrentContext;
1237 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
1239 for (uint32_t i = 0; i < limit; ++i) {
1240 ioData->mBuffers[i].mNumberChannels = 1;
1241 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1243 /* we don't use the channel mapping because audiounits are
1244 never replicated. one plugin instance uses all channels/buffers
1245 passed to PluginInsert::connect_and_run()
1248 ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
1251 cb_offset += inNumberFrames;
1257 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1259 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1261 AudioUnitRenderActionFlags flags = 0;
1264 uint32_t maxbuf = bufs.count().n_audio();
1266 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1267 unit->GlobalReset();
1268 _last_nframes = nframes;
1271 current_buffers = &bufs;
1272 current_maxbuf = maxbuf;
1273 current_offset = offset;
1276 buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
1278 for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
1279 buffers->mBuffers[i].mNumberChannels = 1;
1280 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1281 buffers->mBuffers[i].mData = 0;
1284 ts.mSampleTime = frames_processed;
1285 ts.mFlags = kAudioTimeStampSampleTimeValid;
1287 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1290 frames_processed += nframes;
1292 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1295 for (i = 0; i < limit; ++i) {
1296 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1297 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1298 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1299 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1303 /* now silence any buffers that were passed in but the that the plugin
1304 did not fill/touch/use.
1307 for (;i < maxbuf; ++i) {
1308 Sample* buffer_address= bufs.get_audio (i).data (offset);
1309 memset (buffer_address, 0, nframes * sizeof (Sample));
1315 cerr << name() << " render status " << err << endl;
1320 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1321 Float64* outCurrentTempo)
1323 TempoMap& tmap (_session.tempo_map());
1325 TRACE_API ("AU calls ardour beat&tempo callback\n");
1327 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1328 (and interpretation) of a beat position will be incorrect. So refuse to
1332 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1333 return kAudioUnitErr_CannotDoInCurrentContext;
1336 Timecode::BBT_Time bbt;
1337 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1338 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1340 if (outCurrentBeat) {
1342 beat = metric.meter().beats_per_bar() * bbt.bars;
1344 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1345 *outCurrentBeat = beat;
1348 if (outCurrentTempo) {
1349 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1357 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1358 Float32* outTimeSig_Numerator,
1359 UInt32* outTimeSig_Denominator,
1360 Float64* outCurrentMeasureDownBeat)
1362 TempoMap& tmap (_session.tempo_map());
1364 TRACE_API ("AU calls ardour music time location callback\n");
1366 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1367 (and interpretation) of a beat position will be incorrect. So refuse to
1371 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1372 return kAudioUnitErr_CannotDoInCurrentContext;
1375 Timecode::BBT_Time bbt;
1376 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1377 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1379 if (outDeltaSampleOffsetToNextBeat) {
1380 if (bbt.ticks == 0) {
1382 *outDeltaSampleOffsetToNextBeat = 0;
1384 *outDeltaSampleOffsetToNextBeat = (UInt32)
1385 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1386 metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1390 if (outTimeSig_Numerator) {
1391 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1393 if (outTimeSig_Denominator) {
1394 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1397 if (outCurrentMeasureDownBeat) {
1399 /* beat for the start of the bar.
1401 2|1|0 -> 1 + beats_per_bar
1402 3|1|0 -> 1 + (2 * beats_per_bar)
1406 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1413 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1414 Boolean* outTransportStateChanged,
1415 Float64* outCurrentSampleInTimeLine,
1416 Boolean* outIsCycling,
1417 Float64* outCycleStartBeat,
1418 Float64* outCycleEndBeat)
1423 TRACE_API ("AU calls ardour transport state callback\n");
1425 rolling = _session.transport_rolling();
1426 speed = _session.transport_speed ();
1429 *outIsPlaying = _session.transport_rolling();
1432 if (outTransportStateChanged) {
1433 if (rolling != last_transport_rolling) {
1434 *outTransportStateChanged = true;
1435 } else if (speed != last_transport_speed) {
1436 *outTransportStateChanged = true;
1438 *outTransportStateChanged = false;
1442 if (outCurrentSampleInTimeLine) {
1443 /* this assumes that the AU can only call this host callback from render context,
1444 where current_offset is valid.
1446 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1450 Location* loc = _session.locations()->auto_loop_location();
1452 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1454 if (*outIsCycling) {
1456 if (outCycleStartBeat || outCycleEndBeat) {
1458 TempoMap& tmap (_session.tempo_map());
1460 /* more than 1 meter means that a simplistic computation (and interpretation) of
1461 a beat position will be incorrect. so refuse to offer the value.
1464 if (tmap.n_meters() > 1) {
1465 return kAudioUnitErr_CannotDoInCurrentContext;
1468 Timecode::BBT_Time bbt;
1470 if (outCycleStartBeat) {
1471 TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
1472 _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1475 beat = metric.meter().beats_per_bar() * bbt.bars;
1477 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1479 *outCycleStartBeat = beat;
1482 if (outCycleEndBeat) {
1483 TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
1484 _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1487 beat = metric.meter().beats_per_bar() * bbt.bars;
1489 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1491 *outCycleEndBeat = beat;
1497 last_transport_rolling = rolling;
1498 last_transport_speed = speed;
1503 set<Evoral::Parameter>
1504 AUPlugin::automatable() const
1506 set<Evoral::Parameter> automates;
1508 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1509 if (descriptors[i].automatable) {
1510 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1518 AUPlugin::describe_parameter (Evoral::Parameter param)
1520 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1521 return descriptors[param.id()].label;
1528 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1530 // NameValue stuff here
1534 AUPlugin::parameter_is_audio (uint32_t) const
1540 AUPlugin::parameter_is_control (uint32_t) const
1546 AUPlugin::parameter_is_input (uint32_t) const
1552 AUPlugin::parameter_is_output (uint32_t) const
1558 AUPlugin::add_state (XMLNode* root) const
1560 LocaleGuard lg (X_("POSIX"));
1562 #ifdef AU_STATE_SUPPORT
1564 CFPropertyListRef propertyList;
1566 TRACE_API ("get preset state\n");
1567 if (unit->GetAUPreset (propertyList) != noErr) {
1571 // Convert the property list into XML data.
1573 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1576 error << _("Could not create XML version of property list") << endmsg;
1580 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1581 our state node. GACK!
1586 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1588 root->add_child_copy (*t.root());
1592 CFRelease (xmlData);
1593 CFRelease (propertyList);
1595 if (!seen_get_state_message) {
1596 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1599 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);
1653 Plugin::set_state (node, version);
1656 if (!seen_set_state_message) {
1657 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1661 return Plugin::set_state (node, version);
1666 AUPlugin::load_preset (PresetRecord r)
1668 Plugin::load_preset (r);
1670 #ifdef AU_STATE_SUPPORT
1672 CFPropertyListRef propertyList;
1674 UserPresetMap::iterator ux;
1675 FactoryPresetMap::iterator fx;
1677 /* look first in "user" presets */
1679 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1681 if ((propertyList = load_property_list (ux->second)) != 0) {
1682 TRACE_API ("set preset from user presets\n");
1683 if (unit->SetAUPreset (propertyList) == noErr) {
1686 /* tell the world */
1688 AudioUnitParameter changedUnit;
1689 changedUnit.mAudioUnit = unit->AU();
1690 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1691 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1693 CFRelease(propertyList);
1696 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1700 preset.presetNumber = fx->second;
1701 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1703 TRACE_API ("set preset from factory presets\n");
1705 if (unit->SetPresentPreset (preset) == 0) {
1708 /* tell the world */
1710 AudioUnitParameter changedUnit;
1711 changedUnit.mAudioUnit = unit->AU();
1712 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1713 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1719 if (!seen_loading_message) {
1720 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1723 seen_loading_message = true;
1730 AUPlugin::do_remove_preset (std::string)
1735 AUPlugin::do_save_preset (string preset_name)
1737 #ifdef AU_STATE_SUPPORT
1738 CFPropertyListRef propertyList;
1739 vector<Glib::ustring> v;
1740 Glib::ustring user_preset_path;
1743 std::string m = maker();
1744 std::string n = name();
1746 strip_whitespace_edges (m);
1747 strip_whitespace_edges (n);
1749 v.push_back (Glib::get_home_dir());
1750 v.push_back ("Library");
1751 v.push_back ("Audio");
1752 v.push_back ("Presets");
1756 user_preset_path = Glib::build_filename (v);
1758 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1759 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1763 TRACE_API ("get current preset\n");
1764 if (unit->GetAUPreset (propertyList) != noErr) {
1768 // add the actual preset name */
1770 v.push_back (preset_name + preset_suffix);
1774 user_preset_path = Glib::build_filename (v);
1776 set_preset_name_in_plist (propertyList, preset_name);
1778 if (save_property_list (propertyList, user_preset_path)) {
1779 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1783 CFRelease(propertyList);
1785 return string ("file:///") + user_preset_path;
1787 if (!seen_saving_message) {
1788 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1791 seen_saving_message = true;
1797 //-----------------------------------------------------------------------------
1798 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1800 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1802 CFNumberRef cfNumber;
1803 SInt32 numberValue = 0;
1804 Boolean dummySuccess;
1806 if (outSuccess == NULL)
1807 outSuccess = &dummySuccess;
1808 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1810 *outSuccess = FALSE;
1814 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1815 if (cfNumber == NULL)
1817 *outSuccess = FALSE;
1820 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1828 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1830 CFDictionaryRef auStateDictionary;
1831 ComponentDescription tempDesc = {0,0,0,0,0};
1832 SInt32 versionValue;
1835 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1838 // the property list for AU state data must be of the dictionary type
1839 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1840 return kAudioUnitErr_InvalidPropertyValue;
1843 auStateDictionary = (CFDictionaryRef)inAUStateData;
1845 // first check to make sure that the version of the AU state data is one that we know understand
1846 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1847 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1850 return kAudioUnitErr_InvalidPropertyValue;
1852 #define kCurrentSavedStateVersion 0
1853 if (versionValue != kCurrentSavedStateVersion) {
1854 return kAudioUnitErr_InvalidPropertyValue;
1857 // grab the ComponentDescription values from the AU state data
1858 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1859 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1860 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1861 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1862 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1863 return kAudioUnitErr_InvalidPropertyValue;
1865 *outComponentDescription = tempDesc;
1870 static bool au_preset_filter (const string& str, void* arg)
1872 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1876 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1880 /* check the preset file path name against this plugin
1881 ID. The idea is that all preset files for this plugin
1882 include "<manufacturer>/<plugin-name>" in their path.
1885 Plugin* p = (Plugin *) arg;
1886 string match = p->maker();
1890 ret = str.find (match) != string::npos;
1893 string m = p->maker ();
1894 string n = p->name ();
1895 strip_whitespace_edges (m);
1896 strip_whitespace_edges (n);
1901 ret = str.find (match) != string::npos;
1909 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1912 CFPropertyListRef plist;
1913 ComponentDescription presetDesc;
1916 plist = load_property_list (pathstr);
1922 // get the ComponentDescription from the AU preset file
1924 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1926 if (status == noErr) {
1927 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1929 /* try to get the preset name from the property list */
1931 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1933 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1937 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1940 char buf[PATH_MAX+1];
1942 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1957 AUPlugin::current_preset() const
1961 #ifdef AU_STATE_SUPPORT
1962 CFPropertyListRef propertyList;
1964 TRACE_API ("get current preset for current_preset()\n");
1965 if (unit->GetAUPreset (propertyList) == noErr) {
1966 preset_name = get_preset_name_in_plist (propertyList);
1967 CFRelease(propertyList);
1974 AUPlugin::find_presets ()
1976 #ifdef AU_STATE_SUPPORT
1977 vector<string*>* preset_files;
1978 PathScanner scanner;
1980 user_preset_map.clear ();
1982 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1984 if (!preset_files) {
1988 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1990 string path = *(*x);
1993 /* make an initial guess at the preset name using the path */
1995 preset_name = Glib::path_get_basename (path);
1996 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1998 /* check that this preset file really matches this plugin
1999 and potentially get the "real" preset name from
2003 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2004 user_preset_map[preset_name] = path;
2010 delete preset_files;
2012 /* now fill the vector<string> with the names we have */
2014 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2015 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2018 /* add factory presets */
2020 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2022 string const uri = string_compose ("%1", _presets.size ());
2023 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first)));
2030 AUPlugin::has_editor () const
2032 // even if the plugin doesn't have its own editor, the AU API can be used
2033 // to create one that looks native.
2037 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2040 type = ARDOUR::AudioUnit;
2043 AUPluginInfo::~AUPluginInfo ()
2045 type = ARDOUR::AudioUnit;
2049 AUPluginInfo::load (Session& session)
2054 TRACE_API ("load AU as a component\n");
2055 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2057 if (!comp->IsValid()) {
2058 error << ("AudioUnit: not a valid Component") << endmsg;
2060 plugin.reset (new AUPlugin (session.engine(), session, comp));
2063 AUPluginInfo *aup = new AUPluginInfo (*this);
2064 plugin->set_info (PluginInfoPtr (aup));
2065 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2069 catch (failed_constructor &err) {
2070 return PluginPtr ();
2075 AUPluginInfo::au_cache_path ()
2077 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2081 AUPluginInfo::discover ()
2085 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2086 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2089 PluginInfoList* plugs = new PluginInfoList;
2092 discover_fx (*plugs);
2093 discover_music (*plugs);
2094 discover_generators (*plugs);
2095 discover_instruments (*plugs);
2102 AUPluginInfo::discover_music (PluginInfoList& plugs)
2104 CAComponentDescription desc;
2105 desc.componentFlags = 0;
2106 desc.componentFlagsMask = 0;
2107 desc.componentSubType = 0;
2108 desc.componentManufacturer = 0;
2109 desc.componentType = kAudioUnitType_MusicEffect;
2111 discover_by_description (plugs, desc);
2115 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2117 CAComponentDescription desc;
2118 desc.componentFlags = 0;
2119 desc.componentFlagsMask = 0;
2120 desc.componentSubType = 0;
2121 desc.componentManufacturer = 0;
2122 desc.componentType = kAudioUnitType_Effect;
2124 discover_by_description (plugs, desc);
2128 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2130 CAComponentDescription desc;
2131 desc.componentFlags = 0;
2132 desc.componentFlagsMask = 0;
2133 desc.componentSubType = 0;
2134 desc.componentManufacturer = 0;
2135 desc.componentType = kAudioUnitType_Generator;
2137 discover_by_description (plugs, desc);
2141 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2143 CAComponentDescription desc;
2144 desc.componentFlags = 0;
2145 desc.componentFlagsMask = 0;
2146 desc.componentSubType = 0;
2147 desc.componentManufacturer = 0;
2148 desc.componentType = kAudioUnitType_MusicDevice;
2150 discover_by_description (plugs, desc);
2154 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2158 comp = FindNextComponent (NULL, &desc);
2160 while (comp != NULL) {
2161 CAComponentDescription temp;
2162 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2164 AUPluginInfoPtr info (new AUPluginInfo
2165 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2167 /* although apple designed the subtype field to be a "category" indicator,
2168 its really turned into a plugin ID field for a given manufacturer. Hence
2169 there are no categories for AudioUnits. However, to keep the plugins
2170 showing up under "categories", we'll use the "type" as a high level
2173 NOTE: no panners, format converters or i/o AU's for our purposes
2176 switch (info->descriptor->Type()) {
2177 case kAudioUnitType_Panner:
2178 case kAudioUnitType_OfflineEffect:
2179 case kAudioUnitType_FormatConverter:
2182 case kAudioUnitType_Output:
2183 info->category = _("AudioUnit Outputs");
2185 case kAudioUnitType_MusicDevice:
2186 info->category = _("AudioUnit Instruments");
2188 case kAudioUnitType_MusicEffect:
2189 info->category = _("AudioUnit MusicEffects");
2191 case kAudioUnitType_Effect:
2192 info->category = _("AudioUnit Effects");
2194 case kAudioUnitType_Mixer:
2195 info->category = _("AudioUnit Mixers");
2197 case kAudioUnitType_Generator:
2198 info->category = _("AudioUnit Generators");
2201 info->category = _("AudioUnit (Unknown)");
2205 AUPluginInfo::get_names (temp, info->name, info->creator);
2207 info->type = ARDOUR::AudioUnit;
2208 info->unique_id = stringify_descriptor (*info->descriptor);
2210 /* XXX not sure of the best way to handle plugin versioning yet
2213 CAComponent cacomp (*info->descriptor);
2215 if (cacomp.GetResourceVersion (info->version) != noErr) {
2219 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2221 /* here we have to map apple's wildcard system to a simple pair
2222 of values. in ::can_do() we use the whole system, but here
2223 we need a single pair of values. XXX probably means we should
2224 remove any use of these values.
2227 info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
2228 info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
2230 cerr << "detected AU: " << info->name.c_str() << " (" << info->cache.io_configs.size() << " i/o configurations) - " << info->unique_id << endl;
2232 plugs.push_back (info);
2235 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2238 comp = FindNextComponent (comp, &desc);
2243 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2246 AUPluginCachedInfo& cinfo,
2247 const std::string& name)
2252 /* concatenate unique ID with version to provide a key for cached info lookup.
2253 this ensures we don't get stale information, or should if plugin developers
2254 follow Apple "guidelines".
2257 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2262 CachedInfoMap::iterator cim = cached_info.find (id);
2264 if (cim != cached_info.end()) {
2265 cinfo = cim->second;
2270 AUChannelInfo* channel_info;
2274 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2278 if (CAAudioUnit::Open (comp, unit) != noErr) {
2284 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2285 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
2290 TRACE_API ("get AU channel info\n");
2291 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2296 /* no explicit info available */
2298 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2302 /* store each configuration */
2304 for (uint32_t n = 0; n < cnt; ++n) {
2305 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2306 channel_info[n].outChannels));
2309 free (channel_info);
2312 add_cached_info (id, cinfo);
2313 save_cached_info ();
2319 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2321 cached_info[id] = cinfo;
2324 #define AU_CACHE_VERSION "2.0"
2327 AUPluginInfo::save_cached_info ()
2331 node = new XMLNode (X_("AudioUnitPluginCache"));
2332 node->add_property( "version", AU_CACHE_VERSION );
2334 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2335 XMLNode* parent = new XMLNode (X_("plugin"));
2336 parent->add_property ("id", i->first);
2337 node->add_child_nocopy (*parent);
2339 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2341 XMLNode* child = new XMLNode (X_("io"));
2344 snprintf (buf, sizeof (buf), "%d", j->first);
2345 child->add_property (X_("in"), buf);
2346 snprintf (buf, sizeof (buf), "%d", j->second);
2347 child->add_property (X_("out"), buf);
2348 parent->add_child_nocopy (*child);
2353 Glib::ustring path = au_cache_path ();
2356 tree.set_root (node);
2358 if (!tree.write (path)) {
2359 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2360 unlink (path.c_str());
2365 AUPluginInfo::load_cached_info ()
2367 Glib::ustring path = au_cache_path ();
2370 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2374 if ( !tree.read (path) ) {
2375 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2379 const XMLNode* root (tree.root());
2381 if (root->name() != X_("AudioUnitPluginCache")) {
2385 //initial version has incorrectly stored i/o info, and/or garbage chars.
2386 const XMLProperty* version = root->property(X_("version"));
2387 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2388 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2392 cached_info.clear ();
2394 const XMLNodeList children = root->children();
2396 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2398 const XMLNode* child = *iter;
2400 if (child->name() == X_("plugin")) {
2402 const XMLNode* gchild;
2403 const XMLNodeList gchildren = child->children();
2404 const XMLProperty* prop = child->property (X_("id"));
2410 string id = prop->value();
2414 string::size_type slash = id.find_last_of ('/');
2416 if (slash == string::npos) {
2420 version = id.substr (slash);
2421 id = id.substr (0, slash);
2422 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2424 if (fixed.empty()) {
2425 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2432 AUPluginCachedInfo cinfo;
2434 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2438 if (gchild->name() == X_("io")) {
2442 const XMLProperty* iprop;
2443 const XMLProperty* oprop;
2445 if (((iprop = gchild->property (X_("in"))) != 0) &&
2446 ((oprop = gchild->property (X_("out"))) != 0)) {
2447 in = atoi (iprop->value());
2448 out = atoi (oprop->value());
2450 cinfo.io_configs.push_back (pair<int,int> (in, out));
2455 if (cinfo.io_configs.size()) {
2456 add_cached_info (id, cinfo);
2465 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2467 CFStringRef itemName = NULL;
2469 // Marc Poirier-style item name
2470 CAComponent auComponent (comp_desc);
2471 if (auComponent.IsValid()) {
2472 CAComponentDescription dummydesc;
2473 Handle nameHandle = NewHandle(sizeof(void*));
2474 if (nameHandle != NULL) {
2475 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2477 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2478 if (nameString != NULL) {
2479 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2482 DisposeHandle(nameHandle);
2486 // if Marc-style fails, do the original way
2487 if (itemName == NULL) {
2488 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2489 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2490 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2492 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2493 compTypeString, compManufacturerString, compSubTypeString);
2495 if (compTypeString != NULL)
2496 CFRelease(compTypeString);
2497 if (compSubTypeString != NULL)
2498 CFRelease(compSubTypeString);
2499 if (compManufacturerString != NULL)
2500 CFRelease(compManufacturerString);
2503 string str = CFStringRefToStdString(itemName);
2504 string::size_type colon = str.find (':');
2507 name = str.substr (colon+1);
2508 maker = str.substr (0, colon);
2509 strip_whitespace_edges (maker);
2510 strip_whitespace_edges (name);
2514 strip_whitespace_edges (name);
2519 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2523 /* note: OSType is a compiler-implemenation-defined value,
2524 historically a 32 bit integer created with a multi-character
2525 constant such as 'abcd'. It is, fundamentally, an abomination.
2530 s << desc.SubType();
2538 AUPluginInfo::needs_midi_input ()
2540 return is_effect_with_midi_input () || is_instrument ();
2544 AUPluginInfo::is_effect () const
2546 return is_effect_without_midi_input() || is_effect_with_midi_input();
2550 AUPluginInfo::is_effect_without_midi_input () const
2552 return descriptor->IsAUFX();
2556 AUPluginInfo::is_effect_with_midi_input () const
2558 return descriptor->IsAUFM();
2562 AUPluginInfo::is_instrument () const
2564 return descriptor->IsMusicDevice();