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 , last_transport_rolling (false)
452 , last_transport_speed (0.0)
454 if (!preset_search_path_initialized) {
455 Glib::ustring p = Glib::get_home_dir();
456 p += "/Library/Audio/Presets:";
457 p += preset_search_path;
458 preset_search_path = p;
459 preset_search_path_initialized = true;
460 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
467 AUPlugin::AUPlugin (const AUPlugin& other)
469 , comp (other.get_comp())
470 , unit (new CAAudioUnit)
471 , initialized (false)
472 , _current_block_size (0)
474 , _requires_fixed_size_buffers (false)
476 , variable_inputs (false)
477 , variable_outputs (false)
478 , configured_input_busses (0)
479 , configured_output_busses (0)
486 , frames_processed (0)
487 , _parameter_listener (0)
488 , _parameter_listener_arg (0)
492 for (size_t i = 0; i < descriptors.size(); ++i) {
493 set_parameter (i, other.get_parameter (i));
497 AUPlugin::~AUPlugin ()
499 if (_parameter_listener) {
500 AUListenerDispose (_parameter_listener);
501 _parameter_listener = 0;
505 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
506 unit->Uninitialize ();
516 AUPlugin::discover_factory_presets ()
523 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
524 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
528 assert (dataSize == sizeof (presets));
530 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
531 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
539 CFIndex cnt = CFArrayGetCount (presets);
541 for (CFIndex i = 0; i < cnt; ++i) {
542 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
544 string name = CFStringRefToStdString (preset->presetName);
545 factory_preset_map[name] = preset->presetNumber;
546 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
556 CFStringRef itemName;
558 /* these keep track of *configured* channel set up,
559 not potential set ups.
563 output_channels = -1;
565 CAComponentDescription temp;
567 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
569 AudioComponentGetDescription (comp.get()->Comp(), &temp);
571 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
572 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
573 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
574 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
575 compTypeString, compManufacturerString, compSubTypeString);
576 if (compTypeString != NULL) CFRelease(compTypeString);
577 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
578 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
581 au_blacklist(CFStringRefToStdString(itemName));
584 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
585 err = CAAudioUnit::Open (*(comp.get()), *unit);
587 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
588 throw failed_constructor();
592 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
593 throw failed_constructor ();
596 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
597 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
598 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
599 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
600 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
601 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
603 cb_offsets = (framecnt_t*) calloc (input_elements, sizeof(uint32_t));
604 bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
605 bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
607 for (size_t i = 0; i < output_elements; ++i) {
608 unit->Reset (kAudioUnitScope_Output, i);
609 AudioStreamBasicDescription fmt;
610 err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
612 bus_outputs[i] = fmt.mChannelsPerFrame;
615 UInt32 sz = sizeof (CFStringRef);
616 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
617 i, &name, &sz) == noErr
619 _bus_name_out.push_back (CFStringRefToStdString (name));
622 _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
626 for (size_t i = 0; i < input_elements; ++i) {
627 unit->Reset (kAudioUnitScope_Input, i);
628 AudioStreamBasicDescription fmt;
629 err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
631 bus_inputs[i] = fmt.mChannelsPerFrame;
634 UInt32 sz = sizeof (CFStringRef);
635 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
636 i, &name, &sz) == noErr
638 _bus_name_in.push_back (CFStringRefToStdString (name));
641 _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
645 for (size_t i = 0; i < input_elements; ++i) {
646 /* setup render callback: the plugin calls this to get input data */
647 AURenderCallbackStruct renderCallbackInfo;
648 renderCallbackInfo.inputProc = _render_callback;
649 renderCallbackInfo.inputProcRefCon = this;
650 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
651 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
652 i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
653 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
654 throw failed_constructor();
658 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
660 HostCallbackInfo info;
661 memset (&info, 0, sizeof (HostCallbackInfo));
662 info.hostUserData = this;
663 info.beatAndTempoProc = _get_beat_and_tempo_callback;
664 info.musicalTimeLocationProc = _get_musical_time_location_callback;
665 info.transportStateProc = _get_transport_state_callback;
667 //ignore result of this - don't care if the property isn't supported
668 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
669 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
670 kAudioUnitScope_Global,
673 sizeof (HostCallbackInfo));
675 if (set_block_size (_session.get_block_size())) {
676 error << _("AUPlugin: cannot set processing block size") << endmsg;
677 throw failed_constructor();
680 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
681 discover_parameters ();
682 discover_factory_presets ();
684 // Plugin::setup_controls ();
686 au_unblacklist(CFStringRefToStdString(itemName));
687 if (itemName != NULL) CFRelease(itemName);
691 AUPlugin::discover_parameters ()
693 /* discover writable parameters */
695 AudioUnitScope scopes[] = {
696 kAudioUnitScope_Global,
697 kAudioUnitScope_Output,
698 kAudioUnitScope_Input
701 descriptors.clear ();
703 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
705 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
707 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
709 AUParameterDescriptor d;
711 d.id = param_info.ParamID (i);
713 const CAAUParameter* param = param_info.GetParamInfo (d.id);
714 const AudioUnitParameterInfo& info (param->ParamInfo());
716 const int len = CFStringGetLength (param->GetName());
717 char local_buffer[len*2];
718 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
722 d.label = local_buffer;
725 d.scope = param_info.GetScope ();
726 d.element = param_info.GetElement ();
728 /* info.units to consider */
730 kAudioUnitParameterUnit_Generic = 0
731 kAudioUnitParameterUnit_Indexed = 1
732 kAudioUnitParameterUnit_Boolean = 2
733 kAudioUnitParameterUnit_Percent = 3
734 kAudioUnitParameterUnit_Seconds = 4
735 kAudioUnitParameterUnit_SampleFrames = 5
736 kAudioUnitParameterUnit_Phase = 6
737 kAudioUnitParameterUnit_Rate = 7
738 kAudioUnitParameterUnit_Hertz = 8
739 kAudioUnitParameterUnit_Cents = 9
740 kAudioUnitParameterUnit_RelativeSemiTones = 10
741 kAudioUnitParameterUnit_MIDINoteNumber = 11
742 kAudioUnitParameterUnit_MIDIController = 12
743 kAudioUnitParameterUnit_Decibels = 13
744 kAudioUnitParameterUnit_LinearGain = 14
745 kAudioUnitParameterUnit_Degrees = 15
746 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
747 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
748 kAudioUnitParameterUnit_Pan = 18
749 kAudioUnitParameterUnit_Meters = 19
750 kAudioUnitParameterUnit_AbsoluteCents = 20
751 kAudioUnitParameterUnit_Octaves = 21
752 kAudioUnitParameterUnit_BPM = 22
753 kAudioUnitParameterUnit_Beats = 23
754 kAudioUnitParameterUnit_Milliseconds = 24
755 kAudioUnitParameterUnit_Ratio = 25
758 /* info.flags to consider */
762 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
763 kAudioUnitParameterFlag_HasClump = (1L << 20)
764 kAudioUnitParameterFlag_HasName = (1L << 21)
765 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
766 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
767 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
768 kAudioUnitParameterFlag_CanRamp = (1L << 25)
769 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
770 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
771 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
772 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
773 kAudioUnitParameterFlag_IsReadable = (1L << 30)
774 kAudioUnitParameterFlag_IsWritable = (1L << 31)
777 d.lower = info.minValue;
778 d.upper = info.maxValue;
779 d.normal = info.defaultValue;
781 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
782 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
783 (d.integer_step && ((d.upper - d.lower) == 1.0));
784 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
785 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
786 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
787 (info.flags & kAudioUnitParameterFlag_IsWritable);
789 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
790 d.au_unit = info.unit;
792 case kAudioUnitParameterUnit_Decibels:
793 d.unit = ParameterDescriptor::DB;
795 case kAudioUnitParameterUnit_MIDINoteNumber:
796 d.unit = ParameterDescriptor::MIDI_NOTE;
798 case kAudioUnitParameterUnit_Hertz:
799 d.unit = ParameterDescriptor::HZ;
803 d.min_unbound = 0; // lower is bound
804 d.max_unbound = 0; // upper is bound
807 descriptors.push_back (d);
809 uint32_t last_param = descriptors.size() - 1;
810 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
811 listen_to_parameter (last_param);
818 four_ints_to_four_byte_literal (unsigned char n[4])
820 /* this is actually implementation dependent. sigh. this is what gcc
821 and quite a few others do.
823 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
827 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
829 if (isdigit (id[0])) {
833 /* ID format is xxxx-xxxx-xxxx
834 where x maybe \xNN or a printable character.
836 Split at the '-' and and process each part into an integer.
837 Then put it back together.
841 unsigned char nascent[4];
842 const char* cstr = id.c_str();
843 const char* estr = cstr + id.size();
854 while (*cstr && next_int < 4) {
858 if (estr - cstr < 3) {
860 /* too close to the end for \xNN parsing: treat as literal characters */
868 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
872 memcpy (short_buf, &cstr[2], 2);
873 nascent[in] = strtol (short_buf, NULL, 16);
879 /* treat as literal characters */
893 if (in && (in % 4 == 0)) {
894 /* nascent is ready */
895 n[next_int] = four_ints_to_four_byte_literal (nascent);
899 /* swallow space-hyphen-space */
913 s << n[0] << '-' << n[1] << '-' << n[2];
922 AUPlugin::unique_id () const
924 return AUPluginInfo::stringify_descriptor (comp->Desc());
928 AUPlugin::label () const
930 return _info->name.c_str();
934 AUPlugin::parameter_count () const
936 return descriptors.size();
940 AUPlugin::default_value (uint32_t port)
942 if (port < descriptors.size()) {
943 return descriptors[port].normal;
950 AUPlugin::signal_latency () const
952 return unit->Latency() * _session.frame_rate();
956 AUPlugin::set_parameter (uint32_t which, float val)
958 if (which >= descriptors.size()) {
962 if (get_parameter(which) == val) {
966 const AUParameterDescriptor& d (descriptors[which]);
967 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
968 unit->SetParameter (d.id, d.scope, d.element, val);
970 /* tell the world what we did */
972 AudioUnitEvent theEvent;
974 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
975 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
976 theEvent.mArgument.mParameter.mParameterID = d.id;
977 theEvent.mArgument.mParameter.mScope = d.scope;
978 theEvent.mArgument.mParameter.mElement = d.element;
980 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
981 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
982 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
984 Plugin::set_parameter (which, val);
988 AUPlugin::get_parameter (uint32_t which) const
991 if (which < descriptors.size()) {
992 const AUParameterDescriptor& d (descriptors[which]);
993 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
994 unit->GetParameter(d.id, d.scope, d.element, val);
1000 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
1002 if (which < descriptors.size()) {
1003 pd = descriptors[which];
1010 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
1012 if (which < descriptors.size()) {
1021 AUPlugin::activate ()
1025 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
1026 if ((err = unit->Initialize()) != noErr) {
1027 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
1029 frames_processed = 0;
1036 AUPlugin::deactivate ()
1038 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
1039 unit->Uninitialize ();
1040 initialized = false;
1046 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
1047 unit->GlobalReset ();
1051 AUPlugin::requires_fixed_size_buffers() const
1053 return _requires_fixed_size_buffers;
1058 AUPlugin::set_block_size (pframes_t nframes)
1060 bool was_initialized = initialized;
1061 UInt32 numFrames = nframes;
1068 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
1069 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1070 0, &numFrames, sizeof (numFrames))) != noErr) {
1071 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
1075 if (was_initialized) {
1079 _current_block_size = nframes;
1085 AUPlugin::configure_io (ChanCount in, ChanCount out)
1087 AudioStreamBasicDescription streamFormat;
1088 bool was_initialized = initialized;
1089 int32_t audio_out = out.n_audio();
1090 if (audio_input_cnt > 0) {
1091 in.set (DataType::AUDIO, audio_input_cnt);
1093 const int32_t audio_in = in.n_audio();
1095 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1098 //if we are already running with the requested i/o config, bail out here
1099 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1106 streamFormat.mSampleRate = _session.frame_rate();
1107 streamFormat.mFormatID = kAudioFormatLinearPCM;
1108 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1110 #ifdef __LITTLE_ENDIAN__
1113 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1116 streamFormat.mBitsPerChannel = 32;
1117 streamFormat.mFramesPerPacket = 1;
1119 /* apple says that for non-interleaved data, these
1120 * values always refer to a single channel.
1122 streamFormat.mBytesPerPacket = 4;
1123 streamFormat.mBytesPerFrame = 4;
1125 configured_input_busses = 0;
1126 configured_output_busses = 0;
1128 for (size_t i = 0; i < output_elements; ++i) {
1129 unit->Reset (kAudioUnitScope_Output, i);
1131 for (size_t i = 0; i < input_elements; ++i) {
1132 unit->Reset (kAudioUnitScope_Input, i);
1135 /* now assign the channels to available busses */
1136 uint32_t used_in = 0;
1137 uint32_t used_out = 0;
1139 if (variable_inputs || input_elements == 1) {
1140 // we only ever use the first bus
1141 if (input_elements > 1) {
1142 warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
1144 streamFormat.mChannelsPerFrame = audio_in;
1145 if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
1148 configured_input_busses = 1;
1151 configured_input_busses = 0;
1152 uint32_t remain = audio_in;
1153 for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
1154 uint32_t cnt = std::min (remain, bus_inputs[bus]);
1155 if (cnt == 0) { continue; }
1156 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
1158 streamFormat.mChannelsPerFrame = cnt;
1159 if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
1163 ++configured_input_busses;
1168 if (variable_outputs || output_elements == 1) {
1169 if (output_elements > 1) {
1170 warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
1173 streamFormat.mChannelsPerFrame = audio_out;
1174 if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
1177 configured_output_busses = 1;
1178 used_out = audio_out;
1180 uint32_t remain = audio_out;
1181 configured_output_busses = 0;
1182 for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
1183 uint32_t cnt = std::min (remain, bus_outputs[bus]);
1184 if (cnt == 0) { continue; }
1185 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
1186 streamFormat.mChannelsPerFrame = cnt;
1187 if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
1192 ++configured_output_busses;
1197 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1198 used_out * sizeof(::AudioBuffer));
1200 input_channels = used_in;
1201 output_channels = used_out;
1202 /* reset plugin info to show currently configured state */
1204 _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
1205 _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
1207 if (was_initialized) {
1215 AUPlugin::input_streams() const
1218 if (input_channels < 0) {
1219 // force PluginIoReConfigure -- see also commit msg e38eb06
1220 c.set (DataType::AUDIO, 0);
1221 c.set (DataType::MIDI, 0);
1223 c.set (DataType::AUDIO, input_channels);
1224 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1231 AUPlugin::output_streams() const
1234 if (output_channels < 0) {
1235 // force PluginIoReConfigure - see also commit msg e38eb06
1236 c.set (DataType::AUDIO, 0);
1237 c.set (DataType::MIDI, 0);
1239 c.set (DataType::AUDIO, output_channels);
1240 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1246 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1248 _output_configs.clear ();
1249 const int32_t audio_in = in.n_audio();
1250 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1252 /* lets check MIDI first */
1254 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1258 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1260 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1261 name(), io_configs.size(), in, out));
1264 printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
1265 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1266 printf ("- I/O %d / %d\n", i->first, i->second);
1270 // preferred setting (provided by plugin_insert)
1271 const int preferred_out = out.n_audio ();
1273 bool exact_match = false;
1275 /* kAudioUnitProperty_SupportedNumChannels
1276 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1278 * - both fields are -1
1279 * e.g. inChannels = -1 outChannels = -1
1280 * This is the default case. Any number of input and output channels, as long as the numbers match
1282 * - one field is -1, the other field is positive
1283 * e.g. inChannels = -1 outChannels = 2
1284 * Any number of input channels, exactly two output channels
1286 * - one field is -1, the other field is -2
1287 * e.g. inChannels = -1 outChannels = -2
1288 * Any number of input channels, any number of output channels
1290 * - both fields have non-negative values
1291 * e.g. inChannels = 2 outChannels = 6
1292 * Exactly two input channels, exactly six output channels
1293 * e.g. inChannels = 0 outChannels = 2
1294 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1296 * - both fields have negative values, neither of which is –1 or –2
1297 * e.g. inChannels = -4 outChannels = -8
1298 * Up to four input channels and up to eight output channels
1301 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1303 int32_t possible_in = i->first;
1304 int32_t possible_out = i->second;
1306 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1307 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1308 possible_in, possible_out,
1312 _output_configs.insert (preferred_out);
1319 /* now allow potentially "imprecise" matches */
1320 int32_t audio_out = -1;
1321 float penalty = 9999;
1322 int used_possible_in = 0;
1323 #if defined (__clang__)
1324 # pragma clang diagnostic push
1325 # pragma clang diagnostic ignored "-Wtautological-compare"
1328 #define FOUNDCFG(nch) { \
1329 float p = fabsf ((float)(nch) - preferred_out); \
1330 _output_configs.insert (nch); \
1331 if ((nch) > preferred_out) { p *= 1.1; } \
1332 if (p < penalty) { \
1333 used_possible_in = possible_in; \
1334 audio_out = (nch); \
1337 variable_inputs = possible_in < 0; \
1338 variable_outputs = possible_out < 0; \
1342 #define ANYTHINGGOES \
1343 _output_configs.insert (0);
1345 #define UPTO(nch) { \
1346 for (int n = 1; n <= nch; ++n) { \
1347 _output_configs.insert (n); \
1351 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1353 int32_t possible_in = i->first;
1354 int32_t possible_out = i->second;
1356 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1358 if (possible_out == 0) {
1359 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1360 /* XXX surely this is just a send? (e.g. AUNetSend) */
1364 if (possible_in == 0) {
1365 /* no inputs, generators & instruments */
1366 if (possible_out == -1) {
1367 /* any configuration possible, provide stereo output */
1368 FOUNDCFG (preferred_out);
1370 } else if (possible_out == -2) {
1371 /* invalid, should be (0, -1) */
1372 FOUNDCFG (preferred_out);
1374 } else if (possible_out < -2) {
1375 /* variable number of outputs up to -N, */
1376 FOUNDCFG (min (-possible_out, preferred_out));
1377 UPTO (-possible_out);
1379 /* exact number of outputs */
1380 FOUNDCFG (possible_out);
1384 if (possible_in == -1) {
1385 /* wildcard for input */
1386 if (possible_out == -1) {
1387 /* out must match in */
1388 FOUNDCFG (audio_in);
1389 } else if (possible_out == -2) {
1390 /* any configuration possible, pick matching */
1391 FOUNDCFG (preferred_out);
1393 } else if (possible_out < -2) {
1394 /* explicitly variable number of outputs, pick maximum */
1395 FOUNDCFG (max (-possible_out, preferred_out));
1396 /* and try min, too, in case the penalty is lower */
1397 FOUNDCFG (min (-possible_out, preferred_out));
1398 UPTO (-possible_out)
1400 /* exact number of outputs */
1401 FOUNDCFG (possible_out);
1405 if (possible_in == -2) {
1406 if (possible_out == -1) {
1407 /* any configuration possible, pick matching */
1408 FOUNDCFG (preferred_out);
1410 } else if (possible_out == -2) {
1411 /* invalid. interpret as (-1, -1) */
1412 FOUNDCFG (preferred_out);
1414 } else if (possible_out < -2) {
1415 /* invalid, interpret as (<-2, <-2)
1416 * variable number of outputs up to -N, */
1417 FOUNDCFG (min (-possible_out, preferred_out));
1418 UPTO (-possible_out)
1420 /* exact number of outputs */
1421 FOUNDCFG (possible_out);
1425 if (possible_in < -2) {
1426 /* explicit variable number of inputs */
1427 if (audio_in > -possible_in && imprecise != NULL) {
1428 // hide inputs ports
1429 imprecise->set (DataType::AUDIO, -possible_in);
1432 if (audio_in > -possible_in && imprecise == NULL) {
1433 /* request is too large */
1434 } else if (possible_out == -1) {
1435 /* any output configuration possible */
1436 FOUNDCFG (preferred_out);
1438 } else if (possible_out == -2) {
1439 /* invalid. interpret as (<-2, -1) */
1440 FOUNDCFG (preferred_out);
1442 } else if (possible_out < -2) {
1443 /* variable number of outputs up to -N, */
1444 FOUNDCFG (min (-possible_out, preferred_out));
1445 UPTO (-possible_out)
1447 /* exact number of outputs */
1448 FOUNDCFG (possible_out);
1452 if (possible_in && (possible_in == audio_in)) {
1453 /* exact number of inputs ... must match obviously */
1454 if (possible_out == -1) {
1455 /* any output configuration possible */
1456 FOUNDCFG (preferred_out);
1458 } else if (possible_out == -2) {
1459 /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
1460 FOUNDCFG (preferred_out);
1462 } else if (possible_out < -2) {
1463 /* > 0, < -2 is not specified
1464 * interpret as up to -N */
1465 FOUNDCFG (min (-possible_out, preferred_out));
1466 UPTO (-possible_out)
1468 /* exact number of outputs */
1469 FOUNDCFG (possible_out);
1474 if (!found && imprecise) {
1476 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1477 int32_t possible_in = i->first;
1478 int32_t possible_out = i->second;
1480 assert (possible_in > 0); // all other cases will have been matched above
1481 assert (possible_out !=0 || possible_in !=0); // already handled above
1483 imprecise->set (DataType::AUDIO, possible_in);
1484 if (possible_out == -1 || possible_out == -2) {
1486 } else if (possible_out < -2) {
1487 /* explicitly variable number of outputs, pick maximum */
1488 FOUNDCFG (min (-possible_out, preferred_out));
1490 /* exact number of outputs */
1491 FOUNDCFG (possible_out);
1493 // ideally we'll also find the closest, best matching
1494 // input configuration with minimal output penalty...
1499 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1504 out.set (DataType::MIDI, 0); // currently always zero
1505 out.set (DataType::AUDIO, preferred_out);
1507 if (used_possible_in < -2 && audio_in == 0) {
1508 // input-port count cannot be zero, use as many ports
1509 // as outputs, but at most abs(possible_in)
1510 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1512 out.set (DataType::MIDI, 0); /// XXX
1513 out.set (DataType::AUDIO, audio_out);
1515 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1517 #if defined (__clang__)
1518 # pragma clang diagnostic pop
1524 AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
1528 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1529 (scope == kAudioUnitScope_Input ? "input" : "output"),
1531 if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
1532 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1533 (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
1540 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1541 const AudioTimeStamp*,
1543 UInt32 inNumberFrames,
1544 AudioBufferList* ioData)
1546 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1548 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bus %3 bufs %4\n",
1549 // name(), inNumberFrames, bus, ioData->mNumberBuffers));
1551 if (input_maxbuf == 0) {
1552 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1553 error << _("AUPlugin: render callback called illegally!") << endmsg;
1554 return kAudioUnitErr_CannotDoInCurrentContext;
1557 assert (bus < input_elements);
1558 uint32_t busoff = 0;
1559 for (uint32_t i = 0; i < bus; ++i) {
1560 busoff += bus_inputs[i];
1563 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1565 ChanCount bufs_count (DataType::AUDIO, 1);
1566 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1568 /* apply bus offsets */
1570 for (uint32_t i = 0; i < limit; ++i) {
1571 ioData->mBuffers[i].mNumberChannels = 1;
1572 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1575 uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
1577 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
1579 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
1582 cb_offsets[bus] += inNumberFrames;
1587 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1589 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1591 AudioUnitRenderActionFlags flags = 0;
1595 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1596 unit->GlobalReset();
1597 _last_nframes = nframes;
1600 /* test if we can run in-place; only compare audio buffers */
1601 bool inplace = true; // TODO check plugin-insert in-place ?
1602 ChanMapping::Mappings inmap (in_map.mappings ());
1603 ChanMapping::Mappings outmap (out_map.mappings ());
1604 assert (outmap[DataType::AUDIO].size () > 0);
1605 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1609 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",
1610 name(), input_channels, output_channels, _has_midi_input,
1611 bufs.count(), bufs.available(),
1612 configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
1614 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1615 * has the capacity to handle our outputs.
1618 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1620 input_buffers = &bufs;
1621 input_map = &in_map;
1622 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1623 input_offset = offset;
1624 for (size_t i = 0; i < input_elements; ++i) {
1628 ChanCount bufs_count (DataType::AUDIO, 1);
1629 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1631 if (_has_midi_input) {
1632 uint32_t nmidi = bufs.count().n_midi();
1633 for (uint32_t i = 0; i < nmidi; ++i) {
1634 /* one MIDI port/buffer only */
1635 MidiBuffer& m = bufs.get_midi (i);
1636 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1637 Evoral::MIDIEvent<framepos_t> ev (*i);
1638 if (ev.is_channel_event()) {
1639 const uint8_t* b = ev.buffer();
1640 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1641 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1643 /* XXX need to handle sysex and other message types */
1648 assert (input_maxbuf < 512);
1649 std::bitset<512> used_outputs;
1652 uint32_t busoff = 0;
1653 uint32_t remain = output_channels;
1654 for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
1656 if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
1657 cnt = output_channels;
1659 cnt = std::min (remain, bus_outputs[bus]);
1663 buffers->mNumberBuffers = cnt;
1665 for (uint32_t i = 0; i < cnt; ++i) {
1666 buffers->mBuffers[i].mNumberChannels = 1;
1667 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1668 /* setting this to 0 indicates to the AU that it can provide buffers here
1669 * if necessary. if it can process in-place, it will use the buffers provided
1670 * as input by ::render_callback() above.
1672 * a non-null values tells the plugin to render into the buffer pointed
1676 buffers->mBuffers[i].mData = 0;
1679 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1681 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1683 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1688 /* does this really mean anything ? */
1689 ts.mSampleTime = frames_processed;
1690 ts.mFlags = kAudioTimeStampSampleTimeValid;
1692 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
1693 name(), flags, frames_processed, nframes, bus, buffers->mNumberBuffers));
1695 if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
1697 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1698 name(), buffers->mNumberBuffers, output_channels));
1700 uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
1701 for (uint32_t i = 0; i < limit; ++i) {
1703 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1704 if (!valid) continue;
1705 used_outputs.set (i + busoff);
1706 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1707 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1708 /* plugin provided its own buffer for output so copy it back to where we want it */
1709 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1713 DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
1714 error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
1720 busoff += bus_outputs[bus];
1723 /* now silence any buffers that were passed in but the that the plugin
1724 * did not fill/touch/use.
1726 * TODO: optimize, when plugin-insert is processing in-place
1727 * unconnected buffers are (also) cleared there.
1729 for (uint32_t i = 0; i < input_maxbuf; ++i) {
1730 if (used_outputs.test (i)) { continue; }
1732 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1733 if (!valid) continue;
1734 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1740 frames_processed += nframes;
1747 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1748 Float64* outCurrentTempo)
1750 TempoMap& tmap (_session.tempo_map());
1752 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1754 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1755 (and interpretation) of a beat position will be incorrect. So refuse to
1759 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1760 return kAudioUnitErr_CannotDoInCurrentContext;
1763 Timecode::BBT_Time bbt;
1764 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1765 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1767 if (outCurrentBeat) {
1768 const double ppq_scaling = metric.meter().note_divisor() / 4.0;
1770 beat = metric.meter().divisions_per_bar() * (bbt.bars - 1);
1771 beat += (bbt.beats - 1);
1772 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1773 *outCurrentBeat = beat * ppq_scaling;
1776 if (outCurrentTempo) {
1777 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1785 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1786 Float32* outTimeSig_Numerator,
1787 UInt32* outTimeSig_Denominator,
1788 Float64* outCurrentMeasureDownBeat)
1790 TempoMap& tmap (_session.tempo_map());
1792 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1794 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1795 (and interpretation) of a beat position will be incorrect. So refuse to
1799 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1800 return kAudioUnitErr_CannotDoInCurrentContext;
1803 Timecode::BBT_Time bbt;
1804 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1805 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1807 if (outDeltaSampleOffsetToNextBeat) {
1808 if (bbt.ticks == 0) {
1810 *outDeltaSampleOffsetToNextBeat = 0;
1812 double const beat_frac_to_next = (Timecode::BBT_Time::ticks_per_beat - bbt.ticks) / Timecode::BBT_Time::ticks_per_beat;
1813 *outDeltaSampleOffsetToNextBeat = tmap.frame_at_beat (tmap.beat_at_frame (_session.transport_frame() + input_offset) + beat_frac_to_next);
1817 if (outTimeSig_Numerator) {
1818 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1820 if (outTimeSig_Denominator) {
1821 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1824 if (outCurrentMeasureDownBeat) {
1826 /* beat for the start of the bar.
1828 2|1|0 -> 1 + divisions_per_bar
1829 3|1|0 -> 1 + (2 * divisions_per_bar)
1833 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1840 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1841 Boolean* outTransportStateChanged,
1842 Float64* outCurrentSampleInTimeLine,
1843 Boolean* outIsCycling,
1844 Float64* outCycleStartBeat,
1845 Float64* outCycleEndBeat)
1850 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1852 rolling = _session.transport_rolling();
1853 speed = _session.transport_speed ();
1856 *outIsPlaying = _session.transport_rolling();
1859 if (outTransportStateChanged) {
1860 if (rolling != last_transport_rolling) {
1861 *outTransportStateChanged = true;
1862 } else if (speed != last_transport_speed) {
1863 *outTransportStateChanged = true;
1865 *outTransportStateChanged = false;
1869 if (outCurrentSampleInTimeLine) {
1870 /* this assumes that the AU can only call this host callback from render context,
1871 where input_offset is valid.
1873 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1877 Location* loc = _session.locations()->auto_loop_location();
1879 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1881 if (*outIsCycling) {
1883 if (outCycleStartBeat || outCycleEndBeat) {
1885 TempoMap& tmap (_session.tempo_map());
1887 /* more than 1 meter means that a simplistic computation (and interpretation) of
1888 a beat position will be incorrect. so refuse to offer the value.
1891 if (tmap.n_meters() > 1) {
1892 return kAudioUnitErr_CannotDoInCurrentContext;
1895 Timecode::BBT_Time bbt;
1897 if (outCycleStartBeat) {
1898 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1899 _session.tempo_map().bbt_time (loc->start(), bbt);
1902 beat = metric.meter().divisions_per_bar() * bbt.bars;
1904 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1906 *outCycleStartBeat = beat;
1909 if (outCycleEndBeat) {
1910 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1911 _session.tempo_map().bbt_time (loc->end(), bbt);
1914 beat = metric.meter().divisions_per_bar() * bbt.bars;
1916 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1918 *outCycleEndBeat = beat;
1924 last_transport_rolling = rolling;
1925 last_transport_speed = speed;
1930 set<Evoral::Parameter>
1931 AUPlugin::automatable() const
1933 set<Evoral::Parameter> automates;
1935 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1936 if (descriptors[i].automatable) {
1937 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1944 Plugin::IOPortDescription
1945 AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1947 std::stringstream ss;
1949 case DataType::AUDIO:
1951 case DataType::MIDI:
1959 if (dt == DataType::AUDIO) {
1962 for (uint32_t bus = 0; bus < input_elements; ++bus) {
1963 if (pid < bus_inputs[bus]) {
1965 ss << _bus_name_in[bus];
1966 ss << " / Bus " << (1 + bus);
1969 pid -= bus_inputs[bus];
1974 for (uint32_t bus = 0; bus < output_elements; ++bus) {
1975 if (pid < bus_outputs[bus]) {
1977 ss << _bus_name_out[bus];
1978 ss << " / Bus " << (1 + bus);
1981 pid -= bus_outputs[bus];
1987 ss << " " << _("In") << " ";
1989 ss << " " << _("Out") << " ";
1994 Plugin::IOPortDescription iod (ss.str());
1999 AUPlugin::describe_parameter (Evoral::Parameter param)
2001 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
2002 return descriptors[param.id()].label;
2009 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
2011 // NameValue stuff here
2015 AUPlugin::parameter_is_audio (uint32_t) const
2021 AUPlugin::parameter_is_control (uint32_t param) const
2023 assert(param < descriptors.size());
2024 if (descriptors[param].automatable) {
2025 /* corrently ardour expects all controls to be automatable
2026 * IOW ardour GUI elements mandate an Evoral::Parameter
2027 * for all input+control ports.
2035 AUPlugin::parameter_is_input (uint32_t param) const
2037 /* AU params that are both readable and writeable,
2038 * are listed in kAudioUnitScope_Global
2040 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
2044 AUPlugin::parameter_is_output (uint32_t param) const
2046 assert(param < descriptors.size());
2047 // TODO check if ardour properly handles ports
2048 // that report is_input + is_output == true
2049 // -> add || descriptors[param].scope == kAudioUnitScope_Global
2050 return (descriptors[param].scope == kAudioUnitScope_Output);
2054 AUPlugin::add_state (XMLNode* root) const
2058 CFPropertyListRef propertyList;
2060 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
2061 if (unit->GetAUPreset (propertyList) != noErr) {
2065 // Convert the property list into XML data.
2067 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
2070 error << _("Could not create XML version of property list") << endmsg;
2074 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
2075 our state node. GACK!
2080 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
2082 root->add_child_copy (*t.root());
2086 CFRelease (xmlData);
2087 CFRelease (propertyList);
2091 AUPlugin::set_state(const XMLNode& node, int version)
2094 CFPropertyListRef propertyList;
2097 if (node.name() != state_node_name()) {
2098 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
2102 #ifndef NO_PLUGIN_STATE
2103 if (node.children().empty()) {
2107 XMLNode* top = node.children().front();
2108 XMLNode* copy = new XMLNode (*top);
2113 const string& xml = t.write_buffer ();
2114 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
2115 CFStringRef errorString;
2117 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
2119 kCFPropertyListImmutable,
2122 CFRelease (xmlData);
2125 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
2126 if (unit->SetAUPreset (propertyList) == noErr) {
2129 /* tell the world */
2131 AudioUnitParameter changedUnit;
2132 changedUnit.mAudioUnit = unit->AU();
2133 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2134 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2136 CFRelease (propertyList);
2140 Plugin::set_state (node, version);
2145 AUPlugin::load_preset (PresetRecord r)
2147 Plugin::load_preset (r);
2150 CFPropertyListRef propertyList;
2152 UserPresetMap::iterator ux;
2153 FactoryPresetMap::iterator fx;
2155 /* look first in "user" presets */
2157 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
2159 if ((propertyList = load_property_list (ux->second)) != 0) {
2160 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
2161 if (unit->SetAUPreset (propertyList) == noErr) {
2164 /* tell the world */
2166 AudioUnitParameter changedUnit;
2167 changedUnit.mAudioUnit = unit->AU();
2168 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2169 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2171 CFRelease(propertyList);
2174 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2178 preset.presetNumber = fx->second;
2179 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2181 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2183 if (unit->SetPresentPreset (preset) == 0) {
2186 /* tell the world */
2188 AudioUnitParameter changedUnit;
2189 changedUnit.mAudioUnit = unit->AU();
2190 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2191 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2199 AUPlugin::do_remove_preset (std::string)
2204 AUPlugin::do_save_preset (string preset_name)
2206 CFPropertyListRef propertyList;
2207 vector<Glib::ustring> v;
2208 Glib::ustring user_preset_path;
2210 std::string m = maker();
2211 std::string n = name();
2213 strip_whitespace_edges (m);
2214 strip_whitespace_edges (n);
2216 v.push_back (Glib::get_home_dir());
2217 v.push_back ("Library");
2218 v.push_back ("Audio");
2219 v.push_back ("Presets");
2223 user_preset_path = Glib::build_filename (v);
2225 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2226 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2230 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2231 if (unit->GetAUPreset (propertyList) != noErr) {
2235 // add the actual preset name */
2237 v.push_back (preset_name + preset_suffix);
2241 user_preset_path = Glib::build_filename (v);
2243 set_preset_name_in_plist (propertyList, preset_name);
2245 if (save_property_list (propertyList, user_preset_path)) {
2246 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2250 CFRelease(propertyList);
2252 user_preset_map[preset_name] = user_preset_path;;
2254 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2256 return string ("file:///") + user_preset_path;
2259 //-----------------------------------------------------------------------------
2260 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2262 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2264 CFNumberRef cfNumber;
2265 SInt32 numberValue = 0;
2266 Boolean dummySuccess;
2268 if (outSuccess == NULL)
2269 outSuccess = &dummySuccess;
2270 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2272 *outSuccess = FALSE;
2276 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2277 if (cfNumber == NULL)
2279 *outSuccess = FALSE;
2282 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2290 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2292 CFDictionaryRef auStateDictionary;
2293 ArdourDescription tempDesc = {0,0,0,0,0};
2294 SInt32 versionValue;
2297 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2300 // the property list for AU state data must be of the dictionary type
2301 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2302 return kAudioUnitErr_InvalidPropertyValue;
2305 auStateDictionary = (CFDictionaryRef)inAUStateData;
2307 // first check to make sure that the version of the AU state data is one that we know understand
2308 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2309 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2312 return kAudioUnitErr_InvalidPropertyValue;
2314 #define kCurrentSavedStateVersion 0
2315 if (versionValue != kCurrentSavedStateVersion) {
2316 return kAudioUnitErr_InvalidPropertyValue;
2319 // grab the ComponentDescription values from the AU state data
2320 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2321 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2322 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2323 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2324 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2325 return kAudioUnitErr_InvalidPropertyValue;
2327 *outComponentDescription = tempDesc;
2332 static bool au_preset_filter (const string& str, void* arg)
2334 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2338 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2342 /* check the preset file path name against this plugin
2343 ID. The idea is that all preset files for this plugin
2344 include "<manufacturer>/<plugin-name>" in their path.
2347 AUPluginInfo* p = (AUPluginInfo *) arg;
2348 string match = p->creator;
2352 ret = str.find (match) != string::npos;
2355 string m = p->creator;
2357 strip_whitespace_edges (m);
2358 strip_whitespace_edges (n);
2363 ret = str.find (match) != string::npos;
2371 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2374 CFPropertyListRef plist;
2375 ArdourDescription presetDesc;
2378 plist = load_property_list (pathstr);
2384 // get the ComponentDescription from the AU preset file
2386 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2388 if (status == noErr) {
2389 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2391 /* try to get the preset name from the property list */
2393 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2395 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2399 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2402 char buf[PATH_MAX+1];
2404 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2421 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2423 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2426 CFStringRef itemName = NULL;
2427 // Marc Poirier-style item name
2429 CAComponent auComponent (comp_desc);
2430 if (auComponent.IsValid()) {
2431 CAComponentDescription dummydesc;
2432 Handle nameHandle = NewHandle(sizeof(void*));
2433 if (nameHandle != NULL) {
2434 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2436 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2437 if (nameString != NULL) {
2438 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2441 DisposeHandle(nameHandle);
2446 AudioComponentCopyName (comp, &itemName);
2449 // if Marc-style fails, do the original way
2450 if (itemName == NULL) {
2451 #ifndef COREAUDIO105
2452 CAComponentDescription comp_desc;
2453 AudioComponentGetDescription (comp, &comp_desc);
2455 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2456 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2457 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2459 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2460 compTypeString, compManufacturerString, compSubTypeString);
2462 if (compTypeString != NULL)
2463 CFRelease(compTypeString);
2464 if (compSubTypeString != NULL)
2465 CFRelease(compSubTypeString);
2466 if (compManufacturerString != NULL)
2467 CFRelease(compManufacturerString);
2470 string str = CFStringRefToStdString(itemName);
2471 string::size_type colon = str.find (':');
2474 name = str.substr (colon+1);
2475 maker = str.substr (0, colon);
2476 strip_whitespace_edges (maker);
2477 strip_whitespace_edges (name);
2481 strip_whitespace_edges (name);
2486 AUPlugin::current_preset() const
2490 CFPropertyListRef propertyList;
2492 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2493 if (unit->GetAUPreset (propertyList) == noErr) {
2494 preset_name = get_preset_name_in_plist (propertyList);
2495 CFRelease(propertyList);
2502 AUPlugin::find_presets ()
2504 vector<string> preset_files;
2506 user_preset_map.clear ();
2508 PluginInfoPtr nfo = get_info();
2509 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2510 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2513 if (preset_files.empty()) {
2514 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2517 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2522 /* make an initial guess at the preset name using the path */
2524 preset_name = Glib::path_get_basename (path);
2525 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2527 /* check that this preset file really matches this plugin
2528 and potentially get the "real" preset name from
2532 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2533 user_preset_map[preset_name] = path;
2534 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2536 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2541 /* now fill the vector<string> with the names we have */
2543 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2544 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2545 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2548 /* add factory presets */
2550 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2552 string const uri = string_compose ("%1", _presets.size ());
2553 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2554 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2559 AUPlugin::has_editor () const
2561 // even if the plugin doesn't have its own editor, the AU API can be used
2562 // to create one that looks native.
2566 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2570 type = ARDOUR::AudioUnit;
2573 AUPluginInfo::~AUPluginInfo ()
2575 type = ARDOUR::AudioUnit;
2579 AUPluginInfo::load (Session& session)
2584 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2585 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2587 if (!comp->IsValid()) {
2588 error << ("AudioUnit: not a valid Component") << endmsg;
2590 plugin.reset (new AUPlugin (session.engine(), session, comp));
2593 AUPluginInfo *aup = new AUPluginInfo (*this);
2594 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2595 plugin->set_info (PluginInfoPtr (aup));
2596 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2600 catch (failed_constructor &err) {
2601 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2602 return PluginPtr ();
2606 std::vector<Plugin::PresetRecord>
2607 AUPluginInfo::get_presets (bool user_only) const
2609 std::vector<Plugin::PresetRecord> p;
2610 boost::shared_ptr<CAComponent> comp;
2611 #ifndef NO_PLUGIN_STATE
2613 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2614 if (!comp->IsValid()) {
2615 throw failed_constructor();
2617 } catch (failed_constructor& err) {
2623 if (!preset_search_path_initialized) {
2624 Glib::ustring p = Glib::get_home_dir();
2625 p += "/Library/Audio/Presets:";
2626 p += preset_search_path;
2627 preset_search_path = p;
2628 preset_search_path_initialized = true;
2629 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2632 vector<string> preset_files;
2633 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2635 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2638 preset_name = Glib::path_get_basename (path);
2639 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2640 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2641 p.push_back (Plugin::PresetRecord (path, preset_name));
2655 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2656 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2659 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2660 unit->Uninitialize ();
2663 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2664 unit->Uninitialize ();
2668 unit->Uninitialize ();
2672 CFIndex cnt = CFArrayGetCount (presets);
2673 for (CFIndex i = 0; i < cnt; ++i) {
2674 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2675 string const uri = string_compose ("%1", i);
2676 string name = CFStringRefToStdString (preset->presetName);
2677 p.push_back (Plugin::PresetRecord (uri, name, false));
2679 CFRelease (presets);
2680 unit->Uninitialize ();
2682 #endif // NO_PLUGIN_STATE
2687 AUPluginInfo::au_cache_path ()
2689 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2693 AUPluginInfo::discover (bool scan_only)
2697 /* AU require a CAComponentDescription pointer provided by the OS.
2698 * Ardour only caches port and i/o config. It can't just 'scan' without
2699 * 'discovering' (like we do for VST).
2702 * "Iterate over all plugins. skip the ones where there's no io-cache".
2704 _scan_only = scan_only;
2706 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2707 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2708 // flush RAM cache -- after clear_cache()
2709 cached_info.clear();
2711 // create crash log file
2712 au_start_crashlog ();
2714 PluginInfoList* plugs = new PluginInfoList;
2716 discover_fx (*plugs);
2717 discover_music (*plugs);
2718 discover_generators (*plugs);
2719 discover_instruments (*plugs);
2721 // all fine if we get here
2722 au_remove_crashlog ();
2724 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2730 AUPluginInfo::discover_music (PluginInfoList& plugs)
2732 CAComponentDescription desc;
2733 desc.componentFlags = 0;
2734 desc.componentFlagsMask = 0;
2735 desc.componentSubType = 0;
2736 desc.componentManufacturer = 0;
2737 desc.componentType = kAudioUnitType_MusicEffect;
2739 discover_by_description (plugs, desc);
2743 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2745 CAComponentDescription desc;
2746 desc.componentFlags = 0;
2747 desc.componentFlagsMask = 0;
2748 desc.componentSubType = 0;
2749 desc.componentManufacturer = 0;
2750 desc.componentType = kAudioUnitType_Effect;
2752 discover_by_description (plugs, desc);
2756 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2758 CAComponentDescription desc;
2759 desc.componentFlags = 0;
2760 desc.componentFlagsMask = 0;
2761 desc.componentSubType = 0;
2762 desc.componentManufacturer = 0;
2763 desc.componentType = kAudioUnitType_Generator;
2765 discover_by_description (plugs, desc);
2769 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2771 CAComponentDescription desc;
2772 desc.componentFlags = 0;
2773 desc.componentFlagsMask = 0;
2774 desc.componentSubType = 0;
2775 desc.componentManufacturer = 0;
2776 desc.componentType = kAudioUnitType_MusicDevice;
2778 discover_by_description (plugs, desc);
2783 AUPluginInfo::au_get_crashlog (std::string &msg)
2785 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2786 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2789 std::ifstream ifs(fn.c_str());
2790 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2791 au_remove_crashlog ();
2796 AUPluginInfo::au_start_crashlog ()
2798 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2799 assert(!_crashlog_fd);
2800 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2801 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2802 PBD::error << "Cannot create AU error-log" << fn << "\n";
2803 cerr << "Cannot create AU error-log" << fn << "\n";
2808 AUPluginInfo::au_remove_crashlog ()
2811 ::fclose(_crashlog_fd);
2812 _crashlog_fd = NULL;
2814 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2815 ::g_unlink(fn.c_str());
2816 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2821 AUPluginInfo::au_crashlog (std::string msg)
2823 if (!_crashlog_fd) {
2824 fprintf(stderr, "AU: %s\n", msg.c_str());
2826 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2827 ::fflush(_crashlog_fd);
2832 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2834 ArdourComponent comp = 0;
2835 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2837 comp = ArdourFindNext (NULL, &desc);
2839 while (comp != NULL) {
2840 CAComponentDescription temp;
2842 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2844 AudioComponentGetDescription (comp, &temp);
2846 CFStringRef itemName = NULL;
2849 if (itemName != NULL) CFRelease(itemName);
2850 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2851 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2852 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2853 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2854 compTypeString, compManufacturerString, compSubTypeString);
2855 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2856 if (compTypeString != NULL)
2857 CFRelease(compTypeString);
2858 if (compSubTypeString != NULL)
2859 CFRelease(compSubTypeString);
2860 if (compManufacturerString != NULL)
2861 CFRelease(compManufacturerString);
2864 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2865 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2866 comp = ArdourFindNext (comp, &desc);
2870 bool has_midi_in = false;
2872 AUPluginInfoPtr info (new AUPluginInfo
2873 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2875 /* although apple designed the subtype field to be a "category" indicator,
2876 its really turned into a plugin ID field for a given manufacturer. Hence
2877 there are no categories for AudioUnits. However, to keep the plugins
2878 showing up under "categories", we'll use the "type" as a high level
2881 NOTE: no panners, format converters or i/o AU's for our purposes
2884 switch (info->descriptor->Type()) {
2885 case kAudioUnitType_Panner:
2886 case kAudioUnitType_OfflineEffect:
2887 case kAudioUnitType_FormatConverter:
2888 comp = ArdourFindNext (comp, &desc);
2891 case kAudioUnitType_Output:
2892 info->category = _("AudioUnit Outputs");
2894 case kAudioUnitType_MusicDevice:
2895 info->category = _("AudioUnit Instruments");
2898 case kAudioUnitType_MusicEffect:
2899 info->category = _("AudioUnit MusicEffects");
2902 case kAudioUnitType_Effect:
2903 info->category = _("AudioUnit Effects");
2905 case kAudioUnitType_Mixer:
2906 info->category = _("AudioUnit Mixers");
2908 case kAudioUnitType_Generator:
2909 info->category = _("AudioUnit Generators");
2912 info->category = _("AudioUnit (Unknown)");
2916 au_blacklist(CFStringRefToStdString(itemName));
2918 get_names (temp, info->name, info->creator);
2920 get_names (comp, info->name, info->creator);
2922 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2923 au_crashlog(string_compose("Plugin: %1", info->name));
2925 info->type = ARDOUR::AudioUnit;
2926 info->unique_id = stringify_descriptor (*info->descriptor);
2928 /* XXX not sure of the best way to handle plugin versioning yet */
2930 CAComponent cacomp (*info->descriptor);
2933 if (cacomp.GetResourceVersion (info->version) != noErr)
2935 if (cacomp.GetVersion (info->version) != noErr)
2941 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2944 /* here we have to map apple's wildcard system to a simple pair
2945 of values. in ::can_do() we use the whole system, but here
2946 we need a single pair of values. XXX probably means we should
2947 remove any use of these values.
2949 for now, if the plugin provides a wildcard, treat it as 1. we really
2950 don't care much, because whether we can handle an i/o configuration
2951 depends upon ::can_support_io_configuration(), not these counts.
2953 they exist because other parts of ardour try to present i/o configuration
2954 info to the user, which should perhaps be revisited.
2957 int32_t possible_in = info->cache.io_configs.front().first;
2958 int32_t possible_out = info->cache.io_configs.front().second;
2960 if (possible_in > 0) {
2961 info->n_inputs.set (DataType::AUDIO, possible_in);
2963 info->n_inputs.set (DataType::AUDIO, 1);
2966 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
2968 if (possible_out > 0) {
2969 info->n_outputs.set (DataType::AUDIO, possible_out);
2971 info->n_outputs.set (DataType::AUDIO, 1);
2974 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2975 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2977 plugs.push_back (info);
2980 else if (rv == -1) {
2981 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2984 au_unblacklist(CFStringRefToStdString(itemName));
2985 au_crashlog("Success.");
2986 comp = ArdourFindNext (comp, &desc);
2987 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2989 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2993 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2996 AUPluginCachedInfo& cinfo,
2997 const std::string& name)
3002 /* concatenate unique ID with version to provide a key for cached info lookup.
3003 this ensures we don't get stale information, or should if plugin developers
3004 follow Apple "guidelines".
3007 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
3012 CachedInfoMap::iterator cim = cached_info.find (id);
3014 if (cim != cached_info.end()) {
3015 cinfo = cim->second;
3020 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
3025 AUChannelInfo* channel_info;
3029 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
3033 if (CAAudioUnit::Open (comp, unit) != noErr) {
3039 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
3044 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
3045 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
3050 /* AU is expected to deal with same channel valance in and out */
3051 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
3053 /* CAAudioUnit::GetChannelInfo silently merges bus formats
3054 * check if this was the case and if so, add
3055 * bus configs as incremental options.
3057 Boolean* isWritable = 0;
3058 UInt32 dataSize = 0;
3059 OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
3060 kAudioUnitProperty_SupportedNumChannels,
3061 kAudioUnitScope_Global, 0,
3062 &dataSize, isWritable);
3063 if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
3064 /* incrementally add busses */
3067 for (uint32_t n = 0; n < cnt; ++n) {
3068 in += channel_info[n].inChannels;
3069 out += channel_info[n].outChannels;
3070 cinfo.io_configs.push_back (pair<int,int> (in, out));
3073 /* store each configuration */
3074 for (uint32_t n = 0; n < cnt; ++n) {
3075 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
3076 channel_info[n].outChannels));
3080 free (channel_info);
3083 add_cached_info (id, cinfo);
3084 save_cached_info ();
3090 AUPluginInfo::clear_cache ()
3092 const string& fn = au_cache_path();
3093 if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
3094 ::g_unlink(fn.c_str());
3096 // keep cached_info in RAM until restart or re-scan
3097 cached_info.clear();
3101 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
3103 cached_info[id] = cinfo;
3106 #define AU_CACHE_VERSION "2.0"
3109 AUPluginInfo::save_cached_info ()
3113 node = new XMLNode (X_("AudioUnitPluginCache"));
3114 node->add_property( "version", AU_CACHE_VERSION );
3116 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
3117 XMLNode* parent = new XMLNode (X_("plugin"));
3118 parent->add_property ("id", i->first);
3119 node->add_child_nocopy (*parent);
3121 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
3123 XMLNode* child = new XMLNode (X_("io"));
3126 snprintf (buf, sizeof (buf), "%d", j->first);
3127 child->add_property (X_("in"), buf);
3128 snprintf (buf, sizeof (buf), "%d", j->second);
3129 child->add_property (X_("out"), buf);
3130 parent->add_child_nocopy (*child);
3135 Glib::ustring path = au_cache_path ();
3138 tree.set_root (node);
3140 if (!tree.write (path)) {
3141 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
3142 g_unlink (path.c_str());
3147 AUPluginInfo::load_cached_info ()
3149 Glib::ustring path = au_cache_path ();
3152 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
3156 if ( !tree.read (path) ) {
3157 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
3161 const XMLNode* root (tree.root());
3163 if (root->name() != X_("AudioUnitPluginCache")) {
3167 //initial version has incorrectly stored i/o info, and/or garbage chars.
3168 XMLProperty const * version = root->property(X_("version"));
3169 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
3170 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
3174 cached_info.clear ();
3176 const XMLNodeList children = root->children();
3178 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
3180 const XMLNode* child = *iter;
3182 if (child->name() == X_("plugin")) {
3184 const XMLNode* gchild;
3185 const XMLNodeList gchildren = child->children();
3186 XMLProperty const * prop = child->property (X_("id"));
3192 string id = prop->value();
3196 string::size_type slash = id.find_last_of ('/');
3198 if (slash == string::npos) {
3202 version = id.substr (slash);
3203 id = id.substr (0, slash);
3204 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3206 if (fixed.empty()) {
3207 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3214 AUPluginCachedInfo cinfo;
3216 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3220 if (gchild->name() == X_("io")) {
3224 XMLProperty const * iprop;
3225 XMLProperty const * oprop;
3227 if (((iprop = gchild->property (X_("in"))) != 0) &&
3228 ((oprop = gchild->property (X_("out"))) != 0)) {
3229 in = atoi (iprop->value());
3230 out = atoi (oprop->value());
3232 cinfo.io_configs.push_back (pair<int,int> (in, out));
3237 if (cinfo.io_configs.size()) {
3238 add_cached_info (id, cinfo);
3248 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3252 /* note: OSType is a compiler-implemenation-defined value,
3253 historically a 32 bit integer created with a multi-character
3254 constant such as 'abcd'. It is, fundamentally, an abomination.
3259 s << desc.SubType();
3267 AUPluginInfo::needs_midi_input () const
3269 return is_effect_with_midi_input () || is_instrument ();
3273 AUPluginInfo::is_effect () const
3275 return is_effect_without_midi_input() || is_effect_with_midi_input();
3279 AUPluginInfo::is_effect_without_midi_input () const
3281 return descriptor->IsAUFX();
3285 AUPluginInfo::is_effect_with_midi_input () const
3287 return descriptor->IsAUFM();
3291 AUPluginInfo::is_instrument () const
3293 return descriptor->IsMusicDevice();
3297 AUPlugin::set_info (PluginInfoPtr info)
3299 Plugin::set_info (info);
3301 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3302 _has_midi_input = pinfo->needs_midi_input ();
3303 _has_midi_output = false;
3307 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3310 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3312 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3314 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3316 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3320 _parameter_listener_arg = arg;
3326 AUPlugin::listen_to_parameter (uint32_t param_id)
3328 AudioUnitEvent event;
3330 if (!_parameter_listener || param_id >= descriptors.size()) {
3334 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3335 event.mArgument.mParameter.mAudioUnit = unit->AU();
3336 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3337 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3338 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3340 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3344 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3345 event.mArgument.mParameter.mAudioUnit = unit->AU();
3346 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3347 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3348 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3350 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3354 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
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) {
3368 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3370 AudioUnitEvent event;
3372 if (!_parameter_listener || param_id >= descriptors.size()) {
3376 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3377 event.mArgument.mParameter.mAudioUnit = unit->AU();
3378 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3379 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3380 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3382 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3386 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3387 event.mArgument.mParameter.mAudioUnit = unit->AU();
3388 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3389 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3390 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3392 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3396 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
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) {
3410 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3412 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3416 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3418 ParameterMap::iterator i;
3420 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3424 switch (event->mEventType) {
3425 case kAudioUnitEvent_BeginParameterChangeGesture:
3426 StartTouch (i->second);
3428 case kAudioUnitEvent_EndParameterChangeGesture:
3429 EndTouch (i->second);
3431 case kAudioUnitEvent_ParameterValueChange:
3432 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3433 means that something else (i.e. the plugin GUI) made the change.
3435 ParameterChangedExternally (i->second, new_value);