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";
102 std::ifstream ifs(fn.c_str());
103 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
106 ::g_unlink (fn.c_str());
108 assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
109 assert(id.find("\n") == string::npos);
111 id += "\n"; // add separator
112 const size_t rpl = bl.find(id);
113 if (rpl != string::npos) {
114 bl.replace(rpl, id.size(), "");
120 FILE * blacklist_fd = NULL;
121 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
122 PBD::error << "Cannot open AU blacklist.\n";
125 fprintf(blacklist_fd, "%s", bl.c_str());
126 ::fclose(blacklist_fd);
129 static bool is_blacklisted (std::string id)
131 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
132 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
136 std::ifstream ifs(fn.c_str());
137 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
139 assert(id.find("\n") == string::npos);
141 id += "\n"; // add separator
142 const size_t rpl = bl.find(id);
143 if (rpl != string::npos) {
152 _render_callback(void *userData,
153 AudioUnitRenderActionFlags *ioActionFlags,
154 const AudioTimeStamp *inTimeStamp,
156 UInt32 inNumberFrames,
157 AudioBufferList* ioData)
160 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
166 _get_beat_and_tempo_callback (void* userData,
167 Float64* outCurrentBeat,
168 Float64* outCurrentTempo)
171 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
178 _get_musical_time_location_callback (void * userData,
179 UInt32 * outDeltaSampleOffsetToNextBeat,
180 Float32 * outTimeSig_Numerator,
181 UInt32 * outTimeSig_Denominator,
182 Float64 * outCurrentMeasureDownBeat)
185 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
186 outTimeSig_Numerator,
187 outTimeSig_Denominator,
188 outCurrentMeasureDownBeat);
194 _get_transport_state_callback (void* userData,
195 Boolean* outIsPlaying,
196 Boolean* outTransportStateChanged,
197 Float64* outCurrentSampleInTimeLine,
198 Boolean* outIsCycling,
199 Float64* outCycleStartBeat,
200 Float64* outCycleEndBeat)
203 return ((AUPlugin*)userData)->get_transport_state_callback (
204 outIsPlaying, outTransportStateChanged,
205 outCurrentSampleInTimeLine, outIsCycling,
206 outCycleStartBeat, outCycleEndBeat);
213 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
219 // Convert the property list into XML data.
221 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
224 error << _("Could not create XML version of property list") << endmsg;
228 // Write the XML data to the file.
230 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
232 if (errno == EEXIST) {
233 error << string_compose (_("Preset file %1 exists; not overwriting"),
236 error << string_compose (_("Cannot open preset file %1 (%2)"),
237 path, strerror (errno)) << endmsg;
243 size_t cnt = CFDataGetLength (xmlData);
245 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
256 static CFPropertyListRef
257 load_property_list (Glib::ustring path)
260 CFPropertyListRef propertyList = 0;
262 CFStringRef errorString;
264 // Read the XML file.
266 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
271 off_t len = lseek (fd, 0, SEEK_END);
272 char* buf = new char[len];
273 lseek (fd, 0, SEEK_SET);
275 if (read (fd, buf, len) != len) {
283 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
285 // Reconstitute the dictionary using the XML data.
287 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
289 kCFPropertyListImmutable,
298 //-----------------------------------------------------------------------------
300 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
305 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
307 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
308 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
314 //-----------------------------------------------------------------------------
316 get_preset_name_in_plist (CFPropertyListRef plist)
324 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
325 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
327 CFStringRef str = (CFStringRef) p;
328 int len = CFStringGetLength(str);
330 char local_buffer[len];
331 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
339 //--------------------------------------------------------------------------
340 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
341 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
342 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
343 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
345 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
348 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
349 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
351 // only sub-type and manufacturer IDs need to be equal
354 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
355 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
362 //--------------------------------------------------------------------------
363 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
364 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
365 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
366 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
369 ComponentDescription desc;
371 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
374 // get the ComponentDescription of the input Component
375 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
379 // check if the Component's ComponentDescription matches the input ComponentDescription
380 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
383 //--------------------------------------------------------------------------
384 // determine if 2 ComponentDescriptions are basically equal
385 // (by that, I mean that the important identifying values are compared,
386 // but not the ComponentDescription flags)
387 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
389 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
392 //--------------------------------------------------------------------------
393 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
394 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
396 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
399 //--------------------------------------------------------------------------
400 // determine if a ComponentDescription basically matches that of a particular Component
401 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
403 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
406 //--------------------------------------------------------------------------
407 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
408 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
410 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
414 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
415 : Plugin (engine, session)
417 , unit (new CAAudioUnit)
418 , initialized (false)
419 , _current_block_size (0)
420 , _requires_fixed_size_buffers (false)
425 , frames_processed (0)
426 , _parameter_listener (0)
427 , _parameter_listener_arg (0)
428 , last_transport_rolling (false)
429 , last_transport_speed (0.0)
431 if (!preset_search_path_initialized) {
432 Glib::ustring p = Glib::get_home_dir();
433 p += "/Library/Audio/Presets:";
434 p += preset_search_path;
435 preset_search_path = p;
436 preset_search_path_initialized = true;
437 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
444 AUPlugin::AUPlugin (const AUPlugin& other)
446 , comp (other.get_comp())
447 , unit (new CAAudioUnit)
448 , initialized (false)
449 , _current_block_size (0)
451 , _requires_fixed_size_buffers (false)
456 , frames_processed (0)
457 , _parameter_listener (0)
458 , _parameter_listener_arg (0)
462 for (size_t i = 0; i < descriptors.size(); ++i) {
463 set_parameter (i, other.get_parameter (i));
467 AUPlugin::~AUPlugin ()
469 if (_parameter_listener) {
470 AUListenerDispose (_parameter_listener);
471 _parameter_listener = 0;
475 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
476 unit->Uninitialize ();
485 AUPlugin::discover_factory_presets ()
492 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
493 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
497 assert (dataSize == sizeof (presets));
499 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
500 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
508 CFIndex cnt = CFArrayGetCount (presets);
510 for (CFIndex i = 0; i < cnt; ++i) {
511 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
513 string name = CFStringRefToStdString (preset->presetName);
514 factory_preset_map[name] = preset->presetNumber;
515 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
525 CFStringRef itemName;
527 /* these keep track of *configured* channel set up,
528 not potential set ups.
532 output_channels = -1;
534 CAComponentDescription temp;
535 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
536 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
537 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
538 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
539 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
540 compTypeString, compManufacturerString, compSubTypeString);
541 if (compTypeString != NULL) CFRelease(compTypeString);
542 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
543 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
546 au_blacklist(CFStringRefToStdString(itemName));
549 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
550 err = CAAudioUnit::Open (*(comp.get()), *unit);
552 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
553 throw failed_constructor();
557 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
558 throw failed_constructor ();
561 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
562 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
563 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
564 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
565 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
566 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
568 if (input_elements > 0) {
569 /* setup render callback: the plugin calls this to get input data
572 AURenderCallbackStruct renderCallbackInfo;
574 renderCallbackInfo.inputProc = _render_callback;
575 renderCallbackInfo.inputProcRefCon = this;
577 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
578 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
579 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
580 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
581 throw failed_constructor();
585 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
587 HostCallbackInfo info;
588 memset (&info, 0, sizeof (HostCallbackInfo));
589 info.hostUserData = this;
590 info.beatAndTempoProc = _get_beat_and_tempo_callback;
591 info.musicalTimeLocationProc = _get_musical_time_location_callback;
592 info.transportStateProc = _get_transport_state_callback;
594 //ignore result of this - don't care if the property isn't supported
595 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
596 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
597 kAudioUnitScope_Global,
600 sizeof (HostCallbackInfo));
602 if (set_block_size (_session.get_block_size())) {
603 error << _("AUPlugin: cannot set processing block size") << endmsg;
604 throw failed_constructor();
607 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
608 discover_parameters ();
609 discover_factory_presets ();
611 // Plugin::setup_controls ();
613 au_unblacklist(CFStringRefToStdString(itemName));
614 if (itemName != NULL) CFRelease(itemName);
618 AUPlugin::discover_parameters ()
620 /* discover writable parameters */
622 AudioUnitScope scopes[] = {
623 kAudioUnitScope_Global,
624 kAudioUnitScope_Output,
625 kAudioUnitScope_Input
628 descriptors.clear ();
630 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
632 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
634 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
636 AUParameterDescriptor d;
638 d.id = param_info.ParamID (i);
640 const CAAUParameter* param = param_info.GetParamInfo (d.id);
641 const AudioUnitParameterInfo& info (param->ParamInfo());
643 const int len = CFStringGetLength (param->GetName());;
644 char local_buffer[len*2];
645 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
649 d.label = local_buffer;
652 d.scope = param_info.GetScope ();
653 d.element = param_info.GetElement ();
655 /* info.units to consider */
657 kAudioUnitParameterUnit_Generic = 0
658 kAudioUnitParameterUnit_Indexed = 1
659 kAudioUnitParameterUnit_Boolean = 2
660 kAudioUnitParameterUnit_Percent = 3
661 kAudioUnitParameterUnit_Seconds = 4
662 kAudioUnitParameterUnit_SampleFrames = 5
663 kAudioUnitParameterUnit_Phase = 6
664 kAudioUnitParameterUnit_Rate = 7
665 kAudioUnitParameterUnit_Hertz = 8
666 kAudioUnitParameterUnit_Cents = 9
667 kAudioUnitParameterUnit_RelativeSemiTones = 10
668 kAudioUnitParameterUnit_MIDINoteNumber = 11
669 kAudioUnitParameterUnit_MIDIController = 12
670 kAudioUnitParameterUnit_Decibels = 13
671 kAudioUnitParameterUnit_LinearGain = 14
672 kAudioUnitParameterUnit_Degrees = 15
673 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
674 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
675 kAudioUnitParameterUnit_Pan = 18
676 kAudioUnitParameterUnit_Meters = 19
677 kAudioUnitParameterUnit_AbsoluteCents = 20
678 kAudioUnitParameterUnit_Octaves = 21
679 kAudioUnitParameterUnit_BPM = 22
680 kAudioUnitParameterUnit_Beats = 23
681 kAudioUnitParameterUnit_Milliseconds = 24
682 kAudioUnitParameterUnit_Ratio = 25
685 /* info.flags to consider */
689 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
690 kAudioUnitParameterFlag_HasClump = (1L << 20)
691 kAudioUnitParameterFlag_HasName = (1L << 21)
692 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
693 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
694 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
695 kAudioUnitParameterFlag_CanRamp = (1L << 25)
696 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
697 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
698 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
699 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
700 kAudioUnitParameterFlag_IsReadable = (1L << 30)
701 kAudioUnitParameterFlag_IsWritable = (1L << 31)
704 d.lower = info.minValue;
705 d.upper = info.maxValue;
706 d.normal = info.defaultValue;
708 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
709 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
710 (d.integer_step && ((d.upper - d.lower) == 1.0));
711 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
712 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
713 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
714 (info.flags & kAudioUnitParameterFlag_IsWritable);
716 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
717 d.au_unit = info.unit;
719 case kAudioUnitParameterUnit_Decibels:
720 d.unit = ParameterDescriptor::DB;
722 case kAudioUnitParameterUnit_MIDINoteNumber:
723 d.unit = ParameterDescriptor::MIDI_NOTE;
725 case kAudioUnitParameterUnit_Hertz:
726 d.unit = ParameterDescriptor::HZ;
730 d.min_unbound = 0; // lower is bound
731 d.max_unbound = 0; // upper is bound
734 descriptors.push_back (d);
736 uint32_t last_param = descriptors.size() - 1;
737 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
738 listen_to_parameter (last_param);
745 four_ints_to_four_byte_literal (unsigned char n[4])
747 /* this is actually implementation dependent. sigh. this is what gcc
748 and quite a few others do.
750 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
754 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
756 if (isdigit (id[0])) {
760 /* ID format is xxxx-xxxx-xxxx
761 where x maybe \xNN or a printable character.
763 Split at the '-' and and process each part into an integer.
764 Then put it back together.
768 unsigned char nascent[4];
769 const char* cstr = id.c_str();
770 const char* estr = cstr + id.size();
781 while (*cstr && next_int < 4) {
785 if (estr - cstr < 3) {
787 /* too close to the end for \xNN parsing: treat as literal characters */
795 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
799 memcpy (short_buf, &cstr[2], 2);
800 nascent[in] = strtol (short_buf, NULL, 16);
806 /* treat as literal characters */
820 if (in && (in % 4 == 0)) {
821 /* nascent is ready */
822 n[next_int] = four_ints_to_four_byte_literal (nascent);
826 /* swallow space-hyphen-space */
840 s << n[0] << '-' << n[1] << '-' << n[2];
849 AUPlugin::unique_id () const
851 return AUPluginInfo::stringify_descriptor (comp->Desc());
855 AUPlugin::label () const
857 return _info->name.c_str();
861 AUPlugin::parameter_count () const
863 return descriptors.size();
867 AUPlugin::default_value (uint32_t port)
869 if (port < descriptors.size()) {
870 return descriptors[port].normal;
877 AUPlugin::signal_latency () const
879 return unit->Latency() * _session.frame_rate();
883 AUPlugin::set_parameter (uint32_t which, float val)
885 if (which >= descriptors.size()) {
889 if (get_parameter(which) == val) {
893 const AUParameterDescriptor& d (descriptors[which]);
894 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
895 unit->SetParameter (d.id, d.scope, d.element, val);
897 /* tell the world what we did */
899 AudioUnitEvent theEvent;
901 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
902 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
903 theEvent.mArgument.mParameter.mParameterID = d.id;
904 theEvent.mArgument.mParameter.mScope = d.scope;
905 theEvent.mArgument.mParameter.mElement = d.element;
907 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
908 AUEventListenerNotify (NULL, NULL, &theEvent);
910 Plugin::set_parameter (which, val);
914 AUPlugin::get_parameter (uint32_t which) const
917 if (which < descriptors.size()) {
918 const AUParameterDescriptor& d (descriptors[which]);
919 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
920 unit->GetParameter(d.id, d.scope, d.element, val);
926 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
928 if (which < descriptors.size()) {
929 pd = descriptors[which];
936 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
938 if (which < descriptors.size()) {
947 AUPlugin::activate ()
951 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
952 if ((err = unit->Initialize()) != noErr) {
953 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
955 frames_processed = 0;
962 AUPlugin::deactivate ()
964 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
965 unit->Uninitialize ();
972 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
973 unit->GlobalReset ();
977 AUPlugin::requires_fixed_size_buffers() const
979 return _requires_fixed_size_buffers;
984 AUPlugin::set_block_size (pframes_t nframes)
986 bool was_initialized = initialized;
987 UInt32 numFrames = nframes;
994 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
995 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
996 0, &numFrames, sizeof (numFrames))) != noErr) {
997 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
1001 if (was_initialized) {
1005 _current_block_size = nframes;
1011 AUPlugin::configure_io (ChanCount in, ChanCount out)
1013 AudioStreamBasicDescription streamFormat;
1014 bool was_initialized = initialized;
1015 int32_t audio_in = in.n_audio();
1016 int32_t audio_out = out.n_audio();
1018 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1021 //if we are already running with the requested i/o config, bail out here
1022 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1029 streamFormat.mSampleRate = _session.frame_rate();
1030 streamFormat.mFormatID = kAudioFormatLinearPCM;
1031 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1033 #ifdef __LITTLE_ENDIAN__
1036 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1039 streamFormat.mBitsPerChannel = 32;
1040 streamFormat.mFramesPerPacket = 1;
1042 /* apple says that for non-interleaved data, these
1043 values always refer to a single channel.
1045 streamFormat.mBytesPerPacket = 4;
1046 streamFormat.mBytesPerFrame = 4;
1048 streamFormat.mChannelsPerFrame = audio_in;
1050 if (set_input_format (streamFormat) != 0) {
1054 streamFormat.mChannelsPerFrame = audio_out;
1056 if (set_output_format (streamFormat) != 0) {
1060 /* reset plugin info to show currently configured state */
1062 _info->n_inputs = in;
1063 _info->n_outputs = out;
1065 if (was_initialized) {
1073 AUPlugin::input_streams() const
1078 if (input_channels < 0) {
1079 // force PluginIoReConfigure -- see also commit msg e38eb06
1080 c.set (DataType::AUDIO, 0);
1081 c.set (DataType::MIDI, 0);
1083 c.set (DataType::AUDIO, input_channels);
1084 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1092 AUPlugin::output_streams() const
1096 if (output_channels < 0) {
1097 // force PluginIoReConfigure - see also commit msg e38eb06
1098 c.set (DataType::AUDIO, 0);
1099 c.set (DataType::MIDI, 0);
1101 c.set (DataType::AUDIO, output_channels);
1102 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1109 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1111 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1113 int32_t audio_in = in.n_audio();
1116 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1118 /* lets check MIDI first */
1120 if (in.n_midi() > 0) {
1121 if (!_has_midi_input) {
1126 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1128 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1129 name(), io_configs.size(), in, out));
1131 //Ardour expects the plugin to tell it the output
1132 //configuration but AU plugins can have multiple I/O
1133 //configurations in most cases. so first lets see
1134 //if there's a configuration that keeps out==in
1136 if (in.n_midi() > 0 && audio_in == 0) {
1137 audio_out = 2; // prefer stereo version if available.
1139 audio_out = audio_in;
1142 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1144 int32_t possible_in = i->first;
1145 int32_t possible_out = i->second;
1147 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1148 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1149 possible_in, possible_out,
1152 out.set (DataType::MIDI, 0);
1153 out.set (DataType::AUDIO, audio_out);
1159 /* now allow potentially "imprecise" matches */
1163 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1165 int32_t possible_in = i->first;
1166 int32_t possible_out = i->second;
1168 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1170 if (possible_out == 0) {
1171 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1172 /* XXX surely this is just a send? (e.g. AUNetSend) */
1176 if (possible_in == 0) {
1178 /* instrument plugin, always legal but throws away inputs ...
1181 if (possible_out == -1) {
1182 /* any configuration possible, provide stereo output */
1185 } else if (possible_out == -2) {
1186 /* plugins shouldn't really use (0,-2) but might.
1187 any configuration possible, provide stereo output
1191 } else if (possible_out < -2) {
1192 /* explicitly variable number of outputs.
1194 * We really need to ask the user in this case.
1195 * stereo will be correct in 99.9% of all cases.
1200 /* exact number of outputs */
1201 audio_out = possible_out;
1206 if (possible_in == -1) {
1208 /* wildcard for input */
1210 if (possible_out == -1) {
1211 /* out much match in */
1212 audio_out = audio_in;
1214 } else if (possible_out == -2) {
1215 /* any configuration possible, pick matching */
1216 audio_out = audio_in;
1218 } else if (possible_out < -2) {
1219 /* explicitly variable number of outputs, pick maximum */
1220 audio_out = -possible_out;
1223 /* exact number of outputs */
1224 audio_out = possible_out;
1229 if (possible_in == -2) {
1231 if (possible_out == -1) {
1232 /* any configuration possible, pick matching */
1233 audio_out = audio_in;
1235 } else if (possible_out == -2) {
1236 /* plugins shouldn't really use (-2,-2) but might.
1237 interpret as (-1,-1).
1239 audio_out = audio_in;
1241 } else if (possible_out < -2) {
1242 /* explicitly variable number of outputs, pick maximum */
1243 audio_out = -possible_out;
1246 /* exact number of outputs */
1247 audio_out = possible_out;
1252 if (possible_in < -2) {
1254 /* explicit variable number of inputs */
1256 if (audio_in > -possible_in) {
1257 /* request is too large */
1261 if (possible_out == -1) {
1262 /* any output configuration possible, provide stereo out */
1265 } else if (possible_out == -2) {
1266 /* plugins shouldn't really use (<-2,-2) but might.
1267 interpret as (<-2,-1): any configuration possible, provide stereo output
1271 } else if (possible_out < -2) {
1272 /* explicitly variable number of outputs.
1274 * We really need to ask the user in this case.
1275 * stereo will be correct in 99.9% of all cases.
1280 /* exact number of outputs */
1281 audio_out = possible_out;
1286 if (possible_in && (possible_in == audio_in)) {
1288 /* exact number of inputs ... must match obviously */
1290 if (possible_out == -1) {
1291 /* any output configuration possible, provide stereo output */
1294 } else if (possible_out == -2) {
1295 /* plugins shouldn't really use (>0,-2) but might.
1296 interpret as (>0,-1):
1297 any output configuration possible, provide stereo output
1301 } else if (possible_out < -2) {
1302 /* explicitly variable number of outputs, pick maximum */
1303 audio_out = -possible_out;
1306 /* exact number of outputs */
1307 audio_out = possible_out;
1319 out.set (DataType::MIDI, 0);
1320 out.set (DataType::AUDIO, audio_out);
1321 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1323 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1331 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1333 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1337 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1339 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1348 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1349 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1355 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1359 for (uint32_t i = 0; i < cnt; ++i) {
1360 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1361 (scope == kAudioUnitScope_Input ? "input" : "output"),
1363 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1364 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1365 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1370 if (scope == kAudioUnitScope_Input) {
1371 input_channels = fmt.mChannelsPerFrame;
1373 output_channels = fmt.mChannelsPerFrame;
1380 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1381 const AudioTimeStamp*,
1383 UInt32 inNumberFrames,
1384 AudioBufferList* ioData)
1386 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1388 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1389 // name(), inNumberFrames, ioData->mNumberBuffers));
1391 if (input_maxbuf == 0) {
1392 error << _("AUPlugin: render callback called illegally!") << endmsg;
1393 return kAudioUnitErr_CannotDoInCurrentContext;
1395 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1397 for (uint32_t i = 0; i < limit; ++i) {
1398 ioData->mBuffers[i].mNumberChannels = 1;
1399 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1401 /* we don't use the channel mapping because audiounits are
1402 never replicated. one plugin instance uses all channels/buffers
1403 passed to PluginInsert::connect_and_run()
1406 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1409 cb_offset += inNumberFrames;
1415 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1417 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1419 AudioUnitRenderActionFlags flags = 0;
1423 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1424 unit->GlobalReset();
1425 _last_nframes = nframes;
1428 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1429 name(), input_channels, output_channels, _has_midi_input,
1430 bufs.count(), bufs.available()));
1432 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1433 has the capacity to handle our outputs.
1436 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1438 input_buffers = &bufs;
1439 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1440 input_offset = offset;
1443 buffers->mNumberBuffers = output_channels;
1445 for (int32_t i = 0; i < output_channels; ++i) {
1446 buffers->mBuffers[i].mNumberChannels = 1;
1447 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1448 /* setting this to 0 indicates to the AU that it can provide buffers here
1449 if necessary. if it can process in-place, it will use the buffers provided
1450 as input by ::render_callback() above.
1452 a non-null values tells the plugin to render into the buffer pointed
1455 buffers->mBuffers[i].mData = 0;
1458 if (_has_midi_input) {
1460 uint32_t nmidi = bufs.count().n_midi();
1462 for (uint32_t i = 0; i < nmidi; ++i) {
1464 /* one MIDI port/buffer only */
1466 MidiBuffer& m = bufs.get_midi (i);
1468 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1469 Evoral::MIDIEvent<framepos_t> ev (*i);
1471 if (ev.is_channel_event()) {
1472 const uint8_t* b = ev.buffer();
1473 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1474 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1477 /* XXX need to handle sysex and other message types */
1482 /* does this really mean anything ?
1485 ts.mSampleTime = frames_processed;
1486 ts.mFlags = kAudioTimeStampSampleTimeValid;
1488 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1489 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1491 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1494 frames_processed += nframes;
1496 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1497 name(), buffers->mNumberBuffers, output_channels));
1499 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1502 for (i = 0; i < limit; ++i) {
1503 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1504 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1505 /* plugin provided its own buffer for output so copy it back to where we want it
1507 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1511 /* now silence any buffers that were passed in but the that the plugin
1512 did not fill/touch/use.
1515 for (;i < output_channels; ++i) {
1516 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1522 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1527 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1528 Float64* outCurrentTempo)
1530 TempoMap& tmap (_session.tempo_map());
1532 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1534 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1535 (and interpretation) of a beat position will be incorrect. So refuse to
1539 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1540 return kAudioUnitErr_CannotDoInCurrentContext;
1543 Timecode::BBT_Time bbt;
1544 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1545 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1547 if (outCurrentBeat) {
1549 beat = metric.meter().divisions_per_bar() * bbt.bars;
1551 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1552 *outCurrentBeat = beat;
1555 if (outCurrentTempo) {
1556 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1564 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1565 Float32* outTimeSig_Numerator,
1566 UInt32* outTimeSig_Denominator,
1567 Float64* outCurrentMeasureDownBeat)
1569 TempoMap& tmap (_session.tempo_map());
1571 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1573 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1574 (and interpretation) of a beat position will be incorrect. So refuse to
1578 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1579 return kAudioUnitErr_CannotDoInCurrentContext;
1582 Timecode::BBT_Time bbt;
1583 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1584 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1586 if (outDeltaSampleOffsetToNextBeat) {
1587 if (bbt.ticks == 0) {
1589 *outDeltaSampleOffsetToNextBeat = 0;
1591 *outDeltaSampleOffsetToNextBeat = (UInt32)
1592 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1593 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1597 if (outTimeSig_Numerator) {
1598 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1600 if (outTimeSig_Denominator) {
1601 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1604 if (outCurrentMeasureDownBeat) {
1606 /* beat for the start of the bar.
1608 2|1|0 -> 1 + divisions_per_bar
1609 3|1|0 -> 1 + (2 * divisions_per_bar)
1613 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1620 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1621 Boolean* outTransportStateChanged,
1622 Float64* outCurrentSampleInTimeLine,
1623 Boolean* outIsCycling,
1624 Float64* outCycleStartBeat,
1625 Float64* outCycleEndBeat)
1630 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1632 rolling = _session.transport_rolling();
1633 speed = _session.transport_speed ();
1636 *outIsPlaying = _session.transport_rolling();
1639 if (outTransportStateChanged) {
1640 if (rolling != last_transport_rolling) {
1641 *outTransportStateChanged = true;
1642 } else if (speed != last_transport_speed) {
1643 *outTransportStateChanged = true;
1645 *outTransportStateChanged = false;
1649 if (outCurrentSampleInTimeLine) {
1650 /* this assumes that the AU can only call this host callback from render context,
1651 where input_offset is valid.
1653 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1657 Location* loc = _session.locations()->auto_loop_location();
1659 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1661 if (*outIsCycling) {
1663 if (outCycleStartBeat || outCycleEndBeat) {
1665 TempoMap& tmap (_session.tempo_map());
1667 /* more than 1 meter means that a simplistic computation (and interpretation) of
1668 a beat position will be incorrect. so refuse to offer the value.
1671 if (tmap.n_meters() > 1) {
1672 return kAudioUnitErr_CannotDoInCurrentContext;
1675 Timecode::BBT_Time bbt;
1677 if (outCycleStartBeat) {
1678 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1679 _session.tempo_map().bbt_time (loc->start(), bbt);
1682 beat = metric.meter().divisions_per_bar() * bbt.bars;
1684 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1686 *outCycleStartBeat = beat;
1689 if (outCycleEndBeat) {
1690 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1691 _session.tempo_map().bbt_time (loc->end(), bbt);
1694 beat = metric.meter().divisions_per_bar() * bbt.bars;
1696 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1698 *outCycleEndBeat = beat;
1704 last_transport_rolling = rolling;
1705 last_transport_speed = speed;
1710 set<Evoral::Parameter>
1711 AUPlugin::automatable() const
1713 set<Evoral::Parameter> automates;
1715 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1716 if (descriptors[i].automatable) {
1717 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1725 AUPlugin::describe_parameter (Evoral::Parameter param)
1727 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1728 return descriptors[param.id()].label;
1735 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1737 // NameValue stuff here
1741 AUPlugin::parameter_is_audio (uint32_t) const
1747 AUPlugin::parameter_is_control (uint32_t param) const
1749 assert(param < descriptors.size());
1750 if (descriptors[param].automatable) {
1751 /* corrently ardour expects all controls to be automatable
1752 * IOW ardour GUI elements mandate an Evoral::Parameter
1753 * for all input+control ports.
1761 AUPlugin::parameter_is_input (uint32_t param) const
1763 /* AU params that are both readable and writeable,
1764 * are listed in kAudioUnitScope_Global
1766 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1770 AUPlugin::parameter_is_output (uint32_t param) const
1772 assert(param < descriptors.size());
1773 // TODO check if ardour properly handles ports
1774 // that report is_input + is_output == true
1775 // -> add || descriptors[param].scope == kAudioUnitScope_Global
1776 return (descriptors[param].scope == kAudioUnitScope_Output);
1780 AUPlugin::add_state (XMLNode* root) const
1782 LocaleGuard lg (X_("C"));
1784 CFPropertyListRef propertyList;
1786 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1787 if (unit->GetAUPreset (propertyList) != noErr) {
1791 // Convert the property list into XML data.
1793 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1796 error << _("Could not create XML version of property list") << endmsg;
1800 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1801 our state node. GACK!
1806 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1808 root->add_child_copy (*t.root());
1812 CFRelease (xmlData);
1813 CFRelease (propertyList);
1817 AUPlugin::set_state(const XMLNode& node, int version)
1820 CFPropertyListRef propertyList;
1821 LocaleGuard lg (X_("C"));
1823 if (node.name() != state_node_name()) {
1824 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1828 #ifndef NO_PLUGIN_STATE
1829 if (node.children().empty()) {
1833 XMLNode* top = node.children().front();
1834 XMLNode* copy = new XMLNode (*top);
1839 const string& xml = t.write_buffer ();
1840 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1841 CFStringRef errorString;
1843 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1845 kCFPropertyListImmutable,
1848 CFRelease (xmlData);
1851 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1852 if (unit->SetAUPreset (propertyList) == noErr) {
1855 /* tell the world */
1857 AudioUnitParameter changedUnit;
1858 changedUnit.mAudioUnit = unit->AU();
1859 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1860 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1862 CFRelease (propertyList);
1866 Plugin::set_state (node, version);
1871 AUPlugin::load_preset (PresetRecord r)
1873 Plugin::load_preset (r);
1876 CFPropertyListRef propertyList;
1878 UserPresetMap::iterator ux;
1879 FactoryPresetMap::iterator fx;
1881 /* look first in "user" presets */
1883 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1885 if ((propertyList = load_property_list (ux->second)) != 0) {
1886 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1887 if (unit->SetAUPreset (propertyList) == noErr) {
1890 /* tell the world */
1892 AudioUnitParameter changedUnit;
1893 changedUnit.mAudioUnit = unit->AU();
1894 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1895 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1897 CFRelease(propertyList);
1900 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1904 preset.presetNumber = fx->second;
1905 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1907 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1909 if (unit->SetPresentPreset (preset) == 0) {
1912 /* tell the world */
1914 AudioUnitParameter changedUnit;
1915 changedUnit.mAudioUnit = unit->AU();
1916 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1917 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1925 AUPlugin::do_remove_preset (std::string)
1930 AUPlugin::do_save_preset (string preset_name)
1932 CFPropertyListRef propertyList;
1933 vector<Glib::ustring> v;
1934 Glib::ustring user_preset_path;
1936 std::string m = maker();
1937 std::string n = name();
1939 strip_whitespace_edges (m);
1940 strip_whitespace_edges (n);
1942 v.push_back (Glib::get_home_dir());
1943 v.push_back ("Library");
1944 v.push_back ("Audio");
1945 v.push_back ("Presets");
1949 user_preset_path = Glib::build_filename (v);
1951 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1952 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1956 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1957 if (unit->GetAUPreset (propertyList) != noErr) {
1961 // add the actual preset name */
1963 v.push_back (preset_name + preset_suffix);
1967 user_preset_path = Glib::build_filename (v);
1969 set_preset_name_in_plist (propertyList, preset_name);
1971 if (save_property_list (propertyList, user_preset_path)) {
1972 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1976 CFRelease(propertyList);
1978 user_preset_map[preset_name] = user_preset_path;;
1980 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
1982 return string ("file:///") + user_preset_path;
1985 //-----------------------------------------------------------------------------
1986 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1988 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1990 CFNumberRef cfNumber;
1991 SInt32 numberValue = 0;
1992 Boolean dummySuccess;
1994 if (outSuccess == NULL)
1995 outSuccess = &dummySuccess;
1996 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1998 *outSuccess = FALSE;
2002 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2003 if (cfNumber == NULL)
2005 *outSuccess = FALSE;
2008 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2016 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
2018 CFDictionaryRef auStateDictionary;
2019 ComponentDescription tempDesc = {0,0,0,0,0};
2020 SInt32 versionValue;
2023 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2026 // the property list for AU state data must be of the dictionary type
2027 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2028 return kAudioUnitErr_InvalidPropertyValue;
2031 auStateDictionary = (CFDictionaryRef)inAUStateData;
2033 // first check to make sure that the version of the AU state data is one that we know understand
2034 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2035 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2038 return kAudioUnitErr_InvalidPropertyValue;
2040 #define kCurrentSavedStateVersion 0
2041 if (versionValue != kCurrentSavedStateVersion) {
2042 return kAudioUnitErr_InvalidPropertyValue;
2045 // grab the ComponentDescription values from the AU state data
2046 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2047 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2048 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2049 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2050 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2051 return kAudioUnitErr_InvalidPropertyValue;
2053 *outComponentDescription = tempDesc;
2058 static bool au_preset_filter (const string& str, void* arg)
2060 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2064 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2068 /* check the preset file path name against this plugin
2069 ID. The idea is that all preset files for this plugin
2070 include "<manufacturer>/<plugin-name>" in their path.
2073 Plugin* p = (Plugin *) arg;
2074 string match = p->maker();
2078 ret = str.find (match) != string::npos;
2081 string m = p->maker ();
2082 string n = p->name ();
2083 strip_whitespace_edges (m);
2084 strip_whitespace_edges (n);
2089 ret = str.find (match) != string::npos;
2097 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2100 CFPropertyListRef plist;
2101 ComponentDescription presetDesc;
2104 plist = load_property_list (pathstr);
2110 // get the ComponentDescription from the AU preset file
2112 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2114 if (status == noErr) {
2115 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2117 /* try to get the preset name from the property list */
2119 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2121 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2125 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2128 char buf[PATH_MAX+1];
2130 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2145 AUPlugin::current_preset() const
2149 CFPropertyListRef propertyList;
2151 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2152 if (unit->GetAUPreset (propertyList) == noErr) {
2153 preset_name = get_preset_name_in_plist (propertyList);
2154 CFRelease(propertyList);
2161 AUPlugin::find_presets ()
2163 vector<string> preset_files;
2165 user_preset_map.clear ();
2167 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2169 if (preset_files.empty()) {
2170 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2174 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2179 /* make an initial guess at the preset name using the path */
2181 preset_name = Glib::path_get_basename (path);
2182 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2184 /* check that this preset file really matches this plugin
2185 and potentially get the "real" preset name from
2189 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2190 user_preset_map[preset_name] = path;
2191 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2193 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2198 /* now fill the vector<string> with the names we have */
2200 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2201 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2202 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2205 /* add factory presets */
2207 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2209 string const uri = string_compose ("%1", _presets.size ());
2210 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2211 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2216 AUPlugin::has_editor () const
2218 // even if the plugin doesn't have its own editor, the AU API can be used
2219 // to create one that looks native.
2223 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2226 type = ARDOUR::AudioUnit;
2229 AUPluginInfo::~AUPluginInfo ()
2231 type = ARDOUR::AudioUnit;
2235 AUPluginInfo::load (Session& session)
2240 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2241 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2243 if (!comp->IsValid()) {
2244 error << ("AudioUnit: not a valid Component") << endmsg;
2246 plugin.reset (new AUPlugin (session.engine(), session, comp));
2249 AUPluginInfo *aup = new AUPluginInfo (*this);
2250 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2251 plugin->set_info (PluginInfoPtr (aup));
2252 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2256 catch (failed_constructor &err) {
2257 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2258 return PluginPtr ();
2263 AUPluginInfo::au_cache_path ()
2265 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2269 AUPluginInfo::discover (bool scan_only)
2273 /* AU require a CAComponentDescription pointer provided by the OS.
2274 * Ardour only caches port and i/o config. It can't just 'scan' without
2275 * 'discovering' (like we do for VST).
2278 * "Iterate over all plugins. skip the ones where there's no io-cache".
2280 _scan_only = scan_only;
2282 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2283 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2285 // create crash log file
2286 au_start_crashlog ();
2288 PluginInfoList* plugs = new PluginInfoList;
2290 discover_fx (*plugs);
2291 discover_music (*plugs);
2292 discover_generators (*plugs);
2293 discover_instruments (*plugs);
2295 // all fine if we get here
2296 au_remove_crashlog ();
2298 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2304 AUPluginInfo::discover_music (PluginInfoList& plugs)
2306 CAComponentDescription desc;
2307 desc.componentFlags = 0;
2308 desc.componentFlagsMask = 0;
2309 desc.componentSubType = 0;
2310 desc.componentManufacturer = 0;
2311 desc.componentType = kAudioUnitType_MusicEffect;
2313 discover_by_description (plugs, desc);
2317 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2319 CAComponentDescription desc;
2320 desc.componentFlags = 0;
2321 desc.componentFlagsMask = 0;
2322 desc.componentSubType = 0;
2323 desc.componentManufacturer = 0;
2324 desc.componentType = kAudioUnitType_Effect;
2326 discover_by_description (plugs, desc);
2330 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2332 CAComponentDescription desc;
2333 desc.componentFlags = 0;
2334 desc.componentFlagsMask = 0;
2335 desc.componentSubType = 0;
2336 desc.componentManufacturer = 0;
2337 desc.componentType = kAudioUnitType_Generator;
2339 discover_by_description (plugs, desc);
2343 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2345 CAComponentDescription desc;
2346 desc.componentFlags = 0;
2347 desc.componentFlagsMask = 0;
2348 desc.componentSubType = 0;
2349 desc.componentManufacturer = 0;
2350 desc.componentType = kAudioUnitType_MusicDevice;
2352 discover_by_description (plugs, desc);
2357 AUPluginInfo::au_get_crashlog (std::string &msg)
2359 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2360 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2363 std::ifstream ifs(fn.c_str());
2364 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2365 au_remove_crashlog ();
2370 AUPluginInfo::au_start_crashlog ()
2372 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2373 assert(!_crashlog_fd);
2374 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2375 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2376 PBD::error << "Cannot create AU error-log" << fn << "\n";
2377 cerr << "Cannot create AU error-log" << fn << "\n";
2382 AUPluginInfo::au_remove_crashlog ()
2385 ::fclose(_crashlog_fd);
2386 _crashlog_fd = NULL;
2388 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2389 ::g_unlink(fn.c_str());
2390 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2395 AUPluginInfo::au_crashlog (std::string msg)
2397 if (!_crashlog_fd) {
2398 fprintf(stderr, "AU: %s\n", msg.c_str());
2400 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2401 ::fflush(_crashlog_fd);
2406 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2409 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2411 comp = FindNextComponent (NULL, &desc);
2413 while (comp != NULL) {
2414 CAComponentDescription temp;
2415 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2416 CFStringRef itemName = NULL;
2419 if (itemName != NULL) CFRelease(itemName);
2420 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2421 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2422 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2423 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2424 compTypeString, compManufacturerString, compSubTypeString);
2425 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2426 if (compTypeString != NULL)
2427 CFRelease(compTypeString);
2428 if (compSubTypeString != NULL)
2429 CFRelease(compSubTypeString);
2430 if (compManufacturerString != NULL)
2431 CFRelease(compManufacturerString);
2434 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2435 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2436 comp = FindNextComponent (comp, &desc);
2440 AUPluginInfoPtr info (new AUPluginInfo
2441 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2443 /* although apple designed the subtype field to be a "category" indicator,
2444 its really turned into a plugin ID field for a given manufacturer. Hence
2445 there are no categories for AudioUnits. However, to keep the plugins
2446 showing up under "categories", we'll use the "type" as a high level
2449 NOTE: no panners, format converters or i/o AU's for our purposes
2452 switch (info->descriptor->Type()) {
2453 case kAudioUnitType_Panner:
2454 case kAudioUnitType_OfflineEffect:
2455 case kAudioUnitType_FormatConverter:
2456 comp = FindNextComponent (comp, &desc);
2459 case kAudioUnitType_Output:
2460 info->category = _("AudioUnit Outputs");
2462 case kAudioUnitType_MusicDevice:
2463 info->category = _("AudioUnit Instruments");
2465 case kAudioUnitType_MusicEffect:
2466 info->category = _("AudioUnit MusicEffects");
2468 case kAudioUnitType_Effect:
2469 info->category = _("AudioUnit Effects");
2471 case kAudioUnitType_Mixer:
2472 info->category = _("AudioUnit Mixers");
2474 case kAudioUnitType_Generator:
2475 info->category = _("AudioUnit Generators");
2478 info->category = _("AudioUnit (Unknown)");
2482 au_blacklist(CFStringRefToStdString(itemName));
2483 AUPluginInfo::get_names (temp, info->name, info->creator);
2484 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2485 au_crashlog(string_compose("Plugin: %1", info->name));
2487 info->type = ARDOUR::AudioUnit;
2488 info->unique_id = stringify_descriptor (*info->descriptor);
2490 /* XXX not sure of the best way to handle plugin versioning yet
2493 CAComponent cacomp (*info->descriptor);
2495 if (cacomp.GetResourceVersion (info->version) != noErr) {
2499 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2502 /* here we have to map apple's wildcard system to a simple pair
2503 of values. in ::can_do() we use the whole system, but here
2504 we need a single pair of values. XXX probably means we should
2505 remove any use of these values.
2507 for now, if the plugin provides a wildcard, treat it as 1. we really
2508 don't care much, because whether we can handle an i/o configuration
2509 depends upon ::can_support_io_configuration(), not these counts.
2511 they exist because other parts of ardour try to present i/o configuration
2512 info to the user, which should perhaps be revisited.
2515 int32_t possible_in = info->cache.io_configs.front().first;
2516 int32_t possible_out = info->cache.io_configs.front().second;
2518 if (possible_in > 0) {
2519 info->n_inputs.set (DataType::AUDIO, possible_in);
2521 info->n_inputs.set (DataType::AUDIO, 1);
2524 if (possible_out > 0) {
2525 info->n_outputs.set (DataType::AUDIO, possible_out);
2527 info->n_outputs.set (DataType::AUDIO, 1);
2530 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2531 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2533 plugs.push_back (info);
2536 else if (rv == -1) {
2537 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2540 au_unblacklist(CFStringRefToStdString(itemName));
2541 au_crashlog("Success.");
2542 comp = FindNextComponent (comp, &desc);
2543 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2545 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2549 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2552 AUPluginCachedInfo& cinfo,
2553 const std::string& name)
2558 /* concatenate unique ID with version to provide a key for cached info lookup.
2559 this ensures we don't get stale information, or should if plugin developers
2560 follow Apple "guidelines".
2563 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2568 CachedInfoMap::iterator cim = cached_info.find (id);
2570 if (cim != cached_info.end()) {
2571 cinfo = cim->second;
2576 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
2581 AUChannelInfo* channel_info;
2585 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2589 if (CAAudioUnit::Open (comp, unit) != noErr) {
2595 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2600 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2601 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2607 /* no explicit info available, so default to 1in/1out */
2609 /* XXX this is wrong. we should be indicating wildcard values */
2611 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2615 /* store each configuration */
2617 for (uint32_t n = 0; n < cnt; ++n) {
2618 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2619 channel_info[n].outChannels));
2622 free (channel_info);
2625 add_cached_info (id, cinfo);
2626 save_cached_info ();
2632 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2634 cached_info[id] = cinfo;
2637 #define AU_CACHE_VERSION "2.0"
2640 AUPluginInfo::save_cached_info ()
2644 node = new XMLNode (X_("AudioUnitPluginCache"));
2645 node->add_property( "version", AU_CACHE_VERSION );
2647 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2648 XMLNode* parent = new XMLNode (X_("plugin"));
2649 parent->add_property ("id", i->first);
2650 node->add_child_nocopy (*parent);
2652 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2654 XMLNode* child = new XMLNode (X_("io"));
2657 snprintf (buf, sizeof (buf), "%d", j->first);
2658 child->add_property (X_("in"), buf);
2659 snprintf (buf, sizeof (buf), "%d", j->second);
2660 child->add_property (X_("out"), buf);
2661 parent->add_child_nocopy (*child);
2666 Glib::ustring path = au_cache_path ();
2669 tree.set_root (node);
2671 if (!tree.write (path)) {
2672 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2673 g_unlink (path.c_str());
2678 AUPluginInfo::load_cached_info ()
2680 Glib::ustring path = au_cache_path ();
2683 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2687 if ( !tree.read (path) ) {
2688 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2692 const XMLNode* root (tree.root());
2694 if (root->name() != X_("AudioUnitPluginCache")) {
2698 //initial version has incorrectly stored i/o info, and/or garbage chars.
2699 const XMLProperty* version = root->property(X_("version"));
2700 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2701 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2705 cached_info.clear ();
2707 const XMLNodeList children = root->children();
2709 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2711 const XMLNode* child = *iter;
2713 if (child->name() == X_("plugin")) {
2715 const XMLNode* gchild;
2716 const XMLNodeList gchildren = child->children();
2717 const XMLProperty* prop = child->property (X_("id"));
2723 string id = prop->value();
2727 string::size_type slash = id.find_last_of ('/');
2729 if (slash == string::npos) {
2733 version = id.substr (slash);
2734 id = id.substr (0, slash);
2735 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2737 if (fixed.empty()) {
2738 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2745 AUPluginCachedInfo cinfo;
2747 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2751 if (gchild->name() == X_("io")) {
2755 const XMLProperty* iprop;
2756 const XMLProperty* oprop;
2758 if (((iprop = gchild->property (X_("in"))) != 0) &&
2759 ((oprop = gchild->property (X_("out"))) != 0)) {
2760 in = atoi (iprop->value());
2761 out = atoi (oprop->value());
2763 cinfo.io_configs.push_back (pair<int,int> (in, out));
2768 if (cinfo.io_configs.size()) {
2769 add_cached_info (id, cinfo);
2778 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2780 CFStringRef itemName = NULL;
2782 // Marc Poirier-style item name
2783 CAComponent auComponent (comp_desc);
2784 if (auComponent.IsValid()) {
2785 CAComponentDescription dummydesc;
2786 Handle nameHandle = NewHandle(sizeof(void*));
2787 if (nameHandle != NULL) {
2788 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2790 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2791 if (nameString != NULL) {
2792 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2795 DisposeHandle(nameHandle);
2799 // if Marc-style fails, do the original way
2800 if (itemName == NULL) {
2801 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2802 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2803 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2805 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2806 compTypeString, compManufacturerString, compSubTypeString);
2808 if (compTypeString != NULL)
2809 CFRelease(compTypeString);
2810 if (compSubTypeString != NULL)
2811 CFRelease(compSubTypeString);
2812 if (compManufacturerString != NULL)
2813 CFRelease(compManufacturerString);
2816 string str = CFStringRefToStdString(itemName);
2817 string::size_type colon = str.find (':');
2820 name = str.substr (colon+1);
2821 maker = str.substr (0, colon);
2822 strip_whitespace_edges (maker);
2823 strip_whitespace_edges (name);
2827 strip_whitespace_edges (name);
2832 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2836 /* note: OSType is a compiler-implemenation-defined value,
2837 historically a 32 bit integer created with a multi-character
2838 constant such as 'abcd'. It is, fundamentally, an abomination.
2843 s << desc.SubType();
2851 AUPluginInfo::needs_midi_input ()
2853 return is_effect_with_midi_input () || is_instrument ();
2857 AUPluginInfo::is_effect () const
2859 return is_effect_without_midi_input() || is_effect_with_midi_input();
2863 AUPluginInfo::is_effect_without_midi_input () const
2865 return descriptor->IsAUFX();
2869 AUPluginInfo::is_effect_with_midi_input () const
2871 return descriptor->IsAUFM();
2875 AUPluginInfo::is_instrument () const
2877 return descriptor->IsMusicDevice();
2881 AUPlugin::set_info (PluginInfoPtr info)
2883 Plugin::set_info (info);
2885 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2886 _has_midi_input = pinfo->needs_midi_input ();
2887 _has_midi_output = false;
2891 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2894 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2896 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2898 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2900 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2904 _parameter_listener_arg = arg;
2910 AUPlugin::listen_to_parameter (uint32_t param_id)
2912 AudioUnitEvent event;
2914 if (!_parameter_listener || param_id >= descriptors.size()) {
2918 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2919 event.mArgument.mParameter.mAudioUnit = unit->AU();
2920 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2921 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2922 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2924 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2928 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2929 event.mArgument.mParameter.mAudioUnit = unit->AU();
2930 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2931 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2932 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2934 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2938 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2939 event.mArgument.mParameter.mAudioUnit = unit->AU();
2940 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2941 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2942 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2944 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2952 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2954 AudioUnitEvent event;
2956 if (!_parameter_listener || param_id >= descriptors.size()) {
2960 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2961 event.mArgument.mParameter.mAudioUnit = unit->AU();
2962 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2963 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2964 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2966 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2970 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2971 event.mArgument.mParameter.mAudioUnit = unit->AU();
2972 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2973 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2974 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2976 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2980 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2981 event.mArgument.mParameter.mAudioUnit = unit->AU();
2982 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2983 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2984 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2986 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2994 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2996 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3000 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3002 ParameterMap::iterator i;
3004 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3008 switch (event->mEventType) {
3009 case kAudioUnitEvent_BeginParameterChangeGesture:
3010 StartTouch (i->second);
3012 case kAudioUnitEvent_EndParameterChangeGesture:
3013 EndTouch (i->second);
3015 case kAudioUnitEvent_ParameterValueChange:
3016 ParameterChanged (i->second, new_value);