2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include "pbd/gstdio_compat.h"
29 #include "pbd/transmitter.h"
30 #include "pbd/xml++.h"
31 #include "pbd/convert.h"
32 #include "pbd/whitespace.h"
33 #include "pbd/file_utils.h"
34 #include "pbd/locale_guard.h"
36 #include <glibmm/threads.h>
37 #include <glibmm/fileutils.h>
38 #include <glibmm/miscutils.h>
40 #include "ardour/ardour.h"
41 #include "ardour/audio_unit.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/audio_buffer.h"
44 #include "ardour/debug.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/midi_buffer.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
53 #include "CAAudioUnit.h"
54 #include "CAAUParameter.h"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
61 #include <Carbon/Carbon.h>
65 #define ArdourComponent Component
66 #define ArdourDescription ComponentDescription
67 #define ArdourFindNext FindNextComponent
69 #define ArdourComponent AudioComponent
70 #define ArdourDescription AudioComponentDescription
71 #define ArdourFindNext AudioComponentFindNext
78 using namespace ARDOUR;
80 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
82 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
83 static string preset_suffix = ".aupreset";
84 static bool preset_search_path_initialized = false;
85 FILE * AUPluginInfo::_crashlog_fd = NULL;
86 bool AUPluginInfo::_scan_only = true;
89 static void au_blacklist (std::string id)
91 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
92 FILE * blacklist_fd = NULL;
93 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
94 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
97 assert(id.find("\n") == string::npos);
98 fprintf(blacklist_fd, "%s\n", id.c_str());
99 ::fclose(blacklist_fd);
102 static void au_unblacklist (std::string id)
104 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
105 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
106 PBD::warning << "Expected Blacklist file does not exist.\n";
112 std::ifstream ifs(fn.c_str());
113 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
116 ::g_unlink (fn.c_str());
118 assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
119 assert(id.find("\n") == string::npos);
121 id += "\n"; // add separator
122 const size_t rpl = bl.find(id);
123 if (rpl != string::npos) {
124 bl.replace(rpl, id.size(), "");
130 FILE * blacklist_fd = NULL;
131 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
132 PBD::error << "Cannot open AU blacklist.\n";
135 fprintf(blacklist_fd, "%s", bl.c_str());
136 ::fclose(blacklist_fd);
139 static bool is_blacklisted (std::string id)
141 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
142 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
146 std::ifstream ifs(fn.c_str());
147 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
149 assert(id.find("\n") == string::npos);
151 id += "\n"; // add separator
152 const size_t rpl = bl.find(id);
153 if (rpl != string::npos) {
162 _render_callback(void *userData,
163 AudioUnitRenderActionFlags *ioActionFlags,
164 const AudioTimeStamp *inTimeStamp,
166 UInt32 inNumberSamples,
167 AudioBufferList* ioData)
170 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberSamples, ioData);
176 _get_beat_and_tempo_callback (void* userData,
177 Float64* outCurrentBeat,
178 Float64* outCurrentTempo)
181 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
188 _get_musical_time_location_callback (void * userData,
189 UInt32 * outDeltaSampleOffsetToNextBeat,
190 Float32 * outTimeSig_Numerator,
191 UInt32 * outTimeSig_Denominator,
192 Float64 * outCurrentMeasureDownBeat)
195 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
196 outTimeSig_Numerator,
197 outTimeSig_Denominator,
198 outCurrentMeasureDownBeat);
204 _get_transport_state_callback (void* userData,
205 Boolean* outIsPlaying,
206 Boolean* outTransportStateChanged,
207 Float64* outCurrentSampleInTimeLine,
208 Boolean* outIsCycling,
209 Float64* outCycleStartBeat,
210 Float64* outCycleEndBeat)
213 return ((AUPlugin*)userData)->get_transport_state_callback (
214 outIsPlaying, outTransportStateChanged,
215 outCurrentSampleInTimeLine, outIsCycling,
216 outCycleStartBeat, outCycleEndBeat);
223 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
229 // Convert the property list into XML data.
231 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
234 error << _("Could not create XML version of property list") << endmsg;
238 // Write the XML data to the file.
240 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
242 if (errno == EEXIST) {
243 error << string_compose (_("Preset file %1 exists; not overwriting"),
246 error << string_compose (_("Cannot open preset file %1 (%2)"),
247 path, strerror (errno)) << endmsg;
253 size_t cnt = CFDataGetLength (xmlData);
255 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
266 static CFPropertyListRef
267 load_property_list (Glib::ustring path)
270 CFPropertyListRef propertyList = 0;
272 CFStringRef errorString;
274 // Read the XML file.
276 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
281 off_t len = lseek (fd, 0, SEEK_END);
282 char* buf = new char[len];
283 lseek (fd, 0, SEEK_SET);
285 if (read (fd, buf, len) != len) {
293 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
295 // Reconstitute the dictionary using the XML data.
297 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
299 kCFPropertyListImmutable,
308 //-----------------------------------------------------------------------------
310 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
315 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
317 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
318 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
324 //-----------------------------------------------------------------------------
326 get_preset_name_in_plist (CFPropertyListRef plist)
334 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
335 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
337 CFStringRef str = (CFStringRef) p;
338 int len = CFStringGetLength(str);
340 char local_buffer[len];
341 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
349 //--------------------------------------------------------------------------
350 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
351 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
352 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
353 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
355 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
358 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
359 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
361 // only sub-type and manufacturer IDs need to be equal
364 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
365 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
372 //--------------------------------------------------------------------------
373 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
374 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
375 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
376 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
379 ArdourDescription desc;
381 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
384 // get the ComponentDescription of the input Component
386 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
388 status = AudioComponentGetDescription (inComponent, &desc);
393 // check if the Component's ComponentDescription matches the input ComponentDescription
394 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
397 //--------------------------------------------------------------------------
398 // determine if 2 ComponentDescriptions are basically equal
399 // (by that, I mean that the important identifying values are compared,
400 // but not the ComponentDescription flags)
401 Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
403 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
406 //--------------------------------------------------------------------------
407 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
408 Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
410 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
413 //--------------------------------------------------------------------------
414 // determine if a ComponentDescription basically matches that of a particular Component
415 Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
417 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
420 //--------------------------------------------------------------------------
421 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
422 Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
424 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
428 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
429 : Plugin (engine, session)
431 , unit (new CAAudioUnit)
432 , initialized (false)
434 , _current_latency (UINT_MAX)
435 , _requires_fixed_size_buffers (false)
437 , variable_inputs (false)
438 , variable_outputs (false)
439 , configured_input_busses (0)
440 , configured_output_busses (0)
448 , samples_processed (0)
449 , audio_input_cnt (0)
450 , _parameter_listener (0)
451 , _parameter_listener_arg (0)
452 , transport_sample (0)
453 , transport_speed (0)
454 , last_transport_speed (0.0)
457 if (!preset_search_path_initialized) {
458 Glib::ustring p = Glib::get_home_dir();
459 p += "/Library/Audio/Presets:";
460 p += preset_search_path;
461 preset_search_path = p;
462 preset_search_path_initialized = true;
463 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
470 AUPlugin::AUPlugin (const AUPlugin& other)
472 , comp (other.get_comp())
473 , unit (new CAAudioUnit)
474 , initialized (false)
476 , _current_latency (UINT_MAX)
477 , _requires_fixed_size_buffers (false)
479 , variable_inputs (false)
480 , variable_outputs (false)
481 , configured_input_busses (0)
482 , configured_output_busses (0)
490 , samples_processed (0)
491 , audio_input_cnt (0)
492 , _parameter_listener (0)
493 , _parameter_listener_arg (0)
494 , transport_sample (0)
495 , transport_speed (0)
496 , last_transport_speed (0.0)
501 for (size_t i = 0; i < descriptors.size(); ++i) {
502 set_parameter (i, other.get_parameter (i));
506 AUPlugin::~AUPlugin ()
508 if (_parameter_listener) {
509 AUListenerDispose (_parameter_listener);
510 _parameter_listener = 0;
514 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
515 unit->Uninitialize ();
525 AUPlugin::discover_factory_presets ()
532 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
533 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
537 assert (dataSize == sizeof (presets));
539 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
540 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
548 CFIndex cnt = CFArrayGetCount (presets);
550 for (CFIndex i = 0; i < cnt; ++i) {
551 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
553 string name = CFStringRefToStdString (preset->presetName);
554 factory_preset_map[name] = preset->presetNumber;
555 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
565 CFStringRef itemName;
567 /* these keep track of *configured* channel set up,
568 not potential set ups.
572 output_channels = -1;
574 CAComponentDescription temp;
576 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
578 AudioComponentGetDescription (comp.get()->Comp(), &temp);
580 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
581 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
582 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
583 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
584 compTypeString, compManufacturerString, compSubTypeString);
585 if (compTypeString != NULL) CFRelease(compTypeString);
586 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
587 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
590 au_blacklist(CFStringRefToStdString(itemName));
593 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
594 err = CAAudioUnit::Open (*(comp.get()), *unit);
596 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
597 throw failed_constructor();
601 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
602 throw failed_constructor ();
605 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
606 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
607 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
608 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
609 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
610 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
612 cb_offsets = (samplecnt_t*) calloc (input_elements, sizeof(samplecnt_t));
613 bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
614 bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
616 for (size_t i = 0; i < output_elements; ++i) {
617 unit->Reset (kAudioUnitScope_Output, i);
618 AudioStreamBasicDescription fmt;
619 err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
621 bus_outputs[i] = fmt.mChannelsPerFrame;
624 UInt32 sz = sizeof (CFStringRef);
625 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
626 i, &name, &sz) == noErr
628 _bus_name_out.push_back (CFStringRefToStdString (name));
631 _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
635 for (size_t i = 0; i < input_elements; ++i) {
636 unit->Reset (kAudioUnitScope_Input, i);
637 AudioStreamBasicDescription fmt;
638 err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
640 bus_inputs[i] = fmt.mChannelsPerFrame;
643 UInt32 sz = sizeof (CFStringRef);
644 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
645 i, &name, &sz) == noErr
647 _bus_name_in.push_back (CFStringRefToStdString (name));
650 _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
654 for (size_t i = 0; i < input_elements; ++i) {
655 /* setup render callback: the plugin calls this to get input data */
656 AURenderCallbackStruct renderCallbackInfo;
657 renderCallbackInfo.inputProc = _render_callback;
658 renderCallbackInfo.inputProcRefCon = this;
659 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
660 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
661 i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
662 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
663 throw failed_constructor();
667 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
669 HostCallbackInfo info;
670 memset (&info, 0, sizeof (HostCallbackInfo));
671 info.hostUserData = this;
672 info.beatAndTempoProc = _get_beat_and_tempo_callback;
673 info.musicalTimeLocationProc = _get_musical_time_location_callback;
674 info.transportStateProc = _get_transport_state_callback;
676 //ignore result of this - don't care if the property isn't supported
677 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
678 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
679 kAudioUnitScope_Global,
682 sizeof (HostCallbackInfo));
684 if (set_block_size (_session.get_block_size())) {
685 error << _("AUPlugin: cannot set processing block size") << endmsg;
686 throw failed_constructor();
689 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
690 discover_parameters ();
691 discover_factory_presets ();
693 // Plugin::setup_controls ();
695 au_unblacklist(CFStringRefToStdString(itemName));
696 if (itemName != NULL) CFRelease(itemName);
700 AUPlugin::discover_parameters ()
702 /* discover writable parameters */
704 AudioUnitScope scopes[] = {
705 kAudioUnitScope_Global,
706 kAudioUnitScope_Output,
707 kAudioUnitScope_Input
710 descriptors.clear ();
712 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
714 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
716 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
718 AUParameterDescriptor d;
720 d.id = param_info.ParamID (i);
722 const CAAUParameter* param = param_info.GetParamInfo (d.id);
723 const AudioUnitParameterInfo& info (param->ParamInfo());
725 const int len = CFStringGetLength (param->GetName());
726 char local_buffer[len*2];
727 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
731 d.label = local_buffer;
734 d.scope = param_info.GetScope ();
735 d.element = param_info.GetElement ();
737 /* info.units to consider */
739 kAudioUnitParameterUnit_Generic = 0
740 kAudioUnitParameterUnit_Indexed = 1
741 kAudioUnitParameterUnit_Boolean = 2
742 kAudioUnitParameterUnit_Percent = 3
743 kAudioUnitParameterUnit_Seconds = 4
744 kAudioUnitParameterUnit_SampleFrames = 5
745 kAudioUnitParameterUnit_Phase = 6
746 kAudioUnitParameterUnit_Rate = 7
747 kAudioUnitParameterUnit_Hertz = 8
748 kAudioUnitParameterUnit_Cents = 9
749 kAudioUnitParameterUnit_RelativeSemiTones = 10
750 kAudioUnitParameterUnit_MIDINoteNumber = 11
751 kAudioUnitParameterUnit_MIDIController = 12
752 kAudioUnitParameterUnit_Decibels = 13
753 kAudioUnitParameterUnit_LinearGain = 14
754 kAudioUnitParameterUnit_Degrees = 15
755 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
756 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
757 kAudioUnitParameterUnit_Pan = 18
758 kAudioUnitParameterUnit_Meters = 19
759 kAudioUnitParameterUnit_AbsoluteCents = 20
760 kAudioUnitParameterUnit_Octaves = 21
761 kAudioUnitParameterUnit_BPM = 22
762 kAudioUnitParameterUnit_Beats = 23
763 kAudioUnitParameterUnit_Milliseconds = 24
764 kAudioUnitParameterUnit_Ratio = 25
767 /* info.flags to consider */
771 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
772 kAudioUnitParameterFlag_HasClump = (1L << 20)
773 kAudioUnitParameterFlag_HasName = (1L << 21)
774 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
775 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
776 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
777 kAudioUnitParameterFlag_CanRamp = (1L << 25)
778 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
779 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
780 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
781 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
782 kAudioUnitParameterFlag_IsReadable = (1L << 30)
783 kAudioUnitParameterFlag_IsWritable = (1L << 31)
786 d.lower = info.minValue;
787 d.upper = info.maxValue;
788 d.normal = info.defaultValue;
790 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
791 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
792 (d.integer_step && ((d.upper - d.lower) == 1.0));
793 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
794 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
795 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
796 (info.flags & kAudioUnitParameterFlag_IsWritable);
798 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
799 d.au_unit = info.unit;
801 case kAudioUnitParameterUnit_Decibels:
802 d.unit = ParameterDescriptor::DB;
804 case kAudioUnitParameterUnit_MIDINoteNumber:
805 d.unit = ParameterDescriptor::MIDI_NOTE;
807 case kAudioUnitParameterUnit_Hertz:
808 d.unit = ParameterDescriptor::HZ;
814 descriptors.push_back (d);
816 uint32_t last_param = descriptors.size() - 1;
817 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
818 listen_to_parameter (last_param);
825 four_ints_to_four_byte_literal (unsigned char n[4])
827 /* this is actually implementation dependent. sigh. this is what gcc
828 and quite a few others do.
830 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
834 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
836 if (isdigit (id[0])) {
840 /* ID format is xxxx-xxxx-xxxx
841 where x maybe \xNN or a printable character.
843 Split at the '-' and and process each part into an integer.
844 Then put it back together.
848 unsigned char nascent[4];
849 const char* cstr = id.c_str();
850 const char* estr = cstr + id.size();
861 while (*cstr && next_int < 4) {
865 if (estr - cstr < 3) {
867 /* too close to the end for \xNN parsing: treat as literal characters */
875 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
879 memcpy (short_buf, &cstr[2], 2);
880 nascent[in] = strtol (short_buf, NULL, 16);
886 /* treat as literal characters */
900 if (in && (in % 4 == 0)) {
901 /* nascent is ready */
902 n[next_int] = four_ints_to_four_byte_literal (nascent);
906 /* swallow space-hyphen-space */
920 s << n[0] << '-' << n[1] << '-' << n[2];
929 AUPlugin::unique_id () const
931 return AUPluginInfo::stringify_descriptor (comp->Desc());
935 AUPlugin::label () const
937 return _info->name.c_str();
941 AUPlugin::parameter_count () const
943 return descriptors.size();
947 AUPlugin::default_value (uint32_t port)
949 if (port < descriptors.size()) {
950 return descriptors[port].normal;
957 AUPlugin::plugin_latency () const
959 guint lat = g_atomic_int_get (&_current_latency);;
960 if (lat == UINT_MAX) {
961 lat = unit->Latency() * _session.sample_rate();
962 g_atomic_int_set (&_current_latency, lat);
968 AUPlugin::set_parameter (uint32_t which, float val)
970 if (which >= descriptors.size()) {
974 if (get_parameter(which) == val) {
978 const AUParameterDescriptor& d (descriptors[which]);
979 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
980 unit->SetParameter (d.id, d.scope, d.element, val);
982 /* tell the world what we did */
984 AudioUnitEvent theEvent;
986 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
987 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
988 theEvent.mArgument.mParameter.mParameterID = d.id;
989 theEvent.mArgument.mParameter.mScope = d.scope;
990 theEvent.mArgument.mParameter.mElement = d.element;
992 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
993 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
994 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
996 Plugin::set_parameter (which, val);
1000 AUPlugin::get_parameter (uint32_t which) const
1003 if (which < descriptors.size()) {
1004 const AUParameterDescriptor& d (descriptors[which]);
1005 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
1006 unit->GetParameter(d.id, d.scope, d.element, val);
1012 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
1014 if (which < descriptors.size()) {
1015 pd = descriptors[which];
1022 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
1024 if (which < descriptors.size()) {
1033 AUPlugin::activate ()
1037 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
1038 if ((err = unit->Initialize()) != noErr) {
1039 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
1041 samples_processed = 0;
1048 AUPlugin::deactivate ()
1050 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
1051 unit->Uninitialize ();
1052 initialized = false;
1058 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
1059 unit->GlobalReset ();
1063 AUPlugin::requires_fixed_size_buffers() const
1065 return _requires_fixed_size_buffers;
1070 AUPlugin::set_block_size (pframes_t nframes)
1072 bool was_initialized = initialized;
1073 UInt32 numSamples = nframes;
1080 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numSamples));
1081 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1082 0, &numSamples, sizeof (numSamples))) != noErr) {
1083 error << string_compose (_("AU: cannot set max samples (err = %1)"), err) << endmsg;
1087 if (was_initialized) {
1095 AUPlugin::configure_io (ChanCount in, ChanCount out)
1097 AudioStreamBasicDescription streamFormat;
1098 bool was_initialized = initialized;
1099 int32_t audio_out = out.n_audio();
1100 if (audio_input_cnt > 0) {
1101 in.set (DataType::AUDIO, audio_input_cnt);
1103 const int32_t audio_in = in.n_audio();
1105 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1108 //if we are already running with the requested i/o config, bail out here
1109 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1116 streamFormat.mSampleRate = _session.sample_rate();
1117 streamFormat.mFormatID = kAudioFormatLinearPCM;
1118 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1120 #ifdef __LITTLE_ENDIAN__
1123 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1126 streamFormat.mBitsPerChannel = 32;
1127 streamFormat.mFramesPerPacket = 1;
1129 /* apple says that for non-interleaved data, these
1130 * values always refer to a single channel.
1132 streamFormat.mBytesPerPacket = 4;
1133 streamFormat.mBytesPerFrame = 4;
1135 configured_input_busses = 0;
1136 configured_output_busses = 0;
1138 for (size_t i = 0; i < output_elements; ++i) {
1139 unit->Reset (kAudioUnitScope_Output, i);
1141 for (size_t i = 0; i < input_elements; ++i) {
1142 unit->Reset (kAudioUnitScope_Input, i);
1145 /* now assign the channels to available busses */
1146 uint32_t used_in = 0;
1147 uint32_t used_out = 0;
1149 if (variable_inputs || input_elements == 1) {
1150 // we only ever use the first bus
1151 if (input_elements > 1) {
1152 warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
1154 streamFormat.mChannelsPerFrame = audio_in;
1155 if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
1158 configured_input_busses = 1;
1161 configured_input_busses = 0;
1162 uint32_t remain = audio_in;
1163 for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
1164 uint32_t cnt = std::min (remain, bus_inputs[bus]);
1165 if (cnt == 0) { continue; }
1166 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
1168 streamFormat.mChannelsPerFrame = cnt;
1169 if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
1173 ++configured_input_busses;
1178 if (variable_outputs || output_elements == 1) {
1179 if (output_elements > 1) {
1180 warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
1183 streamFormat.mChannelsPerFrame = audio_out;
1184 if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
1187 configured_output_busses = 1;
1188 used_out = audio_out;
1190 uint32_t remain = audio_out;
1191 configured_output_busses = 0;
1192 for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
1193 uint32_t cnt = std::min (remain, bus_outputs[bus]);
1194 if (cnt == 0) { continue; }
1195 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
1196 streamFormat.mChannelsPerFrame = cnt;
1197 if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
1202 ++configured_output_busses;
1207 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1208 used_out * sizeof(::AudioBuffer));
1210 input_channels = used_in;
1211 output_channels = used_out;
1212 /* reset plugin info to show currently configured state */
1214 _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
1215 _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
1217 if (was_initialized) {
1225 AUPlugin::input_streams() const
1228 if (input_channels < 0) {
1229 // force PluginIoReConfigure -- see also commit msg e38eb06
1230 c.set (DataType::AUDIO, 0);
1231 c.set (DataType::MIDI, 0);
1233 c.set (DataType::AUDIO, input_channels);
1234 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1241 AUPlugin::output_streams() const
1244 if (output_channels < 0) {
1245 // force PluginIoReConfigure - see also commit msg e38eb06
1246 c.set (DataType::AUDIO, 0);
1247 c.set (DataType::MIDI, 0);
1249 c.set (DataType::AUDIO, output_channels);
1250 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1256 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1258 _output_configs.clear ();
1259 const int32_t audio_in = in.n_audio();
1260 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1262 /* lets check MIDI first */
1264 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1268 vector<pair<int,int> > io_configs = pinfo->cache.io_configs;
1270 if (input_elements > 1) {
1271 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1272 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1273 int32_t possible_in = i->first;
1274 int32_t possible_out = i->second;
1275 if (possible_in < 0) {
1278 for (uint32_t i = 1; i < input_elements; ++i) {
1279 // can't use up-to bus_inputs[]
1280 // waves' SC-C6(s) for example fails to configure with only 1 input
1282 io_configs.push_back (pair<int,int> (possible_in + bus_inputs[i], possible_out));
1284 /* only add additional, optional busses to first available config.
1285 * AUPluginInfo::cached_io_configuration () already incrementally
1286 * adds busses (for instruments w/ multiple configurations)
1292 if (output_elements > 1) {
1293 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1294 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1295 int32_t possible_in = i->first;
1296 int32_t possible_out = i->second;
1297 if (possible_out < 0) {
1300 for (uint32_t i = 1; i < output_elements; ++i) {
1301 int32_t c = bus_outputs[i];
1302 for (uint32_t j = 1; j < i; ++j) {
1303 c += bus_outputs [j];
1305 io_configs.push_back (pair<int,int> (possible_in, possible_out + c));
1307 /* only add additional, optional busses to first available config.
1308 * AUPluginInfo::cached_io_configuration () already incrementally
1309 * adds busses (for instruments w/ multiple configurations)
1315 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1316 name(), io_configs.size(), in, out));
1319 printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
1320 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1321 printf ("- I/O %d / %d\n", i->first, i->second);
1325 // preferred setting (provided by plugin_insert)
1326 const int preferred_out = out.n_audio ();
1328 bool exact_match = false;
1330 /* kAudioUnitProperty_SupportedNumChannels
1331 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1333 * - both fields are -1
1334 * e.g. inChannels = -1 outChannels = -1
1335 * This is the default case. Any number of input and output channels, as long as the numbers match
1337 * - one field is -1, the other field is positive
1338 * e.g. inChannels = -1 outChannels = 2
1339 * Any number of input channels, exactly two output channels
1341 * - one field is -1, the other field is -2
1342 * e.g. inChannels = -1 outChannels = -2
1343 * Any number of input channels, any number of output channels
1345 * - both fields have non-negative values
1346 * e.g. inChannels = 2 outChannels = 6
1347 * Exactly two input channels, exactly six output channels
1348 * e.g. inChannels = 0 outChannels = 2
1349 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1351 * - both fields have negative values, neither of which is –1 or –2
1352 * e.g. inChannels = -4 outChannels = -8
1353 * Up to four input channels and up to eight output channels
1356 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1358 int32_t possible_in = i->first;
1359 int32_t possible_out = i->second;
1361 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1362 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1363 possible_in, possible_out,
1367 _output_configs.insert (preferred_out);
1374 /* now allow potentially "imprecise" matches */
1375 int32_t audio_out = -1;
1376 float penalty = 9999;
1377 int used_possible_in = 0;
1378 #if defined (__clang__)
1379 # pragma clang diagnostic push
1380 # pragma clang diagnostic ignored "-Wtautological-compare"
1383 #define FOUNDCFG(nch) { \
1384 float p = fabsf ((float)(nch) - preferred_out); \
1385 _output_configs.insert (nch); \
1386 if ((nch) > preferred_out) { p *= 1.1; } \
1387 if (p < penalty) { \
1388 used_possible_in = possible_in; \
1389 audio_out = (nch); \
1392 variable_inputs = possible_in < 0; \
1393 variable_outputs = possible_out < 0; \
1397 #define ANYTHINGGOES \
1398 _output_configs.insert (0);
1400 #define UPTO(nch) { \
1401 for (int n = 1; n <= nch; ++n) { \
1402 _output_configs.insert (n); \
1406 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1408 int32_t possible_in = i->first;
1409 int32_t possible_out = i->second;
1411 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1413 if (possible_out == 0) {
1414 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1415 /* XXX surely this is just a send? (e.g. AUNetSend) */
1419 if (possible_in == 0) {
1420 /* no inputs, generators & instruments */
1421 if (possible_out == -1) {
1422 /* any configuration possible, provide stereo output */
1423 FOUNDCFG (preferred_out);
1425 } else if (possible_out == -2) {
1426 /* invalid, should be (0, -1) */
1427 FOUNDCFG (preferred_out);
1429 } else if (possible_out < -2) {
1430 /* variable number of outputs up to -N, */
1431 FOUNDCFG (min (-possible_out, preferred_out));
1432 UPTO (-possible_out);
1434 /* exact number of outputs */
1435 FOUNDCFG (possible_out);
1439 if (possible_in == -1) {
1440 /* wildcard for input */
1441 if (possible_out == -1) {
1442 /* out must match in */
1443 FOUNDCFG (audio_in);
1444 } else if (possible_out == -2) {
1445 /* any configuration possible, pick matching */
1446 FOUNDCFG (preferred_out);
1448 } else if (possible_out < -2) {
1449 /* explicitly variable number of outputs, pick maximum */
1450 FOUNDCFG (max (-possible_out, preferred_out));
1451 /* and try min, too, in case the penalty is lower */
1452 FOUNDCFG (min (-possible_out, preferred_out));
1453 UPTO (-possible_out)
1455 /* exact number of outputs */
1456 FOUNDCFG (possible_out);
1460 if (possible_in == -2) {
1461 if (possible_out == -1) {
1462 /* any configuration possible, pick matching */
1463 FOUNDCFG (preferred_out);
1465 } else if (possible_out == -2) {
1466 /* invalid. interpret as (-1, -1) */
1467 FOUNDCFG (preferred_out);
1469 } else if (possible_out < -2) {
1470 /* invalid, interpret as (<-2, <-2)
1471 * variable number of outputs up to -N, */
1472 FOUNDCFG (min (-possible_out, preferred_out));
1473 UPTO (-possible_out)
1475 /* exact number of outputs */
1476 FOUNDCFG (possible_out);
1480 if (possible_in < -2) {
1481 /* explicit variable number of inputs */
1482 if (audio_in > -possible_in && imprecise != NULL) {
1483 // hide inputs ports
1484 imprecise->set (DataType::AUDIO, -possible_in);
1487 if (audio_in > -possible_in && imprecise == NULL) {
1488 /* request is too large */
1489 } else if (possible_out == -1) {
1490 /* any output configuration possible */
1491 FOUNDCFG (preferred_out);
1493 } else if (possible_out == -2) {
1494 /* invalid. interpret as (<-2, -1) */
1495 FOUNDCFG (preferred_out);
1497 } else if (possible_out < -2) {
1498 /* variable number of outputs up to -N, */
1499 FOUNDCFG (min (-possible_out, preferred_out));
1500 UPTO (-possible_out)
1502 /* exact number of outputs */
1503 FOUNDCFG (possible_out);
1507 if (possible_in && (possible_in == audio_in)) {
1508 /* exact number of inputs ... must match obviously */
1509 if (possible_out == -1) {
1510 /* any output configuration possible */
1511 FOUNDCFG (preferred_out);
1513 } else if (possible_out == -2) {
1514 /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
1515 FOUNDCFG (preferred_out);
1517 } else if (possible_out < -2) {
1518 /* > 0, < -2 is not specified
1519 * interpret as up to -N */
1520 FOUNDCFG (min (-possible_out, preferred_out));
1521 UPTO (-possible_out)
1523 /* exact number of outputs */
1524 FOUNDCFG (possible_out);
1529 if (!found && imprecise) {
1531 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1532 int32_t possible_in = i->first;
1533 int32_t possible_out = i->second;
1535 assert (possible_in > 0); // all other cases will have been matched above
1536 assert (possible_out !=0 || possible_in !=0); // already handled above
1538 imprecise->set (DataType::AUDIO, possible_in);
1539 if (possible_out == -1 || possible_out == -2) {
1541 } else if (possible_out < -2) {
1542 /* explicitly variable number of outputs, pick maximum */
1543 FOUNDCFG (min (-possible_out, preferred_out));
1545 /* exact number of outputs */
1546 FOUNDCFG (possible_out);
1548 // ideally we'll also find the closest, best matching
1549 // input configuration with minimal output penalty...
1554 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1559 out.set (DataType::MIDI, 0); // currently always zero
1560 out.set (DataType::AUDIO, preferred_out);
1562 if (used_possible_in < -2 && audio_in == 0) {
1563 // input-port count cannot be zero, use as many ports
1564 // as outputs, but at most abs(possible_in)
1565 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1567 out.set (DataType::MIDI, 0); /// XXX
1568 out.set (DataType::AUDIO, audio_out);
1570 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1572 #if defined (__clang__)
1573 # pragma clang diagnostic pop
1579 AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
1583 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1584 (scope == kAudioUnitScope_Input ? "input" : "output"),
1586 if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
1587 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1588 (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
1595 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1596 const AudioTimeStamp*,
1598 UInt32 inNumberSamples,
1599 AudioBufferList* ioData)
1601 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1603 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, samples %2 bus %3 bufs %4\n",
1604 // name(), inNumberSamples, bus, ioData->mNumberBuffers));
1606 if (input_maxbuf == 0) {
1607 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1608 error << _("AUPlugin: render callback called illegally!") << endmsg;
1609 return kAudioUnitErr_CannotDoInCurrentContext;
1612 assert (bus < input_elements);
1613 uint32_t busoff = 0;
1614 for (uint32_t i = 0; i < bus; ++i) {
1615 busoff += bus_inputs[i];
1618 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1620 ChanCount bufs_count (DataType::AUDIO, 1);
1621 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1623 /* apply bus offsets */
1625 for (uint32_t i = 0; i < limit; ++i) {
1626 ioData->mBuffers[i].mNumberChannels = 1;
1627 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberSamples;
1630 uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
1632 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
1634 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
1637 cb_offsets[bus] += inNumberSamples;
1642 AUPlugin::connect_and_run (BufferSet& bufs,
1643 samplepos_t start, samplepos_t end, double speed,
1644 ChanMapping const& in_map, ChanMapping const& out_map,
1645 pframes_t nframes, samplecnt_t offset)
1647 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
1649 transport_sample = start;
1650 transport_speed = speed;
1652 AudioUnitRenderActionFlags flags = 0;
1656 if (preset_holdoff > 0) {
1657 preset_holdoff -= std::min (nframes, preset_holdoff);
1660 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1661 unit->GlobalReset();
1662 _last_nframes = nframes;
1665 /* test if we can run in-place; only compare audio buffers */
1666 bool inplace = true; // TODO check plugin-insert in-place ?
1667 ChanMapping::Mappings inmap (in_map.mappings ());
1668 ChanMapping::Mappings outmap (out_map.mappings ());
1669 if (outmap[DataType::AUDIO].size () == 0) {
1672 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1676 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",
1677 name(), input_channels, output_channels, _has_midi_input,
1678 bufs.count(), bufs.available(),
1679 configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
1681 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1682 * has the capacity to handle our outputs.
1685 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1687 input_buffers = &bufs;
1688 input_map = &in_map;
1689 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1690 input_offset = offset;
1691 for (size_t i = 0; i < input_elements; ++i) {
1695 ChanCount bufs_count (DataType::AUDIO, 1);
1696 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1698 if (_has_midi_input) {
1699 uint32_t nmidi = bufs.count().n_midi();
1700 for (uint32_t i = 0; i < nmidi; ++i) {
1701 /* one MIDI port/buffer only */
1702 MidiBuffer& m = bufs.get_midi (i);
1703 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1704 Evoral::Event<samplepos_t> ev (*i);
1705 if (ev.is_channel_event()) {
1706 const uint8_t* b = ev.buffer();
1707 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1708 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1710 /* XXX need to handle sysex and other message types */
1715 assert (input_maxbuf < 512);
1716 std::bitset<512> used_outputs;
1719 uint32_t busoff = 0;
1720 uint32_t remain = output_channels;
1721 for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
1723 if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
1724 cnt = output_channels;
1726 cnt = std::min (remain, bus_outputs[bus]);
1730 buffers->mNumberBuffers = cnt;
1732 for (uint32_t i = 0; i < cnt; ++i) {
1733 buffers->mBuffers[i].mNumberChannels = 1;
1734 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1735 /* setting this to 0 indicates to the AU that it can provide buffers here
1736 * if necessary. if it can process in-place, it will use the buffers provided
1737 * as input by ::render_callback() above.
1739 * a non-null values tells the plugin to render into the buffer pointed
1743 buffers->mBuffers[i].mData = 0;
1746 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1748 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1750 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1755 /* does this really mean anything ? */
1756 ts.mSampleTime = samples_processed;
1757 ts.mFlags = kAudioTimeStampSampleTimeValid;
1759 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
1760 name(), flags, samples_processed, nframes, bus, buffers->mNumberBuffers));
1762 if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
1764 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1765 name(), buffers->mNumberBuffers, output_channels));
1767 uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
1768 for (uint32_t i = 0; i < limit; ++i) {
1770 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1771 if (!valid) continue;
1772 used_outputs.set (i + busoff);
1773 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1774 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1775 /* plugin provided its own buffer for output so copy it back to where we want it */
1776 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1780 DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
1781 error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
1787 busoff += bus_outputs[bus];
1790 /* now silence any buffers that were passed in but the that the plugin
1791 * did not fill/touch/use.
1793 * TODO: optimize, when plugin-insert is processing in-place
1794 * unconnected buffers are (also) cleared there.
1796 for (uint32_t i = 0; i < input_maxbuf; ++i) {
1797 if (used_outputs.test (i)) { continue; }
1799 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1800 if (!valid) continue;
1801 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1807 samples_processed += nframes;
1814 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1815 Float64* outCurrentTempo)
1817 TempoMap& tmap (_session.tempo_map());
1819 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1821 if (outCurrentBeat) {
1822 *outCurrentBeat = tmap.quarter_note_at_sample (transport_sample + input_offset);
1825 if (outCurrentTempo) {
1826 *outCurrentTempo = tmap.tempo_at_sample (transport_sample + input_offset).quarter_notes_per_minute();
1834 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1835 Float32* outTimeSig_Numerator,
1836 UInt32* outTimeSig_Denominator,
1837 Float64* outCurrentMeasureDownBeat)
1839 TempoMap& tmap (_session.tempo_map());
1841 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1843 TempoMetric metric = tmap.metric_at (transport_sample + input_offset);
1844 Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_sample (transport_sample + input_offset);
1846 if (outDeltaSampleOffsetToNextBeat) {
1847 if (bbt.ticks == 0) {
1849 *outDeltaSampleOffsetToNextBeat = 0;
1851 double const next_beat = ceil (tmap.quarter_note_at_sample (transport_sample + input_offset));
1852 samplepos_t const next_beat_sample = tmap.sample_at_quarter_note (next_beat);
1854 *outDeltaSampleOffsetToNextBeat = next_beat_sample - (transport_sample + input_offset);
1858 if (outTimeSig_Numerator) {
1859 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1861 if (outTimeSig_Denominator) {
1862 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1865 if (outCurrentMeasureDownBeat) {
1867 /* beat for the start of the bar.
1869 2|1|0 -> 1 + divisions_per_bar
1870 3|1|0 -> 1 + (2 * divisions_per_bar)
1876 *outCurrentMeasureDownBeat = tmap.quarter_note_at_bbt (bbt);
1883 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1884 Boolean* outTransportStateChanged,
1885 Float64* outCurrentSampleInTimeLine,
1886 Boolean* outIsCycling,
1887 Float64* outCycleStartBeat,
1888 Float64* outCycleEndBeat)
1890 const bool rolling = (transport_speed != 0);
1891 const bool last_transport_rolling = (last_transport_speed != 0);
1893 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1897 *outIsPlaying = rolling;
1900 if (outTransportStateChanged) {
1901 if (rolling != last_transport_rolling) {
1902 *outTransportStateChanged = true;
1903 } else if (transport_speed != last_transport_speed) {
1904 *outTransportStateChanged = true;
1906 *outTransportStateChanged = false;
1910 if (outCurrentSampleInTimeLine) {
1911 /* this assumes that the AU can only call this host callback from render context,
1912 where input_offset is valid.
1914 *outCurrentSampleInTimeLine = transport_sample + input_offset;
1918 // TODO check bounce-processing
1919 Location* loc = _session.locations()->auto_loop_location();
1921 *outIsCycling = (loc && rolling && _session.get_play_loop());
1923 if (*outIsCycling) {
1925 if (outCycleStartBeat || outCycleEndBeat) {
1927 TempoMap& tmap (_session.tempo_map());
1929 Timecode::BBT_Time bbt;
1931 if (outCycleStartBeat) {
1932 *outCycleStartBeat = tmap.quarter_note_at_sample (loc->start() + input_offset);
1935 if (outCycleEndBeat) {
1936 *outCycleEndBeat = tmap.quarter_note_at_sample (loc->end() + input_offset);
1942 last_transport_speed = transport_speed;
1947 set<Evoral::Parameter>
1948 AUPlugin::automatable() const
1950 set<Evoral::Parameter> automates;
1952 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1953 if (descriptors[i].automatable) {
1954 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1961 Plugin::IOPortDescription
1962 AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1964 std::stringstream ss;
1966 case DataType::AUDIO:
1968 case DataType::MIDI:
1976 std::string busname;
1978 if (dt == DataType::AUDIO) {
1981 for (uint32_t bus = 0; bus < input_elements; ++bus) {
1982 if (pid < bus_inputs[bus]) {
1984 ss << _bus_name_in[bus];
1985 ss << " / Bus " << (1 + bus);
1986 busname = _bus_name_in[bus];
1989 pid -= bus_inputs[bus];
1994 for (uint32_t bus = 0; bus < output_elements; ++bus) {
1995 if (pid < bus_outputs[bus]) {
1997 ss << _bus_name_out[bus];
1998 ss << " / Bus " << (1 + bus);
1999 busname = _bus_name_out[bus];
2002 pid -= bus_outputs[bus];
2008 ss << " " << _("In") << " ";
2010 ss << " " << _("Out") << " ";
2015 Plugin::IOPortDescription iod (ss.str());
2016 if (!busname.empty()) {
2017 iod.group_name = busname;
2018 iod.group_channel = id;
2024 AUPlugin::describe_parameter (Evoral::Parameter param)
2026 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
2027 return descriptors[param.id()].label;
2034 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
2036 // NameValue stuff here
2038 if (param < parameter_count()) {
2039 snprintf (buf, len, "%.3f", get_parameter (param));
2047 AUPlugin::parameter_is_audio (uint32_t) const
2053 AUPlugin::parameter_is_control (uint32_t param) const
2055 assert(param < descriptors.size());
2056 if (descriptors[param].automatable) {
2057 /* corrently ardour expects all controls to be automatable
2058 * IOW ardour GUI elements mandate an Evoral::Parameter
2059 * for all input+control ports.
2067 AUPlugin::parameter_is_input (uint32_t param) const
2069 /* AU params that are both readable and writeable,
2070 * are listed in kAudioUnitScope_Global
2072 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
2076 AUPlugin::parameter_is_output (uint32_t param) const
2078 assert(param < descriptors.size());
2079 // TODO check if ardour properly handles ports
2080 // that report is_input + is_output == true
2081 // -> add || descriptors[param].scope == kAudioUnitScope_Global
2082 return (descriptors[param].scope == kAudioUnitScope_Output);
2086 AUPlugin::add_state (XMLNode* root) const
2090 CFPropertyListRef propertyList;
2092 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
2093 if (unit->GetAUPreset (propertyList) != noErr) {
2097 // Convert the property list into XML data.
2099 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
2102 error << _("Could not create XML version of property list") << endmsg;
2106 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
2107 our state node. GACK!
2112 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
2114 root->add_child_copy (*t.root());
2118 CFRelease (xmlData);
2119 CFRelease (propertyList);
2123 AUPlugin::set_state(const XMLNode& node, int version)
2126 CFPropertyListRef propertyList;
2129 if (node.name() != state_node_name()) {
2130 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
2134 #ifndef NO_PLUGIN_STATE
2135 if (node.children().empty()) {
2139 XMLNode* top = node.children().front();
2140 XMLNode* copy = new XMLNode (*top);
2145 const string& xml = t.write_buffer ();
2146 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
2147 CFStringRef errorString;
2149 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
2151 kCFPropertyListImmutable,
2154 CFRelease (xmlData);
2157 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
2158 if (unit->SetAUPreset (propertyList) == noErr) {
2161 /* tell the world */
2163 AudioUnitParameter changedUnit;
2164 changedUnit.mAudioUnit = unit->AU();
2165 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2166 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2168 CFRelease (propertyList);
2172 Plugin::set_state (node, version);
2177 AUPlugin::load_preset (PresetRecord r)
2180 CFPropertyListRef propertyList;
2182 UserPresetMap::iterator ux;
2183 FactoryPresetMap::iterator fx;
2185 /* look first in "user" presets */
2187 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
2189 if ((propertyList = load_property_list (ux->second)) != 0) {
2190 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
2191 if (unit->SetAUPreset (propertyList) == noErr) {
2194 /* tell the world */
2196 AudioUnitParameter changedUnit;
2197 changedUnit.mAudioUnit = unit->AU();
2198 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2199 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2201 CFRelease(propertyList);
2204 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2208 preset.presetNumber = fx->second;
2209 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2211 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2213 if (unit->SetPresentPreset (preset) == 0) {
2216 /* tell the world */
2218 AudioUnitParameter changedUnit;
2219 changedUnit.mAudioUnit = unit->AU();
2220 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2221 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2225 preset_holdoff = std::max (_session.get_block_size() * 2.0, _session.sample_rate() * .2);
2228 return ret && Plugin::load_preset (r);
2232 AUPlugin::do_remove_preset (std::string preset_name)
2234 vector<Glib::ustring> v;
2236 std::string m = maker();
2237 std::string n = name();
2239 strip_whitespace_edges (m);
2240 strip_whitespace_edges (n);
2242 v.push_back (Glib::get_home_dir());
2243 v.push_back ("Library");
2244 v.push_back ("Audio");
2245 v.push_back ("Presets");
2248 v.push_back (preset_name + preset_suffix);
2250 Glib::ustring user_preset_path = Glib::build_filename (v);
2252 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Deleting Preset file %1\n", user_preset_path));
2254 if (g_unlink (user_preset_path.c_str())) {
2255 error << string_compose (X_("Could not delete preset at \"%1\": %2"), user_preset_path, strerror (errno)) << endmsg;
2260 AUPlugin::do_save_preset (string preset_name)
2262 CFPropertyListRef propertyList;
2263 vector<Glib::ustring> v;
2264 Glib::ustring user_preset_path;
2266 std::string m = maker();
2267 std::string n = name();
2269 strip_whitespace_edges (m);
2270 strip_whitespace_edges (n);
2272 v.push_back (Glib::get_home_dir());
2273 v.push_back ("Library");
2274 v.push_back ("Audio");
2275 v.push_back ("Presets");
2279 user_preset_path = Glib::build_filename (v);
2281 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2282 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2286 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2287 if (unit->GetAUPreset (propertyList) != noErr) {
2291 // add the actual preset name */
2293 v.push_back (preset_name + preset_suffix);
2297 user_preset_path = Glib::build_filename (v);
2299 set_preset_name_in_plist (propertyList, preset_name);
2301 if (save_property_list (propertyList, user_preset_path)) {
2302 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2306 CFRelease(propertyList);
2308 user_preset_map[preset_name] = user_preset_path;;
2310 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2312 return user_preset_path;
2315 //-----------------------------------------------------------------------------
2316 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2318 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2320 CFNumberRef cfNumber;
2321 SInt32 numberValue = 0;
2322 Boolean dummySuccess;
2324 if (outSuccess == NULL)
2325 outSuccess = &dummySuccess;
2326 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2328 *outSuccess = FALSE;
2332 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2333 if (cfNumber == NULL)
2335 *outSuccess = FALSE;
2338 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2346 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2348 CFDictionaryRef auStateDictionary;
2349 ArdourDescription tempDesc = {0,0,0,0,0};
2350 SInt32 versionValue;
2353 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2356 // the property list for AU state data must be of the dictionary type
2357 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2358 return kAudioUnitErr_InvalidPropertyValue;
2361 auStateDictionary = (CFDictionaryRef)inAUStateData;
2363 // first check to make sure that the version of the AU state data is one that we know understand
2364 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2365 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2368 return kAudioUnitErr_InvalidPropertyValue;
2370 #define kCurrentSavedStateVersion 0
2371 if (versionValue != kCurrentSavedStateVersion) {
2372 return kAudioUnitErr_InvalidPropertyValue;
2375 // grab the ComponentDescription values from the AU state data
2376 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2377 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2378 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2379 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2380 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2381 return kAudioUnitErr_InvalidPropertyValue;
2383 *outComponentDescription = tempDesc;
2388 static bool au_preset_filter (const string& str, void* arg)
2390 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2394 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2398 /* check the preset file path name against this plugin
2399 ID. The idea is that all preset files for this plugin
2400 include "<manufacturer>/<plugin-name>" in their path.
2403 AUPluginInfo* p = (AUPluginInfo *) arg;
2404 string match = p->creator;
2408 ret = str.find (match) != string::npos;
2411 string m = p->creator;
2413 strip_whitespace_edges (m);
2414 strip_whitespace_edges (n);
2419 ret = str.find (match) != string::npos;
2427 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2430 CFPropertyListRef plist;
2431 ArdourDescription presetDesc;
2434 plist = load_property_list (pathstr);
2440 // get the ComponentDescription from the AU preset file
2442 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2444 if (status == noErr) {
2445 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2447 /* try to get the preset name from the property list */
2449 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2451 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2455 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2458 char buf[PATH_MAX+1];
2460 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2477 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2479 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2482 CFStringRef itemName = NULL;
2483 // Marc Poirier-style item name
2485 CAComponent auComponent (comp_desc);
2486 if (auComponent.IsValid()) {
2487 CAComponentDescription dummydesc;
2488 Handle nameHandle = NewHandle(sizeof(void*));
2489 if (nameHandle != NULL) {
2490 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2492 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2493 if (nameString != NULL) {
2494 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2497 DisposeHandle(nameHandle);
2502 AudioComponentCopyName (comp, &itemName);
2505 // if Marc-style fails, do the original way
2506 if (itemName == NULL) {
2507 #ifndef COREAUDIO105
2508 CAComponentDescription comp_desc;
2509 AudioComponentGetDescription (comp, &comp_desc);
2511 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2512 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2513 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2515 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2516 compTypeString, compManufacturerString, compSubTypeString);
2518 if (compTypeString != NULL)
2519 CFRelease(compTypeString);
2520 if (compSubTypeString != NULL)
2521 CFRelease(compSubTypeString);
2522 if (compManufacturerString != NULL)
2523 CFRelease(compManufacturerString);
2526 string str = CFStringRefToStdString(itemName);
2527 string::size_type colon = str.find (':');
2530 name = str.substr (colon+1);
2531 maker = str.substr (0, colon);
2532 strip_whitespace_edges (maker);
2533 strip_whitespace_edges (name);
2537 strip_whitespace_edges (name);
2542 AUPlugin::current_preset() const
2546 CFPropertyListRef propertyList;
2548 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2549 if (unit->GetAUPreset (propertyList) == noErr) {
2550 preset_name = get_preset_name_in_plist (propertyList);
2551 CFRelease(propertyList);
2558 AUPlugin::find_presets ()
2560 vector<string> preset_files;
2562 user_preset_map.clear ();
2564 PluginInfoPtr nfo = get_info();
2565 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2566 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2569 if (preset_files.empty()) {
2570 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2573 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2578 /* make an initial guess at the preset name using the path */
2580 preset_name = Glib::path_get_basename (path);
2581 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2583 /* check that this preset file really matches this plugin
2584 and potentially get the "real" preset name from
2588 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2589 user_preset_map[preset_name] = path;
2590 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2592 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2597 /* now fill the vector<string> with the names we have */
2599 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2600 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2601 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2604 /* add factory presets */
2606 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2607 string const uri = string_compose ("AU2:%1", std::setw(4), std::setfill('0'), i->second);
2608 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2609 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2614 AUPlugin::has_editor () const
2616 // even if the plugin doesn't have its own editor, the AU API can be used
2617 // to create one that looks native.
2621 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2625 type = ARDOUR::AudioUnit;
2628 AUPluginInfo::~AUPluginInfo ()
2630 type = ARDOUR::AudioUnit;
2634 AUPluginInfo::load (Session& session)
2639 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2640 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2642 if (!comp->IsValid()) {
2643 error << ("AudioUnit: not a valid Component") << endmsg;
2645 plugin.reset (new AUPlugin (session.engine(), session, comp));
2648 AUPluginInfo *aup = new AUPluginInfo (*this);
2649 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2650 plugin->set_info (PluginInfoPtr (aup));
2651 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2655 catch (failed_constructor &err) {
2656 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2657 return PluginPtr ();
2661 std::vector<Plugin::PresetRecord>
2662 AUPluginInfo::get_presets (bool user_only) const
2664 std::vector<Plugin::PresetRecord> p;
2665 boost::shared_ptr<CAComponent> comp;
2666 #ifndef NO_PLUGIN_STATE
2668 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2669 if (!comp->IsValid()) {
2670 throw failed_constructor();
2672 } catch (failed_constructor& err) {
2678 if (!preset_search_path_initialized) {
2679 Glib::ustring p = Glib::get_home_dir();
2680 p += "/Library/Audio/Presets:";
2681 p += preset_search_path;
2682 preset_search_path = p;
2683 preset_search_path_initialized = true;
2684 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2687 vector<string> preset_files;
2688 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2690 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2693 preset_name = Glib::path_get_basename (path);
2694 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2695 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2696 p.push_back (Plugin::PresetRecord (path, preset_name));
2710 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2711 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2714 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2715 unit->Uninitialize ();
2718 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2719 unit->Uninitialize ();
2723 unit->Uninitialize ();
2727 CFIndex cnt = CFArrayGetCount (presets);
2728 for (CFIndex i = 0; i < cnt; ++i) {
2729 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2730 string const uri = string_compose ("%1", i);
2731 string name = CFStringRefToStdString (preset->presetName);
2732 p.push_back (Plugin::PresetRecord (uri, name, false));
2734 CFRelease (presets);
2735 unit->Uninitialize ();
2737 #endif // NO_PLUGIN_STATE
2742 AUPluginInfo::au_cache_path ()
2744 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2748 AUPluginInfo::discover (bool scan_only)
2752 /* AU require a CAComponentDescription pointer provided by the OS.
2753 * Ardour only caches port and i/o config. It can't just 'scan' without
2754 * 'discovering' (like we do for VST).
2757 * "Iterate over all plugins. skip the ones where there's no io-cache".
2759 _scan_only = scan_only;
2761 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2762 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2763 // flush RAM cache -- after clear_cache()
2764 cached_info.clear();
2766 // create crash log file
2767 au_start_crashlog ();
2769 PluginInfoList* plugs = new PluginInfoList;
2771 discover_fx (*plugs);
2772 discover_music (*plugs);
2773 discover_generators (*plugs);
2774 discover_instruments (*plugs);
2776 // all fine if we get here
2777 au_remove_crashlog ();
2779 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2785 AUPluginInfo::discover_music (PluginInfoList& plugs)
2787 CAComponentDescription desc;
2788 desc.componentFlags = 0;
2789 desc.componentFlagsMask = 0;
2790 desc.componentSubType = 0;
2791 desc.componentManufacturer = 0;
2792 desc.componentType = kAudioUnitType_MusicEffect;
2794 discover_by_description (plugs, desc);
2798 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2800 CAComponentDescription desc;
2801 desc.componentFlags = 0;
2802 desc.componentFlagsMask = 0;
2803 desc.componentSubType = 0;
2804 desc.componentManufacturer = 0;
2805 desc.componentType = kAudioUnitType_Effect;
2807 discover_by_description (plugs, desc);
2811 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2813 CAComponentDescription desc;
2814 desc.componentFlags = 0;
2815 desc.componentFlagsMask = 0;
2816 desc.componentSubType = 0;
2817 desc.componentManufacturer = 0;
2818 desc.componentType = kAudioUnitType_Generator;
2820 discover_by_description (plugs, desc);
2824 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2826 CAComponentDescription desc;
2827 desc.componentFlags = 0;
2828 desc.componentFlagsMask = 0;
2829 desc.componentSubType = 0;
2830 desc.componentManufacturer = 0;
2831 desc.componentType = kAudioUnitType_MusicDevice;
2833 discover_by_description (plugs, desc);
2838 AUPluginInfo::au_get_crashlog (std::string &msg)
2840 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2841 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2844 std::ifstream ifs(fn.c_str());
2845 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2846 au_remove_crashlog ();
2851 AUPluginInfo::au_start_crashlog ()
2853 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2854 assert(!_crashlog_fd);
2855 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2856 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2857 PBD::error << "Cannot create AU error-log" << fn << "\n";
2858 cerr << "Cannot create AU error-log" << fn << "\n";
2863 AUPluginInfo::au_remove_crashlog ()
2866 ::fclose(_crashlog_fd);
2867 _crashlog_fd = NULL;
2869 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2870 ::g_unlink(fn.c_str());
2871 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2876 AUPluginInfo::au_crashlog (std::string msg)
2878 if (!_crashlog_fd) {
2879 fprintf(stderr, "AU: %s\n", msg.c_str());
2881 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2882 ::fflush(_crashlog_fd);
2887 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2889 ArdourComponent comp = 0;
2890 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2892 comp = ArdourFindNext (NULL, &desc);
2894 while (comp != NULL) {
2895 CAComponentDescription temp;
2897 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2899 AudioComponentGetDescription (comp, &temp);
2901 CFStringRef itemName = NULL;
2904 if (itemName != NULL) CFRelease(itemName);
2905 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2906 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2907 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2908 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2909 compTypeString, compManufacturerString, compSubTypeString);
2910 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2911 if (compTypeString != NULL)
2912 CFRelease(compTypeString);
2913 if (compSubTypeString != NULL)
2914 CFRelease(compSubTypeString);
2915 if (compManufacturerString != NULL)
2916 CFRelease(compManufacturerString);
2919 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2920 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2921 comp = ArdourFindNext (comp, &desc);
2925 bool has_midi_in = false;
2927 AUPluginInfoPtr info (new AUPluginInfo
2928 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2930 /* although apple designed the subtype field to be a "category" indicator,
2931 its really turned into a plugin ID field for a given manufacturer. Hence
2932 there are no categories for AudioUnits. However, to keep the plugins
2933 showing up under "categories", we'll use the "type" as a high level
2936 NOTE: no panners, format converters or i/o AU's for our purposes
2939 switch (info->descriptor->Type()) {
2940 case kAudioUnitType_Panner:
2941 case kAudioUnitType_OfflineEffect:
2942 case kAudioUnitType_FormatConverter:
2943 comp = ArdourFindNext (comp, &desc);
2946 case kAudioUnitType_Output:
2947 info->category = _("Output");
2949 case kAudioUnitType_MusicDevice:
2950 info->category = _("Instrument");
2953 case kAudioUnitType_MusicEffect:
2954 info->category = _("Effect");
2957 case kAudioUnitType_Effect:
2958 info->category = _("Effect");
2960 case kAudioUnitType_Mixer:
2961 info->category = _("Mixer");
2963 case kAudioUnitType_Generator:
2964 info->category = _("Generator");
2967 info->category = _("(Unknown)");
2971 au_blacklist(CFStringRefToStdString(itemName));
2973 get_names (temp, info->name, info->creator);
2975 get_names (comp, info->name, info->creator);
2977 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2978 au_crashlog(string_compose("Plugin: %1", info->name));
2980 info->type = ARDOUR::AudioUnit;
2981 info->unique_id = stringify_descriptor (*info->descriptor);
2983 /* XXX not sure of the best way to handle plugin versioning yet */
2985 CAComponent cacomp (*info->descriptor);
2988 if (cacomp.GetResourceVersion (info->version) != noErr)
2990 if (cacomp.GetVersion (info->version) != noErr)
2996 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2999 /* here we have to map apple's wildcard system to a simple pair
3000 of values. in ::can_do() we use the whole system, but here
3001 we need a single pair of values. XXX probably means we should
3002 remove any use of these values.
3004 for now, if the plugin provides a wildcard, treat it as 1. we really
3005 don't care much, because whether we can handle an i/o configuration
3006 depends upon ::can_support_io_configuration(), not these counts.
3008 they exist because other parts of ardour try to present i/o configuration
3009 info to the user, which should perhaps be revisited.
3012 int32_t possible_in = info->cache.io_configs.front().first;
3013 int32_t possible_out = info->cache.io_configs.front().second;
3015 if (possible_in > 0) {
3016 info->n_inputs.set (DataType::AUDIO, possible_in);
3018 info->n_inputs.set (DataType::AUDIO, 1);
3021 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
3023 if (possible_out > 0) {
3024 info->n_outputs.set (DataType::AUDIO, possible_out);
3026 info->n_outputs.set (DataType::AUDIO, 1);
3029 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
3030 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
3032 plugs.push_back (info);
3035 else if (rv == -1) {
3036 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
3039 au_unblacklist(CFStringRefToStdString(itemName));
3040 au_crashlog("Success.");
3041 comp = ArdourFindNext (comp, &desc);
3042 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
3044 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
3048 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
3051 AUPluginCachedInfo& cinfo,
3052 const std::string& name)
3057 /* concatenate unique ID with version to provide a key for cached info lookup.
3058 this ensures we don't get stale information, or should if plugin developers
3059 follow Apple "guidelines".
3062 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
3067 CachedInfoMap::iterator cim = cached_info.find (id);
3069 if (cim != cached_info.end()) {
3070 cinfo = cim->second;
3075 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
3080 AUChannelInfo* channel_info;
3084 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
3088 if (CAAudioUnit::Open (comp, unit) != noErr) {
3094 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
3099 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
3100 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
3105 /* AU is expected to deal with same channel valance in and out */
3106 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
3108 /* CAAudioUnit::GetChannelInfo silently merges bus formats
3109 * check if this was the case and if so, add
3110 * bus configs as incremental options.
3112 Boolean* isWritable = 0;
3113 UInt32 dataSize = 0;
3114 OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
3115 kAudioUnitProperty_SupportedNumChannels,
3116 kAudioUnitScope_Global, 0,
3117 &dataSize, isWritable);
3118 if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
3119 /* incrementally add busses */
3122 for (uint32_t n = 0; n < cnt; ++n) {
3123 in += channel_info[n].inChannels;
3124 out += channel_info[n].outChannels;
3125 cinfo.io_configs.push_back (pair<int,int> (in, out));
3128 /* store each configuration */
3129 for (uint32_t n = 0; n < cnt; ++n) {
3130 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
3131 channel_info[n].outChannels));
3135 free (channel_info);
3138 add_cached_info (id, cinfo);
3139 save_cached_info ();
3145 AUPluginInfo::clear_cache ()
3147 const string& fn = au_cache_path();
3148 if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
3149 ::g_unlink(fn.c_str());
3151 // keep cached_info in RAM until restart or re-scan
3152 cached_info.clear();
3156 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
3158 cached_info[id] = cinfo;
3161 #define AU_CACHE_VERSION "2.0"
3164 AUPluginInfo::save_cached_info ()
3168 node = new XMLNode (X_("AudioUnitPluginCache"));
3169 node->set_property( "version", AU_CACHE_VERSION );
3171 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
3172 XMLNode* parent = new XMLNode (X_("plugin"));
3173 parent->set_property ("id", i->first);
3174 node->add_child_nocopy (*parent);
3176 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
3178 XMLNode* child = new XMLNode (X_("io"));
3180 child->set_property (X_("in"), j->first);
3181 child->set_property (X_("out"), j->second);
3182 parent->add_child_nocopy (*child);
3187 Glib::ustring path = au_cache_path ();
3190 tree.set_root (node);
3192 if (!tree.write (path)) {
3193 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
3194 g_unlink (path.c_str());
3199 AUPluginInfo::load_cached_info ()
3201 Glib::ustring path = au_cache_path ();
3204 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
3208 if ( !tree.read (path) ) {
3209 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
3213 const XMLNode* root (tree.root());
3215 if (root->name() != X_("AudioUnitPluginCache")) {
3219 //initial version has incorrectly stored i/o info, and/or garbage chars.
3220 XMLProperty const * version = root->property(X_("version"));
3221 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
3222 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
3226 cached_info.clear ();
3228 const XMLNodeList children = root->children();
3230 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
3232 const XMLNode* child = *iter;
3234 if (child->name() == X_("plugin")) {
3236 const XMLNode* gchild;
3237 const XMLNodeList gchildren = child->children();
3240 if (!child->get_property (X_("id"), id)) {
3247 string::size_type slash = id.find_last_of ('/');
3249 if (slash == string::npos) {
3253 version = id.substr (slash);
3254 id = id.substr (0, slash);
3255 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3257 if (fixed.empty()) {
3258 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3265 AUPluginCachedInfo cinfo;
3267 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3271 if (gchild->name() == X_("io")) {
3276 if (gchild->get_property (X_("in"), in) && gchild->get_property (X_("out"), out)) {
3277 cinfo.io_configs.push_back (pair<int,int> (in, out));
3282 if (cinfo.io_configs.size()) {
3283 add_cached_info (id, cinfo);
3293 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3297 /* note: OSType is a compiler-implemenation-defined value,
3298 historically a 32 bit integer created with a multi-character
3299 constant such as 'abcd'. It is, fundamentally, an abomination.
3304 s << desc.SubType();
3312 AUPluginInfo::needs_midi_input () const
3314 return is_effect_with_midi_input () || is_instrument ();
3318 AUPluginInfo::is_effect () const
3320 return is_effect_without_midi_input() || is_effect_with_midi_input();
3324 AUPluginInfo::is_effect_without_midi_input () const
3326 return descriptor->IsAUFX();
3330 AUPluginInfo::is_effect_with_midi_input () const
3332 return descriptor->IsAUFM();
3336 AUPluginInfo::is_instrument () const
3338 return descriptor->IsMusicDevice();
3342 AUPluginInfo::is_utility () const
3344 return (descriptor->IsGenerator() || descriptor->componentType == 'aumi');
3345 // kAudioUnitType_MidiProcessor ..looks like we aren't even scanning for these yet?
3349 AUPlugin::set_info (PluginInfoPtr info)
3351 Plugin::set_info (info);
3353 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3354 _has_midi_input = pinfo->needs_midi_input ();
3355 _has_midi_output = false;
3359 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3362 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3364 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3366 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3368 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3372 _parameter_listener_arg = arg;
3374 // listen for latency changes
3375 AudioUnitEvent event;
3376 event.mEventType = kAudioUnitEvent_PropertyChange;
3377 event.mArgument.mProperty.mAudioUnit = unit->AU();
3378 event.mArgument.mProperty.mPropertyID = kAudioUnitProperty_Latency;
3379 event.mArgument.mProperty.mScope = kAudioUnitScope_Global;
3380 event.mArgument.mProperty.mElement = 0;
3382 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3383 PBD::error << "Failed to create latency event listener\n";
3384 // TODO don't cache _current_latency
3391 AUPlugin::listen_to_parameter (uint32_t param_id)
3393 AudioUnitEvent event;
3395 if (!_parameter_listener || param_id >= descriptors.size()) {
3399 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3400 event.mArgument.mParameter.mAudioUnit = unit->AU();
3401 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3402 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3403 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3405 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3409 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3410 event.mArgument.mParameter.mAudioUnit = unit->AU();
3411 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3412 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3413 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3415 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3419 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3420 event.mArgument.mParameter.mAudioUnit = unit->AU();
3421 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3422 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3423 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3425 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3433 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3435 AudioUnitEvent event;
3437 if (!_parameter_listener || param_id >= descriptors.size()) {
3441 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3442 event.mArgument.mParameter.mAudioUnit = unit->AU();
3443 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3444 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3445 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3447 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3451 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3452 event.mArgument.mParameter.mAudioUnit = unit->AU();
3453 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3454 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3455 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3457 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3461 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3462 event.mArgument.mParameter.mAudioUnit = unit->AU();
3463 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3464 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3465 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3467 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3475 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3477 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3481 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3483 if (event->mEventType == kAudioUnitEvent_PropertyChange) {
3484 if (event->mArgument.mProperty.mPropertyID == kAudioUnitProperty_Latency) {
3485 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Latency Change Event %1 <> %2\n", new_value, unit->Latency()));
3486 guint lat = unit->Latency() * _session.sample_rate();
3487 g_atomic_int_set (&_current_latency, lat);
3492 ParameterMap::iterator i;
3494 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3498 switch (event->mEventType) {
3499 case kAudioUnitEvent_BeginParameterChangeGesture:
3500 StartTouch (i->second);
3502 case kAudioUnitEvent_EndParameterChangeGesture:
3503 EndTouch (i->second);
3505 case kAudioUnitEvent_ParameterValueChange:
3506 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3507 means that something else (i.e. the plugin GUI) made the change.
3509 if (preset_holdoff > 0) {
3510 ParameterChangedExternally (i->second, new_value);
3512 Plugin::parameter_changed_externally (i->second, new_value);