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