2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include "pbd/gstdio_compat.h"
29 #include "pbd/transmitter.h"
30 #include "pbd/xml++.h"
31 #include "pbd/convert.h"
32 #include "pbd/whitespace.h"
33 #include "pbd/file_utils.h"
34 #include "pbd/locale_guard.h"
36 #include <glibmm/threads.h>
37 #include <glibmm/fileutils.h>
38 #include <glibmm/miscutils.h>
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/debug.h"
44 #include "ardour/midi_buffer.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/audio_unit.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
53 #include "CAAudioUnit.h"
54 #include "CAAUParameter.h"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
61 #include <Carbon/Carbon.h>
65 #define ArdourComponent Component
66 #define ArdourDescription ComponentDescription
67 #define ArdourFindNext FindNextComponent
69 #define ArdourComponent AudioComponent
70 #define ArdourDescription AudioComponentDescription
71 #define ArdourFindNext AudioComponentFindNext
78 using namespace ARDOUR;
80 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
82 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
83 static string preset_suffix = ".aupreset";
84 static bool preset_search_path_initialized = false;
85 FILE * AUPluginInfo::_crashlog_fd = NULL;
86 bool AUPluginInfo::_scan_only = true;
89 static void au_blacklist (std::string id)
91 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
92 FILE * blacklist_fd = NULL;
93 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
94 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
97 assert(id.find("\n") == string::npos);
98 fprintf(blacklist_fd, "%s\n", id.c_str());
99 ::fclose(blacklist_fd);
102 static void au_unblacklist (std::string id)
104 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
105 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
106 PBD::warning << "Expected Blacklist file does not exist.\n";
112 std::ifstream ifs(fn.c_str());
113 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
116 ::g_unlink (fn.c_str());
118 assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
119 assert(id.find("\n") == string::npos);
121 id += "\n"; // add separator
122 const size_t rpl = bl.find(id);
123 if (rpl != string::npos) {
124 bl.replace(rpl, id.size(), "");
130 FILE * blacklist_fd = NULL;
131 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
132 PBD::error << "Cannot open AU blacklist.\n";
135 fprintf(blacklist_fd, "%s", bl.c_str());
136 ::fclose(blacklist_fd);
139 static bool is_blacklisted (std::string id)
141 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
142 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
146 std::ifstream ifs(fn.c_str());
147 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
149 assert(id.find("\n") == string::npos);
151 id += "\n"; // add separator
152 const size_t rpl = bl.find(id);
153 if (rpl != string::npos) {
162 _render_callback(void *userData,
163 AudioUnitRenderActionFlags *ioActionFlags,
164 const AudioTimeStamp *inTimeStamp,
166 UInt32 inNumberFrames,
167 AudioBufferList* ioData)
170 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
176 _get_beat_and_tempo_callback (void* userData,
177 Float64* outCurrentBeat,
178 Float64* outCurrentTempo)
181 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
188 _get_musical_time_location_callback (void * userData,
189 UInt32 * outDeltaSampleOffsetToNextBeat,
190 Float32 * outTimeSig_Numerator,
191 UInt32 * outTimeSig_Denominator,
192 Float64 * outCurrentMeasureDownBeat)
195 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
196 outTimeSig_Numerator,
197 outTimeSig_Denominator,
198 outCurrentMeasureDownBeat);
204 _get_transport_state_callback (void* userData,
205 Boolean* outIsPlaying,
206 Boolean* outTransportStateChanged,
207 Float64* outCurrentSampleInTimeLine,
208 Boolean* outIsCycling,
209 Float64* outCycleStartBeat,
210 Float64* outCycleEndBeat)
213 return ((AUPlugin*)userData)->get_transport_state_callback (
214 outIsPlaying, outTransportStateChanged,
215 outCurrentSampleInTimeLine, outIsCycling,
216 outCycleStartBeat, outCycleEndBeat);
223 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
229 // Convert the property list into XML data.
231 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
234 error << _("Could not create XML version of property list") << endmsg;
238 // Write the XML data to the file.
240 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
242 if (errno == EEXIST) {
243 error << string_compose (_("Preset file %1 exists; not overwriting"),
246 error << string_compose (_("Cannot open preset file %1 (%2)"),
247 path, strerror (errno)) << endmsg;
253 size_t cnt = CFDataGetLength (xmlData);
255 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
266 static CFPropertyListRef
267 load_property_list (Glib::ustring path)
270 CFPropertyListRef propertyList = 0;
272 CFStringRef errorString;
274 // Read the XML file.
276 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
281 off_t len = lseek (fd, 0, SEEK_END);
282 char* buf = new char[len];
283 lseek (fd, 0, SEEK_SET);
285 if (read (fd, buf, len) != len) {
293 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
295 // Reconstitute the dictionary using the XML data.
297 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
299 kCFPropertyListImmutable,
308 //-----------------------------------------------------------------------------
310 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
315 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
317 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
318 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
324 //-----------------------------------------------------------------------------
326 get_preset_name_in_plist (CFPropertyListRef plist)
334 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
335 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
337 CFStringRef str = (CFStringRef) p;
338 int len = CFStringGetLength(str);
340 char local_buffer[len];
341 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
349 //--------------------------------------------------------------------------
350 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
351 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
352 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
353 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
355 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
358 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
359 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
361 // only sub-type and manufacturer IDs need to be equal
364 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
365 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
372 //--------------------------------------------------------------------------
373 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
374 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
375 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
376 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
379 ArdourDescription desc;
381 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
384 // get the ComponentDescription of the input Component
386 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
388 status = AudioComponentGetDescription (inComponent, &desc);
393 // check if the Component's ComponentDescription matches the input ComponentDescription
394 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
397 //--------------------------------------------------------------------------
398 // determine if 2 ComponentDescriptions are basically equal
399 // (by that, I mean that the important identifying values are compared,
400 // but not the ComponentDescription flags)
401 Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
403 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
406 //--------------------------------------------------------------------------
407 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
408 Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
410 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
413 //--------------------------------------------------------------------------
414 // determine if a ComponentDescription basically matches that of a particular Component
415 Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
417 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
420 //--------------------------------------------------------------------------
421 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
422 Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
424 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
428 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
429 : Plugin (engine, session)
431 , unit (new CAAudioUnit)
432 , initialized (false)
433 , _current_block_size (0)
434 , _requires_fixed_size_buffers (false)
436 , variable_inputs (false)
437 , variable_outputs (false)
438 , configured_input_busses (0)
439 , configured_output_busses (0)
447 , frames_processed (0)
448 , audio_input_cnt (0)
449 , _parameter_listener (0)
450 , _parameter_listener_arg (0)
451 , transport_frame (false)
452 , transport_speed (false)
453 , last_transport_speed (0.0)
455 if (!preset_search_path_initialized) {
456 Glib::ustring p = Glib::get_home_dir();
457 p += "/Library/Audio/Presets:";
458 p += preset_search_path;
459 preset_search_path = p;
460 preset_search_path_initialized = true;
461 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
468 AUPlugin::AUPlugin (const AUPlugin& other)
470 , comp (other.get_comp())
471 , unit (new CAAudioUnit)
472 , initialized (false)
473 , _current_block_size (0)
475 , _requires_fixed_size_buffers (false)
477 , variable_inputs (false)
478 , variable_outputs (false)
479 , configured_input_busses (0)
480 , configured_output_busses (0)
487 , frames_processed (0)
488 , _parameter_listener (0)
489 , _parameter_listener_arg (0)
493 for (size_t i = 0; i < descriptors.size(); ++i) {
494 set_parameter (i, other.get_parameter (i));
498 AUPlugin::~AUPlugin ()
500 if (_parameter_listener) {
501 AUListenerDispose (_parameter_listener);
502 _parameter_listener = 0;
506 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
507 unit->Uninitialize ();
517 AUPlugin::discover_factory_presets ()
524 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
525 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
529 assert (dataSize == sizeof (presets));
531 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
532 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
540 CFIndex cnt = CFArrayGetCount (presets);
542 for (CFIndex i = 0; i < cnt; ++i) {
543 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
545 string name = CFStringRefToStdString (preset->presetName);
546 factory_preset_map[name] = preset->presetNumber;
547 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
557 CFStringRef itemName;
559 /* these keep track of *configured* channel set up,
560 not potential set ups.
564 output_channels = -1;
566 CAComponentDescription temp;
568 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
570 AudioComponentGetDescription (comp.get()->Comp(), &temp);
572 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
573 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
574 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
575 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
576 compTypeString, compManufacturerString, compSubTypeString);
577 if (compTypeString != NULL) CFRelease(compTypeString);
578 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
579 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
582 au_blacklist(CFStringRefToStdString(itemName));
585 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
586 err = CAAudioUnit::Open (*(comp.get()), *unit);
588 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
589 throw failed_constructor();
593 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
594 throw failed_constructor ();
597 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
598 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
599 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
600 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
601 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
602 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
604 cb_offsets = (framecnt_t*) calloc (input_elements, sizeof(uint32_t));
605 bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
606 bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
608 for (size_t i = 0; i < output_elements; ++i) {
609 unit->Reset (kAudioUnitScope_Output, i);
610 AudioStreamBasicDescription fmt;
611 err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
613 bus_outputs[i] = fmt.mChannelsPerFrame;
616 UInt32 sz = sizeof (CFStringRef);
617 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
618 i, &name, &sz) == noErr
620 _bus_name_out.push_back (CFStringRefToStdString (name));
623 _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
627 for (size_t i = 0; i < input_elements; ++i) {
628 unit->Reset (kAudioUnitScope_Input, i);
629 AudioStreamBasicDescription fmt;
630 err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
632 bus_inputs[i] = fmt.mChannelsPerFrame;
635 UInt32 sz = sizeof (CFStringRef);
636 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
637 i, &name, &sz) == noErr
639 _bus_name_in.push_back (CFStringRefToStdString (name));
642 _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
646 for (size_t i = 0; i < input_elements; ++i) {
647 /* setup render callback: the plugin calls this to get input data */
648 AURenderCallbackStruct renderCallbackInfo;
649 renderCallbackInfo.inputProc = _render_callback;
650 renderCallbackInfo.inputProcRefCon = this;
651 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
652 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
653 i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
654 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
655 throw failed_constructor();
659 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
661 HostCallbackInfo info;
662 memset (&info, 0, sizeof (HostCallbackInfo));
663 info.hostUserData = this;
664 info.beatAndTempoProc = _get_beat_and_tempo_callback;
665 info.musicalTimeLocationProc = _get_musical_time_location_callback;
666 info.transportStateProc = _get_transport_state_callback;
668 //ignore result of this - don't care if the property isn't supported
669 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
670 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
671 kAudioUnitScope_Global,
674 sizeof (HostCallbackInfo));
676 if (set_block_size (_session.get_block_size())) {
677 error << _("AUPlugin: cannot set processing block size") << endmsg;
678 throw failed_constructor();
681 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
682 discover_parameters ();
683 discover_factory_presets ();
685 // Plugin::setup_controls ();
687 au_unblacklist(CFStringRefToStdString(itemName));
688 if (itemName != NULL) CFRelease(itemName);
692 AUPlugin::discover_parameters ()
694 /* discover writable parameters */
696 AudioUnitScope scopes[] = {
697 kAudioUnitScope_Global,
698 kAudioUnitScope_Output,
699 kAudioUnitScope_Input
702 descriptors.clear ();
704 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
706 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
708 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
710 AUParameterDescriptor d;
712 d.id = param_info.ParamID (i);
714 const CAAUParameter* param = param_info.GetParamInfo (d.id);
715 const AudioUnitParameterInfo& info (param->ParamInfo());
717 const int len = CFStringGetLength (param->GetName());
718 char local_buffer[len*2];
719 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
723 d.label = local_buffer;
726 d.scope = param_info.GetScope ();
727 d.element = param_info.GetElement ();
729 /* info.units to consider */
731 kAudioUnitParameterUnit_Generic = 0
732 kAudioUnitParameterUnit_Indexed = 1
733 kAudioUnitParameterUnit_Boolean = 2
734 kAudioUnitParameterUnit_Percent = 3
735 kAudioUnitParameterUnit_Seconds = 4
736 kAudioUnitParameterUnit_SampleFrames = 5
737 kAudioUnitParameterUnit_Phase = 6
738 kAudioUnitParameterUnit_Rate = 7
739 kAudioUnitParameterUnit_Hertz = 8
740 kAudioUnitParameterUnit_Cents = 9
741 kAudioUnitParameterUnit_RelativeSemiTones = 10
742 kAudioUnitParameterUnit_MIDINoteNumber = 11
743 kAudioUnitParameterUnit_MIDIController = 12
744 kAudioUnitParameterUnit_Decibels = 13
745 kAudioUnitParameterUnit_LinearGain = 14
746 kAudioUnitParameterUnit_Degrees = 15
747 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
748 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
749 kAudioUnitParameterUnit_Pan = 18
750 kAudioUnitParameterUnit_Meters = 19
751 kAudioUnitParameterUnit_AbsoluteCents = 20
752 kAudioUnitParameterUnit_Octaves = 21
753 kAudioUnitParameterUnit_BPM = 22
754 kAudioUnitParameterUnit_Beats = 23
755 kAudioUnitParameterUnit_Milliseconds = 24
756 kAudioUnitParameterUnit_Ratio = 25
759 /* info.flags to consider */
763 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
764 kAudioUnitParameterFlag_HasClump = (1L << 20)
765 kAudioUnitParameterFlag_HasName = (1L << 21)
766 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
767 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
768 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
769 kAudioUnitParameterFlag_CanRamp = (1L << 25)
770 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
771 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
772 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
773 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
774 kAudioUnitParameterFlag_IsReadable = (1L << 30)
775 kAudioUnitParameterFlag_IsWritable = (1L << 31)
778 d.lower = info.minValue;
779 d.upper = info.maxValue;
780 d.normal = info.defaultValue;
782 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
783 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
784 (d.integer_step && ((d.upper - d.lower) == 1.0));
785 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
786 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
787 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
788 (info.flags & kAudioUnitParameterFlag_IsWritable);
790 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
791 d.au_unit = info.unit;
793 case kAudioUnitParameterUnit_Decibels:
794 d.unit = ParameterDescriptor::DB;
796 case kAudioUnitParameterUnit_MIDINoteNumber:
797 d.unit = ParameterDescriptor::MIDI_NOTE;
799 case kAudioUnitParameterUnit_Hertz:
800 d.unit = ParameterDescriptor::HZ;
804 d.min_unbound = 0; // lower is bound
805 d.max_unbound = 0; // upper is bound
808 descriptors.push_back (d);
810 uint32_t last_param = descriptors.size() - 1;
811 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
812 listen_to_parameter (last_param);
819 four_ints_to_four_byte_literal (unsigned char n[4])
821 /* this is actually implementation dependent. sigh. this is what gcc
822 and quite a few others do.
824 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
828 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
830 if (isdigit (id[0])) {
834 /* ID format is xxxx-xxxx-xxxx
835 where x maybe \xNN or a printable character.
837 Split at the '-' and and process each part into an integer.
838 Then put it back together.
842 unsigned char nascent[4];
843 const char* cstr = id.c_str();
844 const char* estr = cstr + id.size();
855 while (*cstr && next_int < 4) {
859 if (estr - cstr < 3) {
861 /* too close to the end for \xNN parsing: treat as literal characters */
869 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
873 memcpy (short_buf, &cstr[2], 2);
874 nascent[in] = strtol (short_buf, NULL, 16);
880 /* treat as literal characters */
894 if (in && (in % 4 == 0)) {
895 /* nascent is ready */
896 n[next_int] = four_ints_to_four_byte_literal (nascent);
900 /* swallow space-hyphen-space */
914 s << n[0] << '-' << n[1] << '-' << n[2];
923 AUPlugin::unique_id () const
925 return AUPluginInfo::stringify_descriptor (comp->Desc());
929 AUPlugin::label () const
931 return _info->name.c_str();
935 AUPlugin::parameter_count () const
937 return descriptors.size();
941 AUPlugin::default_value (uint32_t port)
943 if (port < descriptors.size()) {
944 return descriptors[port].normal;
951 AUPlugin::signal_latency () const
953 return unit->Latency() * _session.frame_rate();
957 AUPlugin::set_parameter (uint32_t which, float val)
959 if (which >= descriptors.size()) {
963 if (get_parameter(which) == val) {
967 const AUParameterDescriptor& d (descriptors[which]);
968 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
969 unit->SetParameter (d.id, d.scope, d.element, val);
971 /* tell the world what we did */
973 AudioUnitEvent theEvent;
975 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
976 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
977 theEvent.mArgument.mParameter.mParameterID = d.id;
978 theEvent.mArgument.mParameter.mScope = d.scope;
979 theEvent.mArgument.mParameter.mElement = d.element;
981 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
982 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
983 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
985 Plugin::set_parameter (which, val);
989 AUPlugin::get_parameter (uint32_t which) const
992 if (which < descriptors.size()) {
993 const AUParameterDescriptor& d (descriptors[which]);
994 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
995 unit->GetParameter(d.id, d.scope, d.element, val);
1001 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
1003 if (which < descriptors.size()) {
1004 pd = descriptors[which];
1011 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
1013 if (which < descriptors.size()) {
1022 AUPlugin::activate ()
1026 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
1027 if ((err = unit->Initialize()) != noErr) {
1028 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
1030 frames_processed = 0;
1037 AUPlugin::deactivate ()
1039 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
1040 unit->Uninitialize ();
1041 initialized = false;
1047 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
1048 unit->GlobalReset ();
1052 AUPlugin::requires_fixed_size_buffers() const
1054 return _requires_fixed_size_buffers;
1059 AUPlugin::set_block_size (pframes_t nframes)
1061 bool was_initialized = initialized;
1062 UInt32 numFrames = nframes;
1069 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
1070 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1071 0, &numFrames, sizeof (numFrames))) != noErr) {
1072 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
1076 if (was_initialized) {
1080 _current_block_size = nframes;
1086 AUPlugin::configure_io (ChanCount in, ChanCount out)
1088 AudioStreamBasicDescription streamFormat;
1089 bool was_initialized = initialized;
1090 int32_t audio_out = out.n_audio();
1091 if (audio_input_cnt > 0) {
1092 in.set (DataType::AUDIO, audio_input_cnt);
1094 const int32_t audio_in = in.n_audio();
1096 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1099 //if we are already running with the requested i/o config, bail out here
1100 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1107 streamFormat.mSampleRate = _session.frame_rate();
1108 streamFormat.mFormatID = kAudioFormatLinearPCM;
1109 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1111 #ifdef __LITTLE_ENDIAN__
1114 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1117 streamFormat.mBitsPerChannel = 32;
1118 streamFormat.mFramesPerPacket = 1;
1120 /* apple says that for non-interleaved data, these
1121 * values always refer to a single channel.
1123 streamFormat.mBytesPerPacket = 4;
1124 streamFormat.mBytesPerFrame = 4;
1126 configured_input_busses = 0;
1127 configured_output_busses = 0;
1129 for (size_t i = 0; i < output_elements; ++i) {
1130 unit->Reset (kAudioUnitScope_Output, i);
1132 for (size_t i = 0; i < input_elements; ++i) {
1133 unit->Reset (kAudioUnitScope_Input, i);
1136 /* now assign the channels to available busses */
1137 uint32_t used_in = 0;
1138 uint32_t used_out = 0;
1140 if (variable_inputs || input_elements == 1) {
1141 // we only ever use the first bus
1142 if (input_elements > 1) {
1143 warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
1145 streamFormat.mChannelsPerFrame = audio_in;
1146 if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
1149 configured_input_busses = 1;
1152 configured_input_busses = 0;
1153 uint32_t remain = audio_in;
1154 for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
1155 uint32_t cnt = std::min (remain, bus_inputs[bus]);
1156 if (cnt == 0) { continue; }
1157 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
1159 streamFormat.mChannelsPerFrame = cnt;
1160 if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
1164 ++configured_input_busses;
1169 if (variable_outputs || output_elements == 1) {
1170 if (output_elements > 1) {
1171 warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
1174 streamFormat.mChannelsPerFrame = audio_out;
1175 if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
1178 configured_output_busses = 1;
1179 used_out = audio_out;
1181 uint32_t remain = audio_out;
1182 configured_output_busses = 0;
1183 for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
1184 uint32_t cnt = std::min (remain, bus_outputs[bus]);
1185 if (cnt == 0) { continue; }
1186 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
1187 streamFormat.mChannelsPerFrame = cnt;
1188 if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
1193 ++configured_output_busses;
1198 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1199 used_out * sizeof(::AudioBuffer));
1201 input_channels = used_in;
1202 output_channels = used_out;
1203 /* reset plugin info to show currently configured state */
1205 _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
1206 _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
1208 if (was_initialized) {
1216 AUPlugin::input_streams() const
1219 if (input_channels < 0) {
1220 // force PluginIoReConfigure -- see also commit msg e38eb06
1221 c.set (DataType::AUDIO, 0);
1222 c.set (DataType::MIDI, 0);
1224 c.set (DataType::AUDIO, input_channels);
1225 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1232 AUPlugin::output_streams() const
1235 if (output_channels < 0) {
1236 // force PluginIoReConfigure - see also commit msg e38eb06
1237 c.set (DataType::AUDIO, 0);
1238 c.set (DataType::MIDI, 0);
1240 c.set (DataType::AUDIO, output_channels);
1241 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1247 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1249 _output_configs.clear ();
1250 const int32_t audio_in = in.n_audio();
1251 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1253 /* lets check MIDI first */
1255 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1259 vector<pair<int,int> > io_configs = pinfo->cache.io_configs;
1261 if (input_elements > 1) {
1262 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1263 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1264 int32_t possible_in = i->first;
1265 int32_t possible_out = i->second;
1266 if (possible_in < 1 || possible_out < 1) {
1269 for (uint32_t i = 1; i < input_elements; ++i) {
1270 // can't use up-to bus_inputs[]
1271 // waves' SC-C6(s) for example fails to configure with only 1 input
1273 io_configs.push_back (pair<int,int> (possible_in + bus_inputs[i], possible_out));
1278 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1279 name(), io_configs.size(), in, out));
1282 printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
1283 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1284 printf ("- I/O %d / %d\n", i->first, i->second);
1288 // preferred setting (provided by plugin_insert)
1289 const int preferred_out = out.n_audio ();
1291 bool exact_match = false;
1293 /* kAudioUnitProperty_SupportedNumChannels
1294 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1296 * - both fields are -1
1297 * e.g. inChannels = -1 outChannels = -1
1298 * This is the default case. Any number of input and output channels, as long as the numbers match
1300 * - one field is -1, the other field is positive
1301 * e.g. inChannels = -1 outChannels = 2
1302 * Any number of input channels, exactly two output channels
1304 * - one field is -1, the other field is -2
1305 * e.g. inChannels = -1 outChannels = -2
1306 * Any number of input channels, any number of output channels
1308 * - both fields have non-negative values
1309 * e.g. inChannels = 2 outChannels = 6
1310 * Exactly two input channels, exactly six output channels
1311 * e.g. inChannels = 0 outChannels = 2
1312 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1314 * - both fields have negative values, neither of which is –1 or –2
1315 * e.g. inChannels = -4 outChannels = -8
1316 * Up to four input channels and up to eight output channels
1319 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1321 int32_t possible_in = i->first;
1322 int32_t possible_out = i->second;
1324 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1325 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1326 possible_in, possible_out,
1330 _output_configs.insert (preferred_out);
1337 /* now allow potentially "imprecise" matches */
1338 int32_t audio_out = -1;
1339 float penalty = 9999;
1340 int used_possible_in = 0;
1341 #if defined (__clang__)
1342 # pragma clang diagnostic push
1343 # pragma clang diagnostic ignored "-Wtautological-compare"
1346 #define FOUNDCFG(nch) { \
1347 float p = fabsf ((float)(nch) - preferred_out); \
1348 _output_configs.insert (nch); \
1349 if ((nch) > preferred_out) { p *= 1.1; } \
1350 if (p < penalty) { \
1351 used_possible_in = possible_in; \
1352 audio_out = (nch); \
1355 variable_inputs = possible_in < 0; \
1356 variable_outputs = possible_out < 0; \
1360 #define ANYTHINGGOES \
1361 _output_configs.insert (0);
1363 #define UPTO(nch) { \
1364 for (int n = 1; n <= nch; ++n) { \
1365 _output_configs.insert (n); \
1369 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1371 int32_t possible_in = i->first;
1372 int32_t possible_out = i->second;
1374 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1376 if (possible_out == 0) {
1377 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1378 /* XXX surely this is just a send? (e.g. AUNetSend) */
1382 if (possible_in == 0) {
1383 /* no inputs, generators & instruments */
1384 if (possible_out == -1) {
1385 /* any configuration possible, provide stereo output */
1386 FOUNDCFG (preferred_out);
1388 } else if (possible_out == -2) {
1389 /* invalid, should be (0, -1) */
1390 FOUNDCFG (preferred_out);
1392 } else if (possible_out < -2) {
1393 /* variable number of outputs up to -N, */
1394 FOUNDCFG (min (-possible_out, preferred_out));
1395 UPTO (-possible_out);
1397 /* exact number of outputs */
1398 FOUNDCFG (possible_out);
1402 if (possible_in == -1) {
1403 /* wildcard for input */
1404 if (possible_out == -1) {
1405 /* out must match in */
1406 FOUNDCFG (audio_in);
1407 } else if (possible_out == -2) {
1408 /* any configuration possible, pick matching */
1409 FOUNDCFG (preferred_out);
1411 } else if (possible_out < -2) {
1412 /* explicitly variable number of outputs, pick maximum */
1413 FOUNDCFG (max (-possible_out, preferred_out));
1414 /* and try min, too, in case the penalty is lower */
1415 FOUNDCFG (min (-possible_out, preferred_out));
1416 UPTO (-possible_out)
1418 /* exact number of outputs */
1419 FOUNDCFG (possible_out);
1423 if (possible_in == -2) {
1424 if (possible_out == -1) {
1425 /* any configuration possible, pick matching */
1426 FOUNDCFG (preferred_out);
1428 } else if (possible_out == -2) {
1429 /* invalid. interpret as (-1, -1) */
1430 FOUNDCFG (preferred_out);
1432 } else if (possible_out < -2) {
1433 /* invalid, interpret as (<-2, <-2)
1434 * variable number of outputs up to -N, */
1435 FOUNDCFG (min (-possible_out, preferred_out));
1436 UPTO (-possible_out)
1438 /* exact number of outputs */
1439 FOUNDCFG (possible_out);
1443 if (possible_in < -2) {
1444 /* explicit variable number of inputs */
1445 if (audio_in > -possible_in && imprecise != NULL) {
1446 // hide inputs ports
1447 imprecise->set (DataType::AUDIO, -possible_in);
1450 if (audio_in > -possible_in && imprecise == NULL) {
1451 /* request is too large */
1452 } else if (possible_out == -1) {
1453 /* any output configuration possible */
1454 FOUNDCFG (preferred_out);
1456 } else if (possible_out == -2) {
1457 /* invalid. interpret as (<-2, -1) */
1458 FOUNDCFG (preferred_out);
1460 } else if (possible_out < -2) {
1461 /* variable number of outputs up to -N, */
1462 FOUNDCFG (min (-possible_out, preferred_out));
1463 UPTO (-possible_out)
1465 /* exact number of outputs */
1466 FOUNDCFG (possible_out);
1470 if (possible_in && (possible_in == audio_in)) {
1471 /* exact number of inputs ... must match obviously */
1472 if (possible_out == -1) {
1473 /* any output configuration possible */
1474 FOUNDCFG (preferred_out);
1476 } else if (possible_out == -2) {
1477 /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
1478 FOUNDCFG (preferred_out);
1480 } else if (possible_out < -2) {
1481 /* > 0, < -2 is not specified
1482 * interpret as up to -N */
1483 FOUNDCFG (min (-possible_out, preferred_out));
1484 UPTO (-possible_out)
1486 /* exact number of outputs */
1487 FOUNDCFG (possible_out);
1492 if (!found && imprecise) {
1494 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1495 int32_t possible_in = i->first;
1496 int32_t possible_out = i->second;
1498 assert (possible_in > 0); // all other cases will have been matched above
1499 assert (possible_out !=0 || possible_in !=0); // already handled above
1501 imprecise->set (DataType::AUDIO, possible_in);
1502 if (possible_out == -1 || possible_out == -2) {
1504 } else if (possible_out < -2) {
1505 /* explicitly variable number of outputs, pick maximum */
1506 FOUNDCFG (min (-possible_out, preferred_out));
1508 /* exact number of outputs */
1509 FOUNDCFG (possible_out);
1511 // ideally we'll also find the closest, best matching
1512 // input configuration with minimal output penalty...
1517 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1522 out.set (DataType::MIDI, 0); // currently always zero
1523 out.set (DataType::AUDIO, preferred_out);
1525 if (used_possible_in < -2 && audio_in == 0) {
1526 // input-port count cannot be zero, use as many ports
1527 // as outputs, but at most abs(possible_in)
1528 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1530 out.set (DataType::MIDI, 0); /// XXX
1531 out.set (DataType::AUDIO, audio_out);
1533 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1535 #if defined (__clang__)
1536 # pragma clang diagnostic pop
1542 AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
1546 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1547 (scope == kAudioUnitScope_Input ? "input" : "output"),
1549 if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
1550 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1551 (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
1558 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1559 const AudioTimeStamp*,
1561 UInt32 inNumberFrames,
1562 AudioBufferList* ioData)
1564 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1566 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bus %3 bufs %4\n",
1567 // name(), inNumberFrames, bus, ioData->mNumberBuffers));
1569 if (input_maxbuf == 0) {
1570 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1571 error << _("AUPlugin: render callback called illegally!") << endmsg;
1572 return kAudioUnitErr_CannotDoInCurrentContext;
1575 assert (bus < input_elements);
1576 uint32_t busoff = 0;
1577 for (uint32_t i = 0; i < bus; ++i) {
1578 busoff += bus_inputs[i];
1581 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1583 ChanCount bufs_count (DataType::AUDIO, 1);
1584 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1586 /* apply bus offsets */
1588 for (uint32_t i = 0; i < limit; ++i) {
1589 ioData->mBuffers[i].mNumberChannels = 1;
1590 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1593 uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
1595 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
1597 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
1600 cb_offsets[bus] += inNumberFrames;
1605 AUPlugin::connect_and_run (BufferSet& bufs,
1606 framepos_t start, framepos_t end, double speed,
1607 ChanMapping in_map, ChanMapping out_map,
1608 pframes_t nframes, framecnt_t offset)
1610 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
1612 transport_frame = start;
1613 transport_speed = speed;
1615 AudioUnitRenderActionFlags flags = 0;
1619 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1620 unit->GlobalReset();
1621 _last_nframes = nframes;
1624 /* test if we can run in-place; only compare audio buffers */
1625 bool inplace = true; // TODO check plugin-insert in-place ?
1626 ChanMapping::Mappings inmap (in_map.mappings ());
1627 ChanMapping::Mappings outmap (out_map.mappings ());
1628 assert (outmap[DataType::AUDIO].size () > 0);
1629 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1633 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",
1634 name(), input_channels, output_channels, _has_midi_input,
1635 bufs.count(), bufs.available(),
1636 configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
1638 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1639 * has the capacity to handle our outputs.
1642 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1644 input_buffers = &bufs;
1645 input_map = &in_map;
1646 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1647 input_offset = offset;
1648 for (size_t i = 0; i < input_elements; ++i) {
1652 ChanCount bufs_count (DataType::AUDIO, 1);
1653 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1655 if (_has_midi_input) {
1656 uint32_t nmidi = bufs.count().n_midi();
1657 for (uint32_t i = 0; i < nmidi; ++i) {
1658 /* one MIDI port/buffer only */
1659 MidiBuffer& m = bufs.get_midi (i);
1660 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1661 Evoral::MIDIEvent<framepos_t> ev (*i);
1662 if (ev.is_channel_event()) {
1663 const uint8_t* b = ev.buffer();
1664 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1665 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1667 /* XXX need to handle sysex and other message types */
1672 assert (input_maxbuf < 512);
1673 std::bitset<512> used_outputs;
1676 uint32_t busoff = 0;
1677 uint32_t remain = output_channels;
1678 for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
1680 if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
1681 cnt = output_channels;
1683 cnt = std::min (remain, bus_outputs[bus]);
1687 buffers->mNumberBuffers = cnt;
1689 for (uint32_t i = 0; i < cnt; ++i) {
1690 buffers->mBuffers[i].mNumberChannels = 1;
1691 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1692 /* setting this to 0 indicates to the AU that it can provide buffers here
1693 * if necessary. if it can process in-place, it will use the buffers provided
1694 * as input by ::render_callback() above.
1696 * a non-null values tells the plugin to render into the buffer pointed
1700 buffers->mBuffers[i].mData = 0;
1703 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1705 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1707 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1712 /* does this really mean anything ? */
1713 ts.mSampleTime = frames_processed;
1714 ts.mFlags = kAudioTimeStampSampleTimeValid;
1716 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
1717 name(), flags, frames_processed, nframes, bus, buffers->mNumberBuffers));
1719 if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
1721 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1722 name(), buffers->mNumberBuffers, output_channels));
1724 uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
1725 for (uint32_t i = 0; i < limit; ++i) {
1727 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1728 if (!valid) continue;
1729 used_outputs.set (i + busoff);
1730 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1731 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1732 /* plugin provided its own buffer for output so copy it back to where we want it */
1733 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1737 DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
1738 error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
1744 busoff += bus_outputs[bus];
1747 /* now silence any buffers that were passed in but the that the plugin
1748 * did not fill/touch/use.
1750 * TODO: optimize, when plugin-insert is processing in-place
1751 * unconnected buffers are (also) cleared there.
1753 for (uint32_t i = 0; i < input_maxbuf; ++i) {
1754 if (used_outputs.test (i)) { continue; }
1756 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1757 if (!valid) continue;
1758 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1764 frames_processed += nframes;
1771 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1772 Float64* outCurrentTempo)
1774 TempoMap& tmap (_session.tempo_map());
1776 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1778 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1779 (and interpretation) of a beat position will be incorrect. So refuse to
1783 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1784 return kAudioUnitErr_CannotDoInCurrentContext;
1787 TempoMetric metric = tmap.metric_at (transport_frame + input_offset);
1788 Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_frame (transport_frame + input_offset);
1790 if (outCurrentBeat) {
1791 const double ppq_scaling = metric.meter().note_divisor() / 4.0;
1793 beat = metric.meter().divisions_per_bar() * (bbt.bars - 1);
1794 beat += (bbt.beats - 1);
1795 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1796 *outCurrentBeat = beat * ppq_scaling;
1799 if (outCurrentTempo) {
1800 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1808 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1809 Float32* outTimeSig_Numerator,
1810 UInt32* outTimeSig_Denominator,
1811 Float64* outCurrentMeasureDownBeat)
1813 TempoMap& tmap (_session.tempo_map());
1815 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1817 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1818 (and interpretation) of a beat position will be incorrect. So refuse to
1822 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1823 return kAudioUnitErr_CannotDoInCurrentContext;
1826 TempoMetric metric = tmap.metric_at (transport_frame + input_offset);
1827 Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_frame (transport_frame + input_offset);
1829 if (outDeltaSampleOffsetToNextBeat) {
1830 if (bbt.ticks == 0) {
1832 *outDeltaSampleOffsetToNextBeat = 0;
1834 double const beat_frac_to_next = (Timecode::BBT_Time::ticks_per_beat - bbt.ticks) / Timecode::BBT_Time::ticks_per_beat;
1835 *outDeltaSampleOffsetToNextBeat = tmap.frame_at_beat (tmap.beat_at_frame (transport_frame + input_offset) + beat_frac_to_next);
1839 if (outTimeSig_Numerator) {
1840 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1842 if (outTimeSig_Denominator) {
1843 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1846 if (outCurrentMeasureDownBeat) {
1848 /* beat for the start of the bar.
1850 2|1|0 -> 1 + divisions_per_bar
1851 3|1|0 -> 1 + (2 * divisions_per_bar)
1855 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1862 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1863 Boolean* outTransportStateChanged,
1864 Float64* outCurrentSampleInTimeLine,
1865 Boolean* outIsCycling,
1866 Float64* outCycleStartBeat,
1867 Float64* outCycleEndBeat)
1869 const bool rolling = (transport_speed != 0);
1870 const bool last_transport_rolling = (last_transport_speed != 0);
1872 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1876 *outIsPlaying = rolling;
1879 if (outTransportStateChanged) {
1880 if (rolling != last_transport_rolling) {
1881 *outTransportStateChanged = true;
1882 } else if (transport_speed != last_transport_speed) {
1883 *outTransportStateChanged = true;
1885 *outTransportStateChanged = false;
1889 if (outCurrentSampleInTimeLine) {
1890 /* this assumes that the AU can only call this host callback from render context,
1891 where input_offset is valid.
1893 *outCurrentSampleInTimeLine = transport_frame + input_offset;
1897 // TODO check bounce-processing
1898 Location* loc = _session.locations()->auto_loop_location();
1900 *outIsCycling = (loc && rolling && _session.get_play_loop());
1902 if (*outIsCycling) {
1904 if (outCycleStartBeat || outCycleEndBeat) {
1906 TempoMap& tmap (_session.tempo_map());
1908 /* more than 1 meter means that a simplistic computation (and interpretation) of
1909 a beat position will be incorrect. so refuse to offer the value.
1912 if (tmap.n_meters() > 1) {
1913 return kAudioUnitErr_CannotDoInCurrentContext;
1916 Timecode::BBT_Time bbt;
1918 if (outCycleStartBeat) {
1919 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1920 bbt = _session.tempo_map().bbt_at_frame (loc->start() + input_offset);
1923 beat = metric.meter().divisions_per_bar() * bbt.bars;
1925 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1927 *outCycleStartBeat = beat;
1930 if (outCycleEndBeat) {
1931 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1932 bbt = _session.tempo_map().bbt_at_frame (loc->end() + input_offset);
1935 beat = metric.meter().divisions_per_bar() * bbt.bars;
1937 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1939 *outCycleEndBeat = beat;
1945 last_transport_speed = transport_speed;
1950 set<Evoral::Parameter>
1951 AUPlugin::automatable() const
1953 set<Evoral::Parameter> automates;
1955 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1956 if (descriptors[i].automatable) {
1957 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1964 Plugin::IOPortDescription
1965 AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1967 std::stringstream ss;
1969 case DataType::AUDIO:
1971 case DataType::MIDI:
1979 if (dt == DataType::AUDIO) {
1982 for (uint32_t bus = 0; bus < input_elements; ++bus) {
1983 if (pid < bus_inputs[bus]) {
1985 ss << _bus_name_in[bus];
1986 ss << " / Bus " << (1 + bus);
1989 pid -= bus_inputs[bus];
1994 for (uint32_t bus = 0; bus < output_elements; ++bus) {
1995 if (pid < bus_outputs[bus]) {
1997 ss << _bus_name_out[bus];
1998 ss << " / Bus " << (1 + bus);
2001 pid -= bus_outputs[bus];
2007 ss << " " << _("In") << " ";
2009 ss << " " << _("Out") << " ";
2014 Plugin::IOPortDescription iod (ss.str());
2019 AUPlugin::describe_parameter (Evoral::Parameter param)
2021 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
2022 return descriptors[param.id()].label;
2029 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
2031 // NameValue stuff here
2035 AUPlugin::parameter_is_audio (uint32_t) const
2041 AUPlugin::parameter_is_control (uint32_t param) const
2043 assert(param < descriptors.size());
2044 if (descriptors[param].automatable) {
2045 /* corrently ardour expects all controls to be automatable
2046 * IOW ardour GUI elements mandate an Evoral::Parameter
2047 * for all input+control ports.
2055 AUPlugin::parameter_is_input (uint32_t param) const
2057 /* AU params that are both readable and writeable,
2058 * are listed in kAudioUnitScope_Global
2060 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
2064 AUPlugin::parameter_is_output (uint32_t param) const
2066 assert(param < descriptors.size());
2067 // TODO check if ardour properly handles ports
2068 // that report is_input + is_output == true
2069 // -> add || descriptors[param].scope == kAudioUnitScope_Global
2070 return (descriptors[param].scope == kAudioUnitScope_Output);
2074 AUPlugin::add_state (XMLNode* root) const
2078 CFPropertyListRef propertyList;
2080 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
2081 if (unit->GetAUPreset (propertyList) != noErr) {
2085 // Convert the property list into XML data.
2087 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
2090 error << _("Could not create XML version of property list") << endmsg;
2094 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
2095 our state node. GACK!
2100 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
2102 root->add_child_copy (*t.root());
2106 CFRelease (xmlData);
2107 CFRelease (propertyList);
2111 AUPlugin::set_state(const XMLNode& node, int version)
2114 CFPropertyListRef propertyList;
2117 if (node.name() != state_node_name()) {
2118 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
2122 #ifndef NO_PLUGIN_STATE
2123 if (node.children().empty()) {
2127 XMLNode* top = node.children().front();
2128 XMLNode* copy = new XMLNode (*top);
2133 const string& xml = t.write_buffer ();
2134 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
2135 CFStringRef errorString;
2137 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
2139 kCFPropertyListImmutable,
2142 CFRelease (xmlData);
2145 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
2146 if (unit->SetAUPreset (propertyList) == noErr) {
2149 /* tell the world */
2151 AudioUnitParameter changedUnit;
2152 changedUnit.mAudioUnit = unit->AU();
2153 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2154 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2156 CFRelease (propertyList);
2160 Plugin::set_state (node, version);
2165 AUPlugin::load_preset (PresetRecord r)
2167 Plugin::load_preset (r);
2170 CFPropertyListRef propertyList;
2172 UserPresetMap::iterator ux;
2173 FactoryPresetMap::iterator fx;
2175 /* look first in "user" presets */
2177 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
2179 if ((propertyList = load_property_list (ux->second)) != 0) {
2180 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
2181 if (unit->SetAUPreset (propertyList) == noErr) {
2184 /* tell the world */
2186 AudioUnitParameter changedUnit;
2187 changedUnit.mAudioUnit = unit->AU();
2188 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2189 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2191 CFRelease(propertyList);
2194 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2198 preset.presetNumber = fx->second;
2199 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2201 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2203 if (unit->SetPresentPreset (preset) == 0) {
2206 /* tell the world */
2208 AudioUnitParameter changedUnit;
2209 changedUnit.mAudioUnit = unit->AU();
2210 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2211 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2219 AUPlugin::do_remove_preset (std::string)
2224 AUPlugin::do_save_preset (string preset_name)
2226 CFPropertyListRef propertyList;
2227 vector<Glib::ustring> v;
2228 Glib::ustring user_preset_path;
2230 std::string m = maker();
2231 std::string n = name();
2233 strip_whitespace_edges (m);
2234 strip_whitespace_edges (n);
2236 v.push_back (Glib::get_home_dir());
2237 v.push_back ("Library");
2238 v.push_back ("Audio");
2239 v.push_back ("Presets");
2243 user_preset_path = Glib::build_filename (v);
2245 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2246 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2250 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2251 if (unit->GetAUPreset (propertyList) != noErr) {
2255 // add the actual preset name */
2257 v.push_back (preset_name + preset_suffix);
2261 user_preset_path = Glib::build_filename (v);
2263 set_preset_name_in_plist (propertyList, preset_name);
2265 if (save_property_list (propertyList, user_preset_path)) {
2266 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2270 CFRelease(propertyList);
2272 user_preset_map[preset_name] = user_preset_path;;
2274 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2276 return string ("file:///") + user_preset_path;
2279 //-----------------------------------------------------------------------------
2280 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2282 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2284 CFNumberRef cfNumber;
2285 SInt32 numberValue = 0;
2286 Boolean dummySuccess;
2288 if (outSuccess == NULL)
2289 outSuccess = &dummySuccess;
2290 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2292 *outSuccess = FALSE;
2296 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2297 if (cfNumber == NULL)
2299 *outSuccess = FALSE;
2302 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2310 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2312 CFDictionaryRef auStateDictionary;
2313 ArdourDescription tempDesc = {0,0,0,0,0};
2314 SInt32 versionValue;
2317 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2320 // the property list for AU state data must be of the dictionary type
2321 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2322 return kAudioUnitErr_InvalidPropertyValue;
2325 auStateDictionary = (CFDictionaryRef)inAUStateData;
2327 // first check to make sure that the version of the AU state data is one that we know understand
2328 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2329 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2332 return kAudioUnitErr_InvalidPropertyValue;
2334 #define kCurrentSavedStateVersion 0
2335 if (versionValue != kCurrentSavedStateVersion) {
2336 return kAudioUnitErr_InvalidPropertyValue;
2339 // grab the ComponentDescription values from the AU state data
2340 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2341 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2342 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2343 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2344 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2345 return kAudioUnitErr_InvalidPropertyValue;
2347 *outComponentDescription = tempDesc;
2352 static bool au_preset_filter (const string& str, void* arg)
2354 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2358 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2362 /* check the preset file path name against this plugin
2363 ID. The idea is that all preset files for this plugin
2364 include "<manufacturer>/<plugin-name>" in their path.
2367 AUPluginInfo* p = (AUPluginInfo *) arg;
2368 string match = p->creator;
2372 ret = str.find (match) != string::npos;
2375 string m = p->creator;
2377 strip_whitespace_edges (m);
2378 strip_whitespace_edges (n);
2383 ret = str.find (match) != string::npos;
2391 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2394 CFPropertyListRef plist;
2395 ArdourDescription presetDesc;
2398 plist = load_property_list (pathstr);
2404 // get the ComponentDescription from the AU preset file
2406 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2408 if (status == noErr) {
2409 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2411 /* try to get the preset name from the property list */
2413 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2415 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2419 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2422 char buf[PATH_MAX+1];
2424 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2441 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2443 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2446 CFStringRef itemName = NULL;
2447 // Marc Poirier-style item name
2449 CAComponent auComponent (comp_desc);
2450 if (auComponent.IsValid()) {
2451 CAComponentDescription dummydesc;
2452 Handle nameHandle = NewHandle(sizeof(void*));
2453 if (nameHandle != NULL) {
2454 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2456 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2457 if (nameString != NULL) {
2458 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2461 DisposeHandle(nameHandle);
2466 AudioComponentCopyName (comp, &itemName);
2469 // if Marc-style fails, do the original way
2470 if (itemName == NULL) {
2471 #ifndef COREAUDIO105
2472 CAComponentDescription comp_desc;
2473 AudioComponentGetDescription (comp, &comp_desc);
2475 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2476 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2477 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2479 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2480 compTypeString, compManufacturerString, compSubTypeString);
2482 if (compTypeString != NULL)
2483 CFRelease(compTypeString);
2484 if (compSubTypeString != NULL)
2485 CFRelease(compSubTypeString);
2486 if (compManufacturerString != NULL)
2487 CFRelease(compManufacturerString);
2490 string str = CFStringRefToStdString(itemName);
2491 string::size_type colon = str.find (':');
2494 name = str.substr (colon+1);
2495 maker = str.substr (0, colon);
2496 strip_whitespace_edges (maker);
2497 strip_whitespace_edges (name);
2501 strip_whitespace_edges (name);
2506 AUPlugin::current_preset() const
2510 CFPropertyListRef propertyList;
2512 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2513 if (unit->GetAUPreset (propertyList) == noErr) {
2514 preset_name = get_preset_name_in_plist (propertyList);
2515 CFRelease(propertyList);
2522 AUPlugin::find_presets ()
2524 vector<string> preset_files;
2526 user_preset_map.clear ();
2528 PluginInfoPtr nfo = get_info();
2529 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2530 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2533 if (preset_files.empty()) {
2534 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2537 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2542 /* make an initial guess at the preset name using the path */
2544 preset_name = Glib::path_get_basename (path);
2545 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2547 /* check that this preset file really matches this plugin
2548 and potentially get the "real" preset name from
2552 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2553 user_preset_map[preset_name] = path;
2554 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2556 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2561 /* now fill the vector<string> with the names we have */
2563 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2564 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2565 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2568 /* add factory presets */
2570 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2572 string const uri = string_compose ("%1", _presets.size ());
2573 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2574 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2579 AUPlugin::has_editor () const
2581 // even if the plugin doesn't have its own editor, the AU API can be used
2582 // to create one that looks native.
2586 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2590 type = ARDOUR::AudioUnit;
2593 AUPluginInfo::~AUPluginInfo ()
2595 type = ARDOUR::AudioUnit;
2599 AUPluginInfo::load (Session& session)
2604 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2605 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2607 if (!comp->IsValid()) {
2608 error << ("AudioUnit: not a valid Component") << endmsg;
2610 plugin.reset (new AUPlugin (session.engine(), session, comp));
2613 AUPluginInfo *aup = new AUPluginInfo (*this);
2614 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2615 plugin->set_info (PluginInfoPtr (aup));
2616 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2620 catch (failed_constructor &err) {
2621 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2622 return PluginPtr ();
2626 std::vector<Plugin::PresetRecord>
2627 AUPluginInfo::get_presets (bool user_only) const
2629 std::vector<Plugin::PresetRecord> p;
2630 boost::shared_ptr<CAComponent> comp;
2631 #ifndef NO_PLUGIN_STATE
2633 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2634 if (!comp->IsValid()) {
2635 throw failed_constructor();
2637 } catch (failed_constructor& err) {
2643 if (!preset_search_path_initialized) {
2644 Glib::ustring p = Glib::get_home_dir();
2645 p += "/Library/Audio/Presets:";
2646 p += preset_search_path;
2647 preset_search_path = p;
2648 preset_search_path_initialized = true;
2649 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2652 vector<string> preset_files;
2653 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2655 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2658 preset_name = Glib::path_get_basename (path);
2659 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2660 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2661 p.push_back (Plugin::PresetRecord (path, preset_name));
2675 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2676 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2679 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2680 unit->Uninitialize ();
2683 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2684 unit->Uninitialize ();
2688 unit->Uninitialize ();
2692 CFIndex cnt = CFArrayGetCount (presets);
2693 for (CFIndex i = 0; i < cnt; ++i) {
2694 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2695 string const uri = string_compose ("%1", i);
2696 string name = CFStringRefToStdString (preset->presetName);
2697 p.push_back (Plugin::PresetRecord (uri, name, false));
2699 CFRelease (presets);
2700 unit->Uninitialize ();
2702 #endif // NO_PLUGIN_STATE
2707 AUPluginInfo::au_cache_path ()
2709 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2713 AUPluginInfo::discover (bool scan_only)
2717 /* AU require a CAComponentDescription pointer provided by the OS.
2718 * Ardour only caches port and i/o config. It can't just 'scan' without
2719 * 'discovering' (like we do for VST).
2722 * "Iterate over all plugins. skip the ones where there's no io-cache".
2724 _scan_only = scan_only;
2726 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2727 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2728 // flush RAM cache -- after clear_cache()
2729 cached_info.clear();
2731 // create crash log file
2732 au_start_crashlog ();
2734 PluginInfoList* plugs = new PluginInfoList;
2736 discover_fx (*plugs);
2737 discover_music (*plugs);
2738 discover_generators (*plugs);
2739 discover_instruments (*plugs);
2741 // all fine if we get here
2742 au_remove_crashlog ();
2744 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2750 AUPluginInfo::discover_music (PluginInfoList& plugs)
2752 CAComponentDescription desc;
2753 desc.componentFlags = 0;
2754 desc.componentFlagsMask = 0;
2755 desc.componentSubType = 0;
2756 desc.componentManufacturer = 0;
2757 desc.componentType = kAudioUnitType_MusicEffect;
2759 discover_by_description (plugs, desc);
2763 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2765 CAComponentDescription desc;
2766 desc.componentFlags = 0;
2767 desc.componentFlagsMask = 0;
2768 desc.componentSubType = 0;
2769 desc.componentManufacturer = 0;
2770 desc.componentType = kAudioUnitType_Effect;
2772 discover_by_description (plugs, desc);
2776 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2778 CAComponentDescription desc;
2779 desc.componentFlags = 0;
2780 desc.componentFlagsMask = 0;
2781 desc.componentSubType = 0;
2782 desc.componentManufacturer = 0;
2783 desc.componentType = kAudioUnitType_Generator;
2785 discover_by_description (plugs, desc);
2789 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2791 CAComponentDescription desc;
2792 desc.componentFlags = 0;
2793 desc.componentFlagsMask = 0;
2794 desc.componentSubType = 0;
2795 desc.componentManufacturer = 0;
2796 desc.componentType = kAudioUnitType_MusicDevice;
2798 discover_by_description (plugs, desc);
2803 AUPluginInfo::au_get_crashlog (std::string &msg)
2805 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2806 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2809 std::ifstream ifs(fn.c_str());
2810 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2811 au_remove_crashlog ();
2816 AUPluginInfo::au_start_crashlog ()
2818 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2819 assert(!_crashlog_fd);
2820 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2821 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2822 PBD::error << "Cannot create AU error-log" << fn << "\n";
2823 cerr << "Cannot create AU error-log" << fn << "\n";
2828 AUPluginInfo::au_remove_crashlog ()
2831 ::fclose(_crashlog_fd);
2832 _crashlog_fd = NULL;
2834 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2835 ::g_unlink(fn.c_str());
2836 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2841 AUPluginInfo::au_crashlog (std::string msg)
2843 if (!_crashlog_fd) {
2844 fprintf(stderr, "AU: %s\n", msg.c_str());
2846 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2847 ::fflush(_crashlog_fd);
2852 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2854 ArdourComponent comp = 0;
2855 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2857 comp = ArdourFindNext (NULL, &desc);
2859 while (comp != NULL) {
2860 CAComponentDescription temp;
2862 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2864 AudioComponentGetDescription (comp, &temp);
2866 CFStringRef itemName = NULL;
2869 if (itemName != NULL) CFRelease(itemName);
2870 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2871 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2872 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2873 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2874 compTypeString, compManufacturerString, compSubTypeString);
2875 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2876 if (compTypeString != NULL)
2877 CFRelease(compTypeString);
2878 if (compSubTypeString != NULL)
2879 CFRelease(compSubTypeString);
2880 if (compManufacturerString != NULL)
2881 CFRelease(compManufacturerString);
2884 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2885 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2886 comp = ArdourFindNext (comp, &desc);
2890 bool has_midi_in = false;
2892 AUPluginInfoPtr info (new AUPluginInfo
2893 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2895 /* although apple designed the subtype field to be a "category" indicator,
2896 its really turned into a plugin ID field for a given manufacturer. Hence
2897 there are no categories for AudioUnits. However, to keep the plugins
2898 showing up under "categories", we'll use the "type" as a high level
2901 NOTE: no panners, format converters or i/o AU's for our purposes
2904 switch (info->descriptor->Type()) {
2905 case kAudioUnitType_Panner:
2906 case kAudioUnitType_OfflineEffect:
2907 case kAudioUnitType_FormatConverter:
2908 comp = ArdourFindNext (comp, &desc);
2911 case kAudioUnitType_Output:
2912 info->category = _("AudioUnit Outputs");
2914 case kAudioUnitType_MusicDevice:
2915 info->category = _("AudioUnit Instruments");
2918 case kAudioUnitType_MusicEffect:
2919 info->category = _("AudioUnit MusicEffects");
2922 case kAudioUnitType_Effect:
2923 info->category = _("AudioUnit Effects");
2925 case kAudioUnitType_Mixer:
2926 info->category = _("AudioUnit Mixers");
2928 case kAudioUnitType_Generator:
2929 info->category = _("AudioUnit Generators");
2932 info->category = _("AudioUnit (Unknown)");
2936 au_blacklist(CFStringRefToStdString(itemName));
2938 get_names (temp, info->name, info->creator);
2940 get_names (comp, info->name, info->creator);
2942 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2943 au_crashlog(string_compose("Plugin: %1", info->name));
2945 info->type = ARDOUR::AudioUnit;
2946 info->unique_id = stringify_descriptor (*info->descriptor);
2948 /* XXX not sure of the best way to handle plugin versioning yet */
2950 CAComponent cacomp (*info->descriptor);
2953 if (cacomp.GetResourceVersion (info->version) != noErr)
2955 if (cacomp.GetVersion (info->version) != noErr)
2961 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2964 /* here we have to map apple's wildcard system to a simple pair
2965 of values. in ::can_do() we use the whole system, but here
2966 we need a single pair of values. XXX probably means we should
2967 remove any use of these values.
2969 for now, if the plugin provides a wildcard, treat it as 1. we really
2970 don't care much, because whether we can handle an i/o configuration
2971 depends upon ::can_support_io_configuration(), not these counts.
2973 they exist because other parts of ardour try to present i/o configuration
2974 info to the user, which should perhaps be revisited.
2977 int32_t possible_in = info->cache.io_configs.front().first;
2978 int32_t possible_out = info->cache.io_configs.front().second;
2980 if (possible_in > 0) {
2981 info->n_inputs.set (DataType::AUDIO, possible_in);
2983 info->n_inputs.set (DataType::AUDIO, 1);
2986 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
2988 if (possible_out > 0) {
2989 info->n_outputs.set (DataType::AUDIO, possible_out);
2991 info->n_outputs.set (DataType::AUDIO, 1);
2994 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2995 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2997 plugs.push_back (info);
3000 else if (rv == -1) {
3001 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
3004 au_unblacklist(CFStringRefToStdString(itemName));
3005 au_crashlog("Success.");
3006 comp = ArdourFindNext (comp, &desc);
3007 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
3009 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
3013 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
3016 AUPluginCachedInfo& cinfo,
3017 const std::string& name)
3022 /* concatenate unique ID with version to provide a key for cached info lookup.
3023 this ensures we don't get stale information, or should if plugin developers
3024 follow Apple "guidelines".
3027 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
3032 CachedInfoMap::iterator cim = cached_info.find (id);
3034 if (cim != cached_info.end()) {
3035 cinfo = cim->second;
3040 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
3045 AUChannelInfo* channel_info;
3049 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
3053 if (CAAudioUnit::Open (comp, unit) != noErr) {
3059 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
3064 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
3065 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
3070 /* AU is expected to deal with same channel valance in and out */
3071 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
3073 /* CAAudioUnit::GetChannelInfo silently merges bus formats
3074 * check if this was the case and if so, add
3075 * bus configs as incremental options.
3077 Boolean* isWritable = 0;
3078 UInt32 dataSize = 0;
3079 OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
3080 kAudioUnitProperty_SupportedNumChannels,
3081 kAudioUnitScope_Global, 0,
3082 &dataSize, isWritable);
3083 if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
3084 /* incrementally add busses */
3087 for (uint32_t n = 0; n < cnt; ++n) {
3088 in += channel_info[n].inChannels;
3089 out += channel_info[n].outChannels;
3090 cinfo.io_configs.push_back (pair<int,int> (in, out));
3093 /* store each configuration */
3094 for (uint32_t n = 0; n < cnt; ++n) {
3095 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
3096 channel_info[n].outChannels));
3100 free (channel_info);
3103 add_cached_info (id, cinfo);
3104 save_cached_info ();
3110 AUPluginInfo::clear_cache ()
3112 const string& fn = au_cache_path();
3113 if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
3114 ::g_unlink(fn.c_str());
3116 // keep cached_info in RAM until restart or re-scan
3117 cached_info.clear();
3121 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
3123 cached_info[id] = cinfo;
3126 #define AU_CACHE_VERSION "2.0"
3129 AUPluginInfo::save_cached_info ()
3133 node = new XMLNode (X_("AudioUnitPluginCache"));
3134 node->add_property( "version", AU_CACHE_VERSION );
3136 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
3137 XMLNode* parent = new XMLNode (X_("plugin"));
3138 parent->add_property ("id", i->first);
3139 node->add_child_nocopy (*parent);
3141 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
3143 XMLNode* child = new XMLNode (X_("io"));
3146 snprintf (buf, sizeof (buf), "%d", j->first);
3147 child->add_property (X_("in"), buf);
3148 snprintf (buf, sizeof (buf), "%d", j->second);
3149 child->add_property (X_("out"), buf);
3150 parent->add_child_nocopy (*child);
3155 Glib::ustring path = au_cache_path ();
3158 tree.set_root (node);
3160 if (!tree.write (path)) {
3161 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
3162 g_unlink (path.c_str());
3167 AUPluginInfo::load_cached_info ()
3169 Glib::ustring path = au_cache_path ();
3172 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
3176 if ( !tree.read (path) ) {
3177 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
3181 const XMLNode* root (tree.root());
3183 if (root->name() != X_("AudioUnitPluginCache")) {
3187 //initial version has incorrectly stored i/o info, and/or garbage chars.
3188 XMLProperty const * version = root->property(X_("version"));
3189 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
3190 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
3194 cached_info.clear ();
3196 const XMLNodeList children = root->children();
3198 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
3200 const XMLNode* child = *iter;
3202 if (child->name() == X_("plugin")) {
3204 const XMLNode* gchild;
3205 const XMLNodeList gchildren = child->children();
3206 XMLProperty const * prop = child->property (X_("id"));
3212 string id = prop->value();
3216 string::size_type slash = id.find_last_of ('/');
3218 if (slash == string::npos) {
3222 version = id.substr (slash);
3223 id = id.substr (0, slash);
3224 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3226 if (fixed.empty()) {
3227 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3234 AUPluginCachedInfo cinfo;
3236 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3240 if (gchild->name() == X_("io")) {
3244 XMLProperty const * iprop;
3245 XMLProperty const * oprop;
3247 if (((iprop = gchild->property (X_("in"))) != 0) &&
3248 ((oprop = gchild->property (X_("out"))) != 0)) {
3249 in = atoi (iprop->value());
3250 out = atoi (oprop->value());
3252 cinfo.io_configs.push_back (pair<int,int> (in, out));
3257 if (cinfo.io_configs.size()) {
3258 add_cached_info (id, cinfo);
3268 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3272 /* note: OSType is a compiler-implemenation-defined value,
3273 historically a 32 bit integer created with a multi-character
3274 constant such as 'abcd'. It is, fundamentally, an abomination.
3279 s << desc.SubType();
3287 AUPluginInfo::needs_midi_input () const
3289 return is_effect_with_midi_input () || is_instrument ();
3293 AUPluginInfo::is_effect () const
3295 return is_effect_without_midi_input() || is_effect_with_midi_input();
3299 AUPluginInfo::is_effect_without_midi_input () const
3301 return descriptor->IsAUFX();
3305 AUPluginInfo::is_effect_with_midi_input () const
3307 return descriptor->IsAUFM();
3311 AUPluginInfo::is_instrument () const
3313 return descriptor->IsMusicDevice();
3317 AUPlugin::set_info (PluginInfoPtr info)
3319 Plugin::set_info (info);
3321 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3322 _has_midi_input = pinfo->needs_midi_input ();
3323 _has_midi_output = false;
3327 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3330 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3332 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3334 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3336 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3340 _parameter_listener_arg = arg;
3346 AUPlugin::listen_to_parameter (uint32_t param_id)
3348 AudioUnitEvent event;
3350 if (!_parameter_listener || param_id >= descriptors.size()) {
3354 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3355 event.mArgument.mParameter.mAudioUnit = unit->AU();
3356 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3357 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3358 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3360 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3364 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3365 event.mArgument.mParameter.mAudioUnit = unit->AU();
3366 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3367 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3368 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3370 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3374 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3375 event.mArgument.mParameter.mAudioUnit = unit->AU();
3376 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3377 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3378 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3380 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3388 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3390 AudioUnitEvent event;
3392 if (!_parameter_listener || param_id >= descriptors.size()) {
3396 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3397 event.mArgument.mParameter.mAudioUnit = unit->AU();
3398 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3399 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3400 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3402 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3406 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3407 event.mArgument.mParameter.mAudioUnit = unit->AU();
3408 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3409 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3410 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3412 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3416 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3417 event.mArgument.mParameter.mAudioUnit = unit->AU();
3418 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3419 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3420 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3422 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3430 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3432 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3436 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3438 ParameterMap::iterator i;
3440 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3444 switch (event->mEventType) {
3445 case kAudioUnitEvent_BeginParameterChangeGesture:
3446 StartTouch (i->second);
3448 case kAudioUnitEvent_EndParameterChangeGesture:
3449 EndTouch (i->second);
3451 case kAudioUnitEvent_ParameterValueChange:
3452 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3453 means that something else (i.e. the plugin GUI) made the change.
3455 ParameterChangedExternally (i->second, new_value);