2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include "pbd/gstdio_compat.h"
29 #include "pbd/transmitter.h"
30 #include "pbd/xml++.h"
31 #include "pbd/convert.h"
32 #include "pbd/whitespace.h"
33 #include "pbd/file_utils.h"
34 #include "pbd/locale_guard.h"
36 #include <glibmm/threads.h>
37 #include <glibmm/fileutils.h>
38 #include <glibmm/miscutils.h>
40 #include "ardour/ardour.h"
41 #include "ardour/audio_unit.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/audio_buffer.h"
44 #include "ardour/debug.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/midi_buffer.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
53 #include "CAAudioUnit.h"
54 #include "CAAUParameter.h"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
61 #include <Carbon/Carbon.h>
65 #define ArdourComponent Component
66 #define ArdourDescription ComponentDescription
67 #define ArdourFindNext FindNextComponent
69 #define ArdourComponent AudioComponent
70 #define ArdourDescription AudioComponentDescription
71 #define ArdourFindNext AudioComponentFindNext
78 using namespace ARDOUR;
80 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
82 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
83 static string preset_suffix = ".aupreset";
84 static bool preset_search_path_initialized = false;
85 FILE * AUPluginInfo::_crashlog_fd = NULL;
86 bool AUPluginInfo::_scan_only = true;
89 static void au_blacklist (std::string id)
91 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
92 FILE * blacklist_fd = NULL;
93 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
94 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
97 assert(id.find("\n") == string::npos);
98 fprintf(blacklist_fd, "%s\n", id.c_str());
99 ::fclose(blacklist_fd);
102 static void au_unblacklist (std::string id)
104 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
105 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
106 PBD::warning << "Expected Blacklist file does not exist.\n";
112 std::ifstream ifs(fn.c_str());
113 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
116 ::g_unlink (fn.c_str());
118 assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
119 assert(id.find("\n") == string::npos);
121 id += "\n"; // add separator
122 const size_t rpl = bl.find(id);
123 if (rpl != string::npos) {
124 bl.replace(rpl, id.size(), "");
130 FILE * blacklist_fd = NULL;
131 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
132 PBD::error << "Cannot open AU blacklist.\n";
135 fprintf(blacklist_fd, "%s", bl.c_str());
136 ::fclose(blacklist_fd);
139 static bool is_blacklisted (std::string id)
141 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
142 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
146 std::ifstream ifs(fn.c_str());
147 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
149 assert(id.find("\n") == string::npos);
151 id += "\n"; // add separator
152 const size_t rpl = bl.find(id);
153 if (rpl != string::npos) {
162 _render_callback(void *userData,
163 AudioUnitRenderActionFlags *ioActionFlags,
164 const AudioTimeStamp *inTimeStamp,
166 UInt32 inNumberSamples,
167 AudioBufferList* ioData)
170 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberSamples, ioData);
176 _get_beat_and_tempo_callback (void* userData,
177 Float64* outCurrentBeat,
178 Float64* outCurrentTempo)
181 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
188 _get_musical_time_location_callback (void * userData,
189 UInt32 * outDeltaSampleOffsetToNextBeat,
190 Float32 * outTimeSig_Numerator,
191 UInt32 * outTimeSig_Denominator,
192 Float64 * outCurrentMeasureDownBeat)
195 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
196 outTimeSig_Numerator,
197 outTimeSig_Denominator,
198 outCurrentMeasureDownBeat);
204 _get_transport_state_callback (void* userData,
205 Boolean* outIsPlaying,
206 Boolean* outTransportStateChanged,
207 Float64* outCurrentSampleInTimeLine,
208 Boolean* outIsCycling,
209 Float64* outCycleStartBeat,
210 Float64* outCycleEndBeat)
213 return ((AUPlugin*)userData)->get_transport_state_callback (
214 outIsPlaying, outTransportStateChanged,
215 outCurrentSampleInTimeLine, outIsCycling,
216 outCycleStartBeat, outCycleEndBeat);
223 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
229 // Convert the property list into XML data.
231 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
234 error << _("Could not create XML version of property list") << endmsg;
238 // Write the XML data to the file.
240 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
242 if (errno == EEXIST) {
243 error << string_compose (_("Preset file %1 exists; not overwriting"),
246 error << string_compose (_("Cannot open preset file %1 (%2)"),
247 path, strerror (errno)) << endmsg;
253 size_t cnt = CFDataGetLength (xmlData);
255 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
266 static CFPropertyListRef
267 load_property_list (Glib::ustring path)
270 CFPropertyListRef propertyList = 0;
272 CFStringRef errorString;
274 // Read the XML file.
276 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
281 off_t len = lseek (fd, 0, SEEK_END);
282 char* buf = new char[len];
283 lseek (fd, 0, SEEK_SET);
285 if (read (fd, buf, len) != len) {
293 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
295 // Reconstitute the dictionary using the XML data.
297 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
299 kCFPropertyListImmutable,
308 //-----------------------------------------------------------------------------
310 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
315 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
317 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
318 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
324 //-----------------------------------------------------------------------------
326 get_preset_name_in_plist (CFPropertyListRef plist)
334 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
335 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
337 CFStringRef str = (CFStringRef) p;
338 int len = CFStringGetLength(str);
340 char local_buffer[len];
341 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
349 //--------------------------------------------------------------------------
350 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
351 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
352 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
353 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
355 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
358 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
359 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
361 // only sub-type and manufacturer IDs need to be equal
364 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
365 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
372 //--------------------------------------------------------------------------
373 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
374 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
375 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
376 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
379 ArdourDescription desc;
381 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
384 // get the ComponentDescription of the input Component
386 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
388 status = AudioComponentGetDescription (inComponent, &desc);
393 // check if the Component's ComponentDescription matches the input ComponentDescription
394 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
397 //--------------------------------------------------------------------------
398 // determine if 2 ComponentDescriptions are basically equal
399 // (by that, I mean that the important identifying values are compared,
400 // but not the ComponentDescription flags)
401 Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
403 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
406 //--------------------------------------------------------------------------
407 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
408 Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
410 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
413 //--------------------------------------------------------------------------
414 // determine if a ComponentDescription basically matches that of a particular Component
415 Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
417 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
420 //--------------------------------------------------------------------------
421 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
422 Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
424 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
428 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
429 : Plugin (engine, session)
431 , unit (new CAAudioUnit)
432 , initialized (false)
434 , _current_latency (UINT_MAX)
435 , _requires_fixed_size_buffers (false)
437 , variable_inputs (false)
438 , variable_outputs (false)
439 , configured_input_busses (0)
440 , configured_output_busses (0)
448 , samples_processed (0)
449 , audio_input_cnt (0)
450 , _parameter_listener (0)
451 , _parameter_listener_arg (0)
452 , transport_sample (0)
453 , transport_speed (0)
454 , last_transport_speed (0.0)
456 if (!preset_search_path_initialized) {
457 Glib::ustring p = Glib::get_home_dir();
458 p += "/Library/Audio/Presets:";
459 p += preset_search_path;
460 preset_search_path = p;
461 preset_search_path_initialized = true;
462 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
469 AUPlugin::AUPlugin (const AUPlugin& other)
471 , comp (other.get_comp())
472 , unit (new CAAudioUnit)
473 , initialized (false)
475 , _current_latency (UINT_MAX)
476 , _requires_fixed_size_buffers (false)
478 , variable_inputs (false)
479 , variable_outputs (false)
480 , configured_input_busses (0)
481 , configured_output_busses (0)
489 , samples_processed (0)
490 , audio_input_cnt (0)
491 , _parameter_listener (0)
492 , _parameter_listener_arg (0)
493 , transport_sample (0)
494 , transport_speed (0)
495 , last_transport_speed (0.0)
499 for (size_t i = 0; i < descriptors.size(); ++i) {
500 set_parameter (i, other.get_parameter (i));
504 AUPlugin::~AUPlugin ()
506 if (_parameter_listener) {
507 AUListenerDispose (_parameter_listener);
508 _parameter_listener = 0;
512 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
513 unit->Uninitialize ();
523 AUPlugin::discover_factory_presets ()
530 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
531 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
535 assert (dataSize == sizeof (presets));
537 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
538 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
546 CFIndex cnt = CFArrayGetCount (presets);
548 for (CFIndex i = 0; i < cnt; ++i) {
549 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
551 string name = CFStringRefToStdString (preset->presetName);
552 factory_preset_map[name] = preset->presetNumber;
553 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
563 CFStringRef itemName;
565 /* these keep track of *configured* channel set up,
566 not potential set ups.
570 output_channels = -1;
572 CAComponentDescription temp;
574 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
576 AudioComponentGetDescription (comp.get()->Comp(), &temp);
578 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
579 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
580 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
581 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
582 compTypeString, compManufacturerString, compSubTypeString);
583 if (compTypeString != NULL) CFRelease(compTypeString);
584 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
585 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
588 au_blacklist(CFStringRefToStdString(itemName));
591 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
592 err = CAAudioUnit::Open (*(comp.get()), *unit);
594 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
595 throw failed_constructor();
599 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
600 throw failed_constructor ();
603 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
604 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
605 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
606 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
607 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
608 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
610 cb_offsets = (samplecnt_t*) calloc (input_elements, sizeof(samplecnt_t));
611 bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
612 bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
614 for (size_t i = 0; i < output_elements; ++i) {
615 unit->Reset (kAudioUnitScope_Output, i);
616 AudioStreamBasicDescription fmt;
617 err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
619 bus_outputs[i] = fmt.mChannelsPerFrame;
622 UInt32 sz = sizeof (CFStringRef);
623 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
624 i, &name, &sz) == noErr
626 _bus_name_out.push_back (CFStringRefToStdString (name));
629 _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
633 for (size_t i = 0; i < input_elements; ++i) {
634 unit->Reset (kAudioUnitScope_Input, i);
635 AudioStreamBasicDescription fmt;
636 err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
638 bus_inputs[i] = fmt.mChannelsPerFrame;
641 UInt32 sz = sizeof (CFStringRef);
642 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
643 i, &name, &sz) == noErr
645 _bus_name_in.push_back (CFStringRefToStdString (name));
648 _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
652 for (size_t i = 0; i < input_elements; ++i) {
653 /* setup render callback: the plugin calls this to get input data */
654 AURenderCallbackStruct renderCallbackInfo;
655 renderCallbackInfo.inputProc = _render_callback;
656 renderCallbackInfo.inputProcRefCon = this;
657 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
658 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
659 i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
660 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
661 throw failed_constructor();
665 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
667 HostCallbackInfo info;
668 memset (&info, 0, sizeof (HostCallbackInfo));
669 info.hostUserData = this;
670 info.beatAndTempoProc = _get_beat_and_tempo_callback;
671 info.musicalTimeLocationProc = _get_musical_time_location_callback;
672 info.transportStateProc = _get_transport_state_callback;
674 //ignore result of this - don't care if the property isn't supported
675 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
676 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
677 kAudioUnitScope_Global,
680 sizeof (HostCallbackInfo));
682 if (set_block_size (_session.get_block_size())) {
683 error << _("AUPlugin: cannot set processing block size") << endmsg;
684 throw failed_constructor();
687 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
688 discover_parameters ();
689 discover_factory_presets ();
691 // Plugin::setup_controls ();
693 au_unblacklist(CFStringRefToStdString(itemName));
694 if (itemName != NULL) CFRelease(itemName);
698 AUPlugin::discover_parameters ()
700 /* discover writable parameters */
702 AudioUnitScope scopes[] = {
703 kAudioUnitScope_Global,
704 kAudioUnitScope_Output,
705 kAudioUnitScope_Input
708 descriptors.clear ();
710 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
712 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
714 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
716 AUParameterDescriptor d;
718 d.id = param_info.ParamID (i);
720 const CAAUParameter* param = param_info.GetParamInfo (d.id);
721 const AudioUnitParameterInfo& info (param->ParamInfo());
723 const int len = CFStringGetLength (param->GetName());
724 char local_buffer[len*2];
725 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
729 d.label = local_buffer;
732 d.scope = param_info.GetScope ();
733 d.element = param_info.GetElement ();
735 /* info.units to consider */
737 kAudioUnitParameterUnit_Generic = 0
738 kAudioUnitParameterUnit_Indexed = 1
739 kAudioUnitParameterUnit_Boolean = 2
740 kAudioUnitParameterUnit_Percent = 3
741 kAudioUnitParameterUnit_Seconds = 4
742 kAudioUnitParameterUnit_SampleFrames = 5
743 kAudioUnitParameterUnit_Phase = 6
744 kAudioUnitParameterUnit_Rate = 7
745 kAudioUnitParameterUnit_Hertz = 8
746 kAudioUnitParameterUnit_Cents = 9
747 kAudioUnitParameterUnit_RelativeSemiTones = 10
748 kAudioUnitParameterUnit_MIDINoteNumber = 11
749 kAudioUnitParameterUnit_MIDIController = 12
750 kAudioUnitParameterUnit_Decibels = 13
751 kAudioUnitParameterUnit_LinearGain = 14
752 kAudioUnitParameterUnit_Degrees = 15
753 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
754 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
755 kAudioUnitParameterUnit_Pan = 18
756 kAudioUnitParameterUnit_Meters = 19
757 kAudioUnitParameterUnit_AbsoluteCents = 20
758 kAudioUnitParameterUnit_Octaves = 21
759 kAudioUnitParameterUnit_BPM = 22
760 kAudioUnitParameterUnit_Beats = 23
761 kAudioUnitParameterUnit_Milliseconds = 24
762 kAudioUnitParameterUnit_Ratio = 25
765 /* info.flags to consider */
769 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
770 kAudioUnitParameterFlag_HasClump = (1L << 20)
771 kAudioUnitParameterFlag_HasName = (1L << 21)
772 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
773 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
774 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
775 kAudioUnitParameterFlag_CanRamp = (1L << 25)
776 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
777 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
778 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
779 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
780 kAudioUnitParameterFlag_IsReadable = (1L << 30)
781 kAudioUnitParameterFlag_IsWritable = (1L << 31)
784 d.lower = info.minValue;
785 d.upper = info.maxValue;
786 d.normal = info.defaultValue;
788 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
789 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
790 (d.integer_step && ((d.upper - d.lower) == 1.0));
791 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
792 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
793 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
794 (info.flags & kAudioUnitParameterFlag_IsWritable);
796 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
797 d.au_unit = info.unit;
799 case kAudioUnitParameterUnit_Decibels:
800 d.unit = ParameterDescriptor::DB;
802 case kAudioUnitParameterUnit_MIDINoteNumber:
803 d.unit = ParameterDescriptor::MIDI_NOTE;
805 case kAudioUnitParameterUnit_Hertz:
806 d.unit = ParameterDescriptor::HZ;
812 descriptors.push_back (d);
814 uint32_t last_param = descriptors.size() - 1;
815 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
816 listen_to_parameter (last_param);
823 four_ints_to_four_byte_literal (unsigned char n[4])
825 /* this is actually implementation dependent. sigh. this is what gcc
826 and quite a few others do.
828 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
832 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
834 if (isdigit (id[0])) {
838 /* ID format is xxxx-xxxx-xxxx
839 where x maybe \xNN or a printable character.
841 Split at the '-' and and process each part into an integer.
842 Then put it back together.
846 unsigned char nascent[4];
847 const char* cstr = id.c_str();
848 const char* estr = cstr + id.size();
859 while (*cstr && next_int < 4) {
863 if (estr - cstr < 3) {
865 /* too close to the end for \xNN parsing: treat as literal characters */
873 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
877 memcpy (short_buf, &cstr[2], 2);
878 nascent[in] = strtol (short_buf, NULL, 16);
884 /* treat as literal characters */
898 if (in && (in % 4 == 0)) {
899 /* nascent is ready */
900 n[next_int] = four_ints_to_four_byte_literal (nascent);
904 /* swallow space-hyphen-space */
918 s << n[0] << '-' << n[1] << '-' << n[2];
927 AUPlugin::unique_id () const
929 return AUPluginInfo::stringify_descriptor (comp->Desc());
933 AUPlugin::label () const
935 return _info->name.c_str();
939 AUPlugin::parameter_count () const
941 return descriptors.size();
945 AUPlugin::default_value (uint32_t port)
947 if (port < descriptors.size()) {
948 return descriptors[port].normal;
955 AUPlugin::signal_latency () const
957 guint lat = g_atomic_int_get (&_current_latency);;
958 if (lat == UINT_MAX) {
959 lat = unit->Latency() * _session.sample_rate();
960 g_atomic_int_set (&_current_latency, lat);
966 AUPlugin::set_parameter (uint32_t which, float val)
968 if (which >= descriptors.size()) {
972 if (get_parameter(which) == val) {
976 const AUParameterDescriptor& d (descriptors[which]);
977 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
978 unit->SetParameter (d.id, d.scope, d.element, val);
980 /* tell the world what we did */
982 AudioUnitEvent theEvent;
984 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
985 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
986 theEvent.mArgument.mParameter.mParameterID = d.id;
987 theEvent.mArgument.mParameter.mScope = d.scope;
988 theEvent.mArgument.mParameter.mElement = d.element;
990 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
991 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
992 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
994 Plugin::set_parameter (which, val);
998 AUPlugin::get_parameter (uint32_t which) const
1001 if (which < descriptors.size()) {
1002 const AUParameterDescriptor& d (descriptors[which]);
1003 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
1004 unit->GetParameter(d.id, d.scope, d.element, val);
1010 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
1012 if (which < descriptors.size()) {
1013 pd = descriptors[which];
1020 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
1022 if (which < descriptors.size()) {
1031 AUPlugin::activate ()
1035 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
1036 if ((err = unit->Initialize()) != noErr) {
1037 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
1039 samples_processed = 0;
1046 AUPlugin::deactivate ()
1048 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
1049 unit->Uninitialize ();
1050 initialized = false;
1056 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
1057 unit->GlobalReset ();
1061 AUPlugin::requires_fixed_size_buffers() const
1063 return _requires_fixed_size_buffers;
1068 AUPlugin::set_block_size (pframes_t nframes)
1070 bool was_initialized = initialized;
1071 UInt32 numSamples = nframes;
1078 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numSamples));
1079 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1080 0, &numSamples, sizeof (numSamples))) != noErr) {
1081 error << string_compose (_("AU: cannot set max samples (err = %1)"), err) << endmsg;
1085 if (was_initialized) {
1093 AUPlugin::configure_io (ChanCount in, ChanCount out)
1095 AudioStreamBasicDescription streamFormat;
1096 bool was_initialized = initialized;
1097 int32_t audio_out = out.n_audio();
1098 if (audio_input_cnt > 0) {
1099 in.set (DataType::AUDIO, audio_input_cnt);
1101 const int32_t audio_in = in.n_audio();
1103 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1106 //if we are already running with the requested i/o config, bail out here
1107 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1114 streamFormat.mSampleRate = _session.sample_rate();
1115 streamFormat.mFormatID = kAudioFormatLinearPCM;
1116 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1118 #ifdef __LITTLE_ENDIAN__
1121 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1124 streamFormat.mBitsPerChannel = 32;
1125 streamFormat.mFramesPerPacket = 1;
1127 /* apple says that for non-interleaved data, these
1128 * values always refer to a single channel.
1130 streamFormat.mBytesPerPacket = 4;
1131 streamFormat.mBytesPerFrame = 4;
1133 configured_input_busses = 0;
1134 configured_output_busses = 0;
1136 for (size_t i = 0; i < output_elements; ++i) {
1137 unit->Reset (kAudioUnitScope_Output, i);
1139 for (size_t i = 0; i < input_elements; ++i) {
1140 unit->Reset (kAudioUnitScope_Input, i);
1143 /* now assign the channels to available busses */
1144 uint32_t used_in = 0;
1145 uint32_t used_out = 0;
1147 if (variable_inputs || input_elements == 1) {
1148 // we only ever use the first bus
1149 if (input_elements > 1) {
1150 warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
1152 streamFormat.mChannelsPerFrame = audio_in;
1153 if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
1156 configured_input_busses = 1;
1159 configured_input_busses = 0;
1160 uint32_t remain = audio_in;
1161 for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
1162 uint32_t cnt = std::min (remain, bus_inputs[bus]);
1163 if (cnt == 0) { continue; }
1164 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
1166 streamFormat.mChannelsPerFrame = cnt;
1167 if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
1171 ++configured_input_busses;
1176 if (variable_outputs || output_elements == 1) {
1177 if (output_elements > 1) {
1178 warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
1181 streamFormat.mChannelsPerFrame = audio_out;
1182 if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
1185 configured_output_busses = 1;
1186 used_out = audio_out;
1188 uint32_t remain = audio_out;
1189 configured_output_busses = 0;
1190 for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
1191 uint32_t cnt = std::min (remain, bus_outputs[bus]);
1192 if (cnt == 0) { continue; }
1193 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
1194 streamFormat.mChannelsPerFrame = cnt;
1195 if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
1200 ++configured_output_busses;
1205 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1206 used_out * sizeof(::AudioBuffer));
1208 input_channels = used_in;
1209 output_channels = used_out;
1210 /* reset plugin info to show currently configured state */
1212 _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
1213 _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
1215 if (was_initialized) {
1223 AUPlugin::input_streams() const
1226 if (input_channels < 0) {
1227 // force PluginIoReConfigure -- see also commit msg e38eb06
1228 c.set (DataType::AUDIO, 0);
1229 c.set (DataType::MIDI, 0);
1231 c.set (DataType::AUDIO, input_channels);
1232 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1239 AUPlugin::output_streams() const
1242 if (output_channels < 0) {
1243 // force PluginIoReConfigure - see also commit msg e38eb06
1244 c.set (DataType::AUDIO, 0);
1245 c.set (DataType::MIDI, 0);
1247 c.set (DataType::AUDIO, output_channels);
1248 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1254 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1256 _output_configs.clear ();
1257 const int32_t audio_in = in.n_audio();
1258 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1260 /* lets check MIDI first */
1262 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1266 vector<pair<int,int> > io_configs = pinfo->cache.io_configs;
1268 if (input_elements > 1) {
1269 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1270 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1271 int32_t possible_in = i->first;
1272 int32_t possible_out = i->second;
1273 if (possible_in < 0) {
1276 for (uint32_t i = 1; i < input_elements; ++i) {
1277 // can't use up-to bus_inputs[]
1278 // waves' SC-C6(s) for example fails to configure with only 1 input
1280 io_configs.push_back (pair<int,int> (possible_in + bus_inputs[i], possible_out));
1282 /* only add additional, optional busses to first available config.
1283 * AUPluginInfo::cached_io_configuration () already incrementally
1284 * adds busses (for instruments w/ multiple configurations)
1290 if (output_elements > 1) {
1291 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1292 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1293 int32_t possible_in = i->first;
1294 int32_t possible_out = i->second;
1295 if (possible_out < 0) {
1298 for (uint32_t i = 1; i < output_elements; ++i) {
1299 int32_t c = bus_outputs[i];
1300 for (uint32_t j = 1; j < i; ++j) {
1301 c += bus_outputs [j];
1303 io_configs.push_back (pair<int,int> (possible_in, possible_out + c));
1305 /* only add additional, optional busses to first available config.
1306 * AUPluginInfo::cached_io_configuration () already incrementally
1307 * adds busses (for instruments w/ multiple configurations)
1313 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1314 name(), io_configs.size(), in, out));
1317 printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
1318 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1319 printf ("- I/O %d / %d\n", i->first, i->second);
1323 // preferred setting (provided by plugin_insert)
1324 const int preferred_out = out.n_audio ();
1326 bool exact_match = false;
1328 /* kAudioUnitProperty_SupportedNumChannels
1329 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1331 * - both fields are -1
1332 * e.g. inChannels = -1 outChannels = -1
1333 * This is the default case. Any number of input and output channels, as long as the numbers match
1335 * - one field is -1, the other field is positive
1336 * e.g. inChannels = -1 outChannels = 2
1337 * Any number of input channels, exactly two output channels
1339 * - one field is -1, the other field is -2
1340 * e.g. inChannels = -1 outChannels = -2
1341 * Any number of input channels, any number of output channels
1343 * - both fields have non-negative values
1344 * e.g. inChannels = 2 outChannels = 6
1345 * Exactly two input channels, exactly six output channels
1346 * e.g. inChannels = 0 outChannels = 2
1347 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1349 * - both fields have negative values, neither of which is –1 or –2
1350 * e.g. inChannels = -4 outChannels = -8
1351 * Up to four input channels and up to eight output channels
1354 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1356 int32_t possible_in = i->first;
1357 int32_t possible_out = i->second;
1359 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1360 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1361 possible_in, possible_out,
1365 _output_configs.insert (preferred_out);
1372 /* now allow potentially "imprecise" matches */
1373 int32_t audio_out = -1;
1374 float penalty = 9999;
1375 int used_possible_in = 0;
1376 #if defined (__clang__)
1377 # pragma clang diagnostic push
1378 # pragma clang diagnostic ignored "-Wtautological-compare"
1381 #define FOUNDCFG(nch) { \
1382 float p = fabsf ((float)(nch) - preferred_out); \
1383 _output_configs.insert (nch); \
1384 if ((nch) > preferred_out) { p *= 1.1; } \
1385 if (p < penalty) { \
1386 used_possible_in = possible_in; \
1387 audio_out = (nch); \
1390 variable_inputs = possible_in < 0; \
1391 variable_outputs = possible_out < 0; \
1395 #define ANYTHINGGOES \
1396 _output_configs.insert (0);
1398 #define UPTO(nch) { \
1399 for (int n = 1; n <= nch; ++n) { \
1400 _output_configs.insert (n); \
1404 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1406 int32_t possible_in = i->first;
1407 int32_t possible_out = i->second;
1409 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1411 if (possible_out == 0) {
1412 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1413 /* XXX surely this is just a send? (e.g. AUNetSend) */
1417 if (possible_in == 0) {
1418 /* no inputs, generators & instruments */
1419 if (possible_out == -1) {
1420 /* any configuration possible, provide stereo output */
1421 FOUNDCFG (preferred_out);
1423 } else if (possible_out == -2) {
1424 /* invalid, should be (0, -1) */
1425 FOUNDCFG (preferred_out);
1427 } else if (possible_out < -2) {
1428 /* variable number of outputs up to -N, */
1429 FOUNDCFG (min (-possible_out, preferred_out));
1430 UPTO (-possible_out);
1432 /* exact number of outputs */
1433 FOUNDCFG (possible_out);
1437 if (possible_in == -1) {
1438 /* wildcard for input */
1439 if (possible_out == -1) {
1440 /* out must match in */
1441 FOUNDCFG (audio_in);
1442 } else if (possible_out == -2) {
1443 /* any configuration possible, pick matching */
1444 FOUNDCFG (preferred_out);
1446 } else if (possible_out < -2) {
1447 /* explicitly variable number of outputs, pick maximum */
1448 FOUNDCFG (max (-possible_out, preferred_out));
1449 /* and try min, too, in case the penalty is lower */
1450 FOUNDCFG (min (-possible_out, preferred_out));
1451 UPTO (-possible_out)
1453 /* exact number of outputs */
1454 FOUNDCFG (possible_out);
1458 if (possible_in == -2) {
1459 if (possible_out == -1) {
1460 /* any configuration possible, pick matching */
1461 FOUNDCFG (preferred_out);
1463 } else if (possible_out == -2) {
1464 /* invalid. interpret as (-1, -1) */
1465 FOUNDCFG (preferred_out);
1467 } else if (possible_out < -2) {
1468 /* invalid, interpret as (<-2, <-2)
1469 * variable number of outputs up to -N, */
1470 FOUNDCFG (min (-possible_out, preferred_out));
1471 UPTO (-possible_out)
1473 /* exact number of outputs */
1474 FOUNDCFG (possible_out);
1478 if (possible_in < -2) {
1479 /* explicit variable number of inputs */
1480 if (audio_in > -possible_in && imprecise != NULL) {
1481 // hide inputs ports
1482 imprecise->set (DataType::AUDIO, -possible_in);
1485 if (audio_in > -possible_in && imprecise == NULL) {
1486 /* request is too large */
1487 } else if (possible_out == -1) {
1488 /* any output configuration possible */
1489 FOUNDCFG (preferred_out);
1491 } else if (possible_out == -2) {
1492 /* invalid. interpret as (<-2, -1) */
1493 FOUNDCFG (preferred_out);
1495 } else if (possible_out < -2) {
1496 /* variable number of outputs up to -N, */
1497 FOUNDCFG (min (-possible_out, preferred_out));
1498 UPTO (-possible_out)
1500 /* exact number of outputs */
1501 FOUNDCFG (possible_out);
1505 if (possible_in && (possible_in == audio_in)) {
1506 /* exact number of inputs ... must match obviously */
1507 if (possible_out == -1) {
1508 /* any output configuration possible */
1509 FOUNDCFG (preferred_out);
1511 } else if (possible_out == -2) {
1512 /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
1513 FOUNDCFG (preferred_out);
1515 } else if (possible_out < -2) {
1516 /* > 0, < -2 is not specified
1517 * interpret as up to -N */
1518 FOUNDCFG (min (-possible_out, preferred_out));
1519 UPTO (-possible_out)
1521 /* exact number of outputs */
1522 FOUNDCFG (possible_out);
1527 if (!found && imprecise) {
1529 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1530 int32_t possible_in = i->first;
1531 int32_t possible_out = i->second;
1533 assert (possible_in > 0); // all other cases will have been matched above
1534 assert (possible_out !=0 || possible_in !=0); // already handled above
1536 imprecise->set (DataType::AUDIO, possible_in);
1537 if (possible_out == -1 || possible_out == -2) {
1539 } else if (possible_out < -2) {
1540 /* explicitly variable number of outputs, pick maximum */
1541 FOUNDCFG (min (-possible_out, preferred_out));
1543 /* exact number of outputs */
1544 FOUNDCFG (possible_out);
1546 // ideally we'll also find the closest, best matching
1547 // input configuration with minimal output penalty...
1552 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1557 out.set (DataType::MIDI, 0); // currently always zero
1558 out.set (DataType::AUDIO, preferred_out);
1560 if (used_possible_in < -2 && audio_in == 0) {
1561 // input-port count cannot be zero, use as many ports
1562 // as outputs, but at most abs(possible_in)
1563 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1565 out.set (DataType::MIDI, 0); /// XXX
1566 out.set (DataType::AUDIO, audio_out);
1568 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1570 #if defined (__clang__)
1571 # pragma clang diagnostic pop
1577 AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
1581 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1582 (scope == kAudioUnitScope_Input ? "input" : "output"),
1584 if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
1585 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1586 (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
1593 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1594 const AudioTimeStamp*,
1596 UInt32 inNumberSamples,
1597 AudioBufferList* ioData)
1599 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1601 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, samples %2 bus %3 bufs %4\n",
1602 // name(), inNumberSamples, bus, ioData->mNumberBuffers));
1604 if (input_maxbuf == 0) {
1605 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1606 error << _("AUPlugin: render callback called illegally!") << endmsg;
1607 return kAudioUnitErr_CannotDoInCurrentContext;
1610 assert (bus < input_elements);
1611 uint32_t busoff = 0;
1612 for (uint32_t i = 0; i < bus; ++i) {
1613 busoff += bus_inputs[i];
1616 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1618 ChanCount bufs_count (DataType::AUDIO, 1);
1619 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1621 /* apply bus offsets */
1623 for (uint32_t i = 0; i < limit; ++i) {
1624 ioData->mBuffers[i].mNumberChannels = 1;
1625 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberSamples;
1628 uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
1630 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
1632 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
1635 cb_offsets[bus] += inNumberSamples;
1640 AUPlugin::connect_and_run (BufferSet& bufs,
1641 samplepos_t start, samplepos_t end, double speed,
1642 ChanMapping const& in_map, ChanMapping const& out_map,
1643 pframes_t nframes, samplecnt_t offset)
1645 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
1647 transport_sample = start;
1648 transport_speed = speed;
1650 AudioUnitRenderActionFlags flags = 0;
1654 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1655 unit->GlobalReset();
1656 _last_nframes = nframes;
1659 /* test if we can run in-place; only compare audio buffers */
1660 bool inplace = true; // TODO check plugin-insert in-place ?
1661 ChanMapping::Mappings inmap (in_map.mappings ());
1662 ChanMapping::Mappings outmap (out_map.mappings ());
1663 if (outmap[DataType::AUDIO].size () == 0) {
1666 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1670 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",
1671 name(), input_channels, output_channels, _has_midi_input,
1672 bufs.count(), bufs.available(),
1673 configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
1675 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1676 * has the capacity to handle our outputs.
1679 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1681 input_buffers = &bufs;
1682 input_map = &in_map;
1683 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1684 input_offset = offset;
1685 for (size_t i = 0; i < input_elements; ++i) {
1689 ChanCount bufs_count (DataType::AUDIO, 1);
1690 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1692 if (_has_midi_input) {
1693 uint32_t nmidi = bufs.count().n_midi();
1694 for (uint32_t i = 0; i < nmidi; ++i) {
1695 /* one MIDI port/buffer only */
1696 MidiBuffer& m = bufs.get_midi (i);
1697 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1698 Evoral::Event<samplepos_t> ev (*i);
1699 if (ev.is_channel_event()) {
1700 const uint8_t* b = ev.buffer();
1701 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1702 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1704 /* XXX need to handle sysex and other message types */
1709 assert (input_maxbuf < 512);
1710 std::bitset<512> used_outputs;
1713 uint32_t busoff = 0;
1714 uint32_t remain = output_channels;
1715 for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
1717 if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
1718 cnt = output_channels;
1720 cnt = std::min (remain, bus_outputs[bus]);
1724 buffers->mNumberBuffers = cnt;
1726 for (uint32_t i = 0; i < cnt; ++i) {
1727 buffers->mBuffers[i].mNumberChannels = 1;
1728 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1729 /* setting this to 0 indicates to the AU that it can provide buffers here
1730 * if necessary. if it can process in-place, it will use the buffers provided
1731 * as input by ::render_callback() above.
1733 * a non-null values tells the plugin to render into the buffer pointed
1737 buffers->mBuffers[i].mData = 0;
1740 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1742 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1744 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1749 /* does this really mean anything ? */
1750 ts.mSampleTime = samples_processed;
1751 ts.mFlags = kAudioTimeStampSampleTimeValid;
1753 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
1754 name(), flags, samples_processed, nframes, bus, buffers->mNumberBuffers));
1756 if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
1758 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1759 name(), buffers->mNumberBuffers, output_channels));
1761 uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
1762 for (uint32_t i = 0; i < limit; ++i) {
1764 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1765 if (!valid) continue;
1766 used_outputs.set (i + busoff);
1767 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1768 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1769 /* plugin provided its own buffer for output so copy it back to where we want it */
1770 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1774 DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
1775 error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
1781 busoff += bus_outputs[bus];
1784 /* now silence any buffers that were passed in but the that the plugin
1785 * did not fill/touch/use.
1787 * TODO: optimize, when plugin-insert is processing in-place
1788 * unconnected buffers are (also) cleared there.
1790 for (uint32_t i = 0; i < input_maxbuf; ++i) {
1791 if (used_outputs.test (i)) { continue; }
1793 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1794 if (!valid) continue;
1795 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1801 samples_processed += nframes;
1808 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1809 Float64* outCurrentTempo)
1811 TempoMap& tmap (_session.tempo_map());
1813 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1815 if (outCurrentBeat) {
1816 *outCurrentBeat = tmap.quarter_note_at_sample (transport_sample + input_offset);
1819 if (outCurrentTempo) {
1820 *outCurrentTempo = tmap.tempo_at_sample (transport_sample + input_offset).quarter_notes_per_minute();
1828 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1829 Float32* outTimeSig_Numerator,
1830 UInt32* outTimeSig_Denominator,
1831 Float64* outCurrentMeasureDownBeat)
1833 TempoMap& tmap (_session.tempo_map());
1835 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1837 TempoMetric metric = tmap.metric_at (transport_sample + input_offset);
1838 Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_sample (transport_sample + input_offset);
1840 if (outDeltaSampleOffsetToNextBeat) {
1841 if (bbt.ticks == 0) {
1843 *outDeltaSampleOffsetToNextBeat = 0;
1845 double const next_beat = ceil (tmap.quarter_note_at_sample (transport_sample + input_offset));
1846 samplepos_t const next_beat_sample = tmap.sample_at_quarter_note (next_beat);
1848 *outDeltaSampleOffsetToNextBeat = next_beat_sample - (transport_sample + input_offset);
1852 if (outTimeSig_Numerator) {
1853 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1855 if (outTimeSig_Denominator) {
1856 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1859 if (outCurrentMeasureDownBeat) {
1861 /* beat for the start of the bar.
1863 2|1|0 -> 1 + divisions_per_bar
1864 3|1|0 -> 1 + (2 * divisions_per_bar)
1870 *outCurrentMeasureDownBeat = tmap.quarter_note_at_bbt (bbt);
1877 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1878 Boolean* outTransportStateChanged,
1879 Float64* outCurrentSampleInTimeLine,
1880 Boolean* outIsCycling,
1881 Float64* outCycleStartBeat,
1882 Float64* outCycleEndBeat)
1884 const bool rolling = (transport_speed != 0);
1885 const bool last_transport_rolling = (last_transport_speed != 0);
1887 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1891 *outIsPlaying = rolling;
1894 if (outTransportStateChanged) {
1895 if (rolling != last_transport_rolling) {
1896 *outTransportStateChanged = true;
1897 } else if (transport_speed != last_transport_speed) {
1898 *outTransportStateChanged = true;
1900 *outTransportStateChanged = false;
1904 if (outCurrentSampleInTimeLine) {
1905 /* this assumes that the AU can only call this host callback from render context,
1906 where input_offset is valid.
1908 *outCurrentSampleInTimeLine = transport_sample + input_offset;
1912 // TODO check bounce-processing
1913 Location* loc = _session.locations()->auto_loop_location();
1915 *outIsCycling = (loc && rolling && _session.get_play_loop());
1917 if (*outIsCycling) {
1919 if (outCycleStartBeat || outCycleEndBeat) {
1921 TempoMap& tmap (_session.tempo_map());
1923 Timecode::BBT_Time bbt;
1925 if (outCycleStartBeat) {
1926 *outCycleStartBeat = tmap.quarter_note_at_sample (loc->start() + input_offset);
1929 if (outCycleEndBeat) {
1930 *outCycleEndBeat = tmap.quarter_note_at_sample (loc->end() + input_offset);
1936 last_transport_speed = transport_speed;
1941 set<Evoral::Parameter>
1942 AUPlugin::automatable() const
1944 set<Evoral::Parameter> automates;
1946 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1947 if (descriptors[i].automatable) {
1948 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1955 Plugin::IOPortDescription
1956 AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1958 std::stringstream ss;
1960 case DataType::AUDIO:
1962 case DataType::MIDI:
1970 std::string busname;
1972 if (dt == DataType::AUDIO) {
1975 for (uint32_t bus = 0; bus < input_elements; ++bus) {
1976 if (pid < bus_inputs[bus]) {
1978 ss << _bus_name_in[bus];
1979 ss << " / Bus " << (1 + bus);
1980 busname = _bus_name_in[bus];
1983 pid -= bus_inputs[bus];
1988 for (uint32_t bus = 0; bus < output_elements; ++bus) {
1989 if (pid < bus_outputs[bus]) {
1991 ss << _bus_name_out[bus];
1992 ss << " / Bus " << (1 + bus);
1993 busname = _bus_name_out[bus];
1996 pid -= bus_outputs[bus];
2002 ss << " " << _("In") << " ";
2004 ss << " " << _("Out") << " ";
2009 Plugin::IOPortDescription iod (ss.str());
2010 if (!busname.empty()) {
2011 iod.group_name = busname;
2012 iod.group_channel = id;
2018 AUPlugin::describe_parameter (Evoral::Parameter param)
2020 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
2021 return descriptors[param.id()].label;
2028 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
2030 // NameValue stuff here
2032 if (param < parameter_count()) {
2033 snprintf (buf, len, "%.3f", get_parameter (param));
2041 AUPlugin::parameter_is_audio (uint32_t) const
2047 AUPlugin::parameter_is_control (uint32_t param) const
2049 assert(param < descriptors.size());
2050 if (descriptors[param].automatable) {
2051 /* corrently ardour expects all controls to be automatable
2052 * IOW ardour GUI elements mandate an Evoral::Parameter
2053 * for all input+control ports.
2061 AUPlugin::parameter_is_input (uint32_t param) const
2063 /* AU params that are both readable and writeable,
2064 * are listed in kAudioUnitScope_Global
2066 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
2070 AUPlugin::parameter_is_output (uint32_t param) const
2072 assert(param < descriptors.size());
2073 // TODO check if ardour properly handles ports
2074 // that report is_input + is_output == true
2075 // -> add || descriptors[param].scope == kAudioUnitScope_Global
2076 return (descriptors[param].scope == kAudioUnitScope_Output);
2080 AUPlugin::add_state (XMLNode* root) const
2084 CFPropertyListRef propertyList;
2086 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
2087 if (unit->GetAUPreset (propertyList) != noErr) {
2091 // Convert the property list into XML data.
2093 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
2096 error << _("Could not create XML version of property list") << endmsg;
2100 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
2101 our state node. GACK!
2106 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
2108 root->add_child_copy (*t.root());
2112 CFRelease (xmlData);
2113 CFRelease (propertyList);
2117 AUPlugin::set_state(const XMLNode& node, int version)
2120 CFPropertyListRef propertyList;
2123 if (node.name() != state_node_name()) {
2124 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
2128 #ifndef NO_PLUGIN_STATE
2129 if (node.children().empty()) {
2133 XMLNode* top = node.children().front();
2134 XMLNode* copy = new XMLNode (*top);
2139 const string& xml = t.write_buffer ();
2140 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
2141 CFStringRef errorString;
2143 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
2145 kCFPropertyListImmutable,
2148 CFRelease (xmlData);
2151 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
2152 if (unit->SetAUPreset (propertyList) == noErr) {
2155 /* tell the world */
2157 AudioUnitParameter changedUnit;
2158 changedUnit.mAudioUnit = unit->AU();
2159 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2160 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2162 CFRelease (propertyList);
2166 Plugin::set_state (node, version);
2171 AUPlugin::load_preset (PresetRecord r)
2174 CFPropertyListRef propertyList;
2176 UserPresetMap::iterator ux;
2177 FactoryPresetMap::iterator fx;
2179 /* look first in "user" presets */
2181 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
2183 if ((propertyList = load_property_list (ux->second)) != 0) {
2184 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
2185 if (unit->SetAUPreset (propertyList) == noErr) {
2188 /* tell the world */
2190 AudioUnitParameter changedUnit;
2191 changedUnit.mAudioUnit = unit->AU();
2192 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2193 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2195 CFRelease(propertyList);
2198 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2202 preset.presetNumber = fx->second;
2203 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2205 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2207 if (unit->SetPresentPreset (preset) == 0) {
2210 /* tell the world */
2212 AudioUnitParameter changedUnit;
2213 changedUnit.mAudioUnit = unit->AU();
2214 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2215 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2219 return ret && Plugin::load_preset (r);
2223 AUPlugin::do_remove_preset (std::string)
2228 AUPlugin::do_save_preset (string preset_name)
2230 CFPropertyListRef propertyList;
2231 vector<Glib::ustring> v;
2232 Glib::ustring user_preset_path;
2234 std::string m = maker();
2235 std::string n = name();
2237 strip_whitespace_edges (m);
2238 strip_whitespace_edges (n);
2240 v.push_back (Glib::get_home_dir());
2241 v.push_back ("Library");
2242 v.push_back ("Audio");
2243 v.push_back ("Presets");
2247 user_preset_path = Glib::build_filename (v);
2249 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2250 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2254 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2255 if (unit->GetAUPreset (propertyList) != noErr) {
2259 // add the actual preset name */
2261 v.push_back (preset_name + preset_suffix);
2265 user_preset_path = Glib::build_filename (v);
2267 set_preset_name_in_plist (propertyList, preset_name);
2269 if (save_property_list (propertyList, user_preset_path)) {
2270 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2274 CFRelease(propertyList);
2276 user_preset_map[preset_name] = user_preset_path;;
2278 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2280 return user_preset_path;
2283 //-----------------------------------------------------------------------------
2284 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2286 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2288 CFNumberRef cfNumber;
2289 SInt32 numberValue = 0;
2290 Boolean dummySuccess;
2292 if (outSuccess == NULL)
2293 outSuccess = &dummySuccess;
2294 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2296 *outSuccess = FALSE;
2300 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2301 if (cfNumber == NULL)
2303 *outSuccess = FALSE;
2306 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2314 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2316 CFDictionaryRef auStateDictionary;
2317 ArdourDescription tempDesc = {0,0,0,0,0};
2318 SInt32 versionValue;
2321 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2324 // the property list for AU state data must be of the dictionary type
2325 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2326 return kAudioUnitErr_InvalidPropertyValue;
2329 auStateDictionary = (CFDictionaryRef)inAUStateData;
2331 // first check to make sure that the version of the AU state data is one that we know understand
2332 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2333 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2336 return kAudioUnitErr_InvalidPropertyValue;
2338 #define kCurrentSavedStateVersion 0
2339 if (versionValue != kCurrentSavedStateVersion) {
2340 return kAudioUnitErr_InvalidPropertyValue;
2343 // grab the ComponentDescription values from the AU state data
2344 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2345 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2346 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2347 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2348 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2349 return kAudioUnitErr_InvalidPropertyValue;
2351 *outComponentDescription = tempDesc;
2356 static bool au_preset_filter (const string& str, void* arg)
2358 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2362 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2366 /* check the preset file path name against this plugin
2367 ID. The idea is that all preset files for this plugin
2368 include "<manufacturer>/<plugin-name>" in their path.
2371 AUPluginInfo* p = (AUPluginInfo *) arg;
2372 string match = p->creator;
2376 ret = str.find (match) != string::npos;
2379 string m = p->creator;
2381 strip_whitespace_edges (m);
2382 strip_whitespace_edges (n);
2387 ret = str.find (match) != string::npos;
2395 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2398 CFPropertyListRef plist;
2399 ArdourDescription presetDesc;
2402 plist = load_property_list (pathstr);
2408 // get the ComponentDescription from the AU preset file
2410 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2412 if (status == noErr) {
2413 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2415 /* try to get the preset name from the property list */
2417 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2419 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2423 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2426 char buf[PATH_MAX+1];
2428 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2445 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2447 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2450 CFStringRef itemName = NULL;
2451 // Marc Poirier-style item name
2453 CAComponent auComponent (comp_desc);
2454 if (auComponent.IsValid()) {
2455 CAComponentDescription dummydesc;
2456 Handle nameHandle = NewHandle(sizeof(void*));
2457 if (nameHandle != NULL) {
2458 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2460 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2461 if (nameString != NULL) {
2462 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2465 DisposeHandle(nameHandle);
2470 AudioComponentCopyName (comp, &itemName);
2473 // if Marc-style fails, do the original way
2474 if (itemName == NULL) {
2475 #ifndef COREAUDIO105
2476 CAComponentDescription comp_desc;
2477 AudioComponentGetDescription (comp, &comp_desc);
2479 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2480 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2481 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2483 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2484 compTypeString, compManufacturerString, compSubTypeString);
2486 if (compTypeString != NULL)
2487 CFRelease(compTypeString);
2488 if (compSubTypeString != NULL)
2489 CFRelease(compSubTypeString);
2490 if (compManufacturerString != NULL)
2491 CFRelease(compManufacturerString);
2494 string str = CFStringRefToStdString(itemName);
2495 string::size_type colon = str.find (':');
2498 name = str.substr (colon+1);
2499 maker = str.substr (0, colon);
2500 strip_whitespace_edges (maker);
2501 strip_whitespace_edges (name);
2505 strip_whitespace_edges (name);
2510 AUPlugin::current_preset() const
2514 CFPropertyListRef propertyList;
2516 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2517 if (unit->GetAUPreset (propertyList) == noErr) {
2518 preset_name = get_preset_name_in_plist (propertyList);
2519 CFRelease(propertyList);
2526 AUPlugin::find_presets ()
2528 vector<string> preset_files;
2530 user_preset_map.clear ();
2532 PluginInfoPtr nfo = get_info();
2533 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2534 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2537 if (preset_files.empty()) {
2538 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2541 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2546 /* make an initial guess at the preset name using the path */
2548 preset_name = Glib::path_get_basename (path);
2549 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2551 /* check that this preset file really matches this plugin
2552 and potentially get the "real" preset name from
2556 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2557 user_preset_map[preset_name] = path;
2558 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2560 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2565 /* now fill the vector<string> with the names we have */
2567 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2568 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2569 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2572 /* add factory presets */
2574 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2575 /* XXX: dubious -- deleting & re-adding a preset -> same URI
2576 * good that we don't support deleting AU presets :)
2578 string const uri = PBD::to_string<uint32_t> (_presets.size ());
2579 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2580 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2585 AUPlugin::has_editor () const
2587 // even if the plugin doesn't have its own editor, the AU API can be used
2588 // to create one that looks native.
2592 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2596 type = ARDOUR::AudioUnit;
2599 AUPluginInfo::~AUPluginInfo ()
2601 type = ARDOUR::AudioUnit;
2605 AUPluginInfo::load (Session& session)
2610 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2611 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2613 if (!comp->IsValid()) {
2614 error << ("AudioUnit: not a valid Component") << endmsg;
2616 plugin.reset (new AUPlugin (session.engine(), session, comp));
2619 AUPluginInfo *aup = new AUPluginInfo (*this);
2620 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2621 plugin->set_info (PluginInfoPtr (aup));
2622 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2626 catch (failed_constructor &err) {
2627 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2628 return PluginPtr ();
2632 std::vector<Plugin::PresetRecord>
2633 AUPluginInfo::get_presets (bool user_only) const
2635 std::vector<Plugin::PresetRecord> p;
2636 boost::shared_ptr<CAComponent> comp;
2637 #ifndef NO_PLUGIN_STATE
2639 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2640 if (!comp->IsValid()) {
2641 throw failed_constructor();
2643 } catch (failed_constructor& err) {
2649 if (!preset_search_path_initialized) {
2650 Glib::ustring p = Glib::get_home_dir();
2651 p += "/Library/Audio/Presets:";
2652 p += preset_search_path;
2653 preset_search_path = p;
2654 preset_search_path_initialized = true;
2655 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2658 vector<string> preset_files;
2659 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2661 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2664 preset_name = Glib::path_get_basename (path);
2665 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2666 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2667 p.push_back (Plugin::PresetRecord (path, preset_name));
2681 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2682 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2685 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2686 unit->Uninitialize ();
2689 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2690 unit->Uninitialize ();
2694 unit->Uninitialize ();
2698 CFIndex cnt = CFArrayGetCount (presets);
2699 for (CFIndex i = 0; i < cnt; ++i) {
2700 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2701 string const uri = string_compose ("%1", i);
2702 string name = CFStringRefToStdString (preset->presetName);
2703 p.push_back (Plugin::PresetRecord (uri, name, false));
2705 CFRelease (presets);
2706 unit->Uninitialize ();
2708 #endif // NO_PLUGIN_STATE
2713 AUPluginInfo::au_cache_path ()
2715 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2719 AUPluginInfo::discover (bool scan_only)
2723 /* AU require a CAComponentDescription pointer provided by the OS.
2724 * Ardour only caches port and i/o config. It can't just 'scan' without
2725 * 'discovering' (like we do for VST).
2728 * "Iterate over all plugins. skip the ones where there's no io-cache".
2730 _scan_only = scan_only;
2732 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2733 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2734 // flush RAM cache -- after clear_cache()
2735 cached_info.clear();
2737 // create crash log file
2738 au_start_crashlog ();
2740 PluginInfoList* plugs = new PluginInfoList;
2742 discover_fx (*plugs);
2743 discover_music (*plugs);
2744 discover_generators (*plugs);
2745 discover_instruments (*plugs);
2747 // all fine if we get here
2748 au_remove_crashlog ();
2750 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2756 AUPluginInfo::discover_music (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_MusicEffect;
2765 discover_by_description (plugs, desc);
2769 AUPluginInfo::discover_fx (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_Effect;
2778 discover_by_description (plugs, desc);
2782 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2784 CAComponentDescription desc;
2785 desc.componentFlags = 0;
2786 desc.componentFlagsMask = 0;
2787 desc.componentSubType = 0;
2788 desc.componentManufacturer = 0;
2789 desc.componentType = kAudioUnitType_Generator;
2791 discover_by_description (plugs, desc);
2795 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2797 CAComponentDescription desc;
2798 desc.componentFlags = 0;
2799 desc.componentFlagsMask = 0;
2800 desc.componentSubType = 0;
2801 desc.componentManufacturer = 0;
2802 desc.componentType = kAudioUnitType_MusicDevice;
2804 discover_by_description (plugs, desc);
2809 AUPluginInfo::au_get_crashlog (std::string &msg)
2811 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2812 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2815 std::ifstream ifs(fn.c_str());
2816 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2817 au_remove_crashlog ();
2822 AUPluginInfo::au_start_crashlog ()
2824 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2825 assert(!_crashlog_fd);
2826 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2827 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2828 PBD::error << "Cannot create AU error-log" << fn << "\n";
2829 cerr << "Cannot create AU error-log" << fn << "\n";
2834 AUPluginInfo::au_remove_crashlog ()
2837 ::fclose(_crashlog_fd);
2838 _crashlog_fd = NULL;
2840 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2841 ::g_unlink(fn.c_str());
2842 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2847 AUPluginInfo::au_crashlog (std::string msg)
2849 if (!_crashlog_fd) {
2850 fprintf(stderr, "AU: %s\n", msg.c_str());
2852 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2853 ::fflush(_crashlog_fd);
2858 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2860 ArdourComponent comp = 0;
2861 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2863 comp = ArdourFindNext (NULL, &desc);
2865 while (comp != NULL) {
2866 CAComponentDescription temp;
2868 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2870 AudioComponentGetDescription (comp, &temp);
2872 CFStringRef itemName = NULL;
2875 if (itemName != NULL) CFRelease(itemName);
2876 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2877 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2878 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2879 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2880 compTypeString, compManufacturerString, compSubTypeString);
2881 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2882 if (compTypeString != NULL)
2883 CFRelease(compTypeString);
2884 if (compSubTypeString != NULL)
2885 CFRelease(compSubTypeString);
2886 if (compManufacturerString != NULL)
2887 CFRelease(compManufacturerString);
2890 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2891 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2892 comp = ArdourFindNext (comp, &desc);
2896 bool has_midi_in = false;
2898 AUPluginInfoPtr info (new AUPluginInfo
2899 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2901 /* although apple designed the subtype field to be a "category" indicator,
2902 its really turned into a plugin ID field for a given manufacturer. Hence
2903 there are no categories for AudioUnits. However, to keep the plugins
2904 showing up under "categories", we'll use the "type" as a high level
2907 NOTE: no panners, format converters or i/o AU's for our purposes
2910 switch (info->descriptor->Type()) {
2911 case kAudioUnitType_Panner:
2912 case kAudioUnitType_OfflineEffect:
2913 case kAudioUnitType_FormatConverter:
2914 comp = ArdourFindNext (comp, &desc);
2917 case kAudioUnitType_Output:
2918 info->category = _("Output");
2920 case kAudioUnitType_MusicDevice:
2921 info->category = _("Instrument");
2924 case kAudioUnitType_MusicEffect:
2925 info->category = _("Effect");
2928 case kAudioUnitType_Effect:
2929 info->category = _("Effect");
2931 case kAudioUnitType_Mixer:
2932 info->category = _("Mixer");
2934 case kAudioUnitType_Generator:
2935 info->category = _("Generator");
2938 info->category = _("(Unknown)");
2942 au_blacklist(CFStringRefToStdString(itemName));
2944 get_names (temp, info->name, info->creator);
2946 get_names (comp, info->name, info->creator);
2948 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2949 au_crashlog(string_compose("Plugin: %1", info->name));
2951 info->type = ARDOUR::AudioUnit;
2952 info->unique_id = stringify_descriptor (*info->descriptor);
2954 /* XXX not sure of the best way to handle plugin versioning yet */
2956 CAComponent cacomp (*info->descriptor);
2959 if (cacomp.GetResourceVersion (info->version) != noErr)
2961 if (cacomp.GetVersion (info->version) != noErr)
2967 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2970 /* here we have to map apple's wildcard system to a simple pair
2971 of values. in ::can_do() we use the whole system, but here
2972 we need a single pair of values. XXX probably means we should
2973 remove any use of these values.
2975 for now, if the plugin provides a wildcard, treat it as 1. we really
2976 don't care much, because whether we can handle an i/o configuration
2977 depends upon ::can_support_io_configuration(), not these counts.
2979 they exist because other parts of ardour try to present i/o configuration
2980 info to the user, which should perhaps be revisited.
2983 int32_t possible_in = info->cache.io_configs.front().first;
2984 int32_t possible_out = info->cache.io_configs.front().second;
2986 if (possible_in > 0) {
2987 info->n_inputs.set (DataType::AUDIO, possible_in);
2989 info->n_inputs.set (DataType::AUDIO, 1);
2992 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
2994 if (possible_out > 0) {
2995 info->n_outputs.set (DataType::AUDIO, possible_out);
2997 info->n_outputs.set (DataType::AUDIO, 1);
3000 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
3001 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
3003 plugs.push_back (info);
3006 else if (rv == -1) {
3007 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
3010 au_unblacklist(CFStringRefToStdString(itemName));
3011 au_crashlog("Success.");
3012 comp = ArdourFindNext (comp, &desc);
3013 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
3015 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
3019 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
3022 AUPluginCachedInfo& cinfo,
3023 const std::string& name)
3028 /* concatenate unique ID with version to provide a key for cached info lookup.
3029 this ensures we don't get stale information, or should if plugin developers
3030 follow Apple "guidelines".
3033 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
3038 CachedInfoMap::iterator cim = cached_info.find (id);
3040 if (cim != cached_info.end()) {
3041 cinfo = cim->second;
3046 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
3051 AUChannelInfo* channel_info;
3055 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
3059 if (CAAudioUnit::Open (comp, unit) != noErr) {
3065 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
3070 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
3071 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
3076 /* AU is expected to deal with same channel valance in and out */
3077 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
3079 /* CAAudioUnit::GetChannelInfo silently merges bus formats
3080 * check if this was the case and if so, add
3081 * bus configs as incremental options.
3083 Boolean* isWritable = 0;
3084 UInt32 dataSize = 0;
3085 OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
3086 kAudioUnitProperty_SupportedNumChannels,
3087 kAudioUnitScope_Global, 0,
3088 &dataSize, isWritable);
3089 if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
3090 /* incrementally add busses */
3093 for (uint32_t n = 0; n < cnt; ++n) {
3094 in += channel_info[n].inChannels;
3095 out += channel_info[n].outChannels;
3096 cinfo.io_configs.push_back (pair<int,int> (in, out));
3099 /* store each configuration */
3100 for (uint32_t n = 0; n < cnt; ++n) {
3101 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
3102 channel_info[n].outChannels));
3106 free (channel_info);
3109 add_cached_info (id, cinfo);
3110 save_cached_info ();
3116 AUPluginInfo::clear_cache ()
3118 const string& fn = au_cache_path();
3119 if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
3120 ::g_unlink(fn.c_str());
3122 // keep cached_info in RAM until restart or re-scan
3123 cached_info.clear();
3127 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
3129 cached_info[id] = cinfo;
3132 #define AU_CACHE_VERSION "2.0"
3135 AUPluginInfo::save_cached_info ()
3139 node = new XMLNode (X_("AudioUnitPluginCache"));
3140 node->set_property( "version", AU_CACHE_VERSION );
3142 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
3143 XMLNode* parent = new XMLNode (X_("plugin"));
3144 parent->set_property ("id", i->first);
3145 node->add_child_nocopy (*parent);
3147 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
3149 XMLNode* child = new XMLNode (X_("io"));
3151 child->set_property (X_("in"), j->first);
3152 child->set_property (X_("out"), j->second);
3153 parent->add_child_nocopy (*child);
3158 Glib::ustring path = au_cache_path ();
3161 tree.set_root (node);
3163 if (!tree.write (path)) {
3164 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
3165 g_unlink (path.c_str());
3170 AUPluginInfo::load_cached_info ()
3172 Glib::ustring path = au_cache_path ();
3175 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
3179 if ( !tree.read (path) ) {
3180 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
3184 const XMLNode* root (tree.root());
3186 if (root->name() != X_("AudioUnitPluginCache")) {
3190 //initial version has incorrectly stored i/o info, and/or garbage chars.
3191 XMLProperty const * version = root->property(X_("version"));
3192 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
3193 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
3197 cached_info.clear ();
3199 const XMLNodeList children = root->children();
3201 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
3203 const XMLNode* child = *iter;
3205 if (child->name() == X_("plugin")) {
3207 const XMLNode* gchild;
3208 const XMLNodeList gchildren = child->children();
3211 if (!child->get_property (X_("id"), id)) {
3218 string::size_type slash = id.find_last_of ('/');
3220 if (slash == string::npos) {
3224 version = id.substr (slash);
3225 id = id.substr (0, slash);
3226 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3228 if (fixed.empty()) {
3229 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3236 AUPluginCachedInfo cinfo;
3238 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3242 if (gchild->name() == X_("io")) {
3247 if (gchild->get_property (X_("in"), in) && gchild->get_property (X_("out"), out)) {
3248 cinfo.io_configs.push_back (pair<int,int> (in, out));
3253 if (cinfo.io_configs.size()) {
3254 add_cached_info (id, cinfo);
3264 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3268 /* note: OSType is a compiler-implemenation-defined value,
3269 historically a 32 bit integer created with a multi-character
3270 constant such as 'abcd'. It is, fundamentally, an abomination.
3275 s << desc.SubType();
3283 AUPluginInfo::needs_midi_input () const
3285 return is_effect_with_midi_input () || is_instrument ();
3289 AUPluginInfo::is_effect () const
3291 return is_effect_without_midi_input() || is_effect_with_midi_input();
3295 AUPluginInfo::is_effect_without_midi_input () const
3297 return descriptor->IsAUFX();
3301 AUPluginInfo::is_effect_with_midi_input () const
3303 return descriptor->IsAUFM();
3307 AUPluginInfo::is_instrument () const
3309 return descriptor->IsMusicDevice();
3313 AUPluginInfo::is_utility () const
3315 return (descriptor->IsGenerator() || descriptor->componentType == 'aumi');
3316 // kAudioUnitType_MidiProcessor ..looks like we aren't even scanning for these yet?
3320 AUPlugin::set_info (PluginInfoPtr info)
3322 Plugin::set_info (info);
3324 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3325 _has_midi_input = pinfo->needs_midi_input ();
3326 _has_midi_output = false;
3330 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3333 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3335 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3337 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3339 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3343 _parameter_listener_arg = arg;
3345 // listen for latency changes
3346 AudioUnitEvent event;
3347 event.mEventType = kAudioUnitEvent_PropertyChange;
3348 event.mArgument.mProperty.mAudioUnit = unit->AU();
3349 event.mArgument.mProperty.mPropertyID = kAudioUnitProperty_Latency;
3350 event.mArgument.mProperty.mScope = kAudioUnitScope_Global;
3351 event.mArgument.mProperty.mElement = 0;
3353 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3354 PBD::error << "Failed to create latency event listener\n";
3355 // TODO don't cache _current_latency
3362 AUPlugin::listen_to_parameter (uint32_t param_id)
3364 AudioUnitEvent event;
3366 if (!_parameter_listener || param_id >= descriptors.size()) {
3370 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3371 event.mArgument.mParameter.mAudioUnit = unit->AU();
3372 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3373 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3374 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3376 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3380 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3381 event.mArgument.mParameter.mAudioUnit = unit->AU();
3382 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3383 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3384 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3386 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3390 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3391 event.mArgument.mParameter.mAudioUnit = unit->AU();
3392 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3393 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3394 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3396 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3404 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3406 AudioUnitEvent event;
3408 if (!_parameter_listener || param_id >= descriptors.size()) {
3412 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3413 event.mArgument.mParameter.mAudioUnit = unit->AU();
3414 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3415 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3416 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3418 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3422 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3423 event.mArgument.mParameter.mAudioUnit = unit->AU();
3424 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3425 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3426 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3428 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3432 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3433 event.mArgument.mParameter.mAudioUnit = unit->AU();
3434 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3435 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3436 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3438 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3446 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3448 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3452 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3454 if (event->mEventType == kAudioUnitEvent_PropertyChange) {
3455 if (event->mArgument.mProperty.mPropertyID == kAudioUnitProperty_Latency) {
3456 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Latency Change Event %1 <> %2\n", new_value, unit->Latency()));
3457 guint lat = unit->Latency() * _session.sample_rate();
3458 g_atomic_int_set (&_current_latency, lat);
3463 ParameterMap::iterator i;
3465 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3469 switch (event->mEventType) {
3470 case kAudioUnitEvent_BeginParameterChangeGesture:
3471 StartTouch (i->second);
3473 case kAudioUnitEvent_EndParameterChangeGesture:
3474 EndTouch (i->second);
3476 case kAudioUnitEvent_ParameterValueChange:
3477 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3478 means that something else (i.e. the plugin GUI) made the change.
3480 Plugin::parameter_changed_externally (i->second, new_value);