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)
460 AUPlugin::~AUPlugin ()
462 if (_parameter_listener) {
463 AUListenerDispose (_parameter_listener);
464 _parameter_listener = 0;
468 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
469 unit->Uninitialize ();
478 AUPlugin::discover_factory_presets ()
485 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
486 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
490 assert (dataSize == sizeof (presets));
492 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
493 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
501 CFIndex cnt = CFArrayGetCount (presets);
503 for (CFIndex i = 0; i < cnt; ++i) {
504 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
506 string name = CFStringRefToStdString (preset->presetName);
507 factory_preset_map[name] = preset->presetNumber;
508 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
518 CFStringRef itemName;
520 /* these keep track of *configured* channel set up,
521 not potential set ups.
525 output_channels = -1;
527 CAComponentDescription temp;
528 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
529 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
530 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
531 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
532 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
533 compTypeString, compManufacturerString, compSubTypeString);
534 if (compTypeString != NULL) CFRelease(compTypeString);
535 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
536 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
539 au_blacklist(CFStringRefToStdString(itemName));
542 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
543 err = CAAudioUnit::Open (*(comp.get()), *unit);
545 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
546 throw failed_constructor();
550 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
551 throw failed_constructor ();
554 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
555 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
556 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
557 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
558 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
559 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
561 if (input_elements > 0) {
562 /* setup render callback: the plugin calls this to get input data
565 AURenderCallbackStruct renderCallbackInfo;
567 renderCallbackInfo.inputProc = _render_callback;
568 renderCallbackInfo.inputProcRefCon = this;
570 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
571 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
572 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
573 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
574 throw failed_constructor();
578 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
580 HostCallbackInfo info;
581 memset (&info, 0, sizeof (HostCallbackInfo));
582 info.hostUserData = this;
583 info.beatAndTempoProc = _get_beat_and_tempo_callback;
584 info.musicalTimeLocationProc = _get_musical_time_location_callback;
585 info.transportStateProc = _get_transport_state_callback;
587 //ignore result of this - don't care if the property isn't supported
588 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
589 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
590 kAudioUnitScope_Global,
593 sizeof (HostCallbackInfo));
595 if (set_block_size (_session.get_block_size())) {
596 error << _("AUPlugin: cannot set processing block size") << endmsg;
597 throw failed_constructor();
600 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
601 discover_parameters ();
602 discover_factory_presets ();
604 // Plugin::setup_controls ();
606 au_unblacklist(CFStringRefToStdString(itemName));
607 if (itemName != NULL) CFRelease(itemName);
611 AUPlugin::discover_parameters ()
613 /* discover writable parameters */
615 AudioUnitScope scopes[] = {
616 kAudioUnitScope_Global,
617 kAudioUnitScope_Output,
618 kAudioUnitScope_Input
621 descriptors.clear ();
623 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
625 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
627 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
629 AUParameterDescriptor d;
631 d.id = param_info.ParamID (i);
633 const CAAUParameter* param = param_info.GetParamInfo (d.id);
634 const AudioUnitParameterInfo& info (param->ParamInfo());
636 const int len = CFStringGetLength (param->GetName());;
637 char local_buffer[len*2];
638 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
642 d.label = local_buffer;
645 d.scope = param_info.GetScope ();
646 d.element = param_info.GetElement ();
648 /* info.units to consider */
650 kAudioUnitParameterUnit_Generic = 0
651 kAudioUnitParameterUnit_Indexed = 1
652 kAudioUnitParameterUnit_Boolean = 2
653 kAudioUnitParameterUnit_Percent = 3
654 kAudioUnitParameterUnit_Seconds = 4
655 kAudioUnitParameterUnit_SampleFrames = 5
656 kAudioUnitParameterUnit_Phase = 6
657 kAudioUnitParameterUnit_Rate = 7
658 kAudioUnitParameterUnit_Hertz = 8
659 kAudioUnitParameterUnit_Cents = 9
660 kAudioUnitParameterUnit_RelativeSemiTones = 10
661 kAudioUnitParameterUnit_MIDINoteNumber = 11
662 kAudioUnitParameterUnit_MIDIController = 12
663 kAudioUnitParameterUnit_Decibels = 13
664 kAudioUnitParameterUnit_LinearGain = 14
665 kAudioUnitParameterUnit_Degrees = 15
666 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
667 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
668 kAudioUnitParameterUnit_Pan = 18
669 kAudioUnitParameterUnit_Meters = 19
670 kAudioUnitParameterUnit_AbsoluteCents = 20
671 kAudioUnitParameterUnit_Octaves = 21
672 kAudioUnitParameterUnit_BPM = 22
673 kAudioUnitParameterUnit_Beats = 23
674 kAudioUnitParameterUnit_Milliseconds = 24
675 kAudioUnitParameterUnit_Ratio = 25
678 /* info.flags to consider */
682 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
683 kAudioUnitParameterFlag_HasClump = (1L << 20)
684 kAudioUnitParameterFlag_HasName = (1L << 21)
685 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
686 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
687 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
688 kAudioUnitParameterFlag_CanRamp = (1L << 25)
689 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
690 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
691 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
692 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
693 kAudioUnitParameterFlag_IsReadable = (1L << 30)
694 kAudioUnitParameterFlag_IsWritable = (1L << 31)
697 d.lower = info.minValue;
698 d.upper = info.maxValue;
699 d.normal = info.defaultValue;
701 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
702 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
703 (d.integer_step && ((d.upper - d.lower) == 1.0));
704 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
705 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
706 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
707 (info.flags & kAudioUnitParameterFlag_IsWritable);
709 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
710 d.au_unit = info.unit;
712 case kAudioUnitParameterUnit_Decibels:
713 d.unit = ParameterDescriptor::DB;
715 case kAudioUnitParameterUnit_MIDINoteNumber:
716 d.unit = ParameterDescriptor::MIDI_NOTE;
718 case kAudioUnitParameterUnit_Hertz:
719 d.unit = ParameterDescriptor::HZ;
723 d.min_unbound = 0; // lower is bound
724 d.max_unbound = 0; // upper is bound
727 descriptors.push_back (d);
729 uint32_t last_param = descriptors.size() - 1;
730 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
731 listen_to_parameter (last_param);
738 four_ints_to_four_byte_literal (unsigned char n[4])
740 /* this is actually implementation dependent. sigh. this is what gcc
741 and quite a few others do.
743 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
747 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
749 if (isdigit (id[0])) {
753 /* ID format is xxxx-xxxx-xxxx
754 where x maybe \xNN or a printable character.
756 Split at the '-' and and process each part into an integer.
757 Then put it back together.
761 unsigned char nascent[4];
762 const char* cstr = id.c_str();
763 const char* estr = cstr + id.size();
774 while (*cstr && next_int < 4) {
778 if (estr - cstr < 3) {
780 /* too close to the end for \xNN parsing: treat as literal characters */
788 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
792 memcpy (short_buf, &cstr[2], 2);
793 nascent[in] = strtol (short_buf, NULL, 16);
799 /* treat as literal characters */
813 if (in && (in % 4 == 0)) {
814 /* nascent is ready */
815 n[next_int] = four_ints_to_four_byte_literal (nascent);
819 /* swallow space-hyphen-space */
833 s << n[0] << '-' << n[1] << '-' << n[2];
842 AUPlugin::unique_id () const
844 return AUPluginInfo::stringify_descriptor (comp->Desc());
848 AUPlugin::label () const
850 return _info->name.c_str();
854 AUPlugin::parameter_count () const
856 return descriptors.size();
860 AUPlugin::default_value (uint32_t port)
862 if (port < descriptors.size()) {
863 return descriptors[port].normal;
870 AUPlugin::signal_latency () const
872 return unit->Latency() * _session.frame_rate();
876 AUPlugin::set_parameter (uint32_t which, float val)
878 if (which >= descriptors.size()) {
882 if (get_parameter(which) == val) {
886 const AUParameterDescriptor& d (descriptors[which]);
887 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
888 unit->SetParameter (d.id, d.scope, d.element, val);
890 /* tell the world what we did */
892 AudioUnitEvent theEvent;
894 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
895 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
896 theEvent.mArgument.mParameter.mParameterID = d.id;
897 theEvent.mArgument.mParameter.mScope = d.scope;
898 theEvent.mArgument.mParameter.mElement = d.element;
900 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
901 AUEventListenerNotify (NULL, NULL, &theEvent);
903 Plugin::set_parameter (which, val);
907 AUPlugin::get_parameter (uint32_t which) const
910 if (which < descriptors.size()) {
911 const AUParameterDescriptor& d (descriptors[which]);
912 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
913 unit->GetParameter(d.id, d.scope, d.element, val);
919 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
921 if (which < descriptors.size()) {
922 pd = descriptors[which];
929 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
931 if (which < descriptors.size()) {
940 AUPlugin::activate ()
944 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
945 if ((err = unit->Initialize()) != noErr) {
946 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
948 frames_processed = 0;
955 AUPlugin::deactivate ()
957 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
958 unit->Uninitialize ();
965 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
966 unit->GlobalReset ();
970 AUPlugin::requires_fixed_size_buffers() const
972 return _requires_fixed_size_buffers;
977 AUPlugin::set_block_size (pframes_t nframes)
979 bool was_initialized = initialized;
980 UInt32 numFrames = nframes;
987 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
988 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
989 0, &numFrames, sizeof (numFrames))) != noErr) {
990 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
994 if (was_initialized) {
998 _current_block_size = nframes;
1004 AUPlugin::configure_io (ChanCount in, ChanCount out)
1006 AudioStreamBasicDescription streamFormat;
1007 bool was_initialized = initialized;
1008 int32_t audio_in = in.n_audio();
1009 int32_t audio_out = out.n_audio();
1011 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1014 //if we are already running with the requested i/o config, bail out here
1015 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1022 streamFormat.mSampleRate = _session.frame_rate();
1023 streamFormat.mFormatID = kAudioFormatLinearPCM;
1024 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1026 #ifdef __LITTLE_ENDIAN__
1029 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1032 streamFormat.mBitsPerChannel = 32;
1033 streamFormat.mFramesPerPacket = 1;
1035 /* apple says that for non-interleaved data, these
1036 values always refer to a single channel.
1038 streamFormat.mBytesPerPacket = 4;
1039 streamFormat.mBytesPerFrame = 4;
1041 streamFormat.mChannelsPerFrame = audio_in;
1043 if (set_input_format (streamFormat) != 0) {
1047 streamFormat.mChannelsPerFrame = audio_out;
1049 if (set_output_format (streamFormat) != 0) {
1053 /* reset plugin info to show currently configured state */
1055 _info->n_inputs = in;
1056 _info->n_outputs = out;
1058 if (was_initialized) {
1066 AUPlugin::input_streams() const
1071 if (input_channels < 0) {
1072 // force PluginIoReConfigure -- see also commit msg e38eb06
1073 c.set (DataType::AUDIO, 0);
1074 c.set (DataType::MIDI, 0);
1076 c.set (DataType::AUDIO, input_channels);
1077 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1085 AUPlugin::output_streams() const
1089 if (output_channels < 0) {
1090 // force PluginIoReConfigure - see also commit msg e38eb06
1091 c.set (DataType::AUDIO, 0);
1092 c.set (DataType::MIDI, 0);
1094 c.set (DataType::AUDIO, output_channels);
1095 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1102 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1104 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1106 int32_t audio_in = in.n_audio();
1109 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1111 /* lets check MIDI first */
1113 if (in.n_midi() > 0) {
1114 if (!_has_midi_input) {
1119 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1121 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1122 name(), io_configs.size(), in, out));
1124 //Ardour expects the plugin to tell it the output
1125 //configuration but AU plugins can have multiple I/O
1126 //configurations in most cases. so first lets see
1127 //if there's a configuration that keeps out==in
1129 if (in.n_midi() > 0 && audio_in == 0) {
1130 audio_out = 2; // prefer stereo version if available.
1132 audio_out = audio_in;
1135 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1137 int32_t possible_in = i->first;
1138 int32_t possible_out = i->second;
1140 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1141 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1142 possible_in, possible_out,
1145 out.set (DataType::MIDI, 0);
1146 out.set (DataType::AUDIO, audio_out);
1152 /* now allow potentially "imprecise" matches */
1156 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1158 int32_t possible_in = i->first;
1159 int32_t possible_out = i->second;
1161 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1163 if (possible_out == 0) {
1164 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1165 /* XXX surely this is just a send? (e.g. AUNetSend) */
1169 if (possible_in == 0) {
1171 /* instrument plugin, always legal but throws away inputs ...
1174 if (possible_out == -1) {
1175 /* any configuration possible, provide stereo output */
1178 } else if (possible_out == -2) {
1179 /* plugins shouldn't really use (0,-2) but might.
1180 any configuration possible, provide stereo output
1184 } else if (possible_out < -2) {
1185 /* explicitly variable number of outputs.
1187 Since Ardour can handle any configuration,
1188 we have to somehow pick a number.
1190 We'll use the number of inputs
1191 to the master bus, or 2 if there
1194 boost::shared_ptr<Route> master = _session.master_out();
1196 audio_out = master->input()->n_ports().n_audio();
1202 /* exact number of outputs */
1203 audio_out = possible_out;
1208 if (possible_in == -1) {
1210 /* wildcard for input */
1212 if (possible_out == -1) {
1213 /* out much match in */
1214 audio_out = audio_in;
1216 } else if (possible_out == -2) {
1217 /* any configuration possible, pick matching */
1218 audio_out = audio_in;
1220 } else if (possible_out < -2) {
1221 /* explicitly variable number of outputs, pick maximum */
1222 audio_out = -possible_out;
1225 /* exact number of outputs */
1226 audio_out = possible_out;
1231 if (possible_in == -2) {
1233 if (possible_out == -1) {
1234 /* any configuration possible, pick matching */
1235 audio_out = audio_in;
1237 } else if (possible_out == -2) {
1238 /* plugins shouldn't really use (-2,-2) but might.
1239 interpret as (-1,-1).
1241 audio_out = audio_in;
1243 } else if (possible_out < -2) {
1244 /* explicitly variable number of outputs, pick maximum */
1245 audio_out = -possible_out;
1248 /* exact number of outputs */
1249 audio_out = possible_out;
1254 if (possible_in < -2) {
1256 /* explicit variable number of inputs */
1258 if (audio_in > -possible_in) {
1259 /* request is too large */
1263 if (possible_out == -1) {
1264 /* any output configuration possible, provide stereo out */
1267 } else if (possible_out == -2) {
1268 /* plugins shouldn't really use (<-2,-2) but might.
1269 interpret as (<-2,-1): any configuration possible, provide stereo output
1273 } else if (possible_out < -2) {
1274 /* explicitly variable number of outputs.
1276 Since Ardour can handle any configuration,
1277 we have to somehow pick a number.
1279 We'll use the number of inputs
1280 to the master bus, or 2 if there
1283 boost::shared_ptr<Route> master = _session.master_out();
1285 audio_out = master->input()->n_ports().n_audio();
1291 /* exact number of outputs */
1292 audio_out = possible_out;
1297 if (possible_in && (possible_in == audio_in)) {
1299 /* exact number of inputs ... must match obviously */
1301 if (possible_out == -1) {
1302 /* any output configuration possible, provide stereo output */
1305 } else if (possible_out == -2) {
1306 /* plugins shouldn't really use (>0,-2) but might.
1307 interpret as (>0,-1):
1308 any output configuration possible, provide stereo output
1312 } else if (possible_out < -2) {
1313 /* explicitly variable number of outputs, pick maximum */
1314 audio_out = -possible_out;
1317 /* exact number of outputs */
1318 audio_out = possible_out;
1330 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1332 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1336 out.set (DataType::MIDI, 0);
1337 out.set (DataType::AUDIO, audio_out);
1343 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1345 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1349 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1351 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1360 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1361 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1367 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1371 for (uint32_t i = 0; i < cnt; ++i) {
1372 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1373 (scope == kAudioUnitScope_Input ? "input" : "output"),
1375 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1376 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1377 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1382 if (scope == kAudioUnitScope_Input) {
1383 input_channels = fmt.mChannelsPerFrame;
1385 output_channels = fmt.mChannelsPerFrame;
1392 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1393 const AudioTimeStamp*,
1395 UInt32 inNumberFrames,
1396 AudioBufferList* ioData)
1398 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1400 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1401 // name(), inNumberFrames, ioData->mNumberBuffers));
1403 if (input_maxbuf == 0) {
1404 error << _("AUPlugin: render callback called illegally!") << endmsg;
1405 return kAudioUnitErr_CannotDoInCurrentContext;
1407 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1409 for (uint32_t i = 0; i < limit; ++i) {
1410 ioData->mBuffers[i].mNumberChannels = 1;
1411 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1413 /* we don't use the channel mapping because audiounits are
1414 never replicated. one plugin instance uses all channels/buffers
1415 passed to PluginInsert::connect_and_run()
1418 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1421 cb_offset += inNumberFrames;
1427 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1429 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1431 AudioUnitRenderActionFlags flags = 0;
1435 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1436 unit->GlobalReset();
1437 _last_nframes = nframes;
1440 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1441 name(), input_channels, output_channels, _has_midi_input,
1442 bufs.count(), bufs.available()));
1444 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1445 has the capacity to handle our outputs.
1448 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1450 input_buffers = &bufs;
1451 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1452 input_offset = offset;
1455 buffers->mNumberBuffers = output_channels;
1457 for (int32_t i = 0; i < output_channels; ++i) {
1458 buffers->mBuffers[i].mNumberChannels = 1;
1459 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1460 /* setting this to 0 indicates to the AU that it can provide buffers here
1461 if necessary. if it can process in-place, it will use the buffers provided
1462 as input by ::render_callback() above.
1464 a non-null values tells the plugin to render into the buffer pointed
1467 buffers->mBuffers[i].mData = 0;
1470 if (_has_midi_input) {
1472 uint32_t nmidi = bufs.count().n_midi();
1474 for (uint32_t i = 0; i < nmidi; ++i) {
1476 /* one MIDI port/buffer only */
1478 MidiBuffer& m = bufs.get_midi (i);
1480 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1481 Evoral::MIDIEvent<framepos_t> ev (*i);
1483 if (ev.is_channel_event()) {
1484 const uint8_t* b = ev.buffer();
1485 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1486 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1489 /* XXX need to handle sysex and other message types */
1494 /* does this really mean anything ?
1497 ts.mSampleTime = frames_processed;
1498 ts.mFlags = kAudioTimeStampSampleTimeValid;
1500 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1501 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1503 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1506 frames_processed += nframes;
1508 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1509 name(), buffers->mNumberBuffers, output_channels));
1511 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1514 for (i = 0; i < limit; ++i) {
1515 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1516 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1517 /* plugin provided its own buffer for output so copy it back to where we want it
1519 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1523 /* now silence any buffers that were passed in but the that the plugin
1524 did not fill/touch/use.
1527 for (;i < output_channels; ++i) {
1528 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1534 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1539 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1540 Float64* outCurrentTempo)
1542 TempoMap& tmap (_session.tempo_map());
1544 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1546 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1547 (and interpretation) of a beat position will be incorrect. So refuse to
1551 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1552 return kAudioUnitErr_CannotDoInCurrentContext;
1555 Timecode::BBT_Time bbt;
1556 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1557 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1559 if (outCurrentBeat) {
1561 beat = metric.meter().divisions_per_bar() * bbt.bars;
1563 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1564 *outCurrentBeat = beat;
1567 if (outCurrentTempo) {
1568 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1576 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1577 Float32* outTimeSig_Numerator,
1578 UInt32* outTimeSig_Denominator,
1579 Float64* outCurrentMeasureDownBeat)
1581 TempoMap& tmap (_session.tempo_map());
1583 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1585 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1586 (and interpretation) of a beat position will be incorrect. So refuse to
1590 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1591 return kAudioUnitErr_CannotDoInCurrentContext;
1594 Timecode::BBT_Time bbt;
1595 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1596 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1598 if (outDeltaSampleOffsetToNextBeat) {
1599 if (bbt.ticks == 0) {
1601 *outDeltaSampleOffsetToNextBeat = 0;
1603 *outDeltaSampleOffsetToNextBeat = (UInt32)
1604 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1605 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1609 if (outTimeSig_Numerator) {
1610 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1612 if (outTimeSig_Denominator) {
1613 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1616 if (outCurrentMeasureDownBeat) {
1618 /* beat for the start of the bar.
1620 2|1|0 -> 1 + divisions_per_bar
1621 3|1|0 -> 1 + (2 * divisions_per_bar)
1625 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1632 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1633 Boolean* outTransportStateChanged,
1634 Float64* outCurrentSampleInTimeLine,
1635 Boolean* outIsCycling,
1636 Float64* outCycleStartBeat,
1637 Float64* outCycleEndBeat)
1642 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1644 rolling = _session.transport_rolling();
1645 speed = _session.transport_speed ();
1648 *outIsPlaying = _session.transport_rolling();
1651 if (outTransportStateChanged) {
1652 if (rolling != last_transport_rolling) {
1653 *outTransportStateChanged = true;
1654 } else if (speed != last_transport_speed) {
1655 *outTransportStateChanged = true;
1657 *outTransportStateChanged = false;
1661 if (outCurrentSampleInTimeLine) {
1662 /* this assumes that the AU can only call this host callback from render context,
1663 where input_offset is valid.
1665 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1669 Location* loc = _session.locations()->auto_loop_location();
1671 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1673 if (*outIsCycling) {
1675 if (outCycleStartBeat || outCycleEndBeat) {
1677 TempoMap& tmap (_session.tempo_map());
1679 /* more than 1 meter means that a simplistic computation (and interpretation) of
1680 a beat position will be incorrect. so refuse to offer the value.
1683 if (tmap.n_meters() > 1) {
1684 return kAudioUnitErr_CannotDoInCurrentContext;
1687 Timecode::BBT_Time bbt;
1689 if (outCycleStartBeat) {
1690 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1691 _session.tempo_map().bbt_time (loc->start(), bbt);
1694 beat = metric.meter().divisions_per_bar() * bbt.bars;
1696 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1698 *outCycleStartBeat = beat;
1701 if (outCycleEndBeat) {
1702 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1703 _session.tempo_map().bbt_time (loc->end(), bbt);
1706 beat = metric.meter().divisions_per_bar() * bbt.bars;
1708 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1710 *outCycleEndBeat = beat;
1716 last_transport_rolling = rolling;
1717 last_transport_speed = speed;
1722 set<Evoral::Parameter>
1723 AUPlugin::automatable() const
1725 set<Evoral::Parameter> automates;
1727 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1728 if (descriptors[i].automatable) {
1729 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1737 AUPlugin::describe_parameter (Evoral::Parameter param)
1739 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1740 return descriptors[param.id()].label;
1747 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1749 // NameValue stuff here
1753 AUPlugin::parameter_is_audio (uint32_t) const
1759 AUPlugin::parameter_is_control (uint32_t param) const
1761 assert(param < descriptors.size());
1762 if (descriptors[param].automatable) {
1763 /* corrently ardour expects all controls to be automatable
1764 * IOW ardour GUI elements mandate an Evoral::Parameter
1765 * for all input+control ports.
1773 AUPlugin::parameter_is_input (uint32_t param) const
1775 /* AU params that are both readable and writeable,
1776 * are listed in kAudioUnitScope_Global
1778 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1782 AUPlugin::parameter_is_output (uint32_t param) const
1784 assert(param < descriptors.size());
1785 // TODO check if ardour properly handles ports
1786 // that report is_input + is_output == true
1787 // -> add || descriptors[param].scope == kAudioUnitScope_Global
1788 return (descriptors[param].scope == kAudioUnitScope_Output);
1792 AUPlugin::add_state (XMLNode* root) const
1794 LocaleGuard lg (X_("C"));
1796 CFPropertyListRef propertyList;
1798 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1799 if (unit->GetAUPreset (propertyList) != noErr) {
1803 // Convert the property list into XML data.
1805 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1808 error << _("Could not create XML version of property list") << endmsg;
1812 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1813 our state node. GACK!
1818 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1820 root->add_child_copy (*t.root());
1824 CFRelease (xmlData);
1825 CFRelease (propertyList);
1829 AUPlugin::set_state(const XMLNode& node, int version)
1832 CFPropertyListRef propertyList;
1833 LocaleGuard lg (X_("C"));
1835 if (node.name() != state_node_name()) {
1836 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1840 #ifndef NO_PLUGIN_STATE
1841 if (node.children().empty()) {
1845 XMLNode* top = node.children().front();
1846 XMLNode* copy = new XMLNode (*top);
1851 const string& xml = t.write_buffer ();
1852 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1853 CFStringRef errorString;
1855 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1857 kCFPropertyListImmutable,
1860 CFRelease (xmlData);
1863 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1864 if (unit->SetAUPreset (propertyList) == noErr) {
1867 /* tell the world */
1869 AudioUnitParameter changedUnit;
1870 changedUnit.mAudioUnit = unit->AU();
1871 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1872 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1874 CFRelease (propertyList);
1878 Plugin::set_state (node, version);
1883 AUPlugin::load_preset (PresetRecord r)
1885 Plugin::load_preset (r);
1888 CFPropertyListRef propertyList;
1890 UserPresetMap::iterator ux;
1891 FactoryPresetMap::iterator fx;
1893 /* look first in "user" presets */
1895 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1897 if ((propertyList = load_property_list (ux->second)) != 0) {
1898 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1899 if (unit->SetAUPreset (propertyList) == noErr) {
1902 /* tell the world */
1904 AudioUnitParameter changedUnit;
1905 changedUnit.mAudioUnit = unit->AU();
1906 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1907 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1909 CFRelease(propertyList);
1912 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1916 preset.presetNumber = fx->second;
1917 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1919 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1921 if (unit->SetPresentPreset (preset) == 0) {
1924 /* tell the world */
1926 AudioUnitParameter changedUnit;
1927 changedUnit.mAudioUnit = unit->AU();
1928 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1929 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1937 AUPlugin::do_remove_preset (std::string)
1942 AUPlugin::do_save_preset (string preset_name)
1944 CFPropertyListRef propertyList;
1945 vector<Glib::ustring> v;
1946 Glib::ustring user_preset_path;
1948 std::string m = maker();
1949 std::string n = name();
1951 strip_whitespace_edges (m);
1952 strip_whitespace_edges (n);
1954 v.push_back (Glib::get_home_dir());
1955 v.push_back ("Library");
1956 v.push_back ("Audio");
1957 v.push_back ("Presets");
1961 user_preset_path = Glib::build_filename (v);
1963 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1964 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1968 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1969 if (unit->GetAUPreset (propertyList) != noErr) {
1973 // add the actual preset name */
1975 v.push_back (preset_name + preset_suffix);
1979 user_preset_path = Glib::build_filename (v);
1981 set_preset_name_in_plist (propertyList, preset_name);
1983 if (save_property_list (propertyList, user_preset_path)) {
1984 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1988 CFRelease(propertyList);
1990 user_preset_map[preset_name] = user_preset_path;;
1992 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
1994 return string ("file:///") + user_preset_path;
1997 //-----------------------------------------------------------------------------
1998 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2000 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2002 CFNumberRef cfNumber;
2003 SInt32 numberValue = 0;
2004 Boolean dummySuccess;
2006 if (outSuccess == NULL)
2007 outSuccess = &dummySuccess;
2008 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2010 *outSuccess = FALSE;
2014 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2015 if (cfNumber == NULL)
2017 *outSuccess = FALSE;
2020 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2028 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
2030 CFDictionaryRef auStateDictionary;
2031 ComponentDescription tempDesc = {0,0,0,0,0};
2032 SInt32 versionValue;
2035 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2038 // the property list for AU state data must be of the dictionary type
2039 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2040 return kAudioUnitErr_InvalidPropertyValue;
2043 auStateDictionary = (CFDictionaryRef)inAUStateData;
2045 // first check to make sure that the version of the AU state data is one that we know understand
2046 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2047 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2050 return kAudioUnitErr_InvalidPropertyValue;
2052 #define kCurrentSavedStateVersion 0
2053 if (versionValue != kCurrentSavedStateVersion) {
2054 return kAudioUnitErr_InvalidPropertyValue;
2057 // grab the ComponentDescription values from the AU state data
2058 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2059 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2060 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2061 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2062 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2063 return kAudioUnitErr_InvalidPropertyValue;
2065 *outComponentDescription = tempDesc;
2070 static bool au_preset_filter (const string& str, void* arg)
2072 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2076 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2080 /* check the preset file path name against this plugin
2081 ID. The idea is that all preset files for this plugin
2082 include "<manufacturer>/<plugin-name>" in their path.
2085 Plugin* p = (Plugin *) arg;
2086 string match = p->maker();
2090 ret = str.find (match) != string::npos;
2093 string m = p->maker ();
2094 string n = p->name ();
2095 strip_whitespace_edges (m);
2096 strip_whitespace_edges (n);
2101 ret = str.find (match) != string::npos;
2109 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2112 CFPropertyListRef plist;
2113 ComponentDescription presetDesc;
2116 plist = load_property_list (pathstr);
2122 // get the ComponentDescription from the AU preset file
2124 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2126 if (status == noErr) {
2127 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2129 /* try to get the preset name from the property list */
2131 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2133 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2137 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2140 char buf[PATH_MAX+1];
2142 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2157 AUPlugin::current_preset() const
2161 CFPropertyListRef propertyList;
2163 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2164 if (unit->GetAUPreset (propertyList) == noErr) {
2165 preset_name = get_preset_name_in_plist (propertyList);
2166 CFRelease(propertyList);
2173 AUPlugin::find_presets ()
2175 vector<string> preset_files;
2177 user_preset_map.clear ();
2179 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2181 if (preset_files.empty()) {
2182 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2186 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2191 /* make an initial guess at the preset name using the path */
2193 preset_name = Glib::path_get_basename (path);
2194 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2196 /* check that this preset file really matches this plugin
2197 and potentially get the "real" preset name from
2201 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2202 user_preset_map[preset_name] = path;
2203 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2205 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2210 /* now fill the vector<string> with the names we have */
2212 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2213 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2214 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2217 /* add factory presets */
2219 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2221 string const uri = string_compose ("%1", _presets.size ());
2222 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2223 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2228 AUPlugin::has_editor () const
2230 // even if the plugin doesn't have its own editor, the AU API can be used
2231 // to create one that looks native.
2235 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2238 type = ARDOUR::AudioUnit;
2241 AUPluginInfo::~AUPluginInfo ()
2243 type = ARDOUR::AudioUnit;
2247 AUPluginInfo::load (Session& session)
2252 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2253 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2255 if (!comp->IsValid()) {
2256 error << ("AudioUnit: not a valid Component") << endmsg;
2258 plugin.reset (new AUPlugin (session.engine(), session, comp));
2261 AUPluginInfo *aup = new AUPluginInfo (*this);
2262 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2263 plugin->set_info (PluginInfoPtr (aup));
2264 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2268 catch (failed_constructor &err) {
2269 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2270 return PluginPtr ();
2275 AUPluginInfo::au_cache_path ()
2277 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2281 AUPluginInfo::discover (bool scan_only)
2285 /* AU require a CAComponentDescription pointer provided by the OS.
2286 * Ardour only caches port and i/o config. It can't just 'scan' without
2287 * 'discovering' (like we do for VST).
2290 * "Iterate over all plugins. skip the ones where there's no io-cache".
2292 _scan_only = scan_only;
2294 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2295 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2297 // create crash log file
2298 au_start_crashlog ();
2300 PluginInfoList* plugs = new PluginInfoList;
2302 discover_fx (*plugs);
2303 discover_music (*plugs);
2304 discover_generators (*plugs);
2305 discover_instruments (*plugs);
2307 // all fine if we get here
2308 au_remove_crashlog ();
2310 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2316 AUPluginInfo::discover_music (PluginInfoList& plugs)
2318 CAComponentDescription desc;
2319 desc.componentFlags = 0;
2320 desc.componentFlagsMask = 0;
2321 desc.componentSubType = 0;
2322 desc.componentManufacturer = 0;
2323 desc.componentType = kAudioUnitType_MusicEffect;
2325 discover_by_description (plugs, desc);
2329 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2331 CAComponentDescription desc;
2332 desc.componentFlags = 0;
2333 desc.componentFlagsMask = 0;
2334 desc.componentSubType = 0;
2335 desc.componentManufacturer = 0;
2336 desc.componentType = kAudioUnitType_Effect;
2338 discover_by_description (plugs, desc);
2342 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2344 CAComponentDescription desc;
2345 desc.componentFlags = 0;
2346 desc.componentFlagsMask = 0;
2347 desc.componentSubType = 0;
2348 desc.componentManufacturer = 0;
2349 desc.componentType = kAudioUnitType_Generator;
2351 discover_by_description (plugs, desc);
2355 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2357 CAComponentDescription desc;
2358 desc.componentFlags = 0;
2359 desc.componentFlagsMask = 0;
2360 desc.componentSubType = 0;
2361 desc.componentManufacturer = 0;
2362 desc.componentType = kAudioUnitType_MusicDevice;
2364 discover_by_description (plugs, desc);
2369 AUPluginInfo::au_get_crashlog (std::string &msg)
2371 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2372 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2375 std::ifstream ifs(fn.c_str());
2376 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2377 au_remove_crashlog ();
2382 AUPluginInfo::au_start_crashlog ()
2384 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2385 assert(!_crashlog_fd);
2386 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2387 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2388 PBD::error << "Cannot create AU error-log" << fn << "\n";
2389 cerr << "Cannot create AU error-log" << fn << "\n";
2394 AUPluginInfo::au_remove_crashlog ()
2397 ::fclose(_crashlog_fd);
2398 _crashlog_fd = NULL;
2400 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2401 ::g_unlink(fn.c_str());
2402 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2407 AUPluginInfo::au_crashlog (std::string msg)
2409 if (!_crashlog_fd) {
2410 fprintf(stderr, "AU: %s\n", msg.c_str());
2412 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2413 ::fflush(_crashlog_fd);
2418 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2421 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2423 comp = FindNextComponent (NULL, &desc);
2425 while (comp != NULL) {
2426 CAComponentDescription temp;
2427 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2428 CFStringRef itemName = NULL;
2431 if (itemName != NULL) CFRelease(itemName);
2432 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2433 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2434 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2435 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2436 compTypeString, compManufacturerString, compSubTypeString);
2437 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2438 if (compTypeString != NULL)
2439 CFRelease(compTypeString);
2440 if (compSubTypeString != NULL)
2441 CFRelease(compSubTypeString);
2442 if (compManufacturerString != NULL)
2443 CFRelease(compManufacturerString);
2446 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2447 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2448 comp = FindNextComponent (comp, &desc);
2452 AUPluginInfoPtr info (new AUPluginInfo
2453 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2455 /* although apple designed the subtype field to be a "category" indicator,
2456 its really turned into a plugin ID field for a given manufacturer. Hence
2457 there are no categories for AudioUnits. However, to keep the plugins
2458 showing up under "categories", we'll use the "type" as a high level
2461 NOTE: no panners, format converters or i/o AU's for our purposes
2464 switch (info->descriptor->Type()) {
2465 case kAudioUnitType_Panner:
2466 case kAudioUnitType_OfflineEffect:
2467 case kAudioUnitType_FormatConverter:
2468 comp = FindNextComponent (comp, &desc);
2471 case kAudioUnitType_Output:
2472 info->category = _("AudioUnit Outputs");
2474 case kAudioUnitType_MusicDevice:
2475 info->category = _("AudioUnit Instruments");
2477 case kAudioUnitType_MusicEffect:
2478 info->category = _("AudioUnit MusicEffects");
2480 case kAudioUnitType_Effect:
2481 info->category = _("AudioUnit Effects");
2483 case kAudioUnitType_Mixer:
2484 info->category = _("AudioUnit Mixers");
2486 case kAudioUnitType_Generator:
2487 info->category = _("AudioUnit Generators");
2490 info->category = _("AudioUnit (Unknown)");
2494 au_blacklist(CFStringRefToStdString(itemName));
2495 AUPluginInfo::get_names (temp, info->name, info->creator);
2496 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2497 au_crashlog(string_compose("Plugin: %1", info->name));
2499 info->type = ARDOUR::AudioUnit;
2500 info->unique_id = stringify_descriptor (*info->descriptor);
2502 /* XXX not sure of the best way to handle plugin versioning yet
2505 CAComponent cacomp (*info->descriptor);
2507 if (cacomp.GetResourceVersion (info->version) != noErr) {
2511 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2514 /* here we have to map apple's wildcard system to a simple pair
2515 of values. in ::can_do() we use the whole system, but here
2516 we need a single pair of values. XXX probably means we should
2517 remove any use of these values.
2519 for now, if the plugin provides a wildcard, treat it as 1. we really
2520 don't care much, because whether we can handle an i/o configuration
2521 depends upon ::can_support_io_configuration(), not these counts.
2523 they exist because other parts of ardour try to present i/o configuration
2524 info to the user, which should perhaps be revisited.
2527 int32_t possible_in = info->cache.io_configs.front().first;
2528 int32_t possible_out = info->cache.io_configs.front().second;
2530 if (possible_in > 0) {
2531 info->n_inputs.set (DataType::AUDIO, possible_in);
2533 info->n_inputs.set (DataType::AUDIO, 1);
2536 if (possible_out > 0) {
2537 info->n_outputs.set (DataType::AUDIO, possible_out);
2539 info->n_outputs.set (DataType::AUDIO, 1);
2542 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2543 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2545 plugs.push_back (info);
2548 else if (rv == -1) {
2549 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2552 au_unblacklist(CFStringRefToStdString(itemName));
2553 au_crashlog("Success.");
2554 comp = FindNextComponent (comp, &desc);
2555 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2557 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2561 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2564 AUPluginCachedInfo& cinfo,
2565 const std::string& name)
2570 /* concatenate unique ID with version to provide a key for cached info lookup.
2571 this ensures we don't get stale information, or should if plugin developers
2572 follow Apple "guidelines".
2575 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2580 CachedInfoMap::iterator cim = cached_info.find (id);
2582 if (cim != cached_info.end()) {
2583 cinfo = cim->second;
2588 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), unique_id) << endmsg;
2593 AUChannelInfo* channel_info;
2597 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2601 if (CAAudioUnit::Open (comp, unit) != noErr) {
2607 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2612 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2613 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2619 /* no explicit info available, so default to 1in/1out */
2621 /* XXX this is wrong. we should be indicating wildcard values */
2623 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2627 /* store each configuration */
2629 for (uint32_t n = 0; n < cnt; ++n) {
2630 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2631 channel_info[n].outChannels));
2634 free (channel_info);
2637 add_cached_info (id, cinfo);
2638 save_cached_info ();
2644 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2646 cached_info[id] = cinfo;
2649 #define AU_CACHE_VERSION "2.0"
2652 AUPluginInfo::save_cached_info ()
2656 node = new XMLNode (X_("AudioUnitPluginCache"));
2657 node->add_property( "version", AU_CACHE_VERSION );
2659 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2660 XMLNode* parent = new XMLNode (X_("plugin"));
2661 parent->add_property ("id", i->first);
2662 node->add_child_nocopy (*parent);
2664 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2666 XMLNode* child = new XMLNode (X_("io"));
2669 snprintf (buf, sizeof (buf), "%d", j->first);
2670 child->add_property (X_("in"), buf);
2671 snprintf (buf, sizeof (buf), "%d", j->second);
2672 child->add_property (X_("out"), buf);
2673 parent->add_child_nocopy (*child);
2678 Glib::ustring path = au_cache_path ();
2681 tree.set_root (node);
2683 if (!tree.write (path)) {
2684 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2685 g_unlink (path.c_str());
2690 AUPluginInfo::load_cached_info ()
2692 Glib::ustring path = au_cache_path ();
2695 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2699 if ( !tree.read (path) ) {
2700 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2704 const XMLNode* root (tree.root());
2706 if (root->name() != X_("AudioUnitPluginCache")) {
2710 //initial version has incorrectly stored i/o info, and/or garbage chars.
2711 const XMLProperty* version = root->property(X_("version"));
2712 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2713 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2717 cached_info.clear ();
2719 const XMLNodeList children = root->children();
2721 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2723 const XMLNode* child = *iter;
2725 if (child->name() == X_("plugin")) {
2727 const XMLNode* gchild;
2728 const XMLNodeList gchildren = child->children();
2729 const XMLProperty* prop = child->property (X_("id"));
2735 string id = prop->value();
2739 string::size_type slash = id.find_last_of ('/');
2741 if (slash == string::npos) {
2745 version = id.substr (slash);
2746 id = id.substr (0, slash);
2747 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2749 if (fixed.empty()) {
2750 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2757 AUPluginCachedInfo cinfo;
2759 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2763 if (gchild->name() == X_("io")) {
2767 const XMLProperty* iprop;
2768 const XMLProperty* oprop;
2770 if (((iprop = gchild->property (X_("in"))) != 0) &&
2771 ((oprop = gchild->property (X_("out"))) != 0)) {
2772 in = atoi (iprop->value());
2773 out = atoi (oprop->value());
2775 cinfo.io_configs.push_back (pair<int,int> (in, out));
2780 if (cinfo.io_configs.size()) {
2781 add_cached_info (id, cinfo);
2790 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2792 CFStringRef itemName = NULL;
2794 // Marc Poirier-style item name
2795 CAComponent auComponent (comp_desc);
2796 if (auComponent.IsValid()) {
2797 CAComponentDescription dummydesc;
2798 Handle nameHandle = NewHandle(sizeof(void*));
2799 if (nameHandle != NULL) {
2800 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2802 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2803 if (nameString != NULL) {
2804 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2807 DisposeHandle(nameHandle);
2811 // if Marc-style fails, do the original way
2812 if (itemName == NULL) {
2813 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2814 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2815 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2817 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2818 compTypeString, compManufacturerString, compSubTypeString);
2820 if (compTypeString != NULL)
2821 CFRelease(compTypeString);
2822 if (compSubTypeString != NULL)
2823 CFRelease(compSubTypeString);
2824 if (compManufacturerString != NULL)
2825 CFRelease(compManufacturerString);
2828 string str = CFStringRefToStdString(itemName);
2829 string::size_type colon = str.find (':');
2832 name = str.substr (colon+1);
2833 maker = str.substr (0, colon);
2834 strip_whitespace_edges (maker);
2835 strip_whitespace_edges (name);
2839 strip_whitespace_edges (name);
2844 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2848 /* note: OSType is a compiler-implemenation-defined value,
2849 historically a 32 bit integer created with a multi-character
2850 constant such as 'abcd'. It is, fundamentally, an abomination.
2855 s << desc.SubType();
2863 AUPluginInfo::needs_midi_input ()
2865 return is_effect_with_midi_input () || is_instrument ();
2869 AUPluginInfo::is_effect () const
2871 return is_effect_without_midi_input() || is_effect_with_midi_input();
2875 AUPluginInfo::is_effect_without_midi_input () const
2877 return descriptor->IsAUFX();
2881 AUPluginInfo::is_effect_with_midi_input () const
2883 return descriptor->IsAUFM();
2887 AUPluginInfo::is_instrument () const
2889 return descriptor->IsMusicDevice();
2893 AUPlugin::set_info (PluginInfoPtr info)
2895 Plugin::set_info (info);
2897 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2898 _has_midi_input = pinfo->needs_midi_input ();
2899 _has_midi_output = false;
2903 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2906 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2908 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2910 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2912 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2916 _parameter_listener_arg = arg;
2922 AUPlugin::listen_to_parameter (uint32_t param_id)
2924 AudioUnitEvent event;
2926 if (!_parameter_listener || param_id >= descriptors.size()) {
2930 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2931 event.mArgument.mParameter.mAudioUnit = unit->AU();
2932 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2933 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2934 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2936 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2940 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2941 event.mArgument.mParameter.mAudioUnit = unit->AU();
2942 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2943 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2944 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2946 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2950 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2951 event.mArgument.mParameter.mAudioUnit = unit->AU();
2952 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2953 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2954 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2956 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2964 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2966 AudioUnitEvent event;
2968 if (!_parameter_listener || param_id >= descriptors.size()) {
2972 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2973 event.mArgument.mParameter.mAudioUnit = unit->AU();
2974 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2975 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2976 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2978 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2982 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2983 event.mArgument.mParameter.mAudioUnit = unit->AU();
2984 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2985 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2986 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2988 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2992 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2993 event.mArgument.mParameter.mAudioUnit = unit->AU();
2994 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2995 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2996 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2998 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3006 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3008 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3012 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3014 ParameterMap::iterator i;
3016 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3020 switch (event->mEventType) {
3021 case kAudioUnitEvent_BeginParameterChangeGesture:
3022 StartTouch (i->second);
3024 case kAudioUnitEvent_EndParameterChangeGesture:
3025 EndTouch (i->second);
3027 case kAudioUnitEvent_ParameterValueChange:
3028 ParameterChanged (i->second, new_value);