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.
28 #include "pbd/transmitter.h"
29 #include "pbd/xml++.h"
30 #include "pbd/convert.h"
31 #include "pbd/whitespace.h"
32 #include "pbd/file_utils.h"
33 #include "pbd/locale_guard.h"
35 #include <glibmm/threads.h>
36 #include <glibmm/fileutils.h>
37 #include <glibmm/miscutils.h>
38 #include <glib/gstdio.h>
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/debug.h"
44 #include "ardour/midi_buffer.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/audio_unit.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
53 #include "appleutility/CAAudioUnit.h"
54 #include "appleutility/CAAUParameter.h"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
61 #include <Carbon/Carbon.h>
68 using namespace ARDOUR;
70 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
72 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
73 static string preset_suffix = ".aupreset";
74 static bool preset_search_path_initialized = false;
75 FILE * AUPluginInfo::_crashlog_fd = NULL;
76 bool AUPluginInfo::_scan_only = true;
79 static void au_blacklist (std::string id)
81 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
82 FILE * blacklist_fd = NULL;
83 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
84 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
87 assert(id.find("\n") == string::npos);
88 fprintf(blacklist_fd, "%s\n", id.c_str());
89 ::fclose(blacklist_fd);
92 static void au_unblacklist (std::string id)
94 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
95 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
96 PBD::warning << "Expected Blacklist file does not exist.\n";
101 std::ifstream ifs(fn.c_str());
102 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
103 ::g_unlink(fn.c_str());
105 assert(id.find("\n") == string::npos);
107 id += "\n"; // add separator
108 const size_t rpl = bl.find(id);
109 if (rpl != string::npos) {
110 bl.replace(rpl, id.size(), "");
116 FILE * blacklist_fd = NULL;
117 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
118 PBD::error << "Cannot open AU blacklist.\n";
121 fprintf(blacklist_fd, "%s", bl.c_str());
122 ::fclose(blacklist_fd);
125 static bool is_blacklisted (std::string id)
127 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
128 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
132 std::ifstream ifs(fn.c_str());
133 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
135 assert(id.find("\n") == string::npos);
137 id += "\n"; // add separator
138 const size_t rpl = bl.find(id);
139 if (rpl != string::npos) {
148 _render_callback(void *userData,
149 AudioUnitRenderActionFlags *ioActionFlags,
150 const AudioTimeStamp *inTimeStamp,
152 UInt32 inNumberFrames,
153 AudioBufferList* ioData)
156 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
162 _get_beat_and_tempo_callback (void* userData,
163 Float64* outCurrentBeat,
164 Float64* outCurrentTempo)
167 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
174 _get_musical_time_location_callback (void * userData,
175 UInt32 * outDeltaSampleOffsetToNextBeat,
176 Float32 * outTimeSig_Numerator,
177 UInt32 * outTimeSig_Denominator,
178 Float64 * outCurrentMeasureDownBeat)
181 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
182 outTimeSig_Numerator,
183 outTimeSig_Denominator,
184 outCurrentMeasureDownBeat);
190 _get_transport_state_callback (void* userData,
191 Boolean* outIsPlaying,
192 Boolean* outTransportStateChanged,
193 Float64* outCurrentSampleInTimeLine,
194 Boolean* outIsCycling,
195 Float64* outCycleStartBeat,
196 Float64* outCycleEndBeat)
199 return ((AUPlugin*)userData)->get_transport_state_callback (
200 outIsPlaying, outTransportStateChanged,
201 outCurrentSampleInTimeLine, outIsCycling,
202 outCycleStartBeat, outCycleEndBeat);
209 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
215 // Convert the property list into XML data.
217 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
220 error << _("Could not create XML version of property list") << endmsg;
224 // Write the XML data to the file.
226 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
228 if (errno == EEXIST) {
229 error << string_compose (_("Preset file %1 exists; not overwriting"),
232 error << string_compose (_("Cannot open preset file %1 (%2)"),
233 path, strerror (errno)) << endmsg;
239 size_t cnt = CFDataGetLength (xmlData);
241 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
252 static CFPropertyListRef
253 load_property_list (Glib::ustring path)
256 CFPropertyListRef propertyList = 0;
258 CFStringRef errorString;
260 // Read the XML file.
262 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
267 off_t len = lseek (fd, 0, SEEK_END);
268 char* buf = new char[len];
269 lseek (fd, 0, SEEK_SET);
271 if (read (fd, buf, len) != len) {
279 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
281 // Reconstitute the dictionary using the XML data.
283 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
285 kCFPropertyListImmutable,
294 //-----------------------------------------------------------------------------
296 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
301 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
303 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
304 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
310 //-----------------------------------------------------------------------------
312 get_preset_name_in_plist (CFPropertyListRef plist)
320 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
321 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
323 CFStringRef str = (CFStringRef) p;
324 int len = CFStringGetLength(str);
326 char local_buffer[len];
327 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
335 //--------------------------------------------------------------------------
336 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
337 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
338 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
339 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
341 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
344 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
345 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
347 // only sub-type and manufacturer IDs need to be equal
350 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
351 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
358 //--------------------------------------------------------------------------
359 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
360 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
361 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
362 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
365 ComponentDescription desc;
367 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
370 // get the ComponentDescription of the input Component
371 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
375 // check if the Component's ComponentDescription matches the input ComponentDescription
376 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
379 //--------------------------------------------------------------------------
380 // determine if 2 ComponentDescriptions are basically equal
381 // (by that, I mean that the important identifying values are compared,
382 // but not the ComponentDescription flags)
383 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
385 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
388 //--------------------------------------------------------------------------
389 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
390 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
392 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
395 //--------------------------------------------------------------------------
396 // determine if a ComponentDescription basically matches that of a particular Component
397 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
399 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
402 //--------------------------------------------------------------------------
403 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
404 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
406 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
410 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
411 : Plugin (engine, session)
413 , unit (new CAAudioUnit)
414 , initialized (false)
415 , _current_block_size (0)
416 , _requires_fixed_size_buffers (false)
421 , frames_processed (0)
422 , _parameter_listener (0)
423 , _parameter_listener_arg (0)
424 , last_transport_rolling (false)
425 , last_transport_speed (0.0)
427 if (!preset_search_path_initialized) {
428 Glib::ustring p = Glib::get_home_dir();
429 p += "/Library/Audio/Presets:";
430 p += preset_search_path;
431 preset_search_path = p;
432 preset_search_path_initialized = true;
433 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
440 AUPlugin::AUPlugin (const AUPlugin& other)
442 , comp (other.get_comp())
443 , unit (new CAAudioUnit)
444 , initialized (false)
445 , _current_block_size (0)
447 , _requires_fixed_size_buffers (false)
452 , frames_processed (0)
453 , _parameter_listener (0)
454 , _parameter_listener_arg (0)
458 for (int i = 0; i < descriptors.size(); ++i) {
459 set_parameter (i, other.get_parameter (i));
463 AUPlugin::~AUPlugin ()
465 if (_parameter_listener) {
466 AUListenerDispose (_parameter_listener);
467 _parameter_listener = 0;
471 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
472 unit->Uninitialize ();
481 AUPlugin::discover_factory_presets ()
488 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
489 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
493 assert (dataSize == sizeof (presets));
495 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
496 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
504 CFIndex cnt = CFArrayGetCount (presets);
506 for (CFIndex i = 0; i < cnt; ++i) {
507 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
509 string name = CFStringRefToStdString (preset->presetName);
510 factory_preset_map[name] = preset->presetNumber;
511 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
521 CFStringRef itemName;
523 /* these keep track of *configured* channel set up,
524 not potential set ups.
528 output_channels = -1;
530 CAComponentDescription temp;
531 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
532 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
533 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
534 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
535 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
536 compTypeString, compManufacturerString, compSubTypeString);
537 if (compTypeString != NULL) CFRelease(compTypeString);
538 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
539 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
542 au_blacklist(CFStringRefToStdString(itemName));
545 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
546 err = CAAudioUnit::Open (*(comp.get()), *unit);
548 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
549 throw failed_constructor();
553 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
554 throw failed_constructor ();
557 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
558 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
559 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
560 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
561 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
562 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
564 if (input_elements > 0) {
565 /* setup render callback: the plugin calls this to get input data
568 AURenderCallbackStruct renderCallbackInfo;
570 renderCallbackInfo.inputProc = _render_callback;
571 renderCallbackInfo.inputProcRefCon = this;
573 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
574 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
575 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
576 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
577 throw failed_constructor();
581 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
583 HostCallbackInfo info;
584 memset (&info, 0, sizeof (HostCallbackInfo));
585 info.hostUserData = this;
586 info.beatAndTempoProc = _get_beat_and_tempo_callback;
587 info.musicalTimeLocationProc = _get_musical_time_location_callback;
588 info.transportStateProc = _get_transport_state_callback;
590 //ignore result of this - don't care if the property isn't supported
591 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
592 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
593 kAudioUnitScope_Global,
596 sizeof (HostCallbackInfo));
598 if (set_block_size (_session.get_block_size())) {
599 error << _("AUPlugin: cannot set processing block size") << endmsg;
600 throw failed_constructor();
603 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
604 discover_parameters ();
605 discover_factory_presets ();
607 // Plugin::setup_controls ();
609 au_unblacklist(CFStringRefToStdString(itemName));
610 if (itemName != NULL) CFRelease(itemName);
614 AUPlugin::discover_parameters ()
616 /* discover writable parameters */
618 AudioUnitScope scopes[] = {
619 kAudioUnitScope_Global,
620 kAudioUnitScope_Output,
621 kAudioUnitScope_Input
624 descriptors.clear ();
626 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
628 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
630 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
632 AUParameterDescriptor d;
634 d.id = param_info.ParamID (i);
636 const CAAUParameter* param = param_info.GetParamInfo (d.id);
637 const AudioUnitParameterInfo& info (param->ParamInfo());
639 const int len = CFStringGetLength (param->GetName());;
640 char local_buffer[len*2];
641 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
645 d.label = local_buffer;
648 d.scope = param_info.GetScope ();
649 d.element = param_info.GetElement ();
651 /* info.units to consider */
653 kAudioUnitParameterUnit_Generic = 0
654 kAudioUnitParameterUnit_Indexed = 1
655 kAudioUnitParameterUnit_Boolean = 2
656 kAudioUnitParameterUnit_Percent = 3
657 kAudioUnitParameterUnit_Seconds = 4
658 kAudioUnitParameterUnit_SampleFrames = 5
659 kAudioUnitParameterUnit_Phase = 6
660 kAudioUnitParameterUnit_Rate = 7
661 kAudioUnitParameterUnit_Hertz = 8
662 kAudioUnitParameterUnit_Cents = 9
663 kAudioUnitParameterUnit_RelativeSemiTones = 10
664 kAudioUnitParameterUnit_MIDINoteNumber = 11
665 kAudioUnitParameterUnit_MIDIController = 12
666 kAudioUnitParameterUnit_Decibels = 13
667 kAudioUnitParameterUnit_LinearGain = 14
668 kAudioUnitParameterUnit_Degrees = 15
669 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
670 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
671 kAudioUnitParameterUnit_Pan = 18
672 kAudioUnitParameterUnit_Meters = 19
673 kAudioUnitParameterUnit_AbsoluteCents = 20
674 kAudioUnitParameterUnit_Octaves = 21
675 kAudioUnitParameterUnit_BPM = 22
676 kAudioUnitParameterUnit_Beats = 23
677 kAudioUnitParameterUnit_Milliseconds = 24
678 kAudioUnitParameterUnit_Ratio = 25
681 /* info.flags to consider */
685 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
686 kAudioUnitParameterFlag_HasClump = (1L << 20)
687 kAudioUnitParameterFlag_HasName = (1L << 21)
688 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
689 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
690 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
691 kAudioUnitParameterFlag_CanRamp = (1L << 25)
692 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
693 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
694 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
695 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
696 kAudioUnitParameterFlag_IsReadable = (1L << 30)
697 kAudioUnitParameterFlag_IsWritable = (1L << 31)
700 d.lower = info.minValue;
701 d.upper = info.maxValue;
702 d.normal = info.defaultValue;
704 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
705 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
706 (d.integer_step && ((d.upper - d.lower) == 1.0));
707 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
708 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
709 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
710 (info.flags & kAudioUnitParameterFlag_IsWritable);
712 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
713 d.au_unit = info.unit;
715 case kAudioUnitParameterUnit_Decibels:
716 d.unit = ParameterDescriptor::DB;
718 case kAudioUnitParameterUnit_MIDINoteNumber:
719 d.unit = ParameterDescriptor::MIDI_NOTE;
721 case kAudioUnitParameterUnit_Hertz:
722 d.unit = ParameterDescriptor::HZ;
726 d.min_unbound = 0; // lower is bound
727 d.max_unbound = 0; // upper is bound
730 descriptors.push_back (d);
732 uint32_t last_param = descriptors.size() - 1;
733 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
734 listen_to_parameter (last_param);
741 four_ints_to_four_byte_literal (unsigned char n[4])
743 /* this is actually implementation dependent. sigh. this is what gcc
744 and quite a few others do.
746 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
750 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
752 if (isdigit (id[0])) {
756 /* ID format is xxxx-xxxx-xxxx
757 where x maybe \xNN or a printable character.
759 Split at the '-' and and process each part into an integer.
760 Then put it back together.
764 unsigned char nascent[4];
765 const char* cstr = id.c_str();
766 const char* estr = cstr + id.size();
777 while (*cstr && next_int < 4) {
781 if (estr - cstr < 3) {
783 /* too close to the end for \xNN parsing: treat as literal characters */
791 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
795 memcpy (short_buf, &cstr[2], 2);
796 nascent[in] = strtol (short_buf, NULL, 16);
802 /* treat as literal characters */
816 if (in && (in % 4 == 0)) {
817 /* nascent is ready */
818 n[next_int] = four_ints_to_four_byte_literal (nascent);
822 /* swallow space-hyphen-space */
836 s << n[0] << '-' << n[1] << '-' << n[2];
845 AUPlugin::unique_id () const
847 return AUPluginInfo::stringify_descriptor (comp->Desc());
851 AUPlugin::label () const
853 return _info->name.c_str();
857 AUPlugin::parameter_count () const
859 return descriptors.size();
863 AUPlugin::default_value (uint32_t port)
865 if (port < descriptors.size()) {
866 return descriptors[port].normal;
873 AUPlugin::signal_latency () const
875 return unit->Latency() * _session.frame_rate();
879 AUPlugin::set_parameter (uint32_t which, float val)
881 if (which >= descriptors.size()) {
885 if (get_parameter(which) == val) {
889 const AUParameterDescriptor& d (descriptors[which]);
890 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
891 unit->SetParameter (d.id, d.scope, d.element, val);
893 /* tell the world what we did */
895 AudioUnitEvent theEvent;
897 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
898 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
899 theEvent.mArgument.mParameter.mParameterID = d.id;
900 theEvent.mArgument.mParameter.mScope = d.scope;
901 theEvent.mArgument.mParameter.mElement = d.element;
903 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
904 AUEventListenerNotify (NULL, NULL, &theEvent);
906 Plugin::set_parameter (which, val);
910 AUPlugin::get_parameter (uint32_t which) const
913 if (which < descriptors.size()) {
914 const AUParameterDescriptor& d (descriptors[which]);
915 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
916 unit->GetParameter(d.id, d.scope, d.element, val);
922 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
924 if (which < descriptors.size()) {
925 pd = descriptors[which];
932 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
934 if (which < descriptors.size()) {
943 AUPlugin::activate ()
947 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
948 if ((err = unit->Initialize()) != noErr) {
949 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
951 frames_processed = 0;
958 AUPlugin::deactivate ()
960 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
961 unit->Uninitialize ();
968 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
969 unit->GlobalReset ();
973 AUPlugin::requires_fixed_size_buffers() const
975 return _requires_fixed_size_buffers;
980 AUPlugin::set_block_size (pframes_t nframes)
982 bool was_initialized = initialized;
983 UInt32 numFrames = nframes;
990 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
991 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
992 0, &numFrames, sizeof (numFrames))) != noErr) {
993 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
997 if (was_initialized) {
1001 _current_block_size = nframes;
1007 AUPlugin::configure_io (ChanCount in, ChanCount out)
1009 AudioStreamBasicDescription streamFormat;
1010 bool was_initialized = initialized;
1011 int32_t audio_in = in.n_audio();
1012 int32_t audio_out = out.n_audio();
1014 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1017 //if we are already running with the requested i/o config, bail out here
1018 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1025 streamFormat.mSampleRate = _session.frame_rate();
1026 streamFormat.mFormatID = kAudioFormatLinearPCM;
1027 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1029 #ifdef __LITTLE_ENDIAN__
1032 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1035 streamFormat.mBitsPerChannel = 32;
1036 streamFormat.mFramesPerPacket = 1;
1038 /* apple says that for non-interleaved data, these
1039 values always refer to a single channel.
1041 streamFormat.mBytesPerPacket = 4;
1042 streamFormat.mBytesPerFrame = 4;
1044 streamFormat.mChannelsPerFrame = audio_in;
1046 if (set_input_format (streamFormat) != 0) {
1050 streamFormat.mChannelsPerFrame = audio_out;
1052 if (set_output_format (streamFormat) != 0) {
1056 /* reset plugin info to show currently configured state */
1058 _info->n_inputs = in;
1059 _info->n_outputs = out;
1061 if (was_initialized) {
1069 AUPlugin::input_streams() const
1074 if (input_channels < 0) {
1075 // force PluginIoReConfigure -- see also commit msg e38eb06
1076 c.set (DataType::AUDIO, 0);
1077 c.set (DataType::MIDI, 0);
1079 c.set (DataType::AUDIO, input_channels);
1080 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1088 AUPlugin::output_streams() const
1092 if (output_channels < 0) {
1093 // force PluginIoReConfigure - see also commit msg e38eb06
1094 c.set (DataType::AUDIO, 0);
1095 c.set (DataType::MIDI, 0);
1097 c.set (DataType::AUDIO, output_channels);
1098 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1105 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1107 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1109 int32_t audio_in = in.n_audio();
1112 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1114 /* lets check MIDI first */
1116 if (in.n_midi() > 0) {
1117 if (!_has_midi_input) {
1122 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1124 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1125 name(), io_configs.size(), in, out));
1127 //Ardour expects the plugin to tell it the output
1128 //configuration but AU plugins can have multiple I/O
1129 //configurations in most cases. so first lets see
1130 //if there's a configuration that keeps out==in
1132 if (in.n_midi() > 0 && audio_in == 0) {
1133 audio_out = 2; // prefer stereo version if available.
1135 audio_out = audio_in;
1138 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1140 int32_t possible_in = i->first;
1141 int32_t possible_out = i->second;
1143 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1144 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1145 possible_in, possible_out,
1148 out.set (DataType::MIDI, 0);
1149 out.set (DataType::AUDIO, audio_out);
1155 /* now allow potentially "imprecise" matches */
1159 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1161 int32_t possible_in = i->first;
1162 int32_t possible_out = i->second;
1164 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1166 if (possible_out == 0) {
1167 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1168 /* XXX surely this is just a send? (e.g. AUNetSend) */
1172 if (possible_in == 0) {
1174 /* instrument plugin, always legal but throws away inputs ...
1177 if (possible_out == -1) {
1178 /* any configuration possible, provide stereo output */
1181 } else if (possible_out == -2) {
1182 /* plugins shouldn't really use (0,-2) but might.
1183 any configuration possible, provide stereo output
1187 } else if (possible_out < -2) {
1188 /* explicitly variable number of outputs.
1190 Since Ardour can handle any configuration,
1191 we have to somehow pick a number.
1193 We'll use the number of inputs
1194 to the master bus, or 2 if there
1197 boost::shared_ptr<Route> master = _session.master_out();
1199 audio_out = master->input()->n_ports().n_audio();
1205 /* exact number of outputs */
1206 audio_out = possible_out;
1211 if (possible_in == -1) {
1213 /* wildcard for input */
1215 if (possible_out == -1) {
1216 /* out much match in */
1217 audio_out = audio_in;
1219 } else if (possible_out == -2) {
1220 /* any configuration possible, pick matching */
1221 audio_out = audio_in;
1223 } else if (possible_out < -2) {
1224 /* explicitly variable number of outputs, pick maximum */
1225 audio_out = -possible_out;
1228 /* exact number of outputs */
1229 audio_out = possible_out;
1234 if (possible_in == -2) {
1236 if (possible_out == -1) {
1237 /* any configuration possible, pick matching */
1238 audio_out = audio_in;
1240 } else if (possible_out == -2) {
1241 /* plugins shouldn't really use (-2,-2) but might.
1242 interpret as (-1,-1).
1244 audio_out = audio_in;
1246 } else if (possible_out < -2) {
1247 /* explicitly variable number of outputs, pick maximum */
1248 audio_out = -possible_out;
1251 /* exact number of outputs */
1252 audio_out = possible_out;
1257 if (possible_in < -2) {
1259 /* explicit variable number of inputs */
1261 if (audio_in > -possible_in) {
1262 /* request is too large */
1266 if (possible_out == -1) {
1267 /* any output configuration possible, provide stereo out */
1270 } else if (possible_out == -2) {
1271 /* plugins shouldn't really use (<-2,-2) but might.
1272 interpret as (<-2,-1): any configuration possible, provide stereo output
1276 } else if (possible_out < -2) {
1277 /* explicitly variable number of outputs.
1279 Since Ardour can handle any configuration,
1280 we have to somehow pick a number.
1282 We'll use the number of inputs
1283 to the master bus, or 2 if there
1286 boost::shared_ptr<Route> master = _session.master_out();
1288 audio_out = master->input()->n_ports().n_audio();
1294 /* exact number of outputs */
1295 audio_out = possible_out;
1300 if (possible_in && (possible_in == audio_in)) {
1302 /* exact number of inputs ... must match obviously */
1304 if (possible_out == -1) {
1305 /* any output configuration possible, provide stereo output */
1308 } else if (possible_out == -2) {
1309 /* plugins shouldn't really use (>0,-2) but might.
1310 interpret as (>0,-1):
1311 any output configuration possible, provide stereo output
1315 } else if (possible_out < -2) {
1316 /* explicitly variable number of outputs, pick maximum */
1317 audio_out = -possible_out;
1320 /* exact number of outputs */
1321 audio_out = possible_out;
1333 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1335 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1339 out.set (DataType::MIDI, 0);
1340 out.set (DataType::AUDIO, audio_out);
1346 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1348 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1352 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1354 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1363 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1364 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1370 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1374 for (uint32_t i = 0; i < cnt; ++i) {
1375 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1376 (scope == kAudioUnitScope_Input ? "input" : "output"),
1378 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1379 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1380 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1385 if (scope == kAudioUnitScope_Input) {
1386 input_channels = fmt.mChannelsPerFrame;
1388 output_channels = fmt.mChannelsPerFrame;
1395 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1396 const AudioTimeStamp*,
1398 UInt32 inNumberFrames,
1399 AudioBufferList* ioData)
1401 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1403 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1404 // name(), inNumberFrames, ioData->mNumberBuffers));
1406 if (input_maxbuf == 0) {
1407 error << _("AUPlugin: render callback called illegally!") << endmsg;
1408 return kAudioUnitErr_CannotDoInCurrentContext;
1410 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1412 for (uint32_t i = 0; i < limit; ++i) {
1413 ioData->mBuffers[i].mNumberChannels = 1;
1414 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1416 /* we don't use the channel mapping because audiounits are
1417 never replicated. one plugin instance uses all channels/buffers
1418 passed to PluginInsert::connect_and_run()
1421 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1424 cb_offset += inNumberFrames;
1430 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1432 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1434 AudioUnitRenderActionFlags flags = 0;
1438 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1439 unit->GlobalReset();
1440 _last_nframes = nframes;
1443 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1444 name(), input_channels, output_channels, _has_midi_input,
1445 bufs.count(), bufs.available()));
1447 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1448 has the capacity to handle our outputs.
1451 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1453 input_buffers = &bufs;
1454 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1455 input_offset = offset;
1458 buffers->mNumberBuffers = output_channels;
1460 for (int32_t i = 0; i < output_channels; ++i) {
1461 buffers->mBuffers[i].mNumberChannels = 1;
1462 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1463 /* setting this to 0 indicates to the AU that it can provide buffers here
1464 if necessary. if it can process in-place, it will use the buffers provided
1465 as input by ::render_callback() above.
1467 a non-null values tells the plugin to render into the buffer pointed
1470 buffers->mBuffers[i].mData = 0;
1473 if (_has_midi_input) {
1475 uint32_t nmidi = bufs.count().n_midi();
1477 for (uint32_t i = 0; i < nmidi; ++i) {
1479 /* one MIDI port/buffer only */
1481 MidiBuffer& m = bufs.get_midi (i);
1483 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1484 Evoral::MIDIEvent<framepos_t> ev (*i);
1486 if (ev.is_channel_event()) {
1487 const uint8_t* b = ev.buffer();
1488 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1489 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1492 /* XXX need to handle sysex and other message types */
1497 /* does this really mean anything ?
1500 ts.mSampleTime = frames_processed;
1501 ts.mFlags = kAudioTimeStampSampleTimeValid;
1503 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1504 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1506 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1509 frames_processed += nframes;
1511 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1512 name(), buffers->mNumberBuffers, output_channels));
1514 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1517 for (i = 0; i < limit; ++i) {
1518 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1519 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1520 /* plugin provided its own buffer for output so copy it back to where we want it
1522 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1526 /* now silence any buffers that were passed in but the that the plugin
1527 did not fill/touch/use.
1530 for (;i < output_channels; ++i) {
1531 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1537 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1542 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1543 Float64* outCurrentTempo)
1545 TempoMap& tmap (_session.tempo_map());
1547 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1549 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1550 (and interpretation) of a beat position will be incorrect. So refuse to
1554 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1555 return kAudioUnitErr_CannotDoInCurrentContext;
1558 Timecode::BBT_Time bbt;
1559 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1560 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1562 if (outCurrentBeat) {
1564 beat = metric.meter().divisions_per_bar() * bbt.bars;
1566 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1567 *outCurrentBeat = beat;
1570 if (outCurrentTempo) {
1571 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1579 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1580 Float32* outTimeSig_Numerator,
1581 UInt32* outTimeSig_Denominator,
1582 Float64* outCurrentMeasureDownBeat)
1584 TempoMap& tmap (_session.tempo_map());
1586 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1588 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1589 (and interpretation) of a beat position will be incorrect. So refuse to
1593 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1594 return kAudioUnitErr_CannotDoInCurrentContext;
1597 Timecode::BBT_Time bbt;
1598 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1599 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1601 if (outDeltaSampleOffsetToNextBeat) {
1602 if (bbt.ticks == 0) {
1604 *outDeltaSampleOffsetToNextBeat = 0;
1606 *outDeltaSampleOffsetToNextBeat = (UInt32)
1607 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1608 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1612 if (outTimeSig_Numerator) {
1613 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1615 if (outTimeSig_Denominator) {
1616 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1619 if (outCurrentMeasureDownBeat) {
1621 /* beat for the start of the bar.
1623 2|1|0 -> 1 + divisions_per_bar
1624 3|1|0 -> 1 + (2 * divisions_per_bar)
1628 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1635 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1636 Boolean* outTransportStateChanged,
1637 Float64* outCurrentSampleInTimeLine,
1638 Boolean* outIsCycling,
1639 Float64* outCycleStartBeat,
1640 Float64* outCycleEndBeat)
1645 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1647 rolling = _session.transport_rolling();
1648 speed = _session.transport_speed ();
1651 *outIsPlaying = _session.transport_rolling();
1654 if (outTransportStateChanged) {
1655 if (rolling != last_transport_rolling) {
1656 *outTransportStateChanged = true;
1657 } else if (speed != last_transport_speed) {
1658 *outTransportStateChanged = true;
1660 *outTransportStateChanged = false;
1664 if (outCurrentSampleInTimeLine) {
1665 /* this assumes that the AU can only call this host callback from render context,
1666 where input_offset is valid.
1668 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1672 Location* loc = _session.locations()->auto_loop_location();
1674 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1676 if (*outIsCycling) {
1678 if (outCycleStartBeat || outCycleEndBeat) {
1680 TempoMap& tmap (_session.tempo_map());
1682 /* more than 1 meter means that a simplistic computation (and interpretation) of
1683 a beat position will be incorrect. so refuse to offer the value.
1686 if (tmap.n_meters() > 1) {
1687 return kAudioUnitErr_CannotDoInCurrentContext;
1690 Timecode::BBT_Time bbt;
1692 if (outCycleStartBeat) {
1693 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1694 _session.tempo_map().bbt_time (loc->start(), bbt);
1697 beat = metric.meter().divisions_per_bar() * bbt.bars;
1699 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1701 *outCycleStartBeat = beat;
1704 if (outCycleEndBeat) {
1705 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1706 _session.tempo_map().bbt_time (loc->end(), bbt);
1709 beat = metric.meter().divisions_per_bar() * bbt.bars;
1711 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1713 *outCycleEndBeat = beat;
1719 last_transport_rolling = rolling;
1720 last_transport_speed = speed;
1725 set<Evoral::Parameter>
1726 AUPlugin::automatable() const
1728 set<Evoral::Parameter> automates;
1730 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1731 if (descriptors[i].automatable) {
1732 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1740 AUPlugin::describe_parameter (Evoral::Parameter param)
1742 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1743 return descriptors[param.id()].label;
1750 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1752 // NameValue stuff here
1756 AUPlugin::parameter_is_audio (uint32_t) const
1762 AUPlugin::parameter_is_control (uint32_t param) const
1764 assert(param < descriptors.size());
1765 if (descriptors[param].automatable) {
1766 /* corrently ardour expects all controls to be automatable
1767 * IOW ardour GUI elements mandate an Evoral::Parameter
1768 * for all input+control ports.
1776 AUPlugin::parameter_is_input (uint32_t param) const
1778 /* AU params that are both readable and writeable,
1779 * are listed in kAudioUnitScope_Global
1781 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1785 AUPlugin::parameter_is_output (uint32_t param) const
1787 assert(param < descriptors.size());
1788 // TODO check if ardour properly handles ports
1789 // that report is_input + is_output == true
1790 // -> add || descriptors[param].scope == kAudioUnitScope_Global
1791 return (descriptors[param].scope == kAudioUnitScope_Output);
1795 AUPlugin::add_state (XMLNode* root) const
1797 LocaleGuard lg (X_("C"));
1799 CFPropertyListRef propertyList;
1801 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1802 if (unit->GetAUPreset (propertyList) != noErr) {
1806 // Convert the property list into XML data.
1808 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1811 error << _("Could not create XML version of property list") << endmsg;
1815 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1816 our state node. GACK!
1821 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1823 root->add_child_copy (*t.root());
1827 CFRelease (xmlData);
1828 CFRelease (propertyList);
1832 AUPlugin::set_state(const XMLNode& node, int version)
1835 CFPropertyListRef propertyList;
1836 LocaleGuard lg (X_("C"));
1838 if (node.name() != state_node_name()) {
1839 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1843 #ifndef NO_PLUGIN_STATE
1844 if (node.children().empty()) {
1848 XMLNode* top = node.children().front();
1849 XMLNode* copy = new XMLNode (*top);
1854 const string& xml = t.write_buffer ();
1855 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1856 CFStringRef errorString;
1858 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1860 kCFPropertyListImmutable,
1863 CFRelease (xmlData);
1866 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1867 if (unit->SetAUPreset (propertyList) == noErr) {
1870 /* tell the world */
1872 AudioUnitParameter changedUnit;
1873 changedUnit.mAudioUnit = unit->AU();
1874 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1875 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1877 CFRelease (propertyList);
1881 Plugin::set_state (node, version);
1886 AUPlugin::load_preset (PresetRecord r)
1888 Plugin::load_preset (r);
1891 CFPropertyListRef propertyList;
1893 UserPresetMap::iterator ux;
1894 FactoryPresetMap::iterator fx;
1896 /* look first in "user" presets */
1898 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1900 if ((propertyList = load_property_list (ux->second)) != 0) {
1901 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1902 if (unit->SetAUPreset (propertyList) == noErr) {
1905 /* tell the world */
1907 AudioUnitParameter changedUnit;
1908 changedUnit.mAudioUnit = unit->AU();
1909 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1910 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1912 CFRelease(propertyList);
1915 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1919 preset.presetNumber = fx->second;
1920 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1922 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1924 if (unit->SetPresentPreset (preset) == 0) {
1927 /* tell the world */
1929 AudioUnitParameter changedUnit;
1930 changedUnit.mAudioUnit = unit->AU();
1931 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1932 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1940 AUPlugin::do_remove_preset (std::string)
1945 AUPlugin::do_save_preset (string preset_name)
1947 CFPropertyListRef propertyList;
1948 vector<Glib::ustring> v;
1949 Glib::ustring user_preset_path;
1951 std::string m = maker();
1952 std::string n = name();
1954 strip_whitespace_edges (m);
1955 strip_whitespace_edges (n);
1957 v.push_back (Glib::get_home_dir());
1958 v.push_back ("Library");
1959 v.push_back ("Audio");
1960 v.push_back ("Presets");
1964 user_preset_path = Glib::build_filename (v);
1966 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1967 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1971 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1972 if (unit->GetAUPreset (propertyList) != noErr) {
1976 // add the actual preset name */
1978 v.push_back (preset_name + preset_suffix);
1982 user_preset_path = Glib::build_filename (v);
1984 set_preset_name_in_plist (propertyList, preset_name);
1986 if (save_property_list (propertyList, user_preset_path)) {
1987 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1991 CFRelease(propertyList);
1993 user_preset_map[preset_name] = user_preset_path;;
1995 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
1997 return string ("file:///") + user_preset_path;
2000 //-----------------------------------------------------------------------------
2001 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2003 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2005 CFNumberRef cfNumber;
2006 SInt32 numberValue = 0;
2007 Boolean dummySuccess;
2009 if (outSuccess == NULL)
2010 outSuccess = &dummySuccess;
2011 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2013 *outSuccess = FALSE;
2017 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2018 if (cfNumber == NULL)
2020 *outSuccess = FALSE;
2023 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2031 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
2033 CFDictionaryRef auStateDictionary;
2034 ComponentDescription tempDesc = {0,0,0,0,0};
2035 SInt32 versionValue;
2038 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2041 // the property list for AU state data must be of the dictionary type
2042 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2043 return kAudioUnitErr_InvalidPropertyValue;
2046 auStateDictionary = (CFDictionaryRef)inAUStateData;
2048 // first check to make sure that the version of the AU state data is one that we know understand
2049 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2050 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2053 return kAudioUnitErr_InvalidPropertyValue;
2055 #define kCurrentSavedStateVersion 0
2056 if (versionValue != kCurrentSavedStateVersion) {
2057 return kAudioUnitErr_InvalidPropertyValue;
2060 // grab the ComponentDescription values from the AU state data
2061 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2062 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2063 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2064 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2065 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2066 return kAudioUnitErr_InvalidPropertyValue;
2068 *outComponentDescription = tempDesc;
2073 static bool au_preset_filter (const string& str, void* arg)
2075 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2079 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2083 /* check the preset file path name against this plugin
2084 ID. The idea is that all preset files for this plugin
2085 include "<manufacturer>/<plugin-name>" in their path.
2088 Plugin* p = (Plugin *) arg;
2089 string match = p->maker();
2093 ret = str.find (match) != string::npos;
2096 string m = p->maker ();
2097 string n = p->name ();
2098 strip_whitespace_edges (m);
2099 strip_whitespace_edges (n);
2104 ret = str.find (match) != string::npos;
2112 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2115 CFPropertyListRef plist;
2116 ComponentDescription presetDesc;
2119 plist = load_property_list (pathstr);
2125 // get the ComponentDescription from the AU preset file
2127 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2129 if (status == noErr) {
2130 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2132 /* try to get the preset name from the property list */
2134 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2136 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2140 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2143 char buf[PATH_MAX+1];
2145 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2160 AUPlugin::current_preset() const
2164 CFPropertyListRef propertyList;
2166 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2167 if (unit->GetAUPreset (propertyList) == noErr) {
2168 preset_name = get_preset_name_in_plist (propertyList);
2169 CFRelease(propertyList);
2176 AUPlugin::find_presets ()
2178 vector<string> preset_files;
2180 user_preset_map.clear ();
2182 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2184 if (preset_files.empty()) {
2185 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2189 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2194 /* make an initial guess at the preset name using the path */
2196 preset_name = Glib::path_get_basename (path);
2197 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2199 /* check that this preset file really matches this plugin
2200 and potentially get the "real" preset name from
2204 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2205 user_preset_map[preset_name] = path;
2206 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2208 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2213 /* now fill the vector<string> with the names we have */
2215 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2216 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2217 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2220 /* add factory presets */
2222 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2224 string const uri = string_compose ("%1", _presets.size ());
2225 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2226 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2231 AUPlugin::has_editor () const
2233 // even if the plugin doesn't have its own editor, the AU API can be used
2234 // to create one that looks native.
2238 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2241 type = ARDOUR::AudioUnit;
2244 AUPluginInfo::~AUPluginInfo ()
2246 type = ARDOUR::AudioUnit;
2250 AUPluginInfo::load (Session& session)
2255 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2256 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2258 if (!comp->IsValid()) {
2259 error << ("AudioUnit: not a valid Component") << endmsg;
2261 plugin.reset (new AUPlugin (session.engine(), session, comp));
2264 AUPluginInfo *aup = new AUPluginInfo (*this);
2265 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2266 plugin->set_info (PluginInfoPtr (aup));
2267 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2271 catch (failed_constructor &err) {
2272 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2273 return PluginPtr ();
2278 AUPluginInfo::au_cache_path ()
2280 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2284 AUPluginInfo::discover (bool scan_only)
2288 /* AU require a CAComponentDescription pointer provided by the OS.
2289 * Ardour only caches port and i/o config. It can't just 'scan' without
2290 * 'discovering' (like we do for VST).
2293 * "Iterate over all plugins. skip the ones where there's no io-cache".
2295 _scan_only = scan_only;
2297 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2298 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2300 // create crash log file
2301 au_start_crashlog ();
2303 PluginInfoList* plugs = new PluginInfoList;
2305 discover_fx (*plugs);
2306 discover_music (*plugs);
2307 discover_generators (*plugs);
2308 discover_instruments (*plugs);
2310 // all fine if we get here
2311 au_remove_crashlog ();
2313 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2319 AUPluginInfo::discover_music (PluginInfoList& plugs)
2321 CAComponentDescription desc;
2322 desc.componentFlags = 0;
2323 desc.componentFlagsMask = 0;
2324 desc.componentSubType = 0;
2325 desc.componentManufacturer = 0;
2326 desc.componentType = kAudioUnitType_MusicEffect;
2328 discover_by_description (plugs, desc);
2332 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2334 CAComponentDescription desc;
2335 desc.componentFlags = 0;
2336 desc.componentFlagsMask = 0;
2337 desc.componentSubType = 0;
2338 desc.componentManufacturer = 0;
2339 desc.componentType = kAudioUnitType_Effect;
2341 discover_by_description (plugs, desc);
2345 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2347 CAComponentDescription desc;
2348 desc.componentFlags = 0;
2349 desc.componentFlagsMask = 0;
2350 desc.componentSubType = 0;
2351 desc.componentManufacturer = 0;
2352 desc.componentType = kAudioUnitType_Generator;
2354 discover_by_description (plugs, desc);
2358 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2360 CAComponentDescription desc;
2361 desc.componentFlags = 0;
2362 desc.componentFlagsMask = 0;
2363 desc.componentSubType = 0;
2364 desc.componentManufacturer = 0;
2365 desc.componentType = kAudioUnitType_MusicDevice;
2367 discover_by_description (plugs, desc);
2372 AUPluginInfo::au_get_crashlog (std::string &msg)
2374 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2375 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2378 std::ifstream ifs(fn.c_str());
2379 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2380 au_remove_crashlog ();
2385 AUPluginInfo::au_start_crashlog ()
2387 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2388 assert(!_crashlog_fd);
2389 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2390 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2391 PBD::error << "Cannot create AU error-log" << fn << "\n";
2392 cerr << "Cannot create AU error-log" << fn << "\n";
2397 AUPluginInfo::au_remove_crashlog ()
2400 ::fclose(_crashlog_fd);
2401 _crashlog_fd = NULL;
2403 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2404 ::g_unlink(fn.c_str());
2405 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2410 AUPluginInfo::au_crashlog (std::string msg)
2412 if (!_crashlog_fd) {
2413 fprintf(stderr, "AU: %s\n", msg.c_str());
2415 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2416 ::fflush(_crashlog_fd);
2421 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2424 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2426 comp = FindNextComponent (NULL, &desc);
2428 while (comp != NULL) {
2429 CAComponentDescription temp;
2430 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2431 CFStringRef itemName = NULL;
2434 if (itemName != NULL) CFRelease(itemName);
2435 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2436 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2437 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2438 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2439 compTypeString, compManufacturerString, compSubTypeString);
2440 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2441 if (compTypeString != NULL)
2442 CFRelease(compTypeString);
2443 if (compSubTypeString != NULL)
2444 CFRelease(compSubTypeString);
2445 if (compManufacturerString != NULL)
2446 CFRelease(compManufacturerString);
2449 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2450 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2451 comp = FindNextComponent (comp, &desc);
2455 AUPluginInfoPtr info (new AUPluginInfo
2456 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2458 /* although apple designed the subtype field to be a "category" indicator,
2459 its really turned into a plugin ID field for a given manufacturer. Hence
2460 there are no categories for AudioUnits. However, to keep the plugins
2461 showing up under "categories", we'll use the "type" as a high level
2464 NOTE: no panners, format converters or i/o AU's for our purposes
2467 switch (info->descriptor->Type()) {
2468 case kAudioUnitType_Panner:
2469 case kAudioUnitType_OfflineEffect:
2470 case kAudioUnitType_FormatConverter:
2471 comp = FindNextComponent (comp, &desc);
2474 case kAudioUnitType_Output:
2475 info->category = _("AudioUnit Outputs");
2477 case kAudioUnitType_MusicDevice:
2478 info->category = _("AudioUnit Instruments");
2480 case kAudioUnitType_MusicEffect:
2481 info->category = _("AudioUnit MusicEffects");
2483 case kAudioUnitType_Effect:
2484 info->category = _("AudioUnit Effects");
2486 case kAudioUnitType_Mixer:
2487 info->category = _("AudioUnit Mixers");
2489 case kAudioUnitType_Generator:
2490 info->category = _("AudioUnit Generators");
2493 info->category = _("AudioUnit (Unknown)");
2497 au_blacklist(CFStringRefToStdString(itemName));
2498 AUPluginInfo::get_names (temp, info->name, info->creator);
2499 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2500 au_crashlog(string_compose("Plugin: %1", info->name));
2502 info->type = ARDOUR::AudioUnit;
2503 info->unique_id = stringify_descriptor (*info->descriptor);
2505 /* XXX not sure of the best way to handle plugin versioning yet
2508 CAComponent cacomp (*info->descriptor);
2510 if (cacomp.GetResourceVersion (info->version) != noErr) {
2514 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2517 /* here we have to map apple's wildcard system to a simple pair
2518 of values. in ::can_do() we use the whole system, but here
2519 we need a single pair of values. XXX probably means we should
2520 remove any use of these values.
2522 for now, if the plugin provides a wildcard, treat it as 1. we really
2523 don't care much, because whether we can handle an i/o configuration
2524 depends upon ::can_support_io_configuration(), not these counts.
2526 they exist because other parts of ardour try to present i/o configuration
2527 info to the user, which should perhaps be revisited.
2530 int32_t possible_in = info->cache.io_configs.front().first;
2531 int32_t possible_out = info->cache.io_configs.front().second;
2533 if (possible_in > 0) {
2534 info->n_inputs.set (DataType::AUDIO, possible_in);
2536 info->n_inputs.set (DataType::AUDIO, 1);
2539 if (possible_out > 0) {
2540 info->n_outputs.set (DataType::AUDIO, possible_out);
2542 info->n_outputs.set (DataType::AUDIO, 1);
2545 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2546 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2548 plugs.push_back (info);
2551 else if (rv == -1) {
2552 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2555 au_unblacklist(CFStringRefToStdString(itemName));
2556 au_crashlog("Success.");
2557 comp = FindNextComponent (comp, &desc);
2558 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2560 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2564 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2567 AUPluginCachedInfo& cinfo,
2568 const std::string& name)
2573 /* concatenate unique ID with version to provide a key for cached info lookup.
2574 this ensures we don't get stale information, or should if plugin developers
2575 follow Apple "guidelines".
2578 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2583 CachedInfoMap::iterator cim = cached_info.find (id);
2585 if (cim != cached_info.end()) {
2586 cinfo = cim->second;
2591 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
2596 AUChannelInfo* channel_info;
2600 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2604 if (CAAudioUnit::Open (comp, unit) != noErr) {
2610 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2615 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2616 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2622 /* no explicit info available, so default to 1in/1out */
2624 /* XXX this is wrong. we should be indicating wildcard values */
2626 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2630 /* store each configuration */
2632 for (uint32_t n = 0; n < cnt; ++n) {
2633 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2634 channel_info[n].outChannels));
2637 free (channel_info);
2640 add_cached_info (id, cinfo);
2641 save_cached_info ();
2647 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2649 cached_info[id] = cinfo;
2652 #define AU_CACHE_VERSION "2.0"
2655 AUPluginInfo::save_cached_info ()
2659 node = new XMLNode (X_("AudioUnitPluginCache"));
2660 node->add_property( "version", AU_CACHE_VERSION );
2662 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2663 XMLNode* parent = new XMLNode (X_("plugin"));
2664 parent->add_property ("id", i->first);
2665 node->add_child_nocopy (*parent);
2667 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2669 XMLNode* child = new XMLNode (X_("io"));
2672 snprintf (buf, sizeof (buf), "%d", j->first);
2673 child->add_property (X_("in"), buf);
2674 snprintf (buf, sizeof (buf), "%d", j->second);
2675 child->add_property (X_("out"), buf);
2676 parent->add_child_nocopy (*child);
2681 Glib::ustring path = au_cache_path ();
2684 tree.set_root (node);
2686 if (!tree.write (path)) {
2687 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2688 g_unlink (path.c_str());
2693 AUPluginInfo::load_cached_info ()
2695 Glib::ustring path = au_cache_path ();
2698 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2702 if ( !tree.read (path) ) {
2703 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2707 const XMLNode* root (tree.root());
2709 if (root->name() != X_("AudioUnitPluginCache")) {
2713 //initial version has incorrectly stored i/o info, and/or garbage chars.
2714 const XMLProperty* version = root->property(X_("version"));
2715 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2716 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2720 cached_info.clear ();
2722 const XMLNodeList children = root->children();
2724 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2726 const XMLNode* child = *iter;
2728 if (child->name() == X_("plugin")) {
2730 const XMLNode* gchild;
2731 const XMLNodeList gchildren = child->children();
2732 const XMLProperty* prop = child->property (X_("id"));
2738 string id = prop->value();
2742 string::size_type slash = id.find_last_of ('/');
2744 if (slash == string::npos) {
2748 version = id.substr (slash);
2749 id = id.substr (0, slash);
2750 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2752 if (fixed.empty()) {
2753 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2760 AUPluginCachedInfo cinfo;
2762 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2766 if (gchild->name() == X_("io")) {
2770 const XMLProperty* iprop;
2771 const XMLProperty* oprop;
2773 if (((iprop = gchild->property (X_("in"))) != 0) &&
2774 ((oprop = gchild->property (X_("out"))) != 0)) {
2775 in = atoi (iprop->value());
2776 out = atoi (oprop->value());
2778 cinfo.io_configs.push_back (pair<int,int> (in, out));
2783 if (cinfo.io_configs.size()) {
2784 add_cached_info (id, cinfo);
2793 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2795 CFStringRef itemName = NULL;
2797 // Marc Poirier-style item name
2798 CAComponent auComponent (comp_desc);
2799 if (auComponent.IsValid()) {
2800 CAComponentDescription dummydesc;
2801 Handle nameHandle = NewHandle(sizeof(void*));
2802 if (nameHandle != NULL) {
2803 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2805 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2806 if (nameString != NULL) {
2807 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2810 DisposeHandle(nameHandle);
2814 // if Marc-style fails, do the original way
2815 if (itemName == NULL) {
2816 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2817 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2818 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2820 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2821 compTypeString, compManufacturerString, compSubTypeString);
2823 if (compTypeString != NULL)
2824 CFRelease(compTypeString);
2825 if (compSubTypeString != NULL)
2826 CFRelease(compSubTypeString);
2827 if (compManufacturerString != NULL)
2828 CFRelease(compManufacturerString);
2831 string str = CFStringRefToStdString(itemName);
2832 string::size_type colon = str.find (':');
2835 name = str.substr (colon+1);
2836 maker = str.substr (0, colon);
2837 strip_whitespace_edges (maker);
2838 strip_whitespace_edges (name);
2842 strip_whitespace_edges (name);
2847 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2851 /* note: OSType is a compiler-implemenation-defined value,
2852 historically a 32 bit integer created with a multi-character
2853 constant such as 'abcd'. It is, fundamentally, an abomination.
2858 s << desc.SubType();
2866 AUPluginInfo::needs_midi_input ()
2868 return is_effect_with_midi_input () || is_instrument ();
2872 AUPluginInfo::is_effect () const
2874 return is_effect_without_midi_input() || is_effect_with_midi_input();
2878 AUPluginInfo::is_effect_without_midi_input () const
2880 return descriptor->IsAUFX();
2884 AUPluginInfo::is_effect_with_midi_input () const
2886 return descriptor->IsAUFM();
2890 AUPluginInfo::is_instrument () const
2892 return descriptor->IsMusicDevice();
2896 AUPlugin::set_info (PluginInfoPtr info)
2898 Plugin::set_info (info);
2900 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2901 _has_midi_input = pinfo->needs_midi_input ();
2902 _has_midi_output = false;
2906 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2909 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2911 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2913 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2915 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2919 _parameter_listener_arg = arg;
2925 AUPlugin::listen_to_parameter (uint32_t param_id)
2927 AudioUnitEvent event;
2929 if (!_parameter_listener || param_id >= descriptors.size()) {
2933 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2934 event.mArgument.mParameter.mAudioUnit = unit->AU();
2935 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2936 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2937 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2939 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2943 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2944 event.mArgument.mParameter.mAudioUnit = unit->AU();
2945 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2946 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2947 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2949 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2953 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2954 event.mArgument.mParameter.mAudioUnit = unit->AU();
2955 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2956 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2957 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2959 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2967 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2969 AudioUnitEvent event;
2971 if (!_parameter_listener || param_id >= descriptors.size()) {
2975 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2976 event.mArgument.mParameter.mAudioUnit = unit->AU();
2977 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2978 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2979 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2981 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2985 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2986 event.mArgument.mParameter.mAudioUnit = unit->AU();
2987 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2988 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2989 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2991 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2995 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2996 event.mArgument.mParameter.mAudioUnit = unit->AU();
2997 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2998 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2999 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3001 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3009 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3011 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3015 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3017 ParameterMap::iterator i;
3019 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3023 switch (event->mEventType) {
3024 case kAudioUnitEvent_BeginParameterChangeGesture:
3025 StartTouch (i->second);
3027 case kAudioUnitEvent_EndParameterChangeGesture:
3028 EndTouch (i->second);
3030 case kAudioUnitEvent_ParameterValueChange:
3031 ParameterChanged (i->second, new_value);