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)
440 , frames_processed (0)
441 , audio_input_cnt (0)
442 , _parameter_listener (0)
443 , _parameter_listener_arg (0)
444 , last_transport_rolling (false)
445 , last_transport_speed (0.0)
447 if (!preset_search_path_initialized) {
448 Glib::ustring p = Glib::get_home_dir();
449 p += "/Library/Audio/Presets:";
450 p += preset_search_path;
451 preset_search_path = p;
452 preset_search_path_initialized = true;
453 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
460 AUPlugin::AUPlugin (const AUPlugin& other)
462 , comp (other.get_comp())
463 , unit (new CAAudioUnit)
464 , initialized (false)
465 , _current_block_size (0)
467 , _requires_fixed_size_buffers (false)
473 , frames_processed (0)
474 , _parameter_listener (0)
475 , _parameter_listener_arg (0)
479 for (size_t i = 0; i < descriptors.size(); ++i) {
480 set_parameter (i, other.get_parameter (i));
484 AUPlugin::~AUPlugin ()
486 if (_parameter_listener) {
487 AUListenerDispose (_parameter_listener);
488 _parameter_listener = 0;
492 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
493 unit->Uninitialize ();
502 AUPlugin::discover_factory_presets ()
509 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
510 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
514 assert (dataSize == sizeof (presets));
516 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
517 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
525 CFIndex cnt = CFArrayGetCount (presets);
527 for (CFIndex i = 0; i < cnt; ++i) {
528 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
530 string name = CFStringRefToStdString (preset->presetName);
531 factory_preset_map[name] = preset->presetNumber;
532 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
542 CFStringRef itemName;
544 /* these keep track of *configured* channel set up,
545 not potential set ups.
549 output_channels = -1;
551 CAComponentDescription temp;
553 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
555 AudioComponentGetDescription (comp.get()->Comp(), &temp);
557 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
558 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
559 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
560 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
561 compTypeString, compManufacturerString, compSubTypeString);
562 if (compTypeString != NULL) CFRelease(compTypeString);
563 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
564 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
567 au_blacklist(CFStringRefToStdString(itemName));
570 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
571 err = CAAudioUnit::Open (*(comp.get()), *unit);
573 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
574 throw failed_constructor();
578 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
579 throw failed_constructor ();
582 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
583 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
584 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
585 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
586 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
587 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
589 if (input_elements > 0) {
590 /* setup render callback: the plugin calls this to get input data
593 AURenderCallbackStruct renderCallbackInfo;
595 renderCallbackInfo.inputProc = _render_callback;
596 renderCallbackInfo.inputProcRefCon = this;
598 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
599 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
600 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
601 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
602 throw failed_constructor();
606 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
608 HostCallbackInfo info;
609 memset (&info, 0, sizeof (HostCallbackInfo));
610 info.hostUserData = this;
611 info.beatAndTempoProc = _get_beat_and_tempo_callback;
612 info.musicalTimeLocationProc = _get_musical_time_location_callback;
613 info.transportStateProc = _get_transport_state_callback;
615 //ignore result of this - don't care if the property isn't supported
616 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
617 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
618 kAudioUnitScope_Global,
621 sizeof (HostCallbackInfo));
623 if (set_block_size (_session.get_block_size())) {
624 error << _("AUPlugin: cannot set processing block size") << endmsg;
625 throw failed_constructor();
628 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
629 discover_parameters ();
630 discover_factory_presets ();
632 // Plugin::setup_controls ();
634 au_unblacklist(CFStringRefToStdString(itemName));
635 if (itemName != NULL) CFRelease(itemName);
639 AUPlugin::discover_parameters ()
641 /* discover writable parameters */
643 AudioUnitScope scopes[] = {
644 kAudioUnitScope_Global,
645 kAudioUnitScope_Output,
646 kAudioUnitScope_Input
649 descriptors.clear ();
651 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
653 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
655 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
657 AUParameterDescriptor d;
659 d.id = param_info.ParamID (i);
661 const CAAUParameter* param = param_info.GetParamInfo (d.id);
662 const AudioUnitParameterInfo& info (param->ParamInfo());
664 const int len = CFStringGetLength (param->GetName());
665 char local_buffer[len*2];
666 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
670 d.label = local_buffer;
673 d.scope = param_info.GetScope ();
674 d.element = param_info.GetElement ();
676 /* info.units to consider */
678 kAudioUnitParameterUnit_Generic = 0
679 kAudioUnitParameterUnit_Indexed = 1
680 kAudioUnitParameterUnit_Boolean = 2
681 kAudioUnitParameterUnit_Percent = 3
682 kAudioUnitParameterUnit_Seconds = 4
683 kAudioUnitParameterUnit_SampleFrames = 5
684 kAudioUnitParameterUnit_Phase = 6
685 kAudioUnitParameterUnit_Rate = 7
686 kAudioUnitParameterUnit_Hertz = 8
687 kAudioUnitParameterUnit_Cents = 9
688 kAudioUnitParameterUnit_RelativeSemiTones = 10
689 kAudioUnitParameterUnit_MIDINoteNumber = 11
690 kAudioUnitParameterUnit_MIDIController = 12
691 kAudioUnitParameterUnit_Decibels = 13
692 kAudioUnitParameterUnit_LinearGain = 14
693 kAudioUnitParameterUnit_Degrees = 15
694 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
695 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
696 kAudioUnitParameterUnit_Pan = 18
697 kAudioUnitParameterUnit_Meters = 19
698 kAudioUnitParameterUnit_AbsoluteCents = 20
699 kAudioUnitParameterUnit_Octaves = 21
700 kAudioUnitParameterUnit_BPM = 22
701 kAudioUnitParameterUnit_Beats = 23
702 kAudioUnitParameterUnit_Milliseconds = 24
703 kAudioUnitParameterUnit_Ratio = 25
706 /* info.flags to consider */
710 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
711 kAudioUnitParameterFlag_HasClump = (1L << 20)
712 kAudioUnitParameterFlag_HasName = (1L << 21)
713 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
714 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
715 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
716 kAudioUnitParameterFlag_CanRamp = (1L << 25)
717 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
718 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
719 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
720 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
721 kAudioUnitParameterFlag_IsReadable = (1L << 30)
722 kAudioUnitParameterFlag_IsWritable = (1L << 31)
725 d.lower = info.minValue;
726 d.upper = info.maxValue;
727 d.normal = info.defaultValue;
729 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
730 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
731 (d.integer_step && ((d.upper - d.lower) == 1.0));
732 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
733 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
734 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
735 (info.flags & kAudioUnitParameterFlag_IsWritable);
737 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
738 d.au_unit = info.unit;
740 case kAudioUnitParameterUnit_Decibels:
741 d.unit = ParameterDescriptor::DB;
743 case kAudioUnitParameterUnit_MIDINoteNumber:
744 d.unit = ParameterDescriptor::MIDI_NOTE;
746 case kAudioUnitParameterUnit_Hertz:
747 d.unit = ParameterDescriptor::HZ;
751 d.min_unbound = 0; // lower is bound
752 d.max_unbound = 0; // upper is bound
755 descriptors.push_back (d);
757 uint32_t last_param = descriptors.size() - 1;
758 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
759 listen_to_parameter (last_param);
766 four_ints_to_four_byte_literal (unsigned char n[4])
768 /* this is actually implementation dependent. sigh. this is what gcc
769 and quite a few others do.
771 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
775 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
777 if (isdigit (id[0])) {
781 /* ID format is xxxx-xxxx-xxxx
782 where x maybe \xNN or a printable character.
784 Split at the '-' and and process each part into an integer.
785 Then put it back together.
789 unsigned char nascent[4];
790 const char* cstr = id.c_str();
791 const char* estr = cstr + id.size();
802 while (*cstr && next_int < 4) {
806 if (estr - cstr < 3) {
808 /* too close to the end for \xNN parsing: treat as literal characters */
816 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
820 memcpy (short_buf, &cstr[2], 2);
821 nascent[in] = strtol (short_buf, NULL, 16);
827 /* treat as literal characters */
841 if (in && (in % 4 == 0)) {
842 /* nascent is ready */
843 n[next_int] = four_ints_to_four_byte_literal (nascent);
847 /* swallow space-hyphen-space */
861 s << n[0] << '-' << n[1] << '-' << n[2];
870 AUPlugin::unique_id () const
872 return AUPluginInfo::stringify_descriptor (comp->Desc());
876 AUPlugin::label () const
878 return _info->name.c_str();
882 AUPlugin::parameter_count () const
884 return descriptors.size();
888 AUPlugin::default_value (uint32_t port)
890 if (port < descriptors.size()) {
891 return descriptors[port].normal;
898 AUPlugin::signal_latency () const
900 return unit->Latency() * _session.frame_rate();
904 AUPlugin::set_parameter (uint32_t which, float val)
906 if (which >= descriptors.size()) {
910 if (get_parameter(which) == val) {
914 const AUParameterDescriptor& d (descriptors[which]);
915 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
916 unit->SetParameter (d.id, d.scope, d.element, val);
918 /* tell the world what we did */
920 AudioUnitEvent theEvent;
922 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
923 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
924 theEvent.mArgument.mParameter.mParameterID = d.id;
925 theEvent.mArgument.mParameter.mScope = d.scope;
926 theEvent.mArgument.mParameter.mElement = d.element;
928 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
929 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
930 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
932 Plugin::set_parameter (which, val);
936 AUPlugin::get_parameter (uint32_t which) const
939 if (which < descriptors.size()) {
940 const AUParameterDescriptor& d (descriptors[which]);
941 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
942 unit->GetParameter(d.id, d.scope, d.element, val);
948 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
950 if (which < descriptors.size()) {
951 pd = descriptors[which];
958 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
960 if (which < descriptors.size()) {
969 AUPlugin::activate ()
973 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
974 if ((err = unit->Initialize()) != noErr) {
975 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
977 frames_processed = 0;
984 AUPlugin::deactivate ()
986 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
987 unit->Uninitialize ();
994 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
995 unit->GlobalReset ();
999 AUPlugin::requires_fixed_size_buffers() const
1001 return _requires_fixed_size_buffers;
1006 AUPlugin::set_block_size (pframes_t nframes)
1008 bool was_initialized = initialized;
1009 UInt32 numFrames = nframes;
1016 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
1017 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1018 0, &numFrames, sizeof (numFrames))) != noErr) {
1019 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
1023 if (was_initialized) {
1027 _current_block_size = nframes;
1033 AUPlugin::configure_io (ChanCount in, ChanCount out)
1035 AudioStreamBasicDescription streamFormat;
1036 bool was_initialized = initialized;
1037 int32_t audio_out = out.n_audio();
1038 if (audio_input_cnt > 0) {
1039 in.set (DataType::AUDIO, audio_input_cnt);
1041 int32_t audio_in = in.n_audio();
1043 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1046 //if we are already running with the requested i/o config, bail out here
1047 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1054 streamFormat.mSampleRate = _session.frame_rate();
1055 streamFormat.mFormatID = kAudioFormatLinearPCM;
1056 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1058 #ifdef __LITTLE_ENDIAN__
1061 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1064 streamFormat.mBitsPerChannel = 32;
1065 streamFormat.mFramesPerPacket = 1;
1067 /* apple says that for non-interleaved data, these
1068 values always refer to a single channel.
1070 streamFormat.mBytesPerPacket = 4;
1071 streamFormat.mBytesPerFrame = 4;
1073 streamFormat.mChannelsPerFrame = audio_in;
1075 if (set_input_format (streamFormat) != 0) {
1079 streamFormat.mChannelsPerFrame = audio_out;
1081 if (set_output_format (streamFormat) != 0) {
1085 /* reset plugin info to show currently configured state */
1087 _info->n_inputs = in;
1088 _info->n_outputs = out;
1090 if (was_initialized) {
1098 AUPlugin::input_streams() const
1103 if (input_channels < 0) {
1104 // force PluginIoReConfigure -- see also commit msg e38eb06
1105 c.set (DataType::AUDIO, 0);
1106 c.set (DataType::MIDI, 0);
1108 c.set (DataType::AUDIO, input_channels);
1109 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1117 AUPlugin::output_streams() const
1121 if (output_channels < 0) {
1122 // force PluginIoReConfigure - see also commit msg e38eb06
1123 c.set (DataType::AUDIO, 0);
1124 c.set (DataType::MIDI, 0);
1126 c.set (DataType::AUDIO, output_channels);
1127 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1134 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1136 _output_configs.clear ();
1137 const int32_t audio_in = in.n_audio();
1138 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1140 /* lets check MIDI first */
1142 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1146 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1148 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1149 name(), io_configs.size(), in, out));
1151 // preferred setting (provided by plugin_insert)
1152 const int preferred_out = out.n_audio ();
1154 bool exact_match = false;
1156 /* kAudioUnitProperty_SupportedNumChannels
1157 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1159 * - both fields are -1
1160 * e.g. inChannels = -1 outChannels = -1
1161 * This is the default case. Any number of input and output channels, as long as the numbers match
1163 * - one field is -1, the other field is positive
1164 * e.g. inChannels = -1 outChannels = 2
1165 * Any number of input channels, exactly two output channels
1167 * - one field is -1, the other field is -2
1168 * e.g. inChannels = -1 outChannels = -2
1169 * Any number of input channels, any number of output channels
1171 * - both fields have non-negative values
1172 * e.g. inChannels = 2 outChannels = 6
1173 * Exactly two input channels, exactly six output channels
1174 * e.g. inChannels = 0 outChannels = 2
1175 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1177 * - both fields have negative values, neither of which is –1 or –2
1178 * e.g. inChannels = -4 outChannels = -8
1179 * Up to four input channels and up to eight output channels
1182 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1184 int32_t possible_in = i->first;
1185 int32_t possible_out = i->second;
1187 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1188 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1189 possible_in, possible_out,
1193 _output_configs.insert (preferred_out);
1200 /* now allow potentially "imprecise" matches */
1201 int32_t audio_out = -1;
1202 float penalty = 9999;
1203 int used_possible_in = 0;
1205 #define FOUNDCFG(nch) { \
1206 float p = fabsf ((float)(nch) - preferred_out); \
1207 _output_configs.insert (nch); \
1208 if ((nch) > preferred_out) { p *= 1.1; } \
1209 if (p < penalty) { \
1210 used_possible_in = possible_in; \
1211 audio_out = (nch); \
1217 #define ANYTHINGGOES \
1218 _output_configs.insert (0);
1220 #define UPTO(nch) { \
1221 for (int n = 1; n < nch; ++n) { \
1222 _output_configs.insert (n); \
1226 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1228 int32_t possible_in = i->first;
1229 int32_t possible_out = i->second;
1231 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1233 if (possible_out == 0) {
1234 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1235 /* XXX surely this is just a send? (e.g. AUNetSend) */
1239 if (possible_in == 0) {
1240 /* no inputs, generators & instruments */
1241 if (possible_out == -1) {
1242 /* any configuration possible, provide stereo output */
1243 FOUNDCFG (preferred_out);
1245 } else if (possible_out == -2) {
1246 /* invalid, should be (0, -1) */
1247 FOUNDCFG (preferred_out);
1249 } else if (possible_out < -2) {
1250 /* variable number of outputs up to -N, */
1251 FOUNDCFG (min (-possible_out, preferred_out));
1252 UPTO (-possible_out);
1254 /* exact number of outputs */
1255 FOUNDCFG (possible_out);
1259 if (possible_in == -1) {
1260 /* wildcard for input */
1261 if (possible_out == -1) {
1262 /* out must match in */
1263 FOUNDCFG (audio_in);
1264 } else if (possible_out == -2) {
1265 /* any configuration possible, pick matching */
1266 FOUNDCFG (preferred_out);
1268 } else if (possible_out < -2) {
1269 /* explicitly variable number of outputs, pick maximum */
1270 FOUNDCFG (max (-possible_out, preferred_out));
1271 /* and try min, too, in case the penalty is lower */
1272 FOUNDCFG (min (-possible_out, preferred_out));
1273 UPTO (-possible_out)
1275 /* exact number of outputs */
1276 FOUNDCFG (possible_out);
1280 if (possible_in == -2) {
1281 if (possible_out == -1) {
1282 /* any configuration possible, pick matching */
1283 FOUNDCFG (preferred_out);
1285 } else if (possible_out == -2) {
1286 /* invalid. interpret as (-1, -1) */
1287 FOUNDCFG (preferred_out);
1289 } else if (possible_out < -2) {
1290 /* invalid, interpret as (<-2, <-2)
1291 * variable number of outputs up to -N, */
1292 FOUNDCFG (min (-possible_out, preferred_out));
1293 UPTO (-possible_out)
1295 /* exact number of outputs */
1296 FOUNDCFG (possible_out);
1300 if (possible_in < -2) {
1301 /* explicit variable number of inputs */
1302 if (audio_in > -possible_in && imprecise != NULL) {
1303 // hide inputs ports
1304 imprecise->set (DataType::AUDIO, -possible_in);
1307 if (audio_in > -possible_in && imprecise == NULL) {
1308 /* request is too large */
1309 } else if (possible_out == -1) {
1310 /* any output configuration possible */
1311 FOUNDCFG (preferred_out);
1313 } else if (possible_out == -2) {
1314 /* invalid. interpret as (<-2, -1) */
1315 FOUNDCFG (preferred_out);
1317 } else if (possible_out < -2) {
1318 /* variable number of outputs up to -N, */
1319 FOUNDCFG (min (-possible_out, preferred_out));
1320 UPTO (-possible_out)
1322 /* exact number of outputs */
1323 FOUNDCFG (possible_out);
1327 if (possible_in && (possible_in == audio_in)) {
1328 /* exact number of inputs ... must match obviously */
1329 if (possible_out == -1) {
1330 /* any output configuration possible */
1331 FOUNDCFG (preferred_out);
1333 } else if (possible_out == -2) {
1334 /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
1335 FOUNDCFG (preferred_out);
1337 } else if (possible_out < -2) {
1338 /* > 0, < -2 is not specified
1339 * interpret as up to -N */
1340 FOUNDCFG (min (-possible_out, preferred_out));
1341 UPTO (-possible_out)
1343 /* exact number of outputs */
1344 FOUNDCFG (possible_out);
1349 if (!found && imprecise) {
1351 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1352 int32_t possible_in = i->first;
1353 int32_t possible_out = i->second;
1355 assert (possible_in > 0); // all other cases will have been matched above
1356 assert (possible_out !=0 || possible_in !=0); // already handled above
1358 imprecise->set (DataType::AUDIO, possible_in);
1359 if (possible_out == -1 || possible_out == -2) {
1361 } else if (possible_out < -2) {
1362 /* explicitly variable number of outputs, pick maximum */
1363 FOUNDCFG (min (-possible_out, preferred_out));
1365 /* exact number of outputs */
1366 FOUNDCFG (possible_out);
1368 // ideally we'll also find the closest, best matching
1369 // input configuration with minimal output penalty...
1374 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1379 out.set (DataType::MIDI, 0); // currently always zero
1380 out.set (DataType::AUDIO, preferred_out);
1382 if (used_possible_in < -2 && audio_in == 0) {
1383 // input-port count cannot be zero, use as many ports
1384 // as outputs, but at most abs(possible_in)
1385 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1387 out.set (DataType::MIDI, 0); /// XXX
1388 out.set (DataType::AUDIO, audio_out);
1390 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1396 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1398 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1402 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1404 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1413 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1414 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1420 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1424 for (uint32_t i = 0; i < cnt; ++i) {
1425 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1426 (scope == kAudioUnitScope_Input ? "input" : "output"),
1428 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1429 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1430 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1435 if (scope == kAudioUnitScope_Input) {
1436 input_channels = fmt.mChannelsPerFrame;
1438 output_channels = fmt.mChannelsPerFrame;
1445 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1446 const AudioTimeStamp*,
1448 UInt32 inNumberFrames,
1449 AudioBufferList* ioData)
1451 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1453 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1454 // name(), inNumberFrames, ioData->mNumberBuffers));
1456 if (input_maxbuf == 0) {
1457 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1458 error << _("AUPlugin: render callback called illegally!") << endmsg;
1459 return kAudioUnitErr_CannotDoInCurrentContext;
1461 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1463 ChanCount bufs_count (DataType::AUDIO, 1);
1464 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1466 for (uint32_t i = 0; i < limit; ++i) {
1467 ioData->mBuffers[i].mNumberChannels = 1;
1468 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1471 uint32_t idx = input_map->get (DataType::AUDIO, i, &valid);
1473 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offset + input_offset);
1475 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offset + input_offset);
1479 cb_offset += inNumberFrames;
1485 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1487 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1489 AudioUnitRenderActionFlags flags = 0;
1493 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1494 unit->GlobalReset();
1495 _last_nframes = nframes;
1498 /* test if we can run in-place; only compare audio buffers */
1499 bool inplace = true;
1500 ChanMapping::Mappings inmap (in_map.mappings ());
1501 ChanMapping::Mappings outmap (out_map.mappings ());
1502 assert (outmap[DataType::AUDIO].size () > 0);
1503 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1507 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6) Inplace: %7\n",
1508 name(), input_channels, output_channels, _has_midi_input,
1509 bufs.count(), bufs.available(), inplace));
1511 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1512 * has the capacity to handle our outputs.
1515 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1517 input_buffers = &bufs;
1518 input_map = &in_map;
1519 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1520 input_offset = offset;
1523 buffers->mNumberBuffers = output_channels;
1525 ChanCount bufs_count (DataType::AUDIO, 1);
1526 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1528 for (int32_t i = 0; i < output_channels; ++i) {
1529 buffers->mBuffers[i].mNumberChannels = 1;
1530 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1531 /* setting this to 0 indicates to the AU that it can provide buffers here
1532 * if necessary. if it can process in-place, it will use the buffers provided
1533 * as input by ::render_callback() above.
1535 * a non-null values tells the plugin to render into the buffer pointed
1539 buffers->mBuffers[i].mData = 0;
1542 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1544 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1546 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1551 if (_has_midi_input) {
1553 uint32_t nmidi = bufs.count().n_midi();
1555 for (uint32_t i = 0; i < nmidi; ++i) {
1557 /* one MIDI port/buffer only */
1559 MidiBuffer& m = bufs.get_midi (i);
1561 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1562 Evoral::MIDIEvent<framepos_t> ev (*i);
1564 if (ev.is_channel_event()) {
1565 const uint8_t* b = ev.buffer();
1566 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1567 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1570 /* XXX need to handle sysex and other message types */
1575 /* does this really mean anything ? */
1577 ts.mSampleTime = frames_processed;
1578 ts.mFlags = kAudioTimeStampSampleTimeValid;
1580 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1581 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1583 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1586 frames_processed += nframes;
1588 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1589 name(), buffers->mNumberBuffers, output_channels));
1591 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1594 for (i = 0; i < limit; ++i) {
1596 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1597 if (!valid) continue;
1598 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1599 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1600 /* plugin provided its own buffer for output so copy it back to where we want it
1602 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1606 /* now silence any buffers that were passed in but the that the plugin
1607 * did not fill/touch/use.
1610 for (;i < output_channels; ++i) {
1612 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1613 if (!valid) continue;
1614 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1620 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1625 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1626 Float64* outCurrentTempo)
1628 TempoMap& tmap (_session.tempo_map());
1630 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1632 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1633 (and interpretation) of a beat position will be incorrect. So refuse to
1637 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1638 return kAudioUnitErr_CannotDoInCurrentContext;
1641 Timecode::BBT_Time bbt;
1642 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1643 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1645 if (outCurrentBeat) {
1647 beat = metric.meter().divisions_per_bar() * bbt.bars;
1649 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1650 *outCurrentBeat = beat;
1653 if (outCurrentTempo) {
1654 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1662 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1663 Float32* outTimeSig_Numerator,
1664 UInt32* outTimeSig_Denominator,
1665 Float64* outCurrentMeasureDownBeat)
1667 TempoMap& tmap (_session.tempo_map());
1669 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1671 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1672 (and interpretation) of a beat position will be incorrect. So refuse to
1676 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1677 return kAudioUnitErr_CannotDoInCurrentContext;
1680 Timecode::BBT_Time bbt;
1681 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1682 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1684 if (outDeltaSampleOffsetToNextBeat) {
1685 if (bbt.ticks == 0) {
1687 *outDeltaSampleOffsetToNextBeat = 0;
1689 *outDeltaSampleOffsetToNextBeat = (UInt32)
1690 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1691 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1695 if (outTimeSig_Numerator) {
1696 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1698 if (outTimeSig_Denominator) {
1699 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1702 if (outCurrentMeasureDownBeat) {
1704 /* beat for the start of the bar.
1706 2|1|0 -> 1 + divisions_per_bar
1707 3|1|0 -> 1 + (2 * divisions_per_bar)
1711 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1718 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1719 Boolean* outTransportStateChanged,
1720 Float64* outCurrentSampleInTimeLine,
1721 Boolean* outIsCycling,
1722 Float64* outCycleStartBeat,
1723 Float64* outCycleEndBeat)
1728 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1730 rolling = _session.transport_rolling();
1731 speed = _session.transport_speed ();
1734 *outIsPlaying = _session.transport_rolling();
1737 if (outTransportStateChanged) {
1738 if (rolling != last_transport_rolling) {
1739 *outTransportStateChanged = true;
1740 } else if (speed != last_transport_speed) {
1741 *outTransportStateChanged = true;
1743 *outTransportStateChanged = false;
1747 if (outCurrentSampleInTimeLine) {
1748 /* this assumes that the AU can only call this host callback from render context,
1749 where input_offset is valid.
1751 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1755 Location* loc = _session.locations()->auto_loop_location();
1757 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1759 if (*outIsCycling) {
1761 if (outCycleStartBeat || outCycleEndBeat) {
1763 TempoMap& tmap (_session.tempo_map());
1765 /* more than 1 meter means that a simplistic computation (and interpretation) of
1766 a beat position will be incorrect. so refuse to offer the value.
1769 if (tmap.n_meters() > 1) {
1770 return kAudioUnitErr_CannotDoInCurrentContext;
1773 Timecode::BBT_Time bbt;
1775 if (outCycleStartBeat) {
1776 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1777 _session.tempo_map().bbt_time (loc->start(), bbt);
1780 beat = metric.meter().divisions_per_bar() * bbt.bars;
1782 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1784 *outCycleStartBeat = beat;
1787 if (outCycleEndBeat) {
1788 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1789 _session.tempo_map().bbt_time (loc->end(), bbt);
1792 beat = metric.meter().divisions_per_bar() * bbt.bars;
1794 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1796 *outCycleEndBeat = beat;
1802 last_transport_rolling = rolling;
1803 last_transport_speed = speed;
1808 set<Evoral::Parameter>
1809 AUPlugin::automatable() const
1811 set<Evoral::Parameter> automates;
1813 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1814 if (descriptors[i].automatable) {
1815 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1823 AUPlugin::describe_parameter (Evoral::Parameter param)
1825 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1826 return descriptors[param.id()].label;
1833 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1835 // NameValue stuff here
1839 AUPlugin::parameter_is_audio (uint32_t) const
1845 AUPlugin::parameter_is_control (uint32_t param) const
1847 assert(param < descriptors.size());
1848 if (descriptors[param].automatable) {
1849 /* corrently ardour expects all controls to be automatable
1850 * IOW ardour GUI elements mandate an Evoral::Parameter
1851 * for all input+control ports.
1859 AUPlugin::parameter_is_input (uint32_t param) const
1861 /* AU params that are both readable and writeable,
1862 * are listed in kAudioUnitScope_Global
1864 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1868 AUPlugin::parameter_is_output (uint32_t param) const
1870 assert(param < descriptors.size());
1871 // TODO check if ardour properly handles ports
1872 // that report is_input + is_output == true
1873 // -> add || descriptors[param].scope == kAudioUnitScope_Global
1874 return (descriptors[param].scope == kAudioUnitScope_Output);
1878 AUPlugin::add_state (XMLNode* root) const
1880 LocaleGuard lg (X_("C"));
1882 CFPropertyListRef propertyList;
1884 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1885 if (unit->GetAUPreset (propertyList) != noErr) {
1889 // Convert the property list into XML data.
1891 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1894 error << _("Could not create XML version of property list") << endmsg;
1898 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1899 our state node. GACK!
1904 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1906 root->add_child_copy (*t.root());
1910 CFRelease (xmlData);
1911 CFRelease (propertyList);
1915 AUPlugin::set_state(const XMLNode& node, int version)
1918 CFPropertyListRef propertyList;
1919 LocaleGuard lg (X_("C"));
1921 if (node.name() != state_node_name()) {
1922 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1926 #ifndef NO_PLUGIN_STATE
1927 if (node.children().empty()) {
1931 XMLNode* top = node.children().front();
1932 XMLNode* copy = new XMLNode (*top);
1937 const string& xml = t.write_buffer ();
1938 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1939 CFStringRef errorString;
1941 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1943 kCFPropertyListImmutable,
1946 CFRelease (xmlData);
1949 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1950 if (unit->SetAUPreset (propertyList) == noErr) {
1953 /* tell the world */
1955 AudioUnitParameter changedUnit;
1956 changedUnit.mAudioUnit = unit->AU();
1957 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1958 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1960 CFRelease (propertyList);
1964 Plugin::set_state (node, version);
1969 AUPlugin::load_preset (PresetRecord r)
1971 Plugin::load_preset (r);
1974 CFPropertyListRef propertyList;
1976 UserPresetMap::iterator ux;
1977 FactoryPresetMap::iterator fx;
1979 /* look first in "user" presets */
1981 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1983 if ((propertyList = load_property_list (ux->second)) != 0) {
1984 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1985 if (unit->SetAUPreset (propertyList) == noErr) {
1988 /* tell the world */
1990 AudioUnitParameter changedUnit;
1991 changedUnit.mAudioUnit = unit->AU();
1992 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1993 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1995 CFRelease(propertyList);
1998 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2002 preset.presetNumber = fx->second;
2003 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2005 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2007 if (unit->SetPresentPreset (preset) == 0) {
2010 /* tell the world */
2012 AudioUnitParameter changedUnit;
2013 changedUnit.mAudioUnit = unit->AU();
2014 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2015 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2023 AUPlugin::do_remove_preset (std::string)
2028 AUPlugin::do_save_preset (string preset_name)
2030 CFPropertyListRef propertyList;
2031 vector<Glib::ustring> v;
2032 Glib::ustring user_preset_path;
2034 std::string m = maker();
2035 std::string n = name();
2037 strip_whitespace_edges (m);
2038 strip_whitespace_edges (n);
2040 v.push_back (Glib::get_home_dir());
2041 v.push_back ("Library");
2042 v.push_back ("Audio");
2043 v.push_back ("Presets");
2047 user_preset_path = Glib::build_filename (v);
2049 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2050 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2054 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2055 if (unit->GetAUPreset (propertyList) != noErr) {
2059 // add the actual preset name */
2061 v.push_back (preset_name + preset_suffix);
2065 user_preset_path = Glib::build_filename (v);
2067 set_preset_name_in_plist (propertyList, preset_name);
2069 if (save_property_list (propertyList, user_preset_path)) {
2070 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2074 CFRelease(propertyList);
2076 user_preset_map[preset_name] = user_preset_path;;
2078 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2080 return string ("file:///") + user_preset_path;
2083 //-----------------------------------------------------------------------------
2084 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2086 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2088 CFNumberRef cfNumber;
2089 SInt32 numberValue = 0;
2090 Boolean dummySuccess;
2092 if (outSuccess == NULL)
2093 outSuccess = &dummySuccess;
2094 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2096 *outSuccess = FALSE;
2100 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2101 if (cfNumber == NULL)
2103 *outSuccess = FALSE;
2106 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2114 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2116 CFDictionaryRef auStateDictionary;
2117 ArdourDescription tempDesc = {0,0,0,0,0};
2118 SInt32 versionValue;
2121 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2124 // the property list for AU state data must be of the dictionary type
2125 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2126 return kAudioUnitErr_InvalidPropertyValue;
2129 auStateDictionary = (CFDictionaryRef)inAUStateData;
2131 // first check to make sure that the version of the AU state data is one that we know understand
2132 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2133 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2136 return kAudioUnitErr_InvalidPropertyValue;
2138 #define kCurrentSavedStateVersion 0
2139 if (versionValue != kCurrentSavedStateVersion) {
2140 return kAudioUnitErr_InvalidPropertyValue;
2143 // grab the ComponentDescription values from the AU state data
2144 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2145 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2146 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2147 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2148 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2149 return kAudioUnitErr_InvalidPropertyValue;
2151 *outComponentDescription = tempDesc;
2156 static bool au_preset_filter (const string& str, void* arg)
2158 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2162 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2166 /* check the preset file path name against this plugin
2167 ID. The idea is that all preset files for this plugin
2168 include "<manufacturer>/<plugin-name>" in their path.
2171 AUPluginInfo* p = (AUPluginInfo *) arg;
2172 string match = p->creator;
2176 ret = str.find (match) != string::npos;
2179 string m = p->creator;
2181 strip_whitespace_edges (m);
2182 strip_whitespace_edges (n);
2187 ret = str.find (match) != string::npos;
2195 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2198 CFPropertyListRef plist;
2199 ArdourDescription presetDesc;
2202 plist = load_property_list (pathstr);
2208 // get the ComponentDescription from the AU preset file
2210 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2212 if (status == noErr) {
2213 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2215 /* try to get the preset name from the property list */
2217 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2219 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2223 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2226 char buf[PATH_MAX+1];
2228 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2245 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2247 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2250 CFStringRef itemName = NULL;
2251 // Marc Poirier-style item name
2253 CAComponent auComponent (comp_desc);
2254 if (auComponent.IsValid()) {
2255 CAComponentDescription dummydesc;
2256 Handle nameHandle = NewHandle(sizeof(void*));
2257 if (nameHandle != NULL) {
2258 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2260 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2261 if (nameString != NULL) {
2262 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2265 DisposeHandle(nameHandle);
2270 AudioComponentCopyName (comp, &itemName);
2273 // if Marc-style fails, do the original way
2274 if (itemName == NULL) {
2275 #ifndef COREAUDIO105
2276 CAComponentDescription comp_desc;
2277 AudioComponentGetDescription (comp, &comp_desc);
2279 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2280 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2281 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2283 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2284 compTypeString, compManufacturerString, compSubTypeString);
2286 if (compTypeString != NULL)
2287 CFRelease(compTypeString);
2288 if (compSubTypeString != NULL)
2289 CFRelease(compSubTypeString);
2290 if (compManufacturerString != NULL)
2291 CFRelease(compManufacturerString);
2294 string str = CFStringRefToStdString(itemName);
2295 string::size_type colon = str.find (':');
2298 name = str.substr (colon+1);
2299 maker = str.substr (0, colon);
2300 strip_whitespace_edges (maker);
2301 strip_whitespace_edges (name);
2305 strip_whitespace_edges (name);
2310 AUPlugin::current_preset() const
2314 CFPropertyListRef propertyList;
2316 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2317 if (unit->GetAUPreset (propertyList) == noErr) {
2318 preset_name = get_preset_name_in_plist (propertyList);
2319 CFRelease(propertyList);
2326 AUPlugin::find_presets ()
2328 vector<string> preset_files;
2330 user_preset_map.clear ();
2332 PluginInfoPtr nfo = get_info();
2333 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2334 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2337 if (preset_files.empty()) {
2338 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2341 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2346 /* make an initial guess at the preset name using the path */
2348 preset_name = Glib::path_get_basename (path);
2349 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2351 /* check that this preset file really matches this plugin
2352 and potentially get the "real" preset name from
2356 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2357 user_preset_map[preset_name] = path;
2358 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2360 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2365 /* now fill the vector<string> with the names we have */
2367 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2368 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2369 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2372 /* add factory presets */
2374 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2376 string const uri = string_compose ("%1", _presets.size ());
2377 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2378 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2383 AUPlugin::has_editor () const
2385 // even if the plugin doesn't have its own editor, the AU API can be used
2386 // to create one that looks native.
2390 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2394 type = ARDOUR::AudioUnit;
2397 AUPluginInfo::~AUPluginInfo ()
2399 type = ARDOUR::AudioUnit;
2403 AUPluginInfo::load (Session& session)
2408 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2409 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2411 if (!comp->IsValid()) {
2412 error << ("AudioUnit: not a valid Component") << endmsg;
2414 plugin.reset (new AUPlugin (session.engine(), session, comp));
2417 AUPluginInfo *aup = new AUPluginInfo (*this);
2418 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2419 plugin->set_info (PluginInfoPtr (aup));
2420 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2424 catch (failed_constructor &err) {
2425 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2426 return PluginPtr ();
2430 std::vector<Plugin::PresetRecord>
2431 AUPluginInfo::get_presets (bool user_only) const
2433 std::vector<Plugin::PresetRecord> p;
2434 boost::shared_ptr<CAComponent> comp;
2435 #ifndef NO_PLUGIN_STATE
2437 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2438 if (!comp->IsValid()) {
2439 throw failed_constructor();
2441 } catch (failed_constructor& err) {
2447 if (!preset_search_path_initialized) {
2448 Glib::ustring p = Glib::get_home_dir();
2449 p += "/Library/Audio/Presets:";
2450 p += preset_search_path;
2451 preset_search_path = p;
2452 preset_search_path_initialized = true;
2453 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2456 vector<string> preset_files;
2457 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2459 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2462 preset_name = Glib::path_get_basename (path);
2463 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2464 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2465 p.push_back (Plugin::PresetRecord (path, preset_name));
2479 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2480 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2483 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2484 unit->Uninitialize ();
2487 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2488 unit->Uninitialize ();
2492 unit->Uninitialize ();
2496 CFIndex cnt = CFArrayGetCount (presets);
2497 for (CFIndex i = 0; i < cnt; ++i) {
2498 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2499 string const uri = string_compose ("%1", i);
2500 string name = CFStringRefToStdString (preset->presetName);
2501 p.push_back (Plugin::PresetRecord (uri, name, false));
2503 CFRelease (presets);
2504 unit->Uninitialize ();
2506 #endif // NO_PLUGIN_STATE
2511 AUPluginInfo::au_cache_path ()
2513 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2517 AUPluginInfo::discover (bool scan_only)
2521 /* AU require a CAComponentDescription pointer provided by the OS.
2522 * Ardour only caches port and i/o config. It can't just 'scan' without
2523 * 'discovering' (like we do for VST).
2526 * "Iterate over all plugins. skip the ones where there's no io-cache".
2528 _scan_only = scan_only;
2530 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2531 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2533 // create crash log file
2534 au_start_crashlog ();
2536 PluginInfoList* plugs = new PluginInfoList;
2538 discover_fx (*plugs);
2539 discover_music (*plugs);
2540 discover_generators (*plugs);
2541 discover_instruments (*plugs);
2543 // all fine if we get here
2544 au_remove_crashlog ();
2546 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2552 AUPluginInfo::discover_music (PluginInfoList& plugs)
2554 CAComponentDescription desc;
2555 desc.componentFlags = 0;
2556 desc.componentFlagsMask = 0;
2557 desc.componentSubType = 0;
2558 desc.componentManufacturer = 0;
2559 desc.componentType = kAudioUnitType_MusicEffect;
2561 discover_by_description (plugs, desc);
2565 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2567 CAComponentDescription desc;
2568 desc.componentFlags = 0;
2569 desc.componentFlagsMask = 0;
2570 desc.componentSubType = 0;
2571 desc.componentManufacturer = 0;
2572 desc.componentType = kAudioUnitType_Effect;
2574 discover_by_description (plugs, desc);
2578 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2580 CAComponentDescription desc;
2581 desc.componentFlags = 0;
2582 desc.componentFlagsMask = 0;
2583 desc.componentSubType = 0;
2584 desc.componentManufacturer = 0;
2585 desc.componentType = kAudioUnitType_Generator;
2587 discover_by_description (plugs, desc);
2591 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2593 CAComponentDescription desc;
2594 desc.componentFlags = 0;
2595 desc.componentFlagsMask = 0;
2596 desc.componentSubType = 0;
2597 desc.componentManufacturer = 0;
2598 desc.componentType = kAudioUnitType_MusicDevice;
2600 discover_by_description (plugs, desc);
2605 AUPluginInfo::au_get_crashlog (std::string &msg)
2607 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2608 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2611 std::ifstream ifs(fn.c_str());
2612 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2613 au_remove_crashlog ();
2618 AUPluginInfo::au_start_crashlog ()
2620 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2621 assert(!_crashlog_fd);
2622 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2623 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2624 PBD::error << "Cannot create AU error-log" << fn << "\n";
2625 cerr << "Cannot create AU error-log" << fn << "\n";
2630 AUPluginInfo::au_remove_crashlog ()
2633 ::fclose(_crashlog_fd);
2634 _crashlog_fd = NULL;
2636 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2637 ::g_unlink(fn.c_str());
2638 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2643 AUPluginInfo::au_crashlog (std::string msg)
2645 if (!_crashlog_fd) {
2646 fprintf(stderr, "AU: %s\n", msg.c_str());
2648 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2649 ::fflush(_crashlog_fd);
2654 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2656 ArdourComponent comp = 0;
2657 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2659 comp = ArdourFindNext (NULL, &desc);
2661 while (comp != NULL) {
2662 CAComponentDescription temp;
2664 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2666 AudioComponentGetDescription (comp, &temp);
2668 CFStringRef itemName = NULL;
2671 if (itemName != NULL) CFRelease(itemName);
2672 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2673 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2674 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2675 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2676 compTypeString, compManufacturerString, compSubTypeString);
2677 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2678 if (compTypeString != NULL)
2679 CFRelease(compTypeString);
2680 if (compSubTypeString != NULL)
2681 CFRelease(compSubTypeString);
2682 if (compManufacturerString != NULL)
2683 CFRelease(compManufacturerString);
2686 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2687 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2688 comp = ArdourFindNext (comp, &desc);
2692 bool has_midi_in = false;
2694 AUPluginInfoPtr info (new AUPluginInfo
2695 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2697 /* although apple designed the subtype field to be a "category" indicator,
2698 its really turned into a plugin ID field for a given manufacturer. Hence
2699 there are no categories for AudioUnits. However, to keep the plugins
2700 showing up under "categories", we'll use the "type" as a high level
2703 NOTE: no panners, format converters or i/o AU's for our purposes
2706 switch (info->descriptor->Type()) {
2707 case kAudioUnitType_Panner:
2708 case kAudioUnitType_OfflineEffect:
2709 case kAudioUnitType_FormatConverter:
2710 comp = ArdourFindNext (comp, &desc);
2713 case kAudioUnitType_Output:
2714 info->category = _("AudioUnit Outputs");
2716 case kAudioUnitType_MusicDevice:
2717 info->category = _("AudioUnit Instruments");
2720 case kAudioUnitType_MusicEffect:
2721 info->category = _("AudioUnit MusicEffects");
2724 case kAudioUnitType_Effect:
2725 info->category = _("AudioUnit Effects");
2727 case kAudioUnitType_Mixer:
2728 info->category = _("AudioUnit Mixers");
2730 case kAudioUnitType_Generator:
2731 info->category = _("AudioUnit Generators");
2734 info->category = _("AudioUnit (Unknown)");
2738 au_blacklist(CFStringRefToStdString(itemName));
2740 get_names (temp, info->name, info->creator);
2742 get_names (comp, info->name, info->creator);
2744 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2745 au_crashlog(string_compose("Plugin: %1", info->name));
2747 info->type = ARDOUR::AudioUnit;
2748 info->unique_id = stringify_descriptor (*info->descriptor);
2750 /* XXX not sure of the best way to handle plugin versioning yet
2753 CAComponent cacomp (*info->descriptor);
2756 if (cacomp.GetResourceVersion (info->version) != noErr)
2758 if (cacomp.GetVersion (info->version) != noErr)
2764 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2767 /* here we have to map apple's wildcard system to a simple pair
2768 of values. in ::can_do() we use the whole system, but here
2769 we need a single pair of values. XXX probably means we should
2770 remove any use of these values.
2772 for now, if the plugin provides a wildcard, treat it as 1. we really
2773 don't care much, because whether we can handle an i/o configuration
2774 depends upon ::can_support_io_configuration(), not these counts.
2776 they exist because other parts of ardour try to present i/o configuration
2777 info to the user, which should perhaps be revisited.
2780 int32_t possible_in = info->cache.io_configs.front().first;
2781 int32_t possible_out = info->cache.io_configs.front().second;
2783 if (possible_in > 0) {
2784 info->n_inputs.set (DataType::AUDIO, possible_in);
2786 info->n_inputs.set (DataType::AUDIO, 1);
2789 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
2791 if (possible_out > 0) {
2792 info->n_outputs.set (DataType::AUDIO, possible_out);
2794 info->n_outputs.set (DataType::AUDIO, 1);
2797 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2798 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2800 plugs.push_back (info);
2803 else if (rv == -1) {
2804 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2807 au_unblacklist(CFStringRefToStdString(itemName));
2808 au_crashlog("Success.");
2809 comp = ArdourFindNext (comp, &desc);
2810 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2812 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2816 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2819 AUPluginCachedInfo& cinfo,
2820 const std::string& name)
2825 /* concatenate unique ID with version to provide a key for cached info lookup.
2826 this ensures we don't get stale information, or should if plugin developers
2827 follow Apple "guidelines".
2830 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2835 CachedInfoMap::iterator cim = cached_info.find (id);
2837 if (cim != cached_info.end()) {
2838 cinfo = cim->second;
2843 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
2848 AUChannelInfo* channel_info;
2852 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2856 if (CAAudioUnit::Open (comp, unit) != noErr) {
2862 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2867 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2868 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2874 /* no explicit info available, so default to 1in/1out */
2876 /* XXX this is wrong. we should be indicating wildcard values */
2878 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2882 /* store each configuration */
2884 for (uint32_t n = 0; n < cnt; ++n) {
2885 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2886 channel_info[n].outChannels));
2889 free (channel_info);
2892 add_cached_info (id, cinfo);
2893 save_cached_info ();
2899 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2901 cached_info[id] = cinfo;
2904 #define AU_CACHE_VERSION "2.0"
2907 AUPluginInfo::save_cached_info ()
2911 node = new XMLNode (X_("AudioUnitPluginCache"));
2912 node->add_property( "version", AU_CACHE_VERSION );
2914 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2915 XMLNode* parent = new XMLNode (X_("plugin"));
2916 parent->add_property ("id", i->first);
2917 node->add_child_nocopy (*parent);
2919 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2921 XMLNode* child = new XMLNode (X_("io"));
2924 snprintf (buf, sizeof (buf), "%d", j->first);
2925 child->add_property (X_("in"), buf);
2926 snprintf (buf, sizeof (buf), "%d", j->second);
2927 child->add_property (X_("out"), buf);
2928 parent->add_child_nocopy (*child);
2933 Glib::ustring path = au_cache_path ();
2936 tree.set_root (node);
2938 if (!tree.write (path)) {
2939 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2940 g_unlink (path.c_str());
2945 AUPluginInfo::load_cached_info ()
2947 Glib::ustring path = au_cache_path ();
2950 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2954 if ( !tree.read (path) ) {
2955 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2959 const XMLNode* root (tree.root());
2961 if (root->name() != X_("AudioUnitPluginCache")) {
2965 //initial version has incorrectly stored i/o info, and/or garbage chars.
2966 const XMLProperty* version = root->property(X_("version"));
2967 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2968 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2972 cached_info.clear ();
2974 const XMLNodeList children = root->children();
2976 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2978 const XMLNode* child = *iter;
2980 if (child->name() == X_("plugin")) {
2982 const XMLNode* gchild;
2983 const XMLNodeList gchildren = child->children();
2984 const XMLProperty* prop = child->property (X_("id"));
2990 string id = prop->value();
2994 string::size_type slash = id.find_last_of ('/');
2996 if (slash == string::npos) {
3000 version = id.substr (slash);
3001 id = id.substr (0, slash);
3002 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3004 if (fixed.empty()) {
3005 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3012 AUPluginCachedInfo cinfo;
3014 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3018 if (gchild->name() == X_("io")) {
3022 const XMLProperty* iprop;
3023 const XMLProperty* oprop;
3025 if (((iprop = gchild->property (X_("in"))) != 0) &&
3026 ((oprop = gchild->property (X_("out"))) != 0)) {
3027 in = atoi (iprop->value());
3028 out = atoi (oprop->value());
3030 cinfo.io_configs.push_back (pair<int,int> (in, out));
3035 if (cinfo.io_configs.size()) {
3036 add_cached_info (id, cinfo);
3046 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3050 /* note: OSType is a compiler-implemenation-defined value,
3051 historically a 32 bit integer created with a multi-character
3052 constant such as 'abcd'. It is, fundamentally, an abomination.
3057 s << desc.SubType();
3065 AUPluginInfo::needs_midi_input () const
3067 return is_effect_with_midi_input () || is_instrument ();
3071 AUPluginInfo::is_effect () const
3073 return is_effect_without_midi_input() || is_effect_with_midi_input();
3077 AUPluginInfo::is_effect_without_midi_input () const
3079 return descriptor->IsAUFX();
3083 AUPluginInfo::is_effect_with_midi_input () const
3085 return descriptor->IsAUFM();
3089 AUPluginInfo::is_instrument () const
3091 return descriptor->IsMusicDevice();
3095 AUPlugin::set_info (PluginInfoPtr info)
3097 Plugin::set_info (info);
3099 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3100 _has_midi_input = pinfo->needs_midi_input ();
3101 _has_midi_output = false;
3105 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3108 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3110 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3112 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3114 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3118 _parameter_listener_arg = arg;
3124 AUPlugin::listen_to_parameter (uint32_t param_id)
3126 AudioUnitEvent event;
3128 if (!_parameter_listener || param_id >= descriptors.size()) {
3132 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3133 event.mArgument.mParameter.mAudioUnit = unit->AU();
3134 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3135 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3136 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3138 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3142 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3143 event.mArgument.mParameter.mAudioUnit = unit->AU();
3144 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3145 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3146 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3148 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3152 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3153 event.mArgument.mParameter.mAudioUnit = unit->AU();
3154 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3155 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3156 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3158 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3166 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3168 AudioUnitEvent event;
3170 if (!_parameter_listener || param_id >= descriptors.size()) {
3174 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3175 event.mArgument.mParameter.mAudioUnit = unit->AU();
3176 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3177 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3178 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3180 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3184 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3185 event.mArgument.mParameter.mAudioUnit = unit->AU();
3186 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3187 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3188 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3190 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3194 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3195 event.mArgument.mParameter.mAudioUnit = unit->AU();
3196 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3197 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3198 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3200 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3208 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3210 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3214 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3216 ParameterMap::iterator i;
3218 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3222 switch (event->mEventType) {
3223 case kAudioUnitEvent_BeginParameterChangeGesture:
3224 StartTouch (i->second);
3226 case kAudioUnitEvent_EndParameterChangeGesture:
3227 EndTouch (i->second);
3229 case kAudioUnitEvent_ParameterValueChange:
3230 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3231 means that something else (i.e. the plugin GUI) made the change.
3233 ParameterChangedExternally (i->second, new_value);