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/audio_unit.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/audio_buffer.h"
44 #include "ardour/debug.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/midi_buffer.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 inNumberSamples,
167 AudioBufferList* ioData)
170 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberSamples, 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)
434 , _current_latency (UINT_MAX)
435 , _requires_fixed_size_buffers (false)
437 , variable_inputs (false)
438 , variable_outputs (false)
439 , configured_input_busses (0)
440 , configured_output_busses (0)
448 , samples_processed (0)
449 , audio_input_cnt (0)
450 , _parameter_listener (0)
451 , _parameter_listener_arg (0)
452 , transport_sample (0)
453 , transport_speed (0)
454 , last_transport_speed (0.0)
457 if (!preset_search_path_initialized) {
458 Glib::ustring p = Glib::get_home_dir();
459 p += "/Library/Audio/Presets:";
460 p += preset_search_path;
461 preset_search_path = p;
462 preset_search_path_initialized = true;
463 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
470 AUPlugin::AUPlugin (const AUPlugin& other)
472 , comp (other.get_comp())
473 , unit (new CAAudioUnit)
474 , initialized (false)
476 , _current_latency (UINT_MAX)
477 , _requires_fixed_size_buffers (false)
479 , variable_inputs (false)
480 , variable_outputs (false)
481 , configured_input_busses (0)
482 , configured_output_busses (0)
490 , samples_processed (0)
491 , audio_input_cnt (0)
492 , _parameter_listener (0)
493 , _parameter_listener_arg (0)
494 , transport_sample (0)
495 , transport_speed (0)
496 , last_transport_speed (0.0)
502 XMLNode root (other.state_node_name ());
503 other.add_state (&root);
504 set_state (root, Stateful::loading_state_version);
506 for (size_t i = 0; i < descriptors.size(); ++i) {
507 set_parameter (i, other.get_parameter (i));
511 AUPlugin::~AUPlugin ()
513 if (_parameter_listener) {
514 AUListenerDispose (_parameter_listener);
515 _parameter_listener = 0;
519 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
520 unit->Uninitialize ();
530 AUPlugin::discover_factory_presets ()
537 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
538 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
542 assert (dataSize == sizeof (presets));
544 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
545 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
553 CFIndex cnt = CFArrayGetCount (presets);
555 for (CFIndex i = 0; i < cnt; ++i) {
556 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
558 string name = CFStringRefToStdString (preset->presetName);
559 factory_preset_map[name] = preset->presetNumber;
560 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
570 CFStringRef itemName;
572 /* these keep track of *configured* channel set up,
573 not potential set ups.
577 output_channels = -1;
579 CAComponentDescription temp;
581 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
583 AudioComponentGetDescription (comp.get()->Comp(), &temp);
585 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
586 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
587 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
588 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
589 compTypeString, compManufacturerString, compSubTypeString);
590 if (compTypeString != NULL) CFRelease(compTypeString);
591 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
592 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
595 au_blacklist(CFStringRefToStdString(itemName));
598 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
599 err = CAAudioUnit::Open (*(comp.get()), *unit);
601 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
602 throw failed_constructor();
606 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
607 throw failed_constructor ();
610 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
611 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
612 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
613 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
614 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
615 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
617 cb_offsets = (samplecnt_t*) calloc (input_elements, sizeof(samplecnt_t));
618 bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
619 bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
621 for (size_t i = 0; i < output_elements; ++i) {
622 unit->Reset (kAudioUnitScope_Output, i);
623 AudioStreamBasicDescription fmt;
624 err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
626 bus_outputs[i] = fmt.mChannelsPerFrame;
629 UInt32 sz = sizeof (CFStringRef);
630 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
631 i, &name, &sz) == noErr
633 _bus_name_out.push_back (CFStringRefToStdString (name));
636 _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
640 for (size_t i = 0; i < input_elements; ++i) {
641 unit->Reset (kAudioUnitScope_Input, i);
642 AudioStreamBasicDescription fmt;
643 err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
645 bus_inputs[i] = fmt.mChannelsPerFrame;
648 UInt32 sz = sizeof (CFStringRef);
649 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
650 i, &name, &sz) == noErr
652 _bus_name_in.push_back (CFStringRefToStdString (name));
655 _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
659 for (size_t i = 0; i < input_elements; ++i) {
660 /* setup render callback: the plugin calls this to get input data */
661 AURenderCallbackStruct renderCallbackInfo;
662 renderCallbackInfo.inputProc = _render_callback;
663 renderCallbackInfo.inputProcRefCon = this;
664 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
665 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
666 i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
667 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
668 throw failed_constructor();
672 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
674 HostCallbackInfo info;
675 memset (&info, 0, sizeof (HostCallbackInfo));
676 info.hostUserData = this;
677 info.beatAndTempoProc = _get_beat_and_tempo_callback;
678 info.musicalTimeLocationProc = _get_musical_time_location_callback;
679 info.transportStateProc = _get_transport_state_callback;
681 //ignore result of this - don't care if the property isn't supported
682 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
683 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
684 kAudioUnitScope_Global,
687 sizeof (HostCallbackInfo));
689 if (set_block_size (_session.get_block_size())) {
690 error << _("AUPlugin: cannot set processing block size") << endmsg;
691 throw failed_constructor();
694 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
695 discover_parameters ();
696 discover_factory_presets ();
698 // Plugin::setup_controls ();
700 au_unblacklist(CFStringRefToStdString(itemName));
701 if (itemName != NULL) CFRelease(itemName);
705 AUPlugin::discover_parameters ()
707 /* discover writable parameters */
709 AudioUnitScope scopes[] = {
710 kAudioUnitScope_Global,
711 kAudioUnitScope_Output,
712 kAudioUnitScope_Input
715 descriptors.clear ();
717 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
719 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
721 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
723 AUParameterDescriptor d;
725 d.id = param_info.ParamID (i);
727 const CAAUParameter* param = param_info.GetParamInfo (d.id);
728 const AudioUnitParameterInfo& info (param->ParamInfo());
730 const int len = CFStringGetLength (param->GetName());
731 char local_buffer[len*2];
732 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
736 d.label = local_buffer;
739 d.scope = param_info.GetScope ();
740 d.element = param_info.GetElement ();
742 /* info.units to consider */
744 kAudioUnitParameterUnit_Generic = 0
745 kAudioUnitParameterUnit_Indexed = 1
746 kAudioUnitParameterUnit_Boolean = 2
747 kAudioUnitParameterUnit_Percent = 3
748 kAudioUnitParameterUnit_Seconds = 4
749 kAudioUnitParameterUnit_SampleFrames = 5
750 kAudioUnitParameterUnit_Phase = 6
751 kAudioUnitParameterUnit_Rate = 7
752 kAudioUnitParameterUnit_Hertz = 8
753 kAudioUnitParameterUnit_Cents = 9
754 kAudioUnitParameterUnit_RelativeSemiTones = 10
755 kAudioUnitParameterUnit_MIDINoteNumber = 11
756 kAudioUnitParameterUnit_MIDIController = 12
757 kAudioUnitParameterUnit_Decibels = 13
758 kAudioUnitParameterUnit_LinearGain = 14
759 kAudioUnitParameterUnit_Degrees = 15
760 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
761 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
762 kAudioUnitParameterUnit_Pan = 18
763 kAudioUnitParameterUnit_Meters = 19
764 kAudioUnitParameterUnit_AbsoluteCents = 20
765 kAudioUnitParameterUnit_Octaves = 21
766 kAudioUnitParameterUnit_BPM = 22
767 kAudioUnitParameterUnit_Beats = 23
768 kAudioUnitParameterUnit_Milliseconds = 24
769 kAudioUnitParameterUnit_Ratio = 25
772 /* info.flags to consider */
776 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
777 kAudioUnitParameterFlag_HasClump = (1L << 20)
778 kAudioUnitParameterFlag_HasName = (1L << 21)
779 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
780 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
781 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
782 kAudioUnitParameterFlag_CanRamp = (1L << 25)
783 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
784 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
785 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
786 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
787 kAudioUnitParameterFlag_IsReadable = (1L << 30)
788 kAudioUnitParameterFlag_IsWritable = (1L << 31)
791 d.lower = info.minValue;
792 d.upper = info.maxValue;
793 d.normal = info.defaultValue;
795 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
796 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
797 (d.integer_step && ((d.upper - d.lower) == 1.0));
798 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
799 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
800 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
801 (info.flags & kAudioUnitParameterFlag_IsWritable);
803 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
804 d.au_unit = info.unit;
806 case kAudioUnitParameterUnit_Decibels:
807 d.unit = ParameterDescriptor::DB;
809 case kAudioUnitParameterUnit_MIDINoteNumber:
810 d.unit = ParameterDescriptor::MIDI_NOTE;
812 case kAudioUnitParameterUnit_Hertz:
813 d.unit = ParameterDescriptor::HZ;
819 descriptors.push_back (d);
821 uint32_t last_param = descriptors.size() - 1;
822 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
823 listen_to_parameter (last_param);
830 four_ints_to_four_byte_literal (unsigned char n[4])
832 /* this is actually implementation dependent. sigh. this is what gcc
833 and quite a few others do.
835 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
839 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
841 if (isdigit (id[0])) {
845 /* ID format is xxxx-xxxx-xxxx
846 where x maybe \xNN or a printable character.
848 Split at the '-' and and process each part into an integer.
849 Then put it back together.
853 unsigned char nascent[4];
854 const char* cstr = id.c_str();
855 const char* estr = cstr + id.size();
866 while (*cstr && next_int < 4) {
870 if (estr - cstr < 3) {
872 /* too close to the end for \xNN parsing: treat as literal characters */
880 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
884 memcpy (short_buf, &cstr[2], 2);
885 nascent[in] = strtol (short_buf, NULL, 16);
891 /* treat as literal characters */
905 if (in && (in % 4 == 0)) {
906 /* nascent is ready */
907 n[next_int] = four_ints_to_four_byte_literal (nascent);
911 /* swallow space-hyphen-space */
925 s << n[0] << '-' << n[1] << '-' << n[2];
934 AUPlugin::unique_id () const
936 return AUPluginInfo::stringify_descriptor (comp->Desc());
940 AUPlugin::label () const
942 return _info->name.c_str();
946 AUPlugin::parameter_count () const
948 return descriptors.size();
952 AUPlugin::default_value (uint32_t port)
954 if (port < descriptors.size()) {
955 return descriptors[port].normal;
962 AUPlugin::plugin_latency () const
964 guint lat = g_atomic_int_get (&_current_latency);;
965 if (lat == UINT_MAX) {
966 lat = unit->Latency() * _session.sample_rate();
967 g_atomic_int_set (&_current_latency, lat);
973 AUPlugin::set_parameter (uint32_t which, float val)
975 if (which >= descriptors.size()) {
979 if (get_parameter(which) == val) {
983 const AUParameterDescriptor& d (descriptors[which]);
984 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
985 unit->SetParameter (d.id, d.scope, d.element, val);
987 /* tell the world what we did */
989 AudioUnitEvent theEvent;
991 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
992 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
993 theEvent.mArgument.mParameter.mParameterID = d.id;
994 theEvent.mArgument.mParameter.mScope = d.scope;
995 theEvent.mArgument.mParameter.mElement = d.element;
997 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
998 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
999 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
1001 Plugin::set_parameter (which, val);
1005 AUPlugin::get_parameter (uint32_t which) const
1008 if (which < descriptors.size()) {
1009 const AUParameterDescriptor& d (descriptors[which]);
1010 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
1011 unit->GetParameter(d.id, d.scope, d.element, val);
1017 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
1019 if (which < descriptors.size()) {
1020 pd = descriptors[which];
1027 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
1029 if (which < descriptors.size()) {
1038 AUPlugin::activate ()
1042 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
1043 if ((err = unit->Initialize()) != noErr) {
1044 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
1046 samples_processed = 0;
1053 AUPlugin::deactivate ()
1055 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
1056 unit->Uninitialize ();
1057 initialized = false;
1063 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
1064 unit->GlobalReset ();
1068 AUPlugin::requires_fixed_size_buffers() const
1070 return _requires_fixed_size_buffers;
1075 AUPlugin::set_block_size (pframes_t nframes)
1077 bool was_initialized = initialized;
1078 UInt32 numSamples = nframes;
1085 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numSamples));
1086 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1087 0, &numSamples, sizeof (numSamples))) != noErr) {
1088 error << string_compose (_("AU: cannot set max samples (err = %1)"), err) << endmsg;
1092 if (was_initialized) {
1100 AUPlugin::configure_io (ChanCount in, ChanCount out)
1102 AudioStreamBasicDescription streamFormat;
1103 bool was_initialized = initialized;
1104 int32_t audio_out = out.n_audio();
1105 if (audio_input_cnt > 0) {
1106 in.set (DataType::AUDIO, audio_input_cnt);
1108 const int32_t audio_in = in.n_audio();
1110 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1113 //if we are already running with the requested i/o config, bail out here
1114 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1121 streamFormat.mSampleRate = _session.sample_rate();
1122 streamFormat.mFormatID = kAudioFormatLinearPCM;
1123 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1125 #ifdef __LITTLE_ENDIAN__
1128 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1131 streamFormat.mBitsPerChannel = 32;
1132 streamFormat.mFramesPerPacket = 1;
1134 /* apple says that for non-interleaved data, these
1135 * values always refer to a single channel.
1137 streamFormat.mBytesPerPacket = 4;
1138 streamFormat.mBytesPerFrame = 4;
1140 configured_input_busses = 0;
1141 configured_output_busses = 0;
1143 for (size_t i = 0; i < output_elements; ++i) {
1144 unit->Reset (kAudioUnitScope_Output, i);
1146 for (size_t i = 0; i < input_elements; ++i) {
1147 unit->Reset (kAudioUnitScope_Input, i);
1150 /* now assign the channels to available busses */
1151 uint32_t used_in = 0;
1152 uint32_t used_out = 0;
1154 if (variable_inputs || input_elements == 1) {
1155 // we only ever use the first bus
1156 if (input_elements > 1) {
1157 warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
1159 streamFormat.mChannelsPerFrame = audio_in;
1160 if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
1163 configured_input_busses = 1;
1166 configured_input_busses = 0;
1167 uint32_t remain = audio_in;
1168 for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
1169 uint32_t cnt = std::min (remain, bus_inputs[bus]);
1170 if (cnt == 0) { continue; }
1171 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
1173 streamFormat.mChannelsPerFrame = cnt;
1174 if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
1178 ++configured_input_busses;
1183 if (variable_outputs || output_elements == 1) {
1184 if (output_elements > 1) {
1185 warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
1188 streamFormat.mChannelsPerFrame = audio_out;
1189 if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
1192 configured_output_busses = 1;
1193 used_out = audio_out;
1195 uint32_t remain = audio_out;
1196 configured_output_busses = 0;
1197 for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
1198 uint32_t cnt = std::min (remain, bus_outputs[bus]);
1199 if (cnt == 0) { continue; }
1200 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
1201 streamFormat.mChannelsPerFrame = cnt;
1202 if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
1207 ++configured_output_busses;
1212 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1213 used_out * sizeof(::AudioBuffer));
1215 input_channels = used_in;
1216 output_channels = used_out;
1217 /* reset plugin info to show currently configured state */
1219 _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
1220 _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
1222 if (was_initialized) {
1230 AUPlugin::input_streams() const
1233 if (input_channels < 0) {
1234 // force PluginIoReConfigure -- see also commit msg e38eb06
1235 c.set (DataType::AUDIO, 0);
1236 c.set (DataType::MIDI, 0);
1238 c.set (DataType::AUDIO, input_channels);
1239 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1246 AUPlugin::output_streams() const
1249 if (output_channels < 0) {
1250 // force PluginIoReConfigure - see also commit msg e38eb06
1251 c.set (DataType::AUDIO, 0);
1252 c.set (DataType::MIDI, 0);
1254 c.set (DataType::AUDIO, output_channels);
1255 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1261 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1263 _output_configs.clear ();
1264 const int32_t audio_in = in.n_audio();
1265 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1267 /* lets check MIDI first */
1269 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1273 vector<pair<int,int> > io_configs = pinfo->cache.io_configs;
1275 if (input_elements > 1) {
1276 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1277 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1278 int32_t possible_in = i->first;
1279 int32_t possible_out = i->second;
1280 if (possible_in < 0) {
1283 for (uint32_t i = 1; i < input_elements; ++i) {
1284 // can't use up-to bus_inputs[]
1285 // waves' SC-C6(s) for example fails to configure with only 1 input
1287 io_configs.push_back (pair<int,int> (possible_in + bus_inputs[i], possible_out));
1289 /* only add additional, optional busses to first available config.
1290 * AUPluginInfo::cached_io_configuration () already incrementally
1291 * adds busses (for instruments w/ multiple configurations)
1297 if (output_elements > 1) {
1298 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1299 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1300 int32_t possible_in = i->first;
1301 int32_t possible_out = i->second;
1302 if (possible_out < 0) {
1305 for (uint32_t i = 1; i < output_elements; ++i) {
1306 int32_t c = bus_outputs[i];
1307 for (uint32_t j = 1; j < i; ++j) {
1308 c += bus_outputs [j];
1310 io_configs.push_back (pair<int,int> (possible_in, possible_out + c));
1312 /* only add additional, optional busses to first available config.
1313 * AUPluginInfo::cached_io_configuration () already incrementally
1314 * adds busses (for instruments w/ multiple configurations)
1320 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1321 name(), io_configs.size(), in, out));
1324 printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
1325 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1326 printf ("- I/O %d / %d\n", i->first, i->second);
1330 // preferred setting (provided by plugin_insert)
1331 const int preferred_out = out.n_audio ();
1333 bool exact_match = false;
1335 /* kAudioUnitProperty_SupportedNumChannels
1336 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1338 * - both fields are -1
1339 * e.g. inChannels = -1 outChannels = -1
1340 * This is the default case. Any number of input and output channels, as long as the numbers match
1342 * - one field is -1, the other field is positive
1343 * e.g. inChannels = -1 outChannels = 2
1344 * Any number of input channels, exactly two output channels
1346 * - one field is -1, the other field is -2
1347 * e.g. inChannels = -1 outChannels = -2
1348 * Any number of input channels, any number of output channels
1350 * - both fields have non-negative values
1351 * e.g. inChannels = 2 outChannels = 6
1352 * Exactly two input channels, exactly six output channels
1353 * e.g. inChannels = 0 outChannels = 2
1354 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1356 * - both fields have negative values, neither of which is –1 or –2
1357 * e.g. inChannels = -4 outChannels = -8
1358 * Up to four input channels and up to eight output channels
1361 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1363 int32_t possible_in = i->first;
1364 int32_t possible_out = i->second;
1366 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1367 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1368 possible_in, possible_out,
1372 _output_configs.insert (preferred_out);
1379 /* now allow potentially "imprecise" matches */
1380 int32_t audio_out = -1;
1381 float penalty = 9999;
1382 int used_possible_in = 0;
1383 #if defined (__clang__)
1384 # pragma clang diagnostic push
1385 # pragma clang diagnostic ignored "-Wtautological-compare"
1388 #define FOUNDCFG(nch) { \
1389 float p = fabsf ((float)(nch) - preferred_out); \
1390 _output_configs.insert (nch); \
1391 if ((nch) > preferred_out) { p *= 1.1; } \
1392 if (p < penalty) { \
1393 used_possible_in = possible_in; \
1394 audio_out = (nch); \
1397 variable_inputs = possible_in < 0; \
1398 variable_outputs = possible_out < 0; \
1402 #define ANYTHINGGOES \
1403 _output_configs.insert (0);
1405 #define UPTO(nch) { \
1406 for (int n = 1; n <= nch; ++n) { \
1407 _output_configs.insert (n); \
1411 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1413 int32_t possible_in = i->first;
1414 int32_t possible_out = i->second;
1416 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1418 if (possible_out == 0) {
1419 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1420 /* XXX surely this is just a send? (e.g. AUNetSend) */
1424 if (possible_in == 0) {
1425 /* no inputs, generators & instruments */
1426 if (possible_out == -1) {
1427 /* any configuration possible, provide stereo output */
1428 FOUNDCFG (preferred_out);
1430 } else if (possible_out == -2) {
1431 /* invalid, should be (0, -1) */
1432 FOUNDCFG (preferred_out);
1434 } else if (possible_out < -2) {
1435 /* variable number of outputs up to -N, */
1436 FOUNDCFG (min (-possible_out, preferred_out));
1437 UPTO (-possible_out);
1439 /* exact number of outputs */
1440 FOUNDCFG (possible_out);
1444 if (possible_in == -1) {
1445 /* wildcard for input */
1446 if (possible_out == -1) {
1447 /* out must match in */
1448 FOUNDCFG (audio_in);
1449 } else if (possible_out == -2) {
1450 /* any configuration possible, pick matching */
1451 FOUNDCFG (preferred_out);
1453 } else if (possible_out < -2) {
1454 /* explicitly variable number of outputs, pick maximum */
1455 FOUNDCFG (max (-possible_out, preferred_out));
1456 /* and try min, too, in case the penalty is lower */
1457 FOUNDCFG (min (-possible_out, preferred_out));
1458 UPTO (-possible_out)
1460 /* exact number of outputs */
1461 FOUNDCFG (possible_out);
1465 if (possible_in == -2) {
1466 if (possible_out == -1) {
1467 /* any configuration possible, pick matching */
1468 FOUNDCFG (preferred_out);
1470 } else if (possible_out == -2) {
1471 /* invalid. interpret as (-1, -1) */
1472 FOUNDCFG (preferred_out);
1474 } else if (possible_out < -2) {
1475 /* invalid, interpret as (<-2, <-2)
1476 * variable number of outputs up to -N, */
1477 FOUNDCFG (min (-possible_out, preferred_out));
1478 UPTO (-possible_out)
1480 /* exact number of outputs */
1481 FOUNDCFG (possible_out);
1485 if (possible_in < -2) {
1486 /* explicit variable number of inputs */
1487 if (audio_in > -possible_in && imprecise != NULL) {
1488 // hide inputs ports
1489 imprecise->set (DataType::AUDIO, -possible_in);
1492 if (audio_in > -possible_in && imprecise == NULL) {
1493 /* request is too large */
1494 } else if (possible_out == -1) {
1495 /* any output configuration possible */
1496 FOUNDCFG (preferred_out);
1498 } else if (possible_out == -2) {
1499 /* invalid. interpret as (<-2, -1) */
1500 FOUNDCFG (preferred_out);
1502 } else if (possible_out < -2) {
1503 /* variable number of outputs up to -N, */
1504 FOUNDCFG (min (-possible_out, preferred_out));
1505 UPTO (-possible_out)
1507 /* exact number of outputs */
1508 FOUNDCFG (possible_out);
1512 if (possible_in && (possible_in == audio_in)) {
1513 /* exact number of inputs ... must match obviously */
1514 if (possible_out == -1) {
1515 /* any output configuration possible */
1516 FOUNDCFG (preferred_out);
1518 } else if (possible_out == -2) {
1519 /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
1520 FOUNDCFG (preferred_out);
1522 } else if (possible_out < -2) {
1523 /* > 0, < -2 is not specified
1524 * interpret as up to -N */
1525 FOUNDCFG (min (-possible_out, preferred_out));
1526 UPTO (-possible_out)
1528 /* exact number of outputs */
1529 FOUNDCFG (possible_out);
1534 if (!found && imprecise) {
1536 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1537 int32_t possible_in = i->first;
1538 int32_t possible_out = i->second;
1540 assert (possible_in > 0); // all other cases will have been matched above
1541 assert (possible_out !=0 || possible_in !=0); // already handled above
1543 imprecise->set (DataType::AUDIO, possible_in);
1544 if (possible_out == -1 || possible_out == -2) {
1546 } else if (possible_out < -2) {
1547 /* explicitly variable number of outputs, pick maximum */
1548 FOUNDCFG (min (-possible_out, preferred_out));
1550 /* exact number of outputs */
1551 FOUNDCFG (possible_out);
1553 // ideally we'll also find the closest, best matching
1554 // input configuration with minimal output penalty...
1559 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1564 out.set (DataType::MIDI, 0); // currently always zero
1565 out.set (DataType::AUDIO, preferred_out);
1567 if (used_possible_in < -2 && audio_in == 0) {
1568 // input-port count cannot be zero, use as many ports
1569 // as outputs, but at most abs(possible_in)
1570 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1572 out.set (DataType::MIDI, 0); /// XXX
1573 out.set (DataType::AUDIO, audio_out);
1575 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1577 #if defined (__clang__)
1578 # pragma clang diagnostic pop
1584 AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
1588 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1589 (scope == kAudioUnitScope_Input ? "input" : "output"),
1591 if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
1592 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1593 (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
1600 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1601 const AudioTimeStamp*,
1603 UInt32 inNumberSamples,
1604 AudioBufferList* ioData)
1606 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1608 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, samples %2 bus %3 bufs %4\n",
1609 // name(), inNumberSamples, bus, ioData->mNumberBuffers));
1611 if (input_maxbuf == 0) {
1612 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1613 error << _("AUPlugin: render callback called illegally!") << endmsg;
1614 return kAudioUnitErr_CannotDoInCurrentContext;
1617 assert (bus < input_elements);
1618 uint32_t busoff = 0;
1619 for (uint32_t i = 0; i < bus; ++i) {
1620 busoff += bus_inputs[i];
1623 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1625 ChanCount bufs_count (DataType::AUDIO, 1);
1626 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1628 /* apply bus offsets */
1630 for (uint32_t i = 0; i < limit; ++i) {
1631 ioData->mBuffers[i].mNumberChannels = 1;
1632 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberSamples;
1635 uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
1637 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
1639 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
1642 cb_offsets[bus] += inNumberSamples;
1647 AUPlugin::connect_and_run (BufferSet& bufs,
1648 samplepos_t start, samplepos_t end, double speed,
1649 ChanMapping const& in_map, ChanMapping const& out_map,
1650 pframes_t nframes, samplecnt_t offset)
1652 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
1654 transport_sample = start;
1655 transport_speed = speed;
1657 AudioUnitRenderActionFlags flags = 0;
1661 if (preset_holdoff > 0) {
1662 preset_holdoff -= std::min (nframes, preset_holdoff);
1665 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1666 unit->GlobalReset();
1667 _last_nframes = nframes;
1670 /* test if we can run in-place; only compare audio buffers */
1671 bool inplace = true; // TODO check plugin-insert in-place ?
1672 ChanMapping::Mappings inmap (in_map.mappings ());
1673 ChanMapping::Mappings outmap (out_map.mappings ());
1674 if (outmap[DataType::AUDIO].size () == 0) {
1677 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1681 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6) InBus %7 OutBus %8 Inplace: %9 var-i/o %10 %11\n",
1682 name(), input_channels, output_channels, _has_midi_input,
1683 bufs.count(), bufs.available(),
1684 configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
1686 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1687 * has the capacity to handle our outputs.
1690 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1692 input_buffers = &bufs;
1693 input_map = &in_map;
1694 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1695 input_offset = offset;
1696 for (size_t i = 0; i < input_elements; ++i) {
1700 ChanCount bufs_count (DataType::AUDIO, 1);
1701 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1703 if (_has_midi_input) {
1704 uint32_t nmidi = bufs.count().n_midi();
1705 for (uint32_t i = 0; i < nmidi; ++i) {
1706 /* one MIDI port/buffer only */
1707 MidiBuffer& m = bufs.get_midi (i);
1708 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1709 Evoral::Event<samplepos_t> ev (*i);
1710 if (ev.is_channel_event()) {
1711 const uint8_t* b = ev.buffer();
1712 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1713 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1715 /* XXX need to handle sysex and other message types */
1720 assert (input_maxbuf < 512);
1721 std::bitset<512> used_outputs;
1724 uint32_t busoff = 0;
1725 uint32_t remain = output_channels;
1726 for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
1728 if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
1729 cnt = output_channels;
1731 cnt = std::min (remain, bus_outputs[bus]);
1735 buffers->mNumberBuffers = cnt;
1737 for (uint32_t i = 0; i < cnt; ++i) {
1738 buffers->mBuffers[i].mNumberChannels = 1;
1739 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1740 /* setting this to 0 indicates to the AU that it can provide buffers here
1741 * if necessary. if it can process in-place, it will use the buffers provided
1742 * as input by ::render_callback() above.
1744 * a non-null values tells the plugin to render into the buffer pointed
1748 buffers->mBuffers[i].mData = 0;
1751 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1753 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1755 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1760 /* does this really mean anything ? */
1761 ts.mSampleTime = samples_processed;
1762 ts.mFlags = kAudioTimeStampSampleTimeValid;
1764 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
1765 name(), flags, samples_processed, nframes, bus, buffers->mNumberBuffers));
1767 if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
1769 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1770 name(), buffers->mNumberBuffers, output_channels));
1772 uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
1773 for (uint32_t i = 0; i < limit; ++i) {
1775 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1776 if (!valid) continue;
1777 used_outputs.set (i + busoff);
1778 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1779 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1780 /* plugin provided its own buffer for output so copy it back to where we want it */
1781 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1785 DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
1786 error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
1792 busoff += bus_outputs[bus];
1795 /* now silence any buffers that were passed in but the that the plugin
1796 * did not fill/touch/use.
1798 * TODO: optimize, when plugin-insert is processing in-place
1799 * unconnected buffers are (also) cleared there.
1801 for (uint32_t i = 0; i < input_maxbuf; ++i) {
1802 if (used_outputs.test (i)) { continue; }
1804 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1805 if (!valid) continue;
1806 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1812 samples_processed += nframes;
1819 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1820 Float64* outCurrentTempo)
1822 TempoMap& tmap (_session.tempo_map());
1824 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1826 if (outCurrentBeat) {
1827 *outCurrentBeat = tmap.quarter_note_at_sample (transport_sample + input_offset);
1830 if (outCurrentTempo) {
1831 *outCurrentTempo = tmap.tempo_at_sample (transport_sample + input_offset).quarter_notes_per_minute();
1839 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1840 Float32* outTimeSig_Numerator,
1841 UInt32* outTimeSig_Denominator,
1842 Float64* outCurrentMeasureDownBeat)
1844 TempoMap& tmap (_session.tempo_map());
1846 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1848 TempoMetric metric = tmap.metric_at (transport_sample + input_offset);
1849 Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_sample (transport_sample + input_offset);
1851 if (outDeltaSampleOffsetToNextBeat) {
1852 if (bbt.ticks == 0) {
1854 *outDeltaSampleOffsetToNextBeat = 0;
1856 double const next_beat = ceil (tmap.quarter_note_at_sample (transport_sample + input_offset));
1857 samplepos_t const next_beat_sample = tmap.sample_at_quarter_note (next_beat);
1859 *outDeltaSampleOffsetToNextBeat = next_beat_sample - (transport_sample + input_offset);
1863 if (outTimeSig_Numerator) {
1864 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1866 if (outTimeSig_Denominator) {
1867 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1870 if (outCurrentMeasureDownBeat) {
1872 /* beat for the start of the bar.
1874 2|1|0 -> 1 + divisions_per_bar
1875 3|1|0 -> 1 + (2 * divisions_per_bar)
1881 *outCurrentMeasureDownBeat = tmap.quarter_note_at_bbt (bbt);
1888 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1889 Boolean* outTransportStateChanged,
1890 Float64* outCurrentSampleInTimeLine,
1891 Boolean* outIsCycling,
1892 Float64* outCycleStartBeat,
1893 Float64* outCycleEndBeat)
1895 const bool rolling = (transport_speed != 0);
1896 const bool last_transport_rolling = (last_transport_speed != 0);
1898 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1902 *outIsPlaying = rolling;
1905 if (outTransportStateChanged) {
1906 if (rolling != last_transport_rolling) {
1907 *outTransportStateChanged = true;
1908 } else if (transport_speed != last_transport_speed) {
1909 *outTransportStateChanged = true;
1911 *outTransportStateChanged = false;
1915 if (outCurrentSampleInTimeLine) {
1916 /* this assumes that the AU can only call this host callback from render context,
1917 where input_offset is valid.
1919 *outCurrentSampleInTimeLine = transport_sample + input_offset;
1923 // TODO check bounce-processing
1924 Location* loc = _session.locations()->auto_loop_location();
1926 *outIsCycling = (loc && rolling && _session.get_play_loop());
1928 if (*outIsCycling) {
1930 if (outCycleStartBeat || outCycleEndBeat) {
1932 TempoMap& tmap (_session.tempo_map());
1934 Timecode::BBT_Time bbt;
1936 if (outCycleStartBeat) {
1937 *outCycleStartBeat = tmap.quarter_note_at_sample (loc->start() + input_offset);
1940 if (outCycleEndBeat) {
1941 *outCycleEndBeat = tmap.quarter_note_at_sample (loc->end() + input_offset);
1947 last_transport_speed = transport_speed;
1952 set<Evoral::Parameter>
1953 AUPlugin::automatable() const
1955 set<Evoral::Parameter> automates;
1957 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1958 if (descriptors[i].automatable) {
1959 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1966 Plugin::IOPortDescription
1967 AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1969 std::stringstream ss;
1971 case DataType::AUDIO:
1973 case DataType::MIDI:
1981 std::string busname;
1983 if (dt == DataType::AUDIO) {
1986 for (uint32_t bus = 0; bus < input_elements; ++bus) {
1987 if (pid < bus_inputs[bus]) {
1989 ss << _bus_name_in[bus];
1990 ss << " / Bus " << (1 + bus);
1991 busname = _bus_name_in[bus];
1994 pid -= bus_inputs[bus];
1999 for (uint32_t bus = 0; bus < output_elements; ++bus) {
2000 if (pid < bus_outputs[bus]) {
2002 ss << _bus_name_out[bus];
2003 ss << " / Bus " << (1 + bus);
2004 busname = _bus_name_out[bus];
2007 pid -= bus_outputs[bus];
2013 ss << " " << _("In") << " ";
2015 ss << " " << _("Out") << " ";
2020 Plugin::IOPortDescription iod (ss.str());
2021 if (!busname.empty()) {
2022 iod.group_name = busname;
2023 iod.group_channel = id;
2029 AUPlugin::describe_parameter (Evoral::Parameter param)
2031 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
2032 return descriptors[param.id()].label;
2039 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
2041 // NameValue stuff here
2043 if (param < parameter_count()) {
2044 snprintf (buf, len, "%.3f", get_parameter (param));
2052 AUPlugin::parameter_is_audio (uint32_t) const
2058 AUPlugin::parameter_is_control (uint32_t param) const
2060 assert(param < descriptors.size());
2061 if (descriptors[param].automatable) {
2062 /* corrently ardour expects all controls to be automatable
2063 * IOW ardour GUI elements mandate an Evoral::Parameter
2064 * for all input+control ports.
2072 AUPlugin::parameter_is_input (uint32_t param) const
2074 /* AU params that are both readable and writeable,
2075 * are listed in kAudioUnitScope_Global
2077 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
2081 AUPlugin::parameter_is_output (uint32_t param) const
2083 assert(param < descriptors.size());
2084 // TODO check if ardour properly handles ports
2085 // that report is_input + is_output == true
2086 // -> add || descriptors[param].scope == kAudioUnitScope_Global
2087 return (descriptors[param].scope == kAudioUnitScope_Output);
2091 AUPlugin::add_state (XMLNode* root) const
2095 CFPropertyListRef propertyList;
2097 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
2098 if (unit->GetAUPreset (propertyList) != noErr) {
2102 // Convert the property list into XML data.
2104 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
2107 error << _("Could not create XML version of property list") << endmsg;
2111 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
2112 our state node. GACK!
2117 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
2119 root->add_child_copy (*t.root());
2123 CFRelease (xmlData);
2124 CFRelease (propertyList);
2128 AUPlugin::set_state(const XMLNode& node, int version)
2131 CFPropertyListRef propertyList;
2134 if (node.name() != state_node_name()) {
2135 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
2139 #ifndef NO_PLUGIN_STATE
2140 if (node.children().empty()) {
2144 XMLNode* top = node.children().front();
2145 XMLNode* copy = new XMLNode (*top);
2150 const string& xml = t.write_buffer ();
2151 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
2152 CFStringRef errorString;
2154 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
2156 kCFPropertyListImmutable,
2159 CFRelease (xmlData);
2162 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
2163 if (unit->SetAUPreset (propertyList) == noErr) {
2166 /* tell the world */
2168 AudioUnitParameter changedUnit;
2169 changedUnit.mAudioUnit = unit->AU();
2170 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2171 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2173 CFRelease (propertyList);
2177 Plugin::set_state (node, version);
2182 AUPlugin::load_preset (PresetRecord r)
2185 CFPropertyListRef propertyList;
2187 UserPresetMap::iterator ux;
2188 FactoryPresetMap::iterator fx;
2190 /* look first in "user" presets */
2192 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
2194 if ((propertyList = load_property_list (ux->second)) != 0) {
2195 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
2196 if (unit->SetAUPreset (propertyList) == noErr) {
2199 /* tell the world */
2201 AudioUnitParameter changedUnit;
2202 changedUnit.mAudioUnit = unit->AU();
2203 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2204 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2206 CFRelease(propertyList);
2209 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2213 preset.presetNumber = fx->second;
2214 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2216 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2218 if (unit->SetPresentPreset (preset) == 0) {
2221 /* tell the world */
2223 AudioUnitParameter changedUnit;
2224 changedUnit.mAudioUnit = unit->AU();
2225 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2226 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2230 preset_holdoff = std::max (_session.get_block_size() * 2.0, _session.sample_rate() * .2);
2233 return ret && Plugin::load_preset (r);
2237 AUPlugin::do_remove_preset (std::string preset_name)
2239 vector<Glib::ustring> v;
2241 std::string m = maker();
2242 std::string n = name();
2244 strip_whitespace_edges (m);
2245 strip_whitespace_edges (n);
2247 v.push_back (Glib::get_home_dir());
2248 v.push_back ("Library");
2249 v.push_back ("Audio");
2250 v.push_back ("Presets");
2253 v.push_back (preset_name + preset_suffix);
2255 Glib::ustring user_preset_path = Glib::build_filename (v);
2257 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Deleting Preset file %1\n", user_preset_path));
2259 if (g_unlink (user_preset_path.c_str())) {
2260 error << string_compose (X_("Could not delete preset at \"%1\": %2"), user_preset_path, strerror (errno)) << endmsg;
2265 AUPlugin::do_save_preset (string preset_name)
2267 CFPropertyListRef propertyList;
2268 vector<Glib::ustring> v;
2269 Glib::ustring user_preset_path;
2271 std::string m = maker();
2272 std::string n = name();
2274 strip_whitespace_edges (m);
2275 strip_whitespace_edges (n);
2277 v.push_back (Glib::get_home_dir());
2278 v.push_back ("Library");
2279 v.push_back ("Audio");
2280 v.push_back ("Presets");
2284 user_preset_path = Glib::build_filename (v);
2286 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2287 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2291 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2292 if (unit->GetAUPreset (propertyList) != noErr) {
2296 // add the actual preset name */
2298 v.push_back (preset_name + preset_suffix);
2302 user_preset_path = Glib::build_filename (v);
2304 set_preset_name_in_plist (propertyList, preset_name);
2306 if (save_property_list (propertyList, user_preset_path)) {
2307 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2311 CFRelease(propertyList);
2313 user_preset_map[preset_name] = user_preset_path;;
2315 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2317 return user_preset_path;
2320 //-----------------------------------------------------------------------------
2321 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2323 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2325 CFNumberRef cfNumber;
2326 SInt32 numberValue = 0;
2327 Boolean dummySuccess;
2329 if (outSuccess == NULL)
2330 outSuccess = &dummySuccess;
2331 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2333 *outSuccess = FALSE;
2337 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2338 if (cfNumber == NULL)
2340 *outSuccess = FALSE;
2343 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2351 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2353 CFDictionaryRef auStateDictionary;
2354 ArdourDescription tempDesc = {0,0,0,0,0};
2355 SInt32 versionValue;
2358 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2361 // the property list for AU state data must be of the dictionary type
2362 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2363 return kAudioUnitErr_InvalidPropertyValue;
2366 auStateDictionary = (CFDictionaryRef)inAUStateData;
2368 // first check to make sure that the version of the AU state data is one that we know understand
2369 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2370 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2373 return kAudioUnitErr_InvalidPropertyValue;
2375 #define kCurrentSavedStateVersion 0
2376 if (versionValue != kCurrentSavedStateVersion) {
2377 return kAudioUnitErr_InvalidPropertyValue;
2380 // grab the ComponentDescription values from the AU state data
2381 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2382 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2383 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2384 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2385 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2386 return kAudioUnitErr_InvalidPropertyValue;
2388 *outComponentDescription = tempDesc;
2393 static bool au_preset_filter (const string& str, void* arg)
2395 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2399 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2403 /* check the preset file path name against this plugin
2404 ID. The idea is that all preset files for this plugin
2405 include "<manufacturer>/<plugin-name>" in their path.
2408 AUPluginInfo* p = (AUPluginInfo *) arg;
2409 string match = p->creator;
2413 ret = str.find (match) != string::npos;
2416 string m = p->creator;
2418 strip_whitespace_edges (m);
2419 strip_whitespace_edges (n);
2424 ret = str.find (match) != string::npos;
2432 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2435 CFPropertyListRef plist;
2436 ArdourDescription presetDesc;
2439 plist = load_property_list (pathstr);
2445 // get the ComponentDescription from the AU preset file
2447 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2449 if (status == noErr) {
2450 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2452 /* try to get the preset name from the property list */
2454 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2456 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2460 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2463 char buf[PATH_MAX+1];
2465 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2482 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2484 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2487 CFStringRef itemName = NULL;
2488 // Marc Poirier-style item name
2490 CAComponent auComponent (comp_desc);
2491 if (auComponent.IsValid()) {
2492 CAComponentDescription dummydesc;
2493 Handle nameHandle = NewHandle(sizeof(void*));
2494 if (nameHandle != NULL) {
2495 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2497 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2498 if (nameString != NULL) {
2499 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2502 DisposeHandle(nameHandle);
2507 AudioComponentCopyName (comp, &itemName);
2510 // if Marc-style fails, do the original way
2511 if (itemName == NULL) {
2512 #ifndef COREAUDIO105
2513 CAComponentDescription comp_desc;
2514 AudioComponentGetDescription (comp, &comp_desc);
2516 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2517 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2518 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2520 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2521 compTypeString, compManufacturerString, compSubTypeString);
2523 if (compTypeString != NULL)
2524 CFRelease(compTypeString);
2525 if (compSubTypeString != NULL)
2526 CFRelease(compSubTypeString);
2527 if (compManufacturerString != NULL)
2528 CFRelease(compManufacturerString);
2531 string str = CFStringRefToStdString(itemName);
2532 string::size_type colon = str.find (':');
2535 name = str.substr (colon+1);
2536 maker = str.substr (0, colon);
2537 strip_whitespace_edges (maker);
2538 strip_whitespace_edges (name);
2542 strip_whitespace_edges (name);
2547 AUPlugin::current_preset() const
2551 CFPropertyListRef propertyList;
2553 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2554 if (unit->GetAUPreset (propertyList) == noErr) {
2555 preset_name = get_preset_name_in_plist (propertyList);
2556 CFRelease(propertyList);
2563 AUPlugin::find_presets ()
2565 vector<string> preset_files;
2567 user_preset_map.clear ();
2569 PluginInfoPtr nfo = get_info();
2570 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2571 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2574 if (preset_files.empty()) {
2575 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2578 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2583 /* make an initial guess at the preset name using the path */
2585 preset_name = Glib::path_get_basename (path);
2586 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2588 /* check that this preset file really matches this plugin
2589 and potentially get the "real" preset name from
2593 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2594 user_preset_map[preset_name] = path;
2595 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2597 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2602 /* now fill the vector<string> with the names we have */
2604 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2605 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2606 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2609 /* add factory presets */
2611 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2612 string const uri = string_compose ("AU2:%1", std::setw(4), std::setfill('0'), i->second);
2613 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2614 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2619 AUPlugin::has_editor () const
2621 // even if the plugin doesn't have its own editor, the AU API can be used
2622 // to create one that looks native.
2626 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2630 type = ARDOUR::AudioUnit;
2633 AUPluginInfo::~AUPluginInfo ()
2635 type = ARDOUR::AudioUnit;
2639 AUPluginInfo::load (Session& session)
2644 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2645 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2647 if (!comp->IsValid()) {
2648 error << ("AudioUnit: not a valid Component") << endmsg;
2650 plugin.reset (new AUPlugin (session.engine(), session, comp));
2653 AUPluginInfo *aup = new AUPluginInfo (*this);
2654 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2655 plugin->set_info (PluginInfoPtr (aup));
2656 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2660 catch (failed_constructor &err) {
2661 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2662 return PluginPtr ();
2666 std::vector<Plugin::PresetRecord>
2667 AUPluginInfo::get_presets (bool user_only) const
2669 std::vector<Plugin::PresetRecord> p;
2670 boost::shared_ptr<CAComponent> comp;
2671 #ifndef NO_PLUGIN_STATE
2673 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2674 if (!comp->IsValid()) {
2675 throw failed_constructor();
2677 } catch (failed_constructor& err) {
2683 if (!preset_search_path_initialized) {
2684 Glib::ustring p = Glib::get_home_dir();
2685 p += "/Library/Audio/Presets:";
2686 p += preset_search_path;
2687 preset_search_path = p;
2688 preset_search_path_initialized = true;
2689 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2692 vector<string> preset_files;
2693 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2695 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2698 preset_name = Glib::path_get_basename (path);
2699 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2700 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2701 p.push_back (Plugin::PresetRecord (path, preset_name));
2715 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2716 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2719 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2720 unit->Uninitialize ();
2723 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2724 unit->Uninitialize ();
2728 unit->Uninitialize ();
2732 CFIndex cnt = CFArrayGetCount (presets);
2733 for (CFIndex i = 0; i < cnt; ++i) {
2734 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2735 string const uri = string_compose ("%1", i);
2736 string name = CFStringRefToStdString (preset->presetName);
2737 p.push_back (Plugin::PresetRecord (uri, name, false));
2739 CFRelease (presets);
2740 unit->Uninitialize ();
2742 #endif // NO_PLUGIN_STATE
2747 AUPluginInfo::au_cache_path ()
2749 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2753 AUPluginInfo::discover (bool scan_only)
2757 /* AU require a CAComponentDescription pointer provided by the OS.
2758 * Ardour only caches port and i/o config. It can't just 'scan' without
2759 * 'discovering' (like we do for VST).
2762 * "Iterate over all plugins. skip the ones where there's no io-cache".
2764 _scan_only = scan_only;
2766 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2767 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2768 // flush RAM cache -- after clear_cache()
2769 cached_info.clear();
2771 // create crash log file
2772 au_start_crashlog ();
2774 PluginInfoList* plugs = new PluginInfoList;
2776 discover_fx (*plugs);
2777 discover_music (*plugs);
2778 discover_generators (*plugs);
2779 discover_instruments (*plugs);
2781 // all fine if we get here
2782 au_remove_crashlog ();
2784 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2790 AUPluginInfo::discover_music (PluginInfoList& plugs)
2792 CAComponentDescription desc;
2793 desc.componentFlags = 0;
2794 desc.componentFlagsMask = 0;
2795 desc.componentSubType = 0;
2796 desc.componentManufacturer = 0;
2797 desc.componentType = kAudioUnitType_MusicEffect;
2799 discover_by_description (plugs, desc);
2803 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2805 CAComponentDescription desc;
2806 desc.componentFlags = 0;
2807 desc.componentFlagsMask = 0;
2808 desc.componentSubType = 0;
2809 desc.componentManufacturer = 0;
2810 desc.componentType = kAudioUnitType_Effect;
2812 discover_by_description (plugs, desc);
2816 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2818 CAComponentDescription desc;
2819 desc.componentFlags = 0;
2820 desc.componentFlagsMask = 0;
2821 desc.componentSubType = 0;
2822 desc.componentManufacturer = 0;
2823 desc.componentType = kAudioUnitType_Generator;
2825 discover_by_description (plugs, desc);
2829 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2831 CAComponentDescription desc;
2832 desc.componentFlags = 0;
2833 desc.componentFlagsMask = 0;
2834 desc.componentSubType = 0;
2835 desc.componentManufacturer = 0;
2836 desc.componentType = kAudioUnitType_MusicDevice;
2838 discover_by_description (plugs, desc);
2843 AUPluginInfo::au_get_crashlog (std::string &msg)
2845 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2846 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2849 std::ifstream ifs(fn.c_str());
2850 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2851 au_remove_crashlog ();
2856 AUPluginInfo::au_start_crashlog ()
2858 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2859 assert(!_crashlog_fd);
2860 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2861 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2862 PBD::error << "Cannot create AU error-log" << fn << "\n";
2863 cerr << "Cannot create AU error-log" << fn << "\n";
2868 AUPluginInfo::au_remove_crashlog ()
2871 ::fclose(_crashlog_fd);
2872 _crashlog_fd = NULL;
2874 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2875 ::g_unlink(fn.c_str());
2876 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2881 AUPluginInfo::au_crashlog (std::string msg)
2883 if (!_crashlog_fd) {
2884 fprintf(stderr, "AU: %s\n", msg.c_str());
2886 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2887 ::fflush(_crashlog_fd);
2892 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2894 ArdourComponent comp = 0;
2895 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2897 comp = ArdourFindNext (NULL, &desc);
2899 while (comp != NULL) {
2900 CAComponentDescription temp;
2902 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2904 AudioComponentGetDescription (comp, &temp);
2906 CFStringRef itemName = NULL;
2909 if (itemName != NULL) CFRelease(itemName);
2910 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2911 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2912 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2913 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2914 compTypeString, compManufacturerString, compSubTypeString);
2915 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2916 if (compTypeString != NULL)
2917 CFRelease(compTypeString);
2918 if (compSubTypeString != NULL)
2919 CFRelease(compSubTypeString);
2920 if (compManufacturerString != NULL)
2921 CFRelease(compManufacturerString);
2924 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2925 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2926 comp = ArdourFindNext (comp, &desc);
2930 bool has_midi_in = false;
2932 AUPluginInfoPtr info (new AUPluginInfo
2933 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2935 /* although apple designed the subtype field to be a "category" indicator,
2936 its really turned into a plugin ID field for a given manufacturer. Hence
2937 there are no categories for AudioUnits. However, to keep the plugins
2938 showing up under "categories", we'll use the "type" as a high level
2941 NOTE: no panners, format converters or i/o AU's for our purposes
2944 switch (info->descriptor->Type()) {
2945 case kAudioUnitType_Panner:
2946 case kAudioUnitType_OfflineEffect:
2947 case kAudioUnitType_FormatConverter:
2948 comp = ArdourFindNext (comp, &desc);
2951 case kAudioUnitType_Output:
2952 info->category = _("Output");
2954 case kAudioUnitType_MusicDevice:
2955 info->category = _("Instrument");
2958 case kAudioUnitType_MusicEffect:
2959 info->category = _("Effect");
2962 case kAudioUnitType_Effect:
2963 info->category = _("Effect");
2965 case kAudioUnitType_Mixer:
2966 info->category = _("Mixer");
2968 case kAudioUnitType_Generator:
2969 info->category = _("Generator");
2972 info->category = _("(Unknown)");
2976 au_blacklist(CFStringRefToStdString(itemName));
2978 get_names (temp, info->name, info->creator);
2980 get_names (comp, info->name, info->creator);
2982 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2983 au_crashlog(string_compose("Plugin: %1", info->name));
2985 info->type = ARDOUR::AudioUnit;
2986 info->unique_id = stringify_descriptor (*info->descriptor);
2988 /* XXX not sure of the best way to handle plugin versioning yet */
2990 CAComponent cacomp (*info->descriptor);
2993 if (cacomp.GetResourceVersion (info->version) != noErr)
2995 if (cacomp.GetVersion (info->version) != noErr)
3001 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
3004 /* here we have to map apple's wildcard system to a simple pair
3005 of values. in ::can_do() we use the whole system, but here
3006 we need a single pair of values. XXX probably means we should
3007 remove any use of these values.
3009 for now, if the plugin provides a wildcard, treat it as 1. we really
3010 don't care much, because whether we can handle an i/o configuration
3011 depends upon ::can_support_io_configuration(), not these counts.
3013 they exist because other parts of ardour try to present i/o configuration
3014 info to the user, which should perhaps be revisited.
3017 int32_t possible_in = info->cache.io_configs.front().first;
3018 int32_t possible_out = info->cache.io_configs.front().second;
3020 if (possible_in > 0) {
3021 info->n_inputs.set (DataType::AUDIO, possible_in);
3023 info->n_inputs.set (DataType::AUDIO, 1);
3026 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
3028 if (possible_out > 0) {
3029 info->n_outputs.set (DataType::AUDIO, possible_out);
3031 info->n_outputs.set (DataType::AUDIO, 1);
3034 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
3035 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
3037 plugs.push_back (info);
3040 else if (rv == -1) {
3041 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
3044 au_unblacklist(CFStringRefToStdString(itemName));
3045 au_crashlog("Success.");
3046 comp = ArdourFindNext (comp, &desc);
3047 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
3049 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
3053 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
3056 AUPluginCachedInfo& cinfo,
3057 const std::string& name)
3062 /* concatenate unique ID with version to provide a key for cached info lookup.
3063 this ensures we don't get stale information, or should if plugin developers
3064 follow Apple "guidelines".
3067 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
3072 CachedInfoMap::iterator cim = cached_info.find (id);
3074 if (cim != cached_info.end()) {
3075 cinfo = cim->second;
3080 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
3085 AUChannelInfo* channel_info;
3089 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
3093 if (CAAudioUnit::Open (comp, unit) != noErr) {
3099 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
3104 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
3105 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
3110 /* AU is expected to deal with same channel valance in and out */
3111 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
3113 /* CAAudioUnit::GetChannelInfo silently merges bus formats
3114 * check if this was the case and if so, add
3115 * bus configs as incremental options.
3117 Boolean* isWritable = 0;
3118 UInt32 dataSize = 0;
3119 OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
3120 kAudioUnitProperty_SupportedNumChannels,
3121 kAudioUnitScope_Global, 0,
3122 &dataSize, isWritable);
3123 if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
3124 /* incrementally add busses */
3127 for (uint32_t n = 0; n < cnt; ++n) {
3128 in += channel_info[n].inChannels;
3129 out += channel_info[n].outChannels;
3130 cinfo.io_configs.push_back (pair<int,int> (in, out));
3133 /* store each configuration */
3134 for (uint32_t n = 0; n < cnt; ++n) {
3135 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
3136 channel_info[n].outChannels));
3140 free (channel_info);
3143 add_cached_info (id, cinfo);
3144 save_cached_info ();
3150 AUPluginInfo::clear_cache ()
3152 const string& fn = au_cache_path();
3153 if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
3154 ::g_unlink(fn.c_str());
3156 // keep cached_info in RAM until restart or re-scan
3157 cached_info.clear();
3161 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
3163 cached_info[id] = cinfo;
3166 #define AU_CACHE_VERSION "2.0"
3169 AUPluginInfo::save_cached_info ()
3173 node = new XMLNode (X_("AudioUnitPluginCache"));
3174 node->set_property( "version", AU_CACHE_VERSION );
3176 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
3177 XMLNode* parent = new XMLNode (X_("plugin"));
3178 parent->set_property ("id", i->first);
3179 node->add_child_nocopy (*parent);
3181 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
3183 XMLNode* child = new XMLNode (X_("io"));
3185 child->set_property (X_("in"), j->first);
3186 child->set_property (X_("out"), j->second);
3187 parent->add_child_nocopy (*child);
3192 Glib::ustring path = au_cache_path ();
3195 tree.set_root (node);
3197 if (!tree.write (path)) {
3198 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
3199 g_unlink (path.c_str());
3204 AUPluginInfo::load_cached_info ()
3206 Glib::ustring path = au_cache_path ();
3209 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
3213 if ( !tree.read (path) ) {
3214 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
3218 const XMLNode* root (tree.root());
3220 if (root->name() != X_("AudioUnitPluginCache")) {
3224 //initial version has incorrectly stored i/o info, and/or garbage chars.
3225 XMLProperty const * version = root->property(X_("version"));
3226 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
3227 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
3231 cached_info.clear ();
3233 const XMLNodeList children = root->children();
3235 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
3237 const XMLNode* child = *iter;
3239 if (child->name() == X_("plugin")) {
3241 const XMLNode* gchild;
3242 const XMLNodeList gchildren = child->children();
3245 if (!child->get_property (X_("id"), id)) {
3252 string::size_type slash = id.find_last_of ('/');
3254 if (slash == string::npos) {
3258 version = id.substr (slash);
3259 id = id.substr (0, slash);
3260 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3262 if (fixed.empty()) {
3263 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3270 AUPluginCachedInfo cinfo;
3272 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3276 if (gchild->name() == X_("io")) {
3281 if (gchild->get_property (X_("in"), in) && gchild->get_property (X_("out"), out)) {
3282 cinfo.io_configs.push_back (pair<int,int> (in, out));
3287 if (cinfo.io_configs.size()) {
3288 add_cached_info (id, cinfo);
3298 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3302 /* note: OSType is a compiler-implemenation-defined value,
3303 historically a 32 bit integer created with a multi-character
3304 constant such as 'abcd'. It is, fundamentally, an abomination.
3309 s << desc.SubType();
3317 AUPluginInfo::needs_midi_input () const
3319 return is_effect_with_midi_input () || is_instrument ();
3323 AUPluginInfo::is_effect () const
3325 return is_effect_without_midi_input() || is_effect_with_midi_input();
3329 AUPluginInfo::is_effect_without_midi_input () const
3331 return descriptor->IsAUFX();
3335 AUPluginInfo::is_effect_with_midi_input () const
3337 return descriptor->IsAUFM();
3341 AUPluginInfo::is_instrument () const
3343 return descriptor->IsMusicDevice();
3347 AUPluginInfo::is_utility () const
3349 return (descriptor->IsGenerator() || descriptor->componentType == 'aumi');
3350 // kAudioUnitType_MidiProcessor ..looks like we aren't even scanning for these yet?
3354 AUPlugin::set_info (PluginInfoPtr info)
3356 Plugin::set_info (info);
3358 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3359 _has_midi_input = pinfo->needs_midi_input ();
3360 _has_midi_output = false;
3364 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3367 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3369 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3371 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3373 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3377 _parameter_listener_arg = arg;
3379 // listen for latency changes
3380 AudioUnitEvent event;
3381 event.mEventType = kAudioUnitEvent_PropertyChange;
3382 event.mArgument.mProperty.mAudioUnit = unit->AU();
3383 event.mArgument.mProperty.mPropertyID = kAudioUnitProperty_Latency;
3384 event.mArgument.mProperty.mScope = kAudioUnitScope_Global;
3385 event.mArgument.mProperty.mElement = 0;
3387 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3388 PBD::error << "Failed to create latency event listener\n";
3389 // TODO don't cache _current_latency
3396 AUPlugin::listen_to_parameter (uint32_t param_id)
3398 AudioUnitEvent event;
3400 if (!_parameter_listener || param_id >= descriptors.size()) {
3404 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3405 event.mArgument.mParameter.mAudioUnit = unit->AU();
3406 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3407 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3408 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3410 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3414 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3415 event.mArgument.mParameter.mAudioUnit = unit->AU();
3416 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3417 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3418 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3420 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3424 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3425 event.mArgument.mParameter.mAudioUnit = unit->AU();
3426 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3427 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3428 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3430 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3438 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3440 AudioUnitEvent event;
3442 if (!_parameter_listener || param_id >= descriptors.size()) {
3446 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3447 event.mArgument.mParameter.mAudioUnit = unit->AU();
3448 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3449 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3450 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3452 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3456 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3457 event.mArgument.mParameter.mAudioUnit = unit->AU();
3458 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3459 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3460 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3462 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3466 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3467 event.mArgument.mParameter.mAudioUnit = unit->AU();
3468 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3469 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3470 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3472 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3480 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3482 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3486 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3488 if (event->mEventType == kAudioUnitEvent_PropertyChange) {
3489 if (event->mArgument.mProperty.mPropertyID == kAudioUnitProperty_Latency) {
3490 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Latency Change Event %1 <> %2\n", new_value, unit->Latency()));
3491 guint lat = unit->Latency() * _session.sample_rate();
3492 g_atomic_int_set (&_current_latency, lat);
3497 ParameterMap::iterator i;
3499 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3503 switch (event->mEventType) {
3504 case kAudioUnitEvent_BeginParameterChangeGesture:
3505 StartTouch (i->second);
3507 case kAudioUnitEvent_EndParameterChangeGesture:
3508 EndTouch (i->second);
3510 case kAudioUnitEvent_ParameterValueChange:
3511 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3512 means that something else (i.e. the plugin GUI) made the change.
3514 if (preset_holdoff > 0) {
3515 ParameterChangedExternally (i->second, new_value);
3517 Plugin::parameter_changed_externally (i->second, new_value);