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/gstdio_compat.h"
29 #include "pbd/transmitter.h"
30 #include "pbd/xml++.h"
31 #include "pbd/convert.h"
32 #include "pbd/whitespace.h"
33 #include "pbd/file_utils.h"
34 #include "pbd/locale_guard.h"
36 #include <glibmm/threads.h>
37 #include <glibmm/fileutils.h>
38 #include <glibmm/miscutils.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 "CAAudioUnit.h"
54 #include "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>
65 #define ArdourComponent Component
66 #define ArdourDescription ComponentDescription
67 #define ArdourFindNext FindNextComponent
69 #define ArdourComponent AudioComponent
70 #define ArdourDescription AudioComponentDescription
71 #define ArdourFindNext AudioComponentFindNext
78 using namespace ARDOUR;
80 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
82 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
83 static string preset_suffix = ".aupreset";
84 static bool preset_search_path_initialized = false;
85 FILE * AUPluginInfo::_crashlog_fd = NULL;
86 bool AUPluginInfo::_scan_only = true;
89 static void au_blacklist (std::string id)
91 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
92 FILE * blacklist_fd = NULL;
93 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
94 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
97 assert(id.find("\n") == string::npos);
98 fprintf(blacklist_fd, "%s\n", id.c_str());
99 ::fclose(blacklist_fd);
102 static void au_unblacklist (std::string id)
104 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
105 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
106 PBD::warning << "Expected Blacklist file does not exist.\n";
112 std::ifstream ifs(fn.c_str());
113 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
116 ::g_unlink (fn.c_str());
118 assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
119 assert(id.find("\n") == string::npos);
121 id += "\n"; // add separator
122 const size_t rpl = bl.find(id);
123 if (rpl != string::npos) {
124 bl.replace(rpl, id.size(), "");
130 FILE * blacklist_fd = NULL;
131 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
132 PBD::error << "Cannot open AU blacklist.\n";
135 fprintf(blacklist_fd, "%s", bl.c_str());
136 ::fclose(blacklist_fd);
139 static bool is_blacklisted (std::string id)
141 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
142 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
146 std::ifstream ifs(fn.c_str());
147 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
149 assert(id.find("\n") == string::npos);
151 id += "\n"; // add separator
152 const size_t rpl = bl.find(id);
153 if (rpl != string::npos) {
162 _render_callback(void *userData,
163 AudioUnitRenderActionFlags *ioActionFlags,
164 const AudioTimeStamp *inTimeStamp,
166 UInt32 inNumberFrames,
167 AudioBufferList* ioData)
170 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
176 _get_beat_and_tempo_callback (void* userData,
177 Float64* outCurrentBeat,
178 Float64* outCurrentTempo)
181 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
188 _get_musical_time_location_callback (void * userData,
189 UInt32 * outDeltaSampleOffsetToNextBeat,
190 Float32 * outTimeSig_Numerator,
191 UInt32 * outTimeSig_Denominator,
192 Float64 * outCurrentMeasureDownBeat)
195 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
196 outTimeSig_Numerator,
197 outTimeSig_Denominator,
198 outCurrentMeasureDownBeat);
204 _get_transport_state_callback (void* userData,
205 Boolean* outIsPlaying,
206 Boolean* outTransportStateChanged,
207 Float64* outCurrentSampleInTimeLine,
208 Boolean* outIsCycling,
209 Float64* outCycleStartBeat,
210 Float64* outCycleEndBeat)
213 return ((AUPlugin*)userData)->get_transport_state_callback (
214 outIsPlaying, outTransportStateChanged,
215 outCurrentSampleInTimeLine, outIsCycling,
216 outCycleStartBeat, outCycleEndBeat);
223 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
229 // Convert the property list into XML data.
231 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
234 error << _("Could not create XML version of property list") << endmsg;
238 // Write the XML data to the file.
240 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
242 if (errno == EEXIST) {
243 error << string_compose (_("Preset file %1 exists; not overwriting"),
246 error << string_compose (_("Cannot open preset file %1 (%2)"),
247 path, strerror (errno)) << endmsg;
253 size_t cnt = CFDataGetLength (xmlData);
255 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
266 static CFPropertyListRef
267 load_property_list (Glib::ustring path)
270 CFPropertyListRef propertyList = 0;
272 CFStringRef errorString;
274 // Read the XML file.
276 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
281 off_t len = lseek (fd, 0, SEEK_END);
282 char* buf = new char[len];
283 lseek (fd, 0, SEEK_SET);
285 if (read (fd, buf, len) != len) {
293 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
295 // Reconstitute the dictionary using the XML data.
297 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
299 kCFPropertyListImmutable,
308 //-----------------------------------------------------------------------------
310 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
315 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
317 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
318 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
324 //-----------------------------------------------------------------------------
326 get_preset_name_in_plist (CFPropertyListRef plist)
334 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
335 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
337 CFStringRef str = (CFStringRef) p;
338 int len = CFStringGetLength(str);
340 char local_buffer[len];
341 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
349 //--------------------------------------------------------------------------
350 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
351 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
352 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
353 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
355 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
358 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
359 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
361 // only sub-type and manufacturer IDs need to be equal
364 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
365 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
372 //--------------------------------------------------------------------------
373 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
374 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
375 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
376 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
379 ArdourDescription desc;
381 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
384 // get the ComponentDescription of the input Component
386 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
388 status = AudioComponentGetDescription (inComponent, &desc);
393 // check if the Component's ComponentDescription matches the input ComponentDescription
394 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
397 //--------------------------------------------------------------------------
398 // determine if 2 ComponentDescriptions are basically equal
399 // (by that, I mean that the important identifying values are compared,
400 // but not the ComponentDescription flags)
401 Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
403 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
406 //--------------------------------------------------------------------------
407 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
408 Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
410 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
413 //--------------------------------------------------------------------------
414 // determine if a ComponentDescription basically matches that of a particular Component
415 Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
417 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
420 //--------------------------------------------------------------------------
421 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
422 Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
424 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
428 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
429 : Plugin (engine, session)
431 , unit (new CAAudioUnit)
432 , initialized (false)
433 , _current_block_size (0)
434 , _requires_fixed_size_buffers (false)
439 , frames_processed (0)
440 , audio_input_cnt (0)
441 , _parameter_listener (0)
442 , _parameter_listener_arg (0)
443 , last_transport_rolling (false)
444 , last_transport_speed (0.0)
446 if (!preset_search_path_initialized) {
447 Glib::ustring p = Glib::get_home_dir();
448 p += "/Library/Audio/Presets:";
449 p += preset_search_path;
450 preset_search_path = p;
451 preset_search_path_initialized = true;
452 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
459 AUPlugin::AUPlugin (const AUPlugin& other)
461 , comp (other.get_comp())
462 , unit (new CAAudioUnit)
463 , initialized (false)
464 , _current_block_size (0)
466 , _requires_fixed_size_buffers (false)
471 , frames_processed (0)
472 , _parameter_listener (0)
473 , _parameter_listener_arg (0)
477 for (size_t i = 0; i < descriptors.size(); ++i) {
478 set_parameter (i, other.get_parameter (i));
482 AUPlugin::~AUPlugin ()
484 if (_parameter_listener) {
485 AUListenerDispose (_parameter_listener);
486 _parameter_listener = 0;
490 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
491 unit->Uninitialize ();
500 AUPlugin::discover_factory_presets ()
507 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
508 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
512 assert (dataSize == sizeof (presets));
514 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
515 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
523 CFIndex cnt = CFArrayGetCount (presets);
525 for (CFIndex i = 0; i < cnt; ++i) {
526 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
528 string name = CFStringRefToStdString (preset->presetName);
529 factory_preset_map[name] = preset->presetNumber;
530 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
540 CFStringRef itemName;
542 /* these keep track of *configured* channel set up,
543 not potential set ups.
547 output_channels = -1;
549 CAComponentDescription temp;
551 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
553 AudioComponentGetDescription (comp.get()->Comp(), &temp);
555 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
556 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
557 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
558 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
559 compTypeString, compManufacturerString, compSubTypeString);
560 if (compTypeString != NULL) CFRelease(compTypeString);
561 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
562 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
565 au_blacklist(CFStringRefToStdString(itemName));
568 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
569 err = CAAudioUnit::Open (*(comp.get()), *unit);
571 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
572 throw failed_constructor();
576 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
577 throw failed_constructor ();
580 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
581 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
582 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
583 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
584 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
585 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
587 if (input_elements > 0) {
588 /* setup render callback: the plugin calls this to get input data
591 AURenderCallbackStruct renderCallbackInfo;
593 renderCallbackInfo.inputProc = _render_callback;
594 renderCallbackInfo.inputProcRefCon = this;
596 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
597 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
598 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
599 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
600 throw failed_constructor();
604 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
606 HostCallbackInfo info;
607 memset (&info, 0, sizeof (HostCallbackInfo));
608 info.hostUserData = this;
609 info.beatAndTempoProc = _get_beat_and_tempo_callback;
610 info.musicalTimeLocationProc = _get_musical_time_location_callback;
611 info.transportStateProc = _get_transport_state_callback;
613 //ignore result of this - don't care if the property isn't supported
614 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
615 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
616 kAudioUnitScope_Global,
619 sizeof (HostCallbackInfo));
621 if (set_block_size (_session.get_block_size())) {
622 error << _("AUPlugin: cannot set processing block size") << endmsg;
623 throw failed_constructor();
626 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
627 discover_parameters ();
628 discover_factory_presets ();
630 // Plugin::setup_controls ();
632 au_unblacklist(CFStringRefToStdString(itemName));
633 if (itemName != NULL) CFRelease(itemName);
637 AUPlugin::discover_parameters ()
639 /* discover writable parameters */
641 AudioUnitScope scopes[] = {
642 kAudioUnitScope_Global,
643 kAudioUnitScope_Output,
644 kAudioUnitScope_Input
647 descriptors.clear ();
649 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
651 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
653 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
655 AUParameterDescriptor d;
657 d.id = param_info.ParamID (i);
659 const CAAUParameter* param = param_info.GetParamInfo (d.id);
660 const AudioUnitParameterInfo& info (param->ParamInfo());
662 const int len = CFStringGetLength (param->GetName());
663 char local_buffer[len*2];
664 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
668 d.label = local_buffer;
671 d.scope = param_info.GetScope ();
672 d.element = param_info.GetElement ();
674 /* info.units to consider */
676 kAudioUnitParameterUnit_Generic = 0
677 kAudioUnitParameterUnit_Indexed = 1
678 kAudioUnitParameterUnit_Boolean = 2
679 kAudioUnitParameterUnit_Percent = 3
680 kAudioUnitParameterUnit_Seconds = 4
681 kAudioUnitParameterUnit_SampleFrames = 5
682 kAudioUnitParameterUnit_Phase = 6
683 kAudioUnitParameterUnit_Rate = 7
684 kAudioUnitParameterUnit_Hertz = 8
685 kAudioUnitParameterUnit_Cents = 9
686 kAudioUnitParameterUnit_RelativeSemiTones = 10
687 kAudioUnitParameterUnit_MIDINoteNumber = 11
688 kAudioUnitParameterUnit_MIDIController = 12
689 kAudioUnitParameterUnit_Decibels = 13
690 kAudioUnitParameterUnit_LinearGain = 14
691 kAudioUnitParameterUnit_Degrees = 15
692 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
693 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
694 kAudioUnitParameterUnit_Pan = 18
695 kAudioUnitParameterUnit_Meters = 19
696 kAudioUnitParameterUnit_AbsoluteCents = 20
697 kAudioUnitParameterUnit_Octaves = 21
698 kAudioUnitParameterUnit_BPM = 22
699 kAudioUnitParameterUnit_Beats = 23
700 kAudioUnitParameterUnit_Milliseconds = 24
701 kAudioUnitParameterUnit_Ratio = 25
704 /* info.flags to consider */
708 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
709 kAudioUnitParameterFlag_HasClump = (1L << 20)
710 kAudioUnitParameterFlag_HasName = (1L << 21)
711 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
712 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
713 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
714 kAudioUnitParameterFlag_CanRamp = (1L << 25)
715 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
716 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
717 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
718 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
719 kAudioUnitParameterFlag_IsReadable = (1L << 30)
720 kAudioUnitParameterFlag_IsWritable = (1L << 31)
723 d.lower = info.minValue;
724 d.upper = info.maxValue;
725 d.normal = info.defaultValue;
727 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
728 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
729 (d.integer_step && ((d.upper - d.lower) == 1.0));
730 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
731 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
732 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
733 (info.flags & kAudioUnitParameterFlag_IsWritable);
735 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
736 d.au_unit = info.unit;
738 case kAudioUnitParameterUnit_Decibels:
739 d.unit = ParameterDescriptor::DB;
741 case kAudioUnitParameterUnit_MIDINoteNumber:
742 d.unit = ParameterDescriptor::MIDI_NOTE;
744 case kAudioUnitParameterUnit_Hertz:
745 d.unit = ParameterDescriptor::HZ;
749 d.min_unbound = 0; // lower is bound
750 d.max_unbound = 0; // upper is bound
753 descriptors.push_back (d);
755 uint32_t last_param = descriptors.size() - 1;
756 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
757 listen_to_parameter (last_param);
764 four_ints_to_four_byte_literal (unsigned char n[4])
766 /* this is actually implementation dependent. sigh. this is what gcc
767 and quite a few others do.
769 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
773 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
775 if (isdigit (id[0])) {
779 /* ID format is xxxx-xxxx-xxxx
780 where x maybe \xNN or a printable character.
782 Split at the '-' and and process each part into an integer.
783 Then put it back together.
787 unsigned char nascent[4];
788 const char* cstr = id.c_str();
789 const char* estr = cstr + id.size();
800 while (*cstr && next_int < 4) {
804 if (estr - cstr < 3) {
806 /* too close to the end for \xNN parsing: treat as literal characters */
814 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
818 memcpy (short_buf, &cstr[2], 2);
819 nascent[in] = strtol (short_buf, NULL, 16);
825 /* treat as literal characters */
839 if (in && (in % 4 == 0)) {
840 /* nascent is ready */
841 n[next_int] = four_ints_to_four_byte_literal (nascent);
845 /* swallow space-hyphen-space */
859 s << n[0] << '-' << n[1] << '-' << n[2];
868 AUPlugin::unique_id () const
870 return AUPluginInfo::stringify_descriptor (comp->Desc());
874 AUPlugin::label () const
876 return _info->name.c_str();
880 AUPlugin::parameter_count () const
882 return descriptors.size();
886 AUPlugin::default_value (uint32_t port)
888 if (port < descriptors.size()) {
889 return descriptors[port].normal;
896 AUPlugin::signal_latency () const
898 return unit->Latency() * _session.frame_rate();
902 AUPlugin::set_parameter (uint32_t which, float val)
904 if (which >= descriptors.size()) {
908 if (get_parameter(which) == val) {
912 const AUParameterDescriptor& d (descriptors[which]);
913 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
914 unit->SetParameter (d.id, d.scope, d.element, val);
916 /* tell the world what we did */
918 AudioUnitEvent theEvent;
920 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
921 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
922 theEvent.mArgument.mParameter.mParameterID = d.id;
923 theEvent.mArgument.mParameter.mScope = d.scope;
924 theEvent.mArgument.mParameter.mElement = d.element;
926 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
927 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
928 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
930 Plugin::set_parameter (which, val);
934 AUPlugin::get_parameter (uint32_t which) const
937 if (which < descriptors.size()) {
938 const AUParameterDescriptor& d (descriptors[which]);
939 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
940 unit->GetParameter(d.id, d.scope, d.element, val);
946 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
948 if (which < descriptors.size()) {
949 pd = descriptors[which];
956 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
958 if (which < descriptors.size()) {
967 AUPlugin::activate ()
971 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
972 if ((err = unit->Initialize()) != noErr) {
973 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
975 frames_processed = 0;
982 AUPlugin::deactivate ()
984 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
985 unit->Uninitialize ();
992 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
993 unit->GlobalReset ();
997 AUPlugin::requires_fixed_size_buffers() const
999 return _requires_fixed_size_buffers;
1004 AUPlugin::set_block_size (pframes_t nframes)
1006 bool was_initialized = initialized;
1007 UInt32 numFrames = nframes;
1014 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
1015 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1016 0, &numFrames, sizeof (numFrames))) != noErr) {
1017 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
1021 if (was_initialized) {
1025 _current_block_size = nframes;
1031 AUPlugin::configure_io (ChanCount in, ChanCount out)
1033 AudioStreamBasicDescription streamFormat;
1034 bool was_initialized = initialized;
1035 int32_t audio_out = out.n_audio();
1036 if (audio_input_cnt > 0) {
1037 in.set (DataType::AUDIO, audio_input_cnt);
1039 int32_t audio_in = in.n_audio();
1041 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1044 //if we are already running with the requested i/o config, bail out here
1045 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1052 streamFormat.mSampleRate = _session.frame_rate();
1053 streamFormat.mFormatID = kAudioFormatLinearPCM;
1054 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1056 #ifdef __LITTLE_ENDIAN__
1059 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1062 streamFormat.mBitsPerChannel = 32;
1063 streamFormat.mFramesPerPacket = 1;
1065 /* apple says that for non-interleaved data, these
1066 values always refer to a single channel.
1068 streamFormat.mBytesPerPacket = 4;
1069 streamFormat.mBytesPerFrame = 4;
1071 streamFormat.mChannelsPerFrame = audio_in;
1073 if (set_input_format (streamFormat) != 0) {
1077 streamFormat.mChannelsPerFrame = audio_out;
1079 if (set_output_format (streamFormat) != 0) {
1083 /* reset plugin info to show currently configured state */
1085 _info->n_inputs = in;
1086 _info->n_outputs = out;
1088 if (was_initialized) {
1096 AUPlugin::input_streams() const
1101 if (input_channels < 0) {
1102 // force PluginIoReConfigure -- see also commit msg e38eb06
1103 c.set (DataType::AUDIO, 0);
1104 c.set (DataType::MIDI, 0);
1106 c.set (DataType::AUDIO, input_channels);
1107 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1115 AUPlugin::output_streams() const
1119 if (output_channels < 0) {
1120 // force PluginIoReConfigure - see also commit msg e38eb06
1121 c.set (DataType::AUDIO, 0);
1122 c.set (DataType::MIDI, 0);
1124 c.set (DataType::AUDIO, output_channels);
1125 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1132 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1134 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1136 int32_t audio_in = in.n_audio();
1139 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1141 /* lets check MIDI first */
1143 if (in.n_midi() > 0) {
1144 if (!_has_midi_input) {
1149 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1151 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1152 name(), io_configs.size(), in, out));
1154 //Ardour expects the plugin to tell it the output
1155 //configuration but AU plugins can have multiple I/O
1156 //configurations in most cases. so first lets see
1157 //if there's a configuration that keeps out==in
1159 if (in.n_midi() > 0 && audio_in == 0) {
1160 audio_out = 2; // prefer stereo version if available.
1162 audio_out = audio_in;
1165 /* kAudioUnitProperty_SupportedNumChannels
1166 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1168 * - both fields are -1
1169 * e.g. inChannels = -1 outChannels = -1
1170 * This is the default case. Any number of input and output channels, as long as the numbers match
1172 * - one field is -1, the other field is positive
1173 * e.g. inChannels = -1 outChannels = 2
1174 * Any number of input channels, exactly two output channels
1176 * - one field is -1, the other field is -2
1177 * e.g. inChannels = -1 outChannels = -2
1178 * Any number of input channels, any number of output channels
1180 * - both fields have non-negative values
1181 * e.g. inChannels = 2 outChannels = 6
1182 * Exactly two input channels, exactly six output channels
1183 * e.g. inChannels = 0 outChannels = 2
1184 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1186 * - both fields have negative values, neither of which is –1 or –2
1187 * e.g. inChannels = -4 outChannels = -8
1188 * Up to four input channels and up to eight output channels
1191 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1193 int32_t possible_in = i->first;
1194 int32_t possible_out = i->second;
1196 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1197 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1198 possible_in, possible_out,
1201 out.set (DataType::MIDI, 0);
1202 out.set (DataType::AUDIO, audio_out);
1208 /* now allow potentially "imprecise" matches */
1212 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1214 int32_t possible_in = i->first;
1215 int32_t possible_out = i->second;
1217 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1219 if (possible_out == 0) {
1220 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1221 /* XXX surely this is just a send? (e.g. AUNetSend) */
1225 if (possible_in == 0) {
1227 /* instrument plugin, always legal but throws away inputs ...
1230 if (possible_out == -1) {
1231 /* any configuration possible, provide stereo output */
1234 } else if (possible_out == -2) {
1235 /* plugins shouldn't really use (0,-2) but might.
1236 any configuration possible, provide stereo output
1240 } else if (possible_out < -2) {
1241 /* explicitly variable number of outputs.
1243 * We really need to ask the user in this case.
1244 * stereo will be correct in 99.9% of all cases.
1249 /* exact number of outputs */
1250 audio_out = possible_out;
1255 if (possible_in == -1) {
1257 /* wildcard for input */
1259 if (possible_out == -1) {
1260 /* out much match in */
1261 audio_out = audio_in;
1263 } else if (possible_out == -2) {
1264 /* any configuration possible, pick matching */
1265 audio_out = audio_in;
1267 } else if (possible_out < -2) {
1268 /* explicitly variable number of outputs, pick maximum */
1269 audio_out = -possible_out;
1272 /* exact number of outputs */
1273 audio_out = possible_out;
1278 if (possible_in == -2) {
1280 if (possible_out == -1) {
1281 /* any configuration possible, pick matching */
1282 audio_out = audio_in;
1284 } else if (possible_out == -2) {
1285 /* plugins shouldn't really use (-2,-2) but might.
1286 interpret as (-1,-1).
1288 audio_out = audio_in;
1290 } else if (possible_out < -2) {
1291 /* explicitly variable number of outputs, pick maximum */
1292 audio_out = -possible_out;
1295 /* exact number of outputs */
1296 audio_out = possible_out;
1301 if (possible_in < -2) {
1303 /* explicit variable number of inputs */
1305 if (audio_in > -possible_in) {
1306 /* request is too large */
1310 if (possible_out == -1) {
1311 /* any output configuration possible, provide stereo out */
1314 } else if (possible_out == -2) {
1315 /* plugins shouldn't really use (<-2,-2) but might.
1316 interpret as (<-2,-1): any configuration possible, provide stereo output
1320 } else if (possible_out < -2) {
1321 /* explicitly variable number of outputs.
1323 * We really need to ask the user in this case.
1324 * stereo will be correct in 99.9% of all cases.
1329 /* exact number of outputs */
1330 audio_out = possible_out;
1335 if (possible_in && (possible_in == audio_in)) {
1337 /* exact number of inputs ... must match obviously */
1339 if (possible_out == -1) {
1340 /* any output configuration possible, provide stereo output */
1343 } else if (possible_out == -2) {
1344 /* plugins shouldn't really use (>0,-2) but might.
1345 interpret as (>0,-1):
1346 any output configuration possible, provide stereo output
1350 } else if (possible_out < -2) {
1351 /* explicitly variable number of outputs, pick maximum */
1352 audio_out = -possible_out;
1355 /* exact number of outputs */
1356 audio_out = possible_out;
1362 if (possible_in < -2 && audio_in == 0) {
1363 // input-port count cannot be zero, use as many ports
1364 // as outputs, but at most abs(possible_in)
1365 audio_input_cnt = max (1, min (audio_out, -possible_in));
1373 out.set (DataType::MIDI, 0); /// XXX
1374 out.set (DataType::AUDIO, audio_out);
1375 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1377 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1385 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1387 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1391 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1393 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1402 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1403 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1409 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1413 for (uint32_t i = 0; i < cnt; ++i) {
1414 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1415 (scope == kAudioUnitScope_Input ? "input" : "output"),
1417 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1418 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1419 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1424 if (scope == kAudioUnitScope_Input) {
1425 input_channels = fmt.mChannelsPerFrame;
1427 output_channels = fmt.mChannelsPerFrame;
1434 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1435 const AudioTimeStamp*,
1437 UInt32 inNumberFrames,
1438 AudioBufferList* ioData)
1440 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1442 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1443 // name(), inNumberFrames, ioData->mNumberBuffers));
1445 if (input_maxbuf == 0) {
1446 error << _("AUPlugin: render callback called illegally!") << endmsg;
1447 return kAudioUnitErr_CannotDoInCurrentContext;
1449 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1451 for (uint32_t i = 0; i < limit; ++i) {
1452 ioData->mBuffers[i].mNumberChannels = 1;
1453 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1455 /* we don't use the channel mapping because audiounits are
1456 * never replicated. one plugin instance uses all channels/buffers
1457 * passed to PluginInsert::connect_and_run()
1460 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1463 cb_offset += inNumberFrames;
1469 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1471 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1473 AudioUnitRenderActionFlags flags = 0;
1477 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1478 unit->GlobalReset();
1479 _last_nframes = nframes;
1482 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1483 name(), input_channels, output_channels, _has_midi_input,
1484 bufs.count(), bufs.available()));
1486 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1487 has the capacity to handle our outputs.
1490 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1492 input_buffers = &bufs;
1493 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1494 input_offset = offset;
1497 buffers->mNumberBuffers = output_channels;
1499 for (int32_t i = 0; i < output_channels; ++i) {
1500 buffers->mBuffers[i].mNumberChannels = 1;
1501 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1502 /* setting this to 0 indicates to the AU that it can provide buffers here
1503 * if necessary. if it can process in-place, it will use the buffers provided
1504 * as input by ::render_callback() above.
1506 * a non-null values tells the plugin to render into the buffer pointed
1509 buffers->mBuffers[i].mData = 0;
1512 if (_has_midi_input) {
1514 uint32_t nmidi = bufs.count().n_midi();
1516 for (uint32_t i = 0; i < nmidi; ++i) {
1518 /* one MIDI port/buffer only */
1520 MidiBuffer& m = bufs.get_midi (i);
1522 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1523 Evoral::MIDIEvent<framepos_t> ev (*i);
1525 if (ev.is_channel_event()) {
1526 const uint8_t* b = ev.buffer();
1527 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1528 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1531 /* XXX need to handle sysex and other message types */
1536 /* does this really mean anything ?
1539 ts.mSampleTime = frames_processed;
1540 ts.mFlags = kAudioTimeStampSampleTimeValid;
1542 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1543 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1545 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1548 frames_processed += nframes;
1550 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1551 name(), buffers->mNumberBuffers, output_channels));
1553 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1556 for (i = 0; i < limit; ++i) {
1557 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1558 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1559 /* plugin provided its own buffer for output so copy it back to where we want it
1561 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1565 /* now silence any buffers that were passed in but the that the plugin
1566 * did not fill/touch/use.
1569 for (;i < output_channels; ++i) {
1570 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1576 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1581 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1582 Float64* outCurrentTempo)
1584 TempoMap& tmap (_session.tempo_map());
1586 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1588 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1589 (and interpretation) of a beat position will be incorrect. So refuse to
1593 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1594 return kAudioUnitErr_CannotDoInCurrentContext;
1597 Timecode::BBT_Time bbt;
1598 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1599 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1601 if (outCurrentBeat) {
1603 beat = metric.meter().divisions_per_bar() * bbt.bars;
1605 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1606 *outCurrentBeat = beat;
1609 if (outCurrentTempo) {
1610 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1618 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1619 Float32* outTimeSig_Numerator,
1620 UInt32* outTimeSig_Denominator,
1621 Float64* outCurrentMeasureDownBeat)
1623 TempoMap& tmap (_session.tempo_map());
1625 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1627 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1628 (and interpretation) of a beat position will be incorrect. So refuse to
1632 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1633 return kAudioUnitErr_CannotDoInCurrentContext;
1636 Timecode::BBT_Time bbt;
1637 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1638 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1640 if (outDeltaSampleOffsetToNextBeat) {
1641 if (bbt.ticks == 0) {
1643 *outDeltaSampleOffsetToNextBeat = 0;
1645 *outDeltaSampleOffsetToNextBeat = (UInt32)
1646 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1647 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1651 if (outTimeSig_Numerator) {
1652 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1654 if (outTimeSig_Denominator) {
1655 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1658 if (outCurrentMeasureDownBeat) {
1660 /* beat for the start of the bar.
1662 2|1|0 -> 1 + divisions_per_bar
1663 3|1|0 -> 1 + (2 * divisions_per_bar)
1667 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1674 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1675 Boolean* outTransportStateChanged,
1676 Float64* outCurrentSampleInTimeLine,
1677 Boolean* outIsCycling,
1678 Float64* outCycleStartBeat,
1679 Float64* outCycleEndBeat)
1684 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1686 rolling = _session.transport_rolling();
1687 speed = _session.transport_speed ();
1690 *outIsPlaying = _session.transport_rolling();
1693 if (outTransportStateChanged) {
1694 if (rolling != last_transport_rolling) {
1695 *outTransportStateChanged = true;
1696 } else if (speed != last_transport_speed) {
1697 *outTransportStateChanged = true;
1699 *outTransportStateChanged = false;
1703 if (outCurrentSampleInTimeLine) {
1704 /* this assumes that the AU can only call this host callback from render context,
1705 where input_offset is valid.
1707 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1711 Location* loc = _session.locations()->auto_loop_location();
1713 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1715 if (*outIsCycling) {
1717 if (outCycleStartBeat || outCycleEndBeat) {
1719 TempoMap& tmap (_session.tempo_map());
1721 /* more than 1 meter means that a simplistic computation (and interpretation) of
1722 a beat position will be incorrect. so refuse to offer the value.
1725 if (tmap.n_meters() > 1) {
1726 return kAudioUnitErr_CannotDoInCurrentContext;
1729 Timecode::BBT_Time bbt;
1731 if (outCycleStartBeat) {
1732 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1733 _session.tempo_map().bbt_time (loc->start(), bbt);
1736 beat = metric.meter().divisions_per_bar() * bbt.bars;
1738 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1740 *outCycleStartBeat = beat;
1743 if (outCycleEndBeat) {
1744 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1745 _session.tempo_map().bbt_time (loc->end(), bbt);
1748 beat = metric.meter().divisions_per_bar() * bbt.bars;
1750 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1752 *outCycleEndBeat = beat;
1758 last_transport_rolling = rolling;
1759 last_transport_speed = speed;
1764 set<Evoral::Parameter>
1765 AUPlugin::automatable() const
1767 set<Evoral::Parameter> automates;
1769 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1770 if (descriptors[i].automatable) {
1771 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1779 AUPlugin::describe_parameter (Evoral::Parameter param)
1781 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1782 return descriptors[param.id()].label;
1789 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1791 // NameValue stuff here
1795 AUPlugin::parameter_is_audio (uint32_t) const
1801 AUPlugin::parameter_is_control (uint32_t param) const
1803 assert(param < descriptors.size());
1804 if (descriptors[param].automatable) {
1805 /* corrently ardour expects all controls to be automatable
1806 * IOW ardour GUI elements mandate an Evoral::Parameter
1807 * for all input+control ports.
1815 AUPlugin::parameter_is_input (uint32_t param) const
1817 /* AU params that are both readable and writeable,
1818 * are listed in kAudioUnitScope_Global
1820 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1824 AUPlugin::parameter_is_output (uint32_t param) const
1826 assert(param < descriptors.size());
1827 // TODO check if ardour properly handles ports
1828 // that report is_input + is_output == true
1829 // -> add || descriptors[param].scope == kAudioUnitScope_Global
1830 return (descriptors[param].scope == kAudioUnitScope_Output);
1834 AUPlugin::add_state (XMLNode* root) const
1836 LocaleGuard lg (X_("C"));
1838 CFPropertyListRef propertyList;
1840 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1841 if (unit->GetAUPreset (propertyList) != noErr) {
1845 // Convert the property list into XML data.
1847 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1850 error << _("Could not create XML version of property list") << endmsg;
1854 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1855 our state node. GACK!
1860 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1862 root->add_child_copy (*t.root());
1866 CFRelease (xmlData);
1867 CFRelease (propertyList);
1871 AUPlugin::set_state(const XMLNode& node, int version)
1874 CFPropertyListRef propertyList;
1875 LocaleGuard lg (X_("C"));
1877 if (node.name() != state_node_name()) {
1878 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1882 #ifndef NO_PLUGIN_STATE
1883 if (node.children().empty()) {
1887 XMLNode* top = node.children().front();
1888 XMLNode* copy = new XMLNode (*top);
1893 const string& xml = t.write_buffer ();
1894 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1895 CFStringRef errorString;
1897 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1899 kCFPropertyListImmutable,
1902 CFRelease (xmlData);
1905 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1906 if (unit->SetAUPreset (propertyList) == noErr) {
1909 /* tell the world */
1911 AudioUnitParameter changedUnit;
1912 changedUnit.mAudioUnit = unit->AU();
1913 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1914 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1916 CFRelease (propertyList);
1920 Plugin::set_state (node, version);
1925 AUPlugin::load_preset (PresetRecord r)
1927 Plugin::load_preset (r);
1930 CFPropertyListRef propertyList;
1932 UserPresetMap::iterator ux;
1933 FactoryPresetMap::iterator fx;
1935 /* look first in "user" presets */
1937 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1939 if ((propertyList = load_property_list (ux->second)) != 0) {
1940 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1941 if (unit->SetAUPreset (propertyList) == noErr) {
1944 /* tell the world */
1946 AudioUnitParameter changedUnit;
1947 changedUnit.mAudioUnit = unit->AU();
1948 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1949 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1951 CFRelease(propertyList);
1954 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1958 preset.presetNumber = fx->second;
1959 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1961 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1963 if (unit->SetPresentPreset (preset) == 0) {
1966 /* tell the world */
1968 AudioUnitParameter changedUnit;
1969 changedUnit.mAudioUnit = unit->AU();
1970 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1971 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1979 AUPlugin::do_remove_preset (std::string)
1984 AUPlugin::do_save_preset (string preset_name)
1986 CFPropertyListRef propertyList;
1987 vector<Glib::ustring> v;
1988 Glib::ustring user_preset_path;
1990 std::string m = maker();
1991 std::string n = name();
1993 strip_whitespace_edges (m);
1994 strip_whitespace_edges (n);
1996 v.push_back (Glib::get_home_dir());
1997 v.push_back ("Library");
1998 v.push_back ("Audio");
1999 v.push_back ("Presets");
2003 user_preset_path = Glib::build_filename (v);
2005 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2006 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2010 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2011 if (unit->GetAUPreset (propertyList) != noErr) {
2015 // add the actual preset name */
2017 v.push_back (preset_name + preset_suffix);
2021 user_preset_path = Glib::build_filename (v);
2023 set_preset_name_in_plist (propertyList, preset_name);
2025 if (save_property_list (propertyList, user_preset_path)) {
2026 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2030 CFRelease(propertyList);
2032 user_preset_map[preset_name] = user_preset_path;;
2034 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2036 return string ("file:///") + user_preset_path;
2039 //-----------------------------------------------------------------------------
2040 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2042 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2044 CFNumberRef cfNumber;
2045 SInt32 numberValue = 0;
2046 Boolean dummySuccess;
2048 if (outSuccess == NULL)
2049 outSuccess = &dummySuccess;
2050 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2052 *outSuccess = FALSE;
2056 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2057 if (cfNumber == NULL)
2059 *outSuccess = FALSE;
2062 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2070 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2072 CFDictionaryRef auStateDictionary;
2073 ArdourDescription tempDesc = {0,0,0,0,0};
2074 SInt32 versionValue;
2077 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2080 // the property list for AU state data must be of the dictionary type
2081 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2082 return kAudioUnitErr_InvalidPropertyValue;
2085 auStateDictionary = (CFDictionaryRef)inAUStateData;
2087 // first check to make sure that the version of the AU state data is one that we know understand
2088 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2089 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2092 return kAudioUnitErr_InvalidPropertyValue;
2094 #define kCurrentSavedStateVersion 0
2095 if (versionValue != kCurrentSavedStateVersion) {
2096 return kAudioUnitErr_InvalidPropertyValue;
2099 // grab the ComponentDescription values from the AU state data
2100 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2101 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2102 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2103 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2104 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2105 return kAudioUnitErr_InvalidPropertyValue;
2107 *outComponentDescription = tempDesc;
2112 static bool au_preset_filter (const string& str, void* arg)
2114 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2118 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2122 /* check the preset file path name against this plugin
2123 ID. The idea is that all preset files for this plugin
2124 include "<manufacturer>/<plugin-name>" in their path.
2127 AUPluginInfo* p = (AUPluginInfo *) arg;
2128 string match = p->creator;
2132 ret = str.find (match) != string::npos;
2135 string m = p->creator;
2137 strip_whitespace_edges (m);
2138 strip_whitespace_edges (n);
2143 ret = str.find (match) != string::npos;
2151 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2154 CFPropertyListRef plist;
2155 ArdourDescription presetDesc;
2158 plist = load_property_list (pathstr);
2164 // get the ComponentDescription from the AU preset file
2166 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2168 if (status == noErr) {
2169 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2171 /* try to get the preset name from the property list */
2173 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2175 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2179 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2182 char buf[PATH_MAX+1];
2184 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2201 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2203 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2206 CFStringRef itemName = NULL;
2207 // Marc Poirier-style item name
2209 CAComponent auComponent (comp_desc);
2210 if (auComponent.IsValid()) {
2211 CAComponentDescription dummydesc;
2212 Handle nameHandle = NewHandle(sizeof(void*));
2213 if (nameHandle != NULL) {
2214 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2216 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2217 if (nameString != NULL) {
2218 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2221 DisposeHandle(nameHandle);
2226 AudioComponentCopyName (comp, &itemName);
2229 // if Marc-style fails, do the original way
2230 if (itemName == NULL) {
2231 #ifndef COREAUDIO105
2232 CAComponentDescription comp_desc;
2233 AudioComponentGetDescription (comp, &comp_desc);
2235 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2236 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2237 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2239 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2240 compTypeString, compManufacturerString, compSubTypeString);
2242 if (compTypeString != NULL)
2243 CFRelease(compTypeString);
2244 if (compSubTypeString != NULL)
2245 CFRelease(compSubTypeString);
2246 if (compManufacturerString != NULL)
2247 CFRelease(compManufacturerString);
2250 string str = CFStringRefToStdString(itemName);
2251 string::size_type colon = str.find (':');
2254 name = str.substr (colon+1);
2255 maker = str.substr (0, colon);
2256 strip_whitespace_edges (maker);
2257 strip_whitespace_edges (name);
2261 strip_whitespace_edges (name);
2266 AUPlugin::current_preset() const
2270 CFPropertyListRef propertyList;
2272 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2273 if (unit->GetAUPreset (propertyList) == noErr) {
2274 preset_name = get_preset_name_in_plist (propertyList);
2275 CFRelease(propertyList);
2282 AUPlugin::find_presets ()
2284 vector<string> preset_files;
2286 user_preset_map.clear ();
2288 PluginInfoPtr nfo = get_info();
2289 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2290 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2293 if (preset_files.empty()) {
2294 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2297 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2302 /* make an initial guess at the preset name using the path */
2304 preset_name = Glib::path_get_basename (path);
2305 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2307 /* check that this preset file really matches this plugin
2308 and potentially get the "real" preset name from
2312 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2313 user_preset_map[preset_name] = path;
2314 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2316 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2321 /* now fill the vector<string> with the names we have */
2323 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2324 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2325 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2328 /* add factory presets */
2330 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2332 string const uri = string_compose ("%1", _presets.size ());
2333 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2334 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2339 AUPlugin::has_editor () const
2341 // even if the plugin doesn't have its own editor, the AU API can be used
2342 // to create one that looks native.
2346 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2350 type = ARDOUR::AudioUnit;
2353 AUPluginInfo::~AUPluginInfo ()
2355 type = ARDOUR::AudioUnit;
2359 AUPluginInfo::load (Session& session)
2364 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2365 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2367 if (!comp->IsValid()) {
2368 error << ("AudioUnit: not a valid Component") << endmsg;
2370 plugin.reset (new AUPlugin (session.engine(), session, comp));
2373 AUPluginInfo *aup = new AUPluginInfo (*this);
2374 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2375 plugin->set_info (PluginInfoPtr (aup));
2376 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2380 catch (failed_constructor &err) {
2381 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2382 return PluginPtr ();
2386 std::vector<Plugin::PresetRecord>
2387 AUPluginInfo::get_presets (bool user_only) const
2389 std::vector<Plugin::PresetRecord> p;
2390 boost::shared_ptr<CAComponent> comp;
2391 #ifndef NO_PLUGIN_STATE
2393 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2394 if (!comp->IsValid()) {
2395 throw failed_constructor();
2397 } catch (failed_constructor& err) {
2403 if (!preset_search_path_initialized) {
2404 Glib::ustring p = Glib::get_home_dir();
2405 p += "/Library/Audio/Presets:";
2406 p += preset_search_path;
2407 preset_search_path = p;
2408 preset_search_path_initialized = true;
2409 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2412 vector<string> preset_files;
2413 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2415 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2418 preset_name = Glib::path_get_basename (path);
2419 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2420 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2421 p.push_back (Plugin::PresetRecord (path, preset_name));
2435 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2436 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2439 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2440 unit->Uninitialize ();
2443 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2444 unit->Uninitialize ();
2448 unit->Uninitialize ();
2452 CFIndex cnt = CFArrayGetCount (presets);
2453 for (CFIndex i = 0; i < cnt; ++i) {
2454 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2455 string const uri = string_compose ("%1", i);
2456 string name = CFStringRefToStdString (preset->presetName);
2457 p.push_back (Plugin::PresetRecord (uri, name, false));
2459 CFRelease (presets);
2460 unit->Uninitialize ();
2462 #endif // NO_PLUGIN_STATE
2467 AUPluginInfo::au_cache_path ()
2469 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2473 AUPluginInfo::discover (bool scan_only)
2477 /* AU require a CAComponentDescription pointer provided by the OS.
2478 * Ardour only caches port and i/o config. It can't just 'scan' without
2479 * 'discovering' (like we do for VST).
2482 * "Iterate over all plugins. skip the ones where there's no io-cache".
2484 _scan_only = scan_only;
2486 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2487 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2489 // create crash log file
2490 au_start_crashlog ();
2492 PluginInfoList* plugs = new PluginInfoList;
2494 discover_fx (*plugs);
2495 discover_music (*plugs);
2496 discover_generators (*plugs);
2497 discover_instruments (*plugs);
2499 // all fine if we get here
2500 au_remove_crashlog ();
2502 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2508 AUPluginInfo::discover_music (PluginInfoList& plugs)
2510 CAComponentDescription desc;
2511 desc.componentFlags = 0;
2512 desc.componentFlagsMask = 0;
2513 desc.componentSubType = 0;
2514 desc.componentManufacturer = 0;
2515 desc.componentType = kAudioUnitType_MusicEffect;
2517 discover_by_description (plugs, desc);
2521 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2523 CAComponentDescription desc;
2524 desc.componentFlags = 0;
2525 desc.componentFlagsMask = 0;
2526 desc.componentSubType = 0;
2527 desc.componentManufacturer = 0;
2528 desc.componentType = kAudioUnitType_Effect;
2530 discover_by_description (plugs, desc);
2534 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2536 CAComponentDescription desc;
2537 desc.componentFlags = 0;
2538 desc.componentFlagsMask = 0;
2539 desc.componentSubType = 0;
2540 desc.componentManufacturer = 0;
2541 desc.componentType = kAudioUnitType_Generator;
2543 discover_by_description (plugs, desc);
2547 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2549 CAComponentDescription desc;
2550 desc.componentFlags = 0;
2551 desc.componentFlagsMask = 0;
2552 desc.componentSubType = 0;
2553 desc.componentManufacturer = 0;
2554 desc.componentType = kAudioUnitType_MusicDevice;
2556 discover_by_description (plugs, desc);
2561 AUPluginInfo::au_get_crashlog (std::string &msg)
2563 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2564 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2567 std::ifstream ifs(fn.c_str());
2568 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2569 au_remove_crashlog ();
2574 AUPluginInfo::au_start_crashlog ()
2576 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2577 assert(!_crashlog_fd);
2578 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2579 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2580 PBD::error << "Cannot create AU error-log" << fn << "\n";
2581 cerr << "Cannot create AU error-log" << fn << "\n";
2586 AUPluginInfo::au_remove_crashlog ()
2589 ::fclose(_crashlog_fd);
2590 _crashlog_fd = NULL;
2592 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2593 ::g_unlink(fn.c_str());
2594 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2599 AUPluginInfo::au_crashlog (std::string msg)
2601 if (!_crashlog_fd) {
2602 fprintf(stderr, "AU: %s\n", msg.c_str());
2604 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2605 ::fflush(_crashlog_fd);
2610 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2612 ArdourComponent comp = 0;
2613 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2615 comp = ArdourFindNext (NULL, &desc);
2617 while (comp != NULL) {
2618 CAComponentDescription temp;
2620 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2622 AudioComponentGetDescription (comp, &temp);
2624 CFStringRef itemName = NULL;
2627 if (itemName != NULL) CFRelease(itemName);
2628 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2629 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2630 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2631 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2632 compTypeString, compManufacturerString, compSubTypeString);
2633 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2634 if (compTypeString != NULL)
2635 CFRelease(compTypeString);
2636 if (compSubTypeString != NULL)
2637 CFRelease(compSubTypeString);
2638 if (compManufacturerString != NULL)
2639 CFRelease(compManufacturerString);
2642 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2643 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2644 comp = ArdourFindNext (comp, &desc);
2648 AUPluginInfoPtr info (new AUPluginInfo
2649 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2651 /* although apple designed the subtype field to be a "category" indicator,
2652 its really turned into a plugin ID field for a given manufacturer. Hence
2653 there are no categories for AudioUnits. However, to keep the plugins
2654 showing up under "categories", we'll use the "type" as a high level
2657 NOTE: no panners, format converters or i/o AU's for our purposes
2660 switch (info->descriptor->Type()) {
2661 case kAudioUnitType_Panner:
2662 case kAudioUnitType_OfflineEffect:
2663 case kAudioUnitType_FormatConverter:
2664 comp = ArdourFindNext (comp, &desc);
2667 case kAudioUnitType_Output:
2668 info->category = _("AudioUnit Outputs");
2670 case kAudioUnitType_MusicDevice:
2671 info->category = _("AudioUnit Instruments");
2673 case kAudioUnitType_MusicEffect:
2674 info->category = _("AudioUnit MusicEffects");
2676 case kAudioUnitType_Effect:
2677 info->category = _("AudioUnit Effects");
2679 case kAudioUnitType_Mixer:
2680 info->category = _("AudioUnit Mixers");
2682 case kAudioUnitType_Generator:
2683 info->category = _("AudioUnit Generators");
2686 info->category = _("AudioUnit (Unknown)");
2690 au_blacklist(CFStringRefToStdString(itemName));
2692 get_names (temp, info->name, info->creator);
2694 get_names (comp, info->name, info->creator);
2696 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2697 au_crashlog(string_compose("Plugin: %1", info->name));
2699 info->type = ARDOUR::AudioUnit;
2700 info->unique_id = stringify_descriptor (*info->descriptor);
2702 /* XXX not sure of the best way to handle plugin versioning yet
2705 CAComponent cacomp (*info->descriptor);
2708 if (cacomp.GetResourceVersion (info->version) != noErr)
2710 if (cacomp.GetVersion (info->version) != noErr)
2716 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2719 /* here we have to map apple's wildcard system to a simple pair
2720 of values. in ::can_do() we use the whole system, but here
2721 we need a single pair of values. XXX probably means we should
2722 remove any use of these values.
2724 for now, if the plugin provides a wildcard, treat it as 1. we really
2725 don't care much, because whether we can handle an i/o configuration
2726 depends upon ::can_support_io_configuration(), not these counts.
2728 they exist because other parts of ardour try to present i/o configuration
2729 info to the user, which should perhaps be revisited.
2732 int32_t possible_in = info->cache.io_configs.front().first;
2733 int32_t possible_out = info->cache.io_configs.front().second;
2735 if (possible_in > 0) {
2736 info->n_inputs.set (DataType::AUDIO, possible_in);
2738 info->n_inputs.set (DataType::AUDIO, 1);
2741 if (possible_out > 0) {
2742 info->n_outputs.set (DataType::AUDIO, possible_out);
2744 info->n_outputs.set (DataType::AUDIO, 1);
2747 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2748 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2750 plugs.push_back (info);
2753 else if (rv == -1) {
2754 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2757 au_unblacklist(CFStringRefToStdString(itemName));
2758 au_crashlog("Success.");
2759 comp = ArdourFindNext (comp, &desc);
2760 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2762 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2766 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2769 AUPluginCachedInfo& cinfo,
2770 const std::string& name)
2775 /* concatenate unique ID with version to provide a key for cached info lookup.
2776 this ensures we don't get stale information, or should if plugin developers
2777 follow Apple "guidelines".
2780 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2785 CachedInfoMap::iterator cim = cached_info.find (id);
2787 if (cim != cached_info.end()) {
2788 cinfo = cim->second;
2793 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
2798 AUChannelInfo* channel_info;
2802 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2806 if (CAAudioUnit::Open (comp, unit) != noErr) {
2812 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2817 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2818 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2824 /* no explicit info available, so default to 1in/1out */
2826 /* XXX this is wrong. we should be indicating wildcard values */
2828 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2832 /* store each configuration */
2834 for (uint32_t n = 0; n < cnt; ++n) {
2835 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2836 channel_info[n].outChannels));
2839 free (channel_info);
2842 add_cached_info (id, cinfo);
2843 save_cached_info ();
2849 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2851 cached_info[id] = cinfo;
2854 #define AU_CACHE_VERSION "2.0"
2857 AUPluginInfo::save_cached_info ()
2861 node = new XMLNode (X_("AudioUnitPluginCache"));
2862 node->add_property( "version", AU_CACHE_VERSION );
2864 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2865 XMLNode* parent = new XMLNode (X_("plugin"));
2866 parent->add_property ("id", i->first);
2867 node->add_child_nocopy (*parent);
2869 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2871 XMLNode* child = new XMLNode (X_("io"));
2874 snprintf (buf, sizeof (buf), "%d", j->first);
2875 child->add_property (X_("in"), buf);
2876 snprintf (buf, sizeof (buf), "%d", j->second);
2877 child->add_property (X_("out"), buf);
2878 parent->add_child_nocopy (*child);
2883 Glib::ustring path = au_cache_path ();
2886 tree.set_root (node);
2888 if (!tree.write (path)) {
2889 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2890 g_unlink (path.c_str());
2895 AUPluginInfo::load_cached_info ()
2897 Glib::ustring path = au_cache_path ();
2900 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2904 if ( !tree.read (path) ) {
2905 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2909 const XMLNode* root (tree.root());
2911 if (root->name() != X_("AudioUnitPluginCache")) {
2915 //initial version has incorrectly stored i/o info, and/or garbage chars.
2916 const XMLProperty* version = root->property(X_("version"));
2917 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2918 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2922 cached_info.clear ();
2924 const XMLNodeList children = root->children();
2926 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2928 const XMLNode* child = *iter;
2930 if (child->name() == X_("plugin")) {
2932 const XMLNode* gchild;
2933 const XMLNodeList gchildren = child->children();
2934 const XMLProperty* prop = child->property (X_("id"));
2940 string id = prop->value();
2944 string::size_type slash = id.find_last_of ('/');
2946 if (slash == string::npos) {
2950 version = id.substr (slash);
2951 id = id.substr (0, slash);
2952 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2954 if (fixed.empty()) {
2955 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2962 AUPluginCachedInfo cinfo;
2964 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2968 if (gchild->name() == X_("io")) {
2972 const XMLProperty* iprop;
2973 const XMLProperty* oprop;
2975 if (((iprop = gchild->property (X_("in"))) != 0) &&
2976 ((oprop = gchild->property (X_("out"))) != 0)) {
2977 in = atoi (iprop->value());
2978 out = atoi (oprop->value());
2980 cinfo.io_configs.push_back (pair<int,int> (in, out));
2985 if (cinfo.io_configs.size()) {
2986 add_cached_info (id, cinfo);
2996 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3000 /* note: OSType is a compiler-implemenation-defined value,
3001 historically a 32 bit integer created with a multi-character
3002 constant such as 'abcd'. It is, fundamentally, an abomination.
3007 s << desc.SubType();
3015 AUPluginInfo::needs_midi_input ()
3017 return is_effect_with_midi_input () || is_instrument ();
3021 AUPluginInfo::is_effect () const
3023 return is_effect_without_midi_input() || is_effect_with_midi_input();
3027 AUPluginInfo::is_effect_without_midi_input () const
3029 return descriptor->IsAUFX();
3033 AUPluginInfo::is_effect_with_midi_input () const
3035 return descriptor->IsAUFM();
3039 AUPluginInfo::is_instrument () const
3041 return descriptor->IsMusicDevice();
3045 AUPlugin::set_info (PluginInfoPtr info)
3047 Plugin::set_info (info);
3049 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3050 _has_midi_input = pinfo->needs_midi_input ();
3051 _has_midi_output = false;
3055 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3058 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3060 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3062 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3064 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3068 _parameter_listener_arg = arg;
3074 AUPlugin::listen_to_parameter (uint32_t param_id)
3076 AudioUnitEvent event;
3078 if (!_parameter_listener || param_id >= descriptors.size()) {
3082 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3083 event.mArgument.mParameter.mAudioUnit = unit->AU();
3084 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3085 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3086 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3088 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3092 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3093 event.mArgument.mParameter.mAudioUnit = unit->AU();
3094 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3095 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3096 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3098 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3102 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3103 event.mArgument.mParameter.mAudioUnit = unit->AU();
3104 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3105 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3106 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3108 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3116 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3118 AudioUnitEvent event;
3120 if (!_parameter_listener || param_id >= descriptors.size()) {
3124 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3125 event.mArgument.mParameter.mAudioUnit = unit->AU();
3126 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3127 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3128 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3130 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3134 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3135 event.mArgument.mParameter.mAudioUnit = unit->AU();
3136 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3137 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3138 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3140 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3144 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3145 event.mArgument.mParameter.mAudioUnit = unit->AU();
3146 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3147 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3148 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3150 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3158 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3160 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3164 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3166 ParameterMap::iterator i;
3168 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3172 switch (event->mEventType) {
3173 case kAudioUnitEvent_BeginParameterChangeGesture:
3174 StartTouch (i->second);
3176 case kAudioUnitEvent_EndParameterChangeGesture:
3177 EndTouch (i->second);
3179 case kAudioUnitEvent_ParameterValueChange:
3180 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3181 means that something else (i.e. the plugin GUI) made the change.
3183 ParameterChangedExternally (i->second, new_value);