2 * Copyright (C) 2006-2016 David Robillard <d@drobilla.net>
3 * Copyright (C) 2007-2017 Paul Davis <paul@linuxaudiosystems.com>
4 * Copyright (C) 2010 Carl Hetherington <carl@carlh.net>
5 * Copyright (C) 2013-2019 Robin Gareus <robin@gareus.org>
6 * Copyright (C) 2014-2017 Tim Mayberry <mojofunk@gmail.com>
7 * Copyright (C) 2015-2016 Nick Mainsbridge <mainsbridge@gmail.com>
8 * Copyright (C) 2018 Julien "_FrnchFrgg_" RIVAUD <frnchfrgg@free.fr>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
32 #include "pbd/gstdio_compat.h"
33 #include "pbd/transmitter.h"
34 #include "pbd/xml++.h"
35 #include "pbd/convert.h"
36 #include "pbd/whitespace.h"
37 #include "pbd/file_utils.h"
38 #include "pbd/locale_guard.h"
40 #include <glibmm/threads.h>
41 #include <glibmm/fileutils.h>
42 #include <glibmm/miscutils.h>
44 #include "ardour/ardour.h"
45 #include "ardour/audio_unit.h"
46 #include "ardour/audioengine.h"
47 #include "ardour/audio_buffer.h"
48 #include "ardour/debug.h"
49 #include "ardour/filesystem_paths.h"
50 #include "ardour/io.h"
51 #include "ardour/midi_buffer.h"
52 #include "ardour/route.h"
53 #include "ardour/session.h"
54 #include "ardour/tempo.h"
55 #include "ardour/utils.h"
57 #include "CAAudioUnit.h"
58 #include "CAAUParameter.h"
60 #include <CoreFoundation/CoreFoundation.h>
61 #include <CoreServices/CoreServices.h>
62 #include <AudioUnit/AudioUnit.h>
63 #include <AudioToolbox/AudioUnitUtilities.h>
65 #include <Carbon/Carbon.h>
69 #define ArdourComponent Component
70 #define ArdourDescription ComponentDescription
71 #define ArdourFindNext FindNextComponent
73 #define ArdourComponent AudioComponent
74 #define ArdourDescription AudioComponentDescription
75 #define ArdourFindNext AudioComponentFindNext
82 using namespace ARDOUR;
84 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
86 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
87 static string preset_suffix = ".aupreset";
88 static bool preset_search_path_initialized = false;
89 FILE * AUPluginInfo::_crashlog_fd = NULL;
90 bool AUPluginInfo::_scan_only = true;
93 static void au_blacklist (std::string id)
95 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
96 FILE * blacklist_fd = NULL;
97 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
98 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
101 assert(id.find("\n") == string::npos);
102 fprintf(blacklist_fd, "%s\n", id.c_str());
103 ::fclose(blacklist_fd);
106 static void au_unblacklist (std::string id)
108 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
109 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
110 PBD::warning << "Expected Blacklist file does not exist.\n";
116 std::ifstream ifs(fn.c_str());
117 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
120 ::g_unlink (fn.c_str());
122 assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
123 assert(id.find("\n") == string::npos);
125 id += "\n"; // add separator
126 const size_t rpl = bl.find(id);
127 if (rpl != string::npos) {
128 bl.replace(rpl, id.size(), "");
134 FILE * blacklist_fd = NULL;
135 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
136 PBD::error << "Cannot open AU blacklist.\n";
139 fprintf(blacklist_fd, "%s", bl.c_str());
140 ::fclose(blacklist_fd);
143 static bool is_blacklisted (std::string id)
145 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
146 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
150 std::ifstream ifs(fn.c_str());
151 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
153 assert(id.find("\n") == string::npos);
155 id += "\n"; // add separator
156 const size_t rpl = bl.find(id);
157 if (rpl != string::npos) {
166 _render_callback(void *userData,
167 AudioUnitRenderActionFlags *ioActionFlags,
168 const AudioTimeStamp *inTimeStamp,
170 UInt32 inNumberSamples,
171 AudioBufferList* ioData)
174 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberSamples, ioData);
180 _get_beat_and_tempo_callback (void* userData,
181 Float64* outCurrentBeat,
182 Float64* outCurrentTempo)
185 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
192 _get_musical_time_location_callback (void * userData,
193 UInt32 * outDeltaSampleOffsetToNextBeat,
194 Float32 * outTimeSig_Numerator,
195 UInt32 * outTimeSig_Denominator,
196 Float64 * outCurrentMeasureDownBeat)
199 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
200 outTimeSig_Numerator,
201 outTimeSig_Denominator,
202 outCurrentMeasureDownBeat);
208 _get_transport_state_callback (void* userData,
209 Boolean* outIsPlaying,
210 Boolean* outTransportStateChanged,
211 Float64* outCurrentSampleInTimeLine,
212 Boolean* outIsCycling,
213 Float64* outCycleStartBeat,
214 Float64* outCycleEndBeat)
217 return ((AUPlugin*)userData)->get_transport_state_callback (
218 outIsPlaying, outTransportStateChanged,
219 outCurrentSampleInTimeLine, outIsCycling,
220 outCycleStartBeat, outCycleEndBeat);
227 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
233 // Convert the property list into XML data.
235 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
238 error << _("Could not create XML version of property list") << endmsg;
242 // Write the XML data to the file.
244 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
246 if (errno == EEXIST) {
247 error << string_compose (_("Preset file %1 exists; not overwriting"),
250 error << string_compose (_("Cannot open preset file %1 (%2)"),
251 path, strerror (errno)) << endmsg;
257 size_t cnt = CFDataGetLength (xmlData);
259 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
270 static CFPropertyListRef
271 load_property_list (Glib::ustring path)
274 CFPropertyListRef propertyList = 0;
276 CFStringRef errorString;
278 // Read the XML file.
280 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
285 off_t len = lseek (fd, 0, SEEK_END);
286 char* buf = new char[len];
287 lseek (fd, 0, SEEK_SET);
289 if (read (fd, buf, len) != len) {
297 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
299 // Reconstitute the dictionary using the XML data.
301 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
303 kCFPropertyListImmutable,
312 //-----------------------------------------------------------------------------
314 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
319 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
321 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
322 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
328 //-----------------------------------------------------------------------------
330 get_preset_name_in_plist (CFPropertyListRef plist)
338 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
339 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
341 CFStringRef str = (CFStringRef) p;
342 int len = CFStringGetLength(str);
344 char local_buffer[len];
345 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
353 //--------------------------------------------------------------------------
354 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
355 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
356 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
357 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
359 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
362 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
363 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
365 // only sub-type and manufacturer IDs need to be equal
368 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
369 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
376 //--------------------------------------------------------------------------
377 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
378 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
379 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
380 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
383 ArdourDescription desc;
385 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
388 // get the ComponentDescription of the input Component
390 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
392 status = AudioComponentGetDescription (inComponent, &desc);
397 // check if the Component's ComponentDescription matches the input ComponentDescription
398 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
401 //--------------------------------------------------------------------------
402 // determine if 2 ComponentDescriptions are basically equal
403 // (by that, I mean that the important identifying values are compared,
404 // but not the ComponentDescription flags)
405 Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
407 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
410 //--------------------------------------------------------------------------
411 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
412 Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
414 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
417 //--------------------------------------------------------------------------
418 // determine if a ComponentDescription basically matches that of a particular Component
419 Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
421 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
424 //--------------------------------------------------------------------------
425 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
426 Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
428 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
432 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
433 : Plugin (engine, session)
435 , unit (new CAAudioUnit)
436 , initialized (false)
438 , _current_latency (UINT_MAX)
439 , _requires_fixed_size_buffers (false)
441 , variable_inputs (false)
442 , variable_outputs (false)
443 , configured_input_busses (0)
444 , configured_output_busses (0)
452 , samples_processed (0)
453 , audio_input_cnt (0)
454 , _parameter_listener (0)
455 , _parameter_listener_arg (0)
456 , transport_sample (0)
457 , transport_speed (0)
458 , last_transport_speed (0.0)
461 if (!preset_search_path_initialized) {
462 Glib::ustring p = Glib::get_home_dir();
463 p += "/Library/Audio/Presets:";
464 p += preset_search_path;
465 preset_search_path = p;
466 preset_search_path_initialized = true;
467 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
474 AUPlugin::AUPlugin (const AUPlugin& other)
476 , comp (other.get_comp())
477 , unit (new CAAudioUnit)
478 , initialized (false)
480 , _current_latency (UINT_MAX)
481 , _requires_fixed_size_buffers (false)
483 , variable_inputs (false)
484 , variable_outputs (false)
485 , configured_input_busses (0)
486 , configured_output_busses (0)
494 , samples_processed (0)
495 , audio_input_cnt (0)
496 , _parameter_listener (0)
497 , _parameter_listener_arg (0)
498 , transport_sample (0)
499 , transport_speed (0)
500 , last_transport_speed (0.0)
506 XMLNode root (other.state_node_name ());
507 other.add_state (&root);
508 set_state (root, Stateful::loading_state_version);
510 for (size_t i = 0; i < descriptors.size(); ++i) {
511 set_parameter (i, other.get_parameter (i));
515 AUPlugin::~AUPlugin ()
517 if (_parameter_listener) {
518 AUListenerDispose (_parameter_listener);
519 _parameter_listener = 0;
523 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
524 unit->Uninitialize ();
534 AUPlugin::discover_factory_presets ()
541 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
542 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
546 assert (dataSize == sizeof (presets));
548 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
549 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
557 CFIndex cnt = CFArrayGetCount (presets);
559 for (CFIndex i = 0; i < cnt; ++i) {
560 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
562 string name = CFStringRefToStdString (preset->presetName);
563 factory_preset_map[name] = preset->presetNumber;
564 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
574 CFStringRef itemName;
576 /* these keep track of *configured* channel set up,
577 not potential set ups.
581 output_channels = -1;
583 CAComponentDescription temp;
585 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
587 AudioComponentGetDescription (comp.get()->Comp(), &temp);
589 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
590 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
591 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
592 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
593 compTypeString, compManufacturerString, compSubTypeString);
594 if (compTypeString != NULL) CFRelease(compTypeString);
595 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
596 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
599 au_blacklist(CFStringRefToStdString(itemName));
602 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
603 err = CAAudioUnit::Open (*(comp.get()), *unit);
605 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
606 throw failed_constructor();
610 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
611 throw failed_constructor ();
614 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
615 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
616 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
617 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
618 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
619 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
621 cb_offsets = (samplecnt_t*) calloc (input_elements, sizeof(samplecnt_t));
622 bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
623 bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
625 for (size_t i = 0; i < output_elements; ++i) {
626 unit->Reset (kAudioUnitScope_Output, i);
627 AudioStreamBasicDescription fmt;
628 err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
630 bus_outputs[i] = fmt.mChannelsPerFrame;
633 UInt32 sz = sizeof (CFStringRef);
634 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
635 i, &name, &sz) == noErr
637 _bus_name_out.push_back (CFStringRefToStdString (name));
640 _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
644 for (size_t i = 0; i < input_elements; ++i) {
645 unit->Reset (kAudioUnitScope_Input, i);
646 AudioStreamBasicDescription fmt;
647 err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
649 bus_inputs[i] = fmt.mChannelsPerFrame;
652 UInt32 sz = sizeof (CFStringRef);
653 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
654 i, &name, &sz) == noErr
656 _bus_name_in.push_back (CFStringRefToStdString (name));
659 _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
663 for (size_t i = 0; i < input_elements; ++i) {
664 /* setup render callback: the plugin calls this to get input data */
665 AURenderCallbackStruct renderCallbackInfo;
666 renderCallbackInfo.inputProc = _render_callback;
667 renderCallbackInfo.inputProcRefCon = this;
668 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
669 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
670 i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
671 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
672 throw failed_constructor();
676 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
678 HostCallbackInfo info;
679 memset (&info, 0, sizeof (HostCallbackInfo));
680 info.hostUserData = this;
681 info.beatAndTempoProc = _get_beat_and_tempo_callback;
682 info.musicalTimeLocationProc = _get_musical_time_location_callback;
683 info.transportStateProc = _get_transport_state_callback;
685 //ignore result of this - don't care if the property isn't supported
686 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
687 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
688 kAudioUnitScope_Global,
691 sizeof (HostCallbackInfo));
693 if (set_block_size (_session.get_block_size())) {
694 error << _("AUPlugin: cannot set processing block size") << endmsg;
695 throw failed_constructor();
698 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
699 discover_parameters ();
700 discover_factory_presets ();
702 // Plugin::setup_controls ();
704 au_unblacklist(CFStringRefToStdString(itemName));
705 if (itemName != NULL) CFRelease(itemName);
709 AUPlugin::discover_parameters ()
711 /* discover writable parameters */
713 AudioUnitScope scopes[] = {
714 kAudioUnitScope_Global,
715 kAudioUnitScope_Output,
716 kAudioUnitScope_Input
719 descriptors.clear ();
721 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
723 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
725 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
727 AUParameterDescriptor d;
729 d.id = param_info.ParamID (i);
731 const CAAUParameter* param = param_info.GetParamInfo (d.id);
732 const AudioUnitParameterInfo& info (param->ParamInfo());
734 const int len = CFStringGetLength (param->GetName());
735 char local_buffer[len*2];
736 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
740 d.label = local_buffer;
743 d.scope = param_info.GetScope ();
744 d.element = param_info.GetElement ();
746 /* info.units to consider */
748 kAudioUnitParameterUnit_Generic = 0
749 kAudioUnitParameterUnit_Indexed = 1
750 kAudioUnitParameterUnit_Boolean = 2
751 kAudioUnitParameterUnit_Percent = 3
752 kAudioUnitParameterUnit_Seconds = 4
753 kAudioUnitParameterUnit_SampleFrames = 5
754 kAudioUnitParameterUnit_Phase = 6
755 kAudioUnitParameterUnit_Rate = 7
756 kAudioUnitParameterUnit_Hertz = 8
757 kAudioUnitParameterUnit_Cents = 9
758 kAudioUnitParameterUnit_RelativeSemiTones = 10
759 kAudioUnitParameterUnit_MIDINoteNumber = 11
760 kAudioUnitParameterUnit_MIDIController = 12
761 kAudioUnitParameterUnit_Decibels = 13
762 kAudioUnitParameterUnit_LinearGain = 14
763 kAudioUnitParameterUnit_Degrees = 15
764 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
765 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
766 kAudioUnitParameterUnit_Pan = 18
767 kAudioUnitParameterUnit_Meters = 19
768 kAudioUnitParameterUnit_AbsoluteCents = 20
769 kAudioUnitParameterUnit_Octaves = 21
770 kAudioUnitParameterUnit_BPM = 22
771 kAudioUnitParameterUnit_Beats = 23
772 kAudioUnitParameterUnit_Milliseconds = 24
773 kAudioUnitParameterUnit_Ratio = 25
776 /* info.flags to consider */
780 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
781 kAudioUnitParameterFlag_HasClump = (1L << 20)
782 kAudioUnitParameterFlag_HasName = (1L << 21)
783 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
784 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
785 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
786 kAudioUnitParameterFlag_CanRamp = (1L << 25)
787 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
788 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
789 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
790 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
791 kAudioUnitParameterFlag_IsReadable = (1L << 30)
792 kAudioUnitParameterFlag_IsWritable = (1L << 31)
795 d.lower = info.minValue;
796 d.upper = info.maxValue;
797 d.normal = info.defaultValue;
799 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
800 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
801 (d.integer_step && ((d.upper - d.lower) == 1.0));
802 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
803 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
804 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
805 (info.flags & kAudioUnitParameterFlag_IsWritable);
807 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
808 d.au_unit = info.unit;
810 case kAudioUnitParameterUnit_Decibels:
811 d.unit = ParameterDescriptor::DB;
813 case kAudioUnitParameterUnit_MIDINoteNumber:
814 d.unit = ParameterDescriptor::MIDI_NOTE;
816 case kAudioUnitParameterUnit_Hertz:
817 d.unit = ParameterDescriptor::HZ;
823 descriptors.push_back (d);
825 uint32_t last_param = descriptors.size() - 1;
826 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
827 listen_to_parameter (last_param);
834 four_ints_to_four_byte_literal (unsigned char n[4])
836 /* this is actually implementation dependent. sigh. this is what gcc
837 and quite a few others do.
839 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
843 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
845 if (isdigit (id[0])) {
849 /* ID format is xxxx-xxxx-xxxx
850 where x maybe \xNN or a printable character.
852 Split at the '-' and and process each part into an integer.
853 Then put it back together.
857 unsigned char nascent[4];
858 const char* cstr = id.c_str();
859 const char* estr = cstr + id.size();
870 while (*cstr && next_int < 4) {
874 if (estr - cstr < 3) {
876 /* too close to the end for \xNN parsing: treat as literal characters */
884 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
888 memcpy (short_buf, &cstr[2], 2);
889 nascent[in] = strtol (short_buf, NULL, 16);
895 /* treat as literal characters */
909 if (in && (in % 4 == 0)) {
910 /* nascent is ready */
911 n[next_int] = four_ints_to_four_byte_literal (nascent);
915 /* swallow space-hyphen-space */
929 s << n[0] << '-' << n[1] << '-' << n[2];
938 AUPlugin::unique_id () const
940 return AUPluginInfo::stringify_descriptor (comp->Desc());
944 AUPlugin::label () const
946 return _info->name.c_str();
950 AUPlugin::parameter_count () const
952 return descriptors.size();
956 AUPlugin::default_value (uint32_t port)
958 if (port < descriptors.size()) {
959 return descriptors[port].normal;
966 AUPlugin::plugin_latency () const
968 guint lat = g_atomic_int_get (&_current_latency);;
969 if (lat == UINT_MAX) {
970 lat = unit->Latency() * _session.sample_rate();
971 g_atomic_int_set (&_current_latency, lat);
977 AUPlugin::set_parameter (uint32_t which, float val)
979 if (which >= descriptors.size()) {
983 if (get_parameter(which) == val) {
987 const AUParameterDescriptor& d (descriptors[which]);
988 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
989 unit->SetParameter (d.id, d.scope, d.element, val);
991 /* tell the world what we did */
993 AudioUnitEvent theEvent;
995 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
996 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
997 theEvent.mArgument.mParameter.mParameterID = d.id;
998 theEvent.mArgument.mParameter.mScope = d.scope;
999 theEvent.mArgument.mParameter.mElement = d.element;
1001 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
1002 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
1003 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
1005 Plugin::set_parameter (which, val);
1009 AUPlugin::get_parameter (uint32_t which) const
1012 if (which < descriptors.size()) {
1013 const AUParameterDescriptor& d (descriptors[which]);
1014 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
1015 unit->GetParameter(d.id, d.scope, d.element, val);
1021 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
1023 if (which < descriptors.size()) {
1024 pd = descriptors[which];
1031 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
1033 if (which < descriptors.size()) {
1042 AUPlugin::activate ()
1046 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
1047 if ((err = unit->Initialize()) != noErr) {
1048 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
1050 samples_processed = 0;
1057 AUPlugin::deactivate ()
1059 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
1060 unit->Uninitialize ();
1061 initialized = false;
1067 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
1068 unit->GlobalReset ();
1072 AUPlugin::requires_fixed_size_buffers() const
1074 return _requires_fixed_size_buffers;
1079 AUPlugin::set_block_size (pframes_t nframes)
1081 bool was_initialized = initialized;
1082 UInt32 numSamples = nframes;
1089 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numSamples));
1090 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1091 0, &numSamples, sizeof (numSamples))) != noErr) {
1092 error << string_compose (_("AU: cannot set max samples (err = %1)"), err) << endmsg;
1096 if (was_initialized) {
1104 AUPlugin::configure_io (ChanCount in, ChanCount out)
1106 AudioStreamBasicDescription streamFormat;
1107 bool was_initialized = initialized;
1108 int32_t audio_out = out.n_audio();
1109 if (audio_input_cnt > 0) {
1110 in.set (DataType::AUDIO, audio_input_cnt);
1112 const int32_t audio_in = in.n_audio();
1114 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1117 //if we are already running with the requested i/o config, bail out here
1118 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1125 streamFormat.mSampleRate = _session.sample_rate();
1126 streamFormat.mFormatID = kAudioFormatLinearPCM;
1127 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1129 #ifdef __LITTLE_ENDIAN__
1132 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1135 streamFormat.mBitsPerChannel = 32;
1136 streamFormat.mFramesPerPacket = 1;
1138 /* apple says that for non-interleaved data, these
1139 * values always refer to a single channel.
1141 streamFormat.mBytesPerPacket = 4;
1142 streamFormat.mBytesPerFrame = 4;
1144 configured_input_busses = 0;
1145 configured_output_busses = 0;
1147 for (size_t i = 0; i < output_elements; ++i) {
1148 unit->Reset (kAudioUnitScope_Output, i);
1150 for (size_t i = 0; i < input_elements; ++i) {
1151 unit->Reset (kAudioUnitScope_Input, i);
1154 /* now assign the channels to available busses */
1155 uint32_t used_in = 0;
1156 uint32_t used_out = 0;
1158 if (variable_inputs || input_elements == 1) {
1159 // we only ever use the first bus
1160 if (input_elements > 1) {
1161 warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
1163 streamFormat.mChannelsPerFrame = audio_in;
1164 if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
1167 configured_input_busses = 1;
1170 configured_input_busses = 0;
1171 uint32_t remain = audio_in;
1172 for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
1173 uint32_t cnt = std::min (remain, bus_inputs[bus]);
1174 if (cnt == 0) { continue; }
1175 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
1177 streamFormat.mChannelsPerFrame = cnt;
1178 if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
1182 ++configured_input_busses;
1187 if (variable_outputs || output_elements == 1) {
1188 if (output_elements > 1) {
1189 warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
1192 streamFormat.mChannelsPerFrame = audio_out;
1193 if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
1196 configured_output_busses = 1;
1197 used_out = audio_out;
1199 uint32_t remain = audio_out;
1200 configured_output_busses = 0;
1201 for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
1202 uint32_t cnt = std::min (remain, bus_outputs[bus]);
1203 if (cnt == 0) { continue; }
1204 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
1205 streamFormat.mChannelsPerFrame = cnt;
1206 if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
1211 ++configured_output_busses;
1216 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1217 used_out * sizeof(::AudioBuffer));
1219 input_channels = used_in;
1220 output_channels = used_out;
1221 /* reset plugin info to show currently configured state */
1223 _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
1224 _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
1226 if (was_initialized) {
1234 AUPlugin::input_streams() const
1237 if (input_channels < 0) {
1238 // force PluginIoReConfigure -- see also commit msg e38eb06
1239 c.set (DataType::AUDIO, 0);
1240 c.set (DataType::MIDI, 0);
1242 c.set (DataType::AUDIO, input_channels);
1243 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1250 AUPlugin::output_streams() const
1253 if (output_channels < 0) {
1254 // force PluginIoReConfigure - see also commit msg e38eb06
1255 c.set (DataType::AUDIO, 0);
1256 c.set (DataType::MIDI, 0);
1258 c.set (DataType::AUDIO, output_channels);
1259 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1265 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1267 _output_configs.clear ();
1268 const int32_t audio_in = in.n_audio();
1269 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1271 /* lets check MIDI first */
1273 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1277 vector<pair<int,int> > io_configs = pinfo->cache.io_configs;
1279 if (input_elements > 1) {
1280 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1281 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1282 int32_t possible_in = i->first;
1283 int32_t possible_out = i->second;
1284 if (possible_in < 0) {
1287 for (uint32_t i = 1; i < input_elements; ++i) {
1288 // can't use up-to bus_inputs[]
1289 // waves' SC-C6(s) for example fails to configure with only 1 input
1291 io_configs.push_back (pair<int,int> (possible_in + bus_inputs[i], possible_out));
1293 /* only add additional, optional busses to first available config.
1294 * AUPluginInfo::cached_io_configuration () already incrementally
1295 * adds busses (for instruments w/ multiple configurations)
1301 if (output_elements > 1) {
1302 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1303 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1304 int32_t possible_in = i->first;
1305 int32_t possible_out = i->second;
1306 if (possible_out < 0) {
1309 for (uint32_t i = 1; i < output_elements; ++i) {
1310 int32_t c = bus_outputs[i];
1311 for (uint32_t j = 1; j < i; ++j) {
1312 c += bus_outputs [j];
1314 io_configs.push_back (pair<int,int> (possible_in, possible_out + c));
1316 /* only add additional, optional busses to first available config.
1317 * AUPluginInfo::cached_io_configuration () already incrementally
1318 * adds busses (for instruments w/ multiple configurations)
1324 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1325 name(), io_configs.size(), in, out));
1328 printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
1329 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1330 printf ("- I/O %d / %d\n", i->first, i->second);
1334 // preferred setting (provided by plugin_insert)
1335 const int32_t preferred_out = out.n_audio ();
1337 /* kAudioUnitProperty_SupportedNumChannels
1338 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1340 * - both fields are -1
1341 * e.g. inChannels = -1 outChannels = -1
1342 * This is the default case. Any number of input and output channels, as long as the numbers match
1344 * - one field is -1, the other field is positive
1345 * e.g. inChannels = -1 outChannels = 2
1346 * Any number of input channels, exactly two output channels
1348 * - one field is -1, the other field is -2
1349 * e.g. inChannels = -1 outChannels = -2
1350 * Any number of input channels, any number of output channels
1352 * - both fields have non-negative values
1353 * e.g. inChannels = 2 outChannels = 6
1354 * Exactly two input channels, exactly six output channels
1355 * e.g. inChannels = 0 outChannels = 2
1356 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1358 * - both fields have negative values, neither of which is –1 or –2
1359 * e.g. inChannels = -4 outChannels = -8
1360 * Up to four input channels and up to eight output channels
1363 int32_t audio_out = -1;
1364 float penalty = 9999;
1365 int32_t used_possible_in = 0;
1367 #if defined (__clang__)
1368 # pragma clang diagnostic push
1369 # pragma clang diagnostic ignored "-Wtautological-compare"
1372 #define FOUNDCFG_PENALTY(in, out, p) { \
1373 _output_configs.insert (out); \
1374 if (p < penalty) { \
1375 used_possible_in = possible_in; \
1376 audio_out = (out); \
1378 imprecise->set (DataType::AUDIO, (in)); \
1382 variable_inputs = possible_in < 0; \
1383 variable_outputs = possible_out < 0; \
1387 #define FOUNDCFG_IMPRECISE(in, out) { \
1389 fabsf ((float)(out) - preferred_out) * \
1390 (((out) > preferred_out) ? 1.1 : 1) \
1391 + fabsf ((float)(in) - audio_in) * \
1392 (((in) > audio_in) ? 275 : 250); \
1393 FOUNDCFG_PENALTY(in, out, p); \
1396 #define FOUNDCFG(out) \
1397 FOUNDCFG_IMPRECISE(audio_in, out)
1399 #define ANYTHINGGOES \
1400 _output_configs.insert (0);
1402 #define UPTO(nch) { \
1403 for (int32_t n = 1; n <= nch; ++n) { \
1404 _output_configs.insert (n); \
1412 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1414 int32_t possible_in = i->first;
1415 int32_t possible_out = i->second;
1417 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1420 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1421 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1422 possible_in, possible_out,
1424 /* Set penalty so low that this output configuration
1425 * will trump any other one */
1426 FOUNDCFG_PENALTY(audio_in, preferred_out, -1);
1430 if (possible_out == 0) {
1431 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1432 /* XXX surely this is just a send? (e.g. AUNetSend) */
1436 /* now allow potentially "imprecise" matches */
1437 if (possible_in == -1 || possible_in == -2) {
1438 /* wildcard for input */
1439 if (possible_out == possible_in) {
1440 /* either both -1 or both -2 (invalid and
1441 * interpreted as both -1): out must match in */
1442 FOUNDCFG (audio_in);
1443 } else if (possible_out == -3 - possible_in) {
1444 /* one is -1, the other is -2: any output configuration
1445 * possible, pick what the insert prefers */
1446 FOUNDCFG (preferred_out);
1448 } else if (possible_out < -2) {
1449 /* variable number of outputs up to -N,
1450 * invalid if in == -2 but we accept it anyway */
1451 FOUNDCFG (min (-possible_out, preferred_out));
1452 UPTO (-possible_out)
1454 /* exact number of outputs */
1455 FOUNDCFG (possible_out);
1459 if (possible_in < -2 || possible_in >= 0) {
1460 /* specified number, exact or up to */
1462 if (possible_in >= 0) {
1463 /* configuration can only match possible_in */
1464 desired_in = possible_in;
1466 /* configuration can match up to -possible_in */
1467 desired_in = min (-possible_in, audio_in);
1469 if (!imprecise && audio_in != desired_in) {
1470 /* skip that configuration, it cannot match
1471 * the required audio input count, and we
1472 * cannot ask for change via \imprecise */
1473 } else if (possible_out == -1 || possible_out == -2) {
1474 /* any output configuration possible
1475 * out == -2 is invalid, interpreted as out == -1
1476 * Really imprecise only if desired_in != audio_in */
1477 FOUNDCFG_IMPRECISE (desired_in, preferred_out);
1479 } else if (possible_out < -2) {
1480 /* variable number of outputs up to -N
1481 * not specified if in > 0, but we accept it anyway
1482 * Really imprecise only if desired_in != audio_in */
1483 FOUNDCFG_IMPRECISE (desired_in, min (-possible_out, preferred_out));
1484 UPTO (-possible_out)
1486 /* exact number of outputs
1487 * Really imprecise only if desired_in != audio_in */
1488 FOUNDCFG_IMPRECISE (desired_in, possible_out);
1495 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1499 if (used_possible_in < -2 && audio_in == 0) {
1500 // input-port count cannot be zero, use as many ports
1501 // as outputs, but at most abs(possible_in)
1502 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1504 out.set (DataType::MIDI, 0); /// XXX currently always zero
1505 out.set (DataType::AUDIO, audio_out);
1506 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1508 #if defined (__clang__)
1509 # pragma clang diagnostic pop
1515 AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
1519 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1520 (scope == kAudioUnitScope_Input ? "input" : "output"),
1522 if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
1523 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1524 (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
1531 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1532 const AudioTimeStamp*,
1534 UInt32 inNumberSamples,
1535 AudioBufferList* ioData)
1537 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1539 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, samples %2 bus %3 bufs %4\n",
1540 // name(), inNumberSamples, bus, ioData->mNumberBuffers));
1542 if (input_maxbuf == 0) {
1543 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1544 error << _("AUPlugin: render callback called illegally!") << endmsg;
1545 return kAudioUnitErr_CannotDoInCurrentContext;
1548 assert (bus < input_elements);
1549 uint32_t busoff = 0;
1550 for (uint32_t i = 0; i < bus; ++i) {
1551 busoff += bus_inputs[i];
1554 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1556 ChanCount bufs_count (DataType::AUDIO, 1);
1557 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1559 /* apply bus offsets */
1561 for (uint32_t i = 0; i < limit; ++i) {
1562 ioData->mBuffers[i].mNumberChannels = 1;
1563 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberSamples;
1566 uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
1568 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
1570 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
1573 cb_offsets[bus] += inNumberSamples;
1578 AUPlugin::connect_and_run (BufferSet& bufs,
1579 samplepos_t start, samplepos_t end, double speed,
1580 ChanMapping const& in_map, ChanMapping const& out_map,
1581 pframes_t nframes, samplecnt_t offset)
1583 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
1585 transport_sample = start;
1586 transport_speed = speed;
1588 AudioUnitRenderActionFlags flags = 0;
1592 if (preset_holdoff > 0) {
1593 preset_holdoff -= std::min (nframes, preset_holdoff);
1596 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1597 unit->GlobalReset();
1598 _last_nframes = nframes;
1601 /* test if we can run in-place; only compare audio buffers */
1602 bool inplace = true; // TODO check plugin-insert in-place ?
1603 ChanMapping::Mappings inmap (in_map.mappings ());
1604 ChanMapping::Mappings outmap (out_map.mappings ());
1605 if (outmap[DataType::AUDIO].size () == 0 || inmap[DataType::AUDIO].size() == 0) {
1608 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1612 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",
1613 name(), input_channels, output_channels, _has_midi_input,
1614 bufs.count(), bufs.available(),
1615 configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
1617 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1618 * has the capacity to handle our outputs.
1621 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1623 input_buffers = &bufs;
1624 input_map = &in_map;
1625 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1626 input_offset = offset;
1627 for (size_t i = 0; i < input_elements; ++i) {
1631 ChanCount bufs_count (DataType::AUDIO, 1);
1632 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1634 if (_has_midi_input) {
1635 uint32_t nmidi = bufs.count().n_midi();
1636 for (uint32_t i = 0; i < nmidi; ++i) {
1637 /* one MIDI port/buffer only */
1638 MidiBuffer& m = bufs.get_midi (i);
1639 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1640 Evoral::Event<samplepos_t> ev (*i);
1641 if (ev.is_channel_event()) {
1642 const uint8_t* b = ev.buffer();
1643 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1644 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1646 /* XXX need to handle sysex and other message types */
1651 assert (input_maxbuf < 512);
1652 std::bitset<512> used_outputs;
1655 uint32_t busoff = 0;
1656 uint32_t remain = output_channels;
1657 for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
1659 if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
1660 cnt = output_channels;
1662 cnt = std::min (remain, bus_outputs[bus]);
1666 buffers->mNumberBuffers = cnt;
1668 for (uint32_t i = 0; i < cnt; ++i) {
1669 buffers->mBuffers[i].mNumberChannels = 1;
1670 /* setting this to 0 indicates to the AU that it *can* provide buffers here
1671 * if necessary. if it can process in-place, it will use the buffers provided
1672 * as input by ::render_callback() above.
1674 * a non-null values tells the plugin to render into the buffer pointed
1676 * https://developer.apple.com/documentation/audiotoolbox/1438430-audiounitrender?language=objc
1679 buffers->mBuffers[i].mDataByteSize = 0;
1680 buffers->mBuffers[i].mData = 0;
1682 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1684 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1686 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1688 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1693 /* does this really mean anything ? */
1694 ts.mSampleTime = samples_processed;
1695 ts.mFlags = kAudioTimeStampSampleTimeValid;
1697 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
1698 name(), flags, samples_processed, nframes, bus, buffers->mNumberBuffers));
1700 if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
1702 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1703 name(), buffers->mNumberBuffers, output_channels));
1705 uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
1706 for (uint32_t i = 0; i < limit; ++i) {
1708 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1712 if (buffers->mBuffers[i].mData == 0 || buffers->mBuffers[i].mNumberChannels != 1) {
1715 used_outputs.set (i + busoff);
1716 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1717 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1718 /* plugin provided its own buffer for output so copy it back to where we want it */
1719 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1723 DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
1724 error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
1730 busoff += bus_outputs[bus];
1733 /* now silence any buffers that were passed in but the that the plugin
1734 * did not fill/touch/use.
1736 * TODO: optimize, when plugin-insert is processing in-place
1737 * unconnected buffers are (also) cleared there.
1739 for (uint32_t i = 0; i < input_maxbuf; ++i) {
1740 if (used_outputs.test (i)) { continue; }
1742 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1743 if (!valid) continue;
1744 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1750 samples_processed += nframes;
1757 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1758 Float64* outCurrentTempo)
1760 TempoMap& tmap (_session.tempo_map());
1762 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1764 if (outCurrentBeat) {
1765 *outCurrentBeat = tmap.quarter_note_at_sample (transport_sample + input_offset);
1768 if (outCurrentTempo) {
1769 *outCurrentTempo = tmap.tempo_at_sample (transport_sample + input_offset).quarter_notes_per_minute();
1777 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1778 Float32* outTimeSig_Numerator,
1779 UInt32* outTimeSig_Denominator,
1780 Float64* outCurrentMeasureDownBeat)
1782 TempoMap& tmap (_session.tempo_map());
1784 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1786 TempoMetric metric = tmap.metric_at (transport_sample + input_offset);
1787 Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_sample (transport_sample + input_offset);
1789 if (outDeltaSampleOffsetToNextBeat) {
1790 if (bbt.ticks == 0) {
1792 *outDeltaSampleOffsetToNextBeat = 0;
1794 double const next_beat = ceil (tmap.quarter_note_at_sample (transport_sample + input_offset));
1795 samplepos_t const next_beat_sample = tmap.sample_at_quarter_note (next_beat);
1797 *outDeltaSampleOffsetToNextBeat = next_beat_sample - (transport_sample + input_offset);
1801 if (outTimeSig_Numerator) {
1802 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1804 if (outTimeSig_Denominator) {
1805 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1808 if (outCurrentMeasureDownBeat) {
1810 /* beat for the start of the bar.
1812 2|1|0 -> 1 + divisions_per_bar
1813 3|1|0 -> 1 + (2 * divisions_per_bar)
1819 *outCurrentMeasureDownBeat = tmap.quarter_note_at_bbt (bbt);
1826 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1827 Boolean* outTransportStateChanged,
1828 Float64* outCurrentSampleInTimeLine,
1829 Boolean* outIsCycling,
1830 Float64* outCycleStartBeat,
1831 Float64* outCycleEndBeat)
1833 const bool rolling = (transport_speed != 0);
1834 const bool last_transport_rolling = (last_transport_speed != 0);
1836 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1840 *outIsPlaying = rolling;
1843 if (outTransportStateChanged) {
1844 if (rolling != last_transport_rolling) {
1845 *outTransportStateChanged = true;
1846 } else if (transport_speed != last_transport_speed) {
1847 *outTransportStateChanged = true;
1849 *outTransportStateChanged = false;
1853 if (outCurrentSampleInTimeLine) {
1854 /* this assumes that the AU can only call this host callback from render context,
1855 where input_offset is valid.
1857 *outCurrentSampleInTimeLine = transport_sample + input_offset;
1861 // TODO check bounce-processing
1862 Location* loc = _session.locations()->auto_loop_location();
1864 *outIsCycling = (loc && rolling && _session.get_play_loop());
1866 if (*outIsCycling) {
1868 if (outCycleStartBeat || outCycleEndBeat) {
1870 TempoMap& tmap (_session.tempo_map());
1872 Timecode::BBT_Time bbt;
1874 if (outCycleStartBeat) {
1875 *outCycleStartBeat = tmap.quarter_note_at_sample (loc->start() + input_offset);
1878 if (outCycleEndBeat) {
1879 *outCycleEndBeat = tmap.quarter_note_at_sample (loc->end() + input_offset);
1885 last_transport_speed = transport_speed;
1890 set<Evoral::Parameter>
1891 AUPlugin::automatable() const
1893 set<Evoral::Parameter> automates;
1895 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1896 if (descriptors[i].automatable) {
1897 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1904 Plugin::IOPortDescription
1905 AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1907 std::stringstream ss;
1909 case DataType::AUDIO:
1911 case DataType::MIDI:
1919 std::string busname;
1921 if (dt == DataType::AUDIO) {
1924 for (uint32_t bus = 0; bus < input_elements; ++bus) {
1925 if (pid < bus_inputs[bus]) {
1927 ss << _bus_name_in[bus];
1928 ss << " / Bus " << (1 + bus);
1929 busname = _bus_name_in[bus];
1932 pid -= bus_inputs[bus];
1937 for (uint32_t bus = 0; bus < output_elements; ++bus) {
1938 if (pid < bus_outputs[bus]) {
1940 ss << _bus_name_out[bus];
1941 ss << " / Bus " << (1 + bus);
1942 busname = _bus_name_out[bus];
1945 pid -= bus_outputs[bus];
1951 ss << " " << _("In") << " ";
1953 ss << " " << _("Out") << " ";
1958 Plugin::IOPortDescription iod (ss.str());
1959 if (!busname.empty()) {
1960 iod.group_name = busname;
1961 iod.group_channel = id;
1967 AUPlugin::describe_parameter (Evoral::Parameter param)
1969 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1970 return descriptors[param.id()].label;
1977 AUPlugin::parameter_is_audio (uint32_t) const
1983 AUPlugin::parameter_is_control (uint32_t param) const
1985 assert(param < descriptors.size());
1986 if (descriptors[param].automatable) {
1987 /* corrently ardour expects all controls to be automatable
1988 * IOW ardour GUI elements mandate an Evoral::Parameter
1989 * for all input+control ports.
1997 AUPlugin::parameter_is_input (uint32_t param) const
1999 /* AU params that are both readable and writeable,
2000 * are listed in kAudioUnitScope_Global
2002 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
2006 AUPlugin::parameter_is_output (uint32_t param) const
2008 assert(param < descriptors.size());
2009 // TODO check if ardour properly handles ports
2010 // that report is_input + is_output == true
2011 // -> add || descriptors[param].scope == kAudioUnitScope_Global
2012 return (descriptors[param].scope == kAudioUnitScope_Output);
2016 AUPlugin::add_state (XMLNode* root) const
2020 CFPropertyListRef propertyList;
2022 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
2023 if (unit->GetAUPreset (propertyList) != noErr) {
2027 // Convert the property list into XML data.
2029 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
2032 error << _("Could not create XML version of property list") << endmsg;
2036 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
2037 our state node. GACK!
2042 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
2044 root->add_child_copy (*t.root());
2048 CFRelease (xmlData);
2049 CFRelease (propertyList);
2053 AUPlugin::set_state(const XMLNode& node, int version)
2056 CFPropertyListRef propertyList;
2059 if (node.name() != state_node_name()) {
2060 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
2064 if (node.children().empty()) {
2068 XMLNode* top = node.children().front();
2069 XMLNode* copy = new XMLNode (*top);
2074 const string& xml = t.write_buffer ();
2075 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
2076 CFStringRef errorString;
2078 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
2080 kCFPropertyListImmutable,
2083 CFRelease (xmlData);
2086 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
2087 if (unit->SetAUPreset (propertyList) == noErr) {
2090 /* tell the world */
2092 AudioUnitParameter changedUnit;
2093 changedUnit.mAudioUnit = unit->AU();
2094 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2095 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2097 CFRelease (propertyList);
2100 Plugin::set_state (node, version);
2105 AUPlugin::load_preset (PresetRecord r)
2108 CFPropertyListRef propertyList;
2110 UserPresetMap::iterator ux;
2111 FactoryPresetMap::iterator fx;
2113 /* look first in "user" presets */
2115 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
2117 if ((propertyList = load_property_list (ux->second)) != 0) {
2118 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
2119 if (unit->SetAUPreset (propertyList) == noErr) {
2122 /* tell the world */
2124 AudioUnitParameter changedUnit;
2125 changedUnit.mAudioUnit = unit->AU();
2126 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2127 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2129 CFRelease(propertyList);
2132 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2136 preset.presetNumber = fx->second;
2137 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2139 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2141 if (unit->SetPresentPreset (preset) == 0) {
2144 /* tell the world */
2146 AudioUnitParameter changedUnit;
2147 changedUnit.mAudioUnit = unit->AU();
2148 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2149 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2153 preset_holdoff = std::max (_session.get_block_size() * 2.0, _session.sample_rate() * .2);
2156 return ret && Plugin::load_preset (r);
2160 AUPlugin::do_remove_preset (std::string preset_name)
2162 vector<Glib::ustring> v;
2164 std::string m = maker();
2165 std::string n = name();
2167 strip_whitespace_edges (m);
2168 strip_whitespace_edges (n);
2170 v.push_back (Glib::get_home_dir());
2171 v.push_back ("Library");
2172 v.push_back ("Audio");
2173 v.push_back ("Presets");
2176 v.push_back (preset_name + preset_suffix);
2178 Glib::ustring user_preset_path = Glib::build_filename (v);
2180 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Deleting Preset file %1\n", user_preset_path));
2182 if (g_unlink (user_preset_path.c_str())) {
2183 error << string_compose (X_("Could not delete preset at \"%1\": %2"), user_preset_path, strerror (errno)) << endmsg;
2188 AUPlugin::do_save_preset (string preset_name)
2190 CFPropertyListRef propertyList;
2191 vector<Glib::ustring> v;
2192 Glib::ustring user_preset_path;
2194 std::string m = maker();
2195 std::string n = name();
2197 strip_whitespace_edges (m);
2198 strip_whitespace_edges (n);
2200 v.push_back (Glib::get_home_dir());
2201 v.push_back ("Library");
2202 v.push_back ("Audio");
2203 v.push_back ("Presets");
2207 user_preset_path = Glib::build_filename (v);
2209 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2210 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2214 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2215 if (unit->GetAUPreset (propertyList) != noErr) {
2219 // add the actual preset name */
2221 v.push_back (preset_name + preset_suffix);
2225 user_preset_path = Glib::build_filename (v);
2227 set_preset_name_in_plist (propertyList, preset_name);
2229 if (save_property_list (propertyList, user_preset_path)) {
2230 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2234 CFRelease(propertyList);
2236 user_preset_map[preset_name] = user_preset_path;;
2238 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2240 return user_preset_path;
2243 //-----------------------------------------------------------------------------
2244 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2246 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2248 CFNumberRef cfNumber;
2249 SInt32 numberValue = 0;
2250 Boolean dummySuccess;
2252 if (outSuccess == NULL)
2253 outSuccess = &dummySuccess;
2254 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2256 *outSuccess = FALSE;
2260 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2261 if (cfNumber == NULL)
2263 *outSuccess = FALSE;
2266 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2274 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2276 CFDictionaryRef auStateDictionary;
2277 ArdourDescription tempDesc = {0,0,0,0,0};
2278 SInt32 versionValue;
2281 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2284 // the property list for AU state data must be of the dictionary type
2285 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2286 return kAudioUnitErr_InvalidPropertyValue;
2289 auStateDictionary = (CFDictionaryRef)inAUStateData;
2291 // first check to make sure that the version of the AU state data is one that we know understand
2292 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2293 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2296 return kAudioUnitErr_InvalidPropertyValue;
2298 #define kCurrentSavedStateVersion 0
2299 if (versionValue != kCurrentSavedStateVersion) {
2300 return kAudioUnitErr_InvalidPropertyValue;
2303 // grab the ComponentDescription values from the AU state data
2304 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2305 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2306 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2307 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2308 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2309 return kAudioUnitErr_InvalidPropertyValue;
2311 *outComponentDescription = tempDesc;
2316 static bool au_preset_filter (const string& str, void* arg)
2318 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2322 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2326 /* check the preset file path name against this plugin
2327 ID. The idea is that all preset files for this plugin
2328 include "<manufacturer>/<plugin-name>" in their path.
2331 AUPluginInfo* p = (AUPluginInfo *) arg;
2332 string match = p->creator;
2336 ret = str.find (match) != string::npos;
2339 string m = p->creator;
2341 strip_whitespace_edges (m);
2342 strip_whitespace_edges (n);
2347 ret = str.find (match) != string::npos;
2355 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2358 CFPropertyListRef plist;
2359 ArdourDescription presetDesc;
2362 plist = load_property_list (pathstr);
2368 // get the ComponentDescription from the AU preset file
2370 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2372 if (status == noErr) {
2373 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2375 /* try to get the preset name from the property list */
2377 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2379 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2383 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2386 char buf[PATH_MAX+1];
2388 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2405 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2407 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2410 CFStringRef itemName = NULL;
2411 // Marc Poirier-style item name
2413 CAComponent auComponent (comp_desc);
2414 if (auComponent.IsValid()) {
2415 CAComponentDescription dummydesc;
2416 Handle nameHandle = NewHandle(sizeof(void*));
2417 if (nameHandle != NULL) {
2418 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2420 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2421 if (nameString != NULL) {
2422 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2425 DisposeHandle(nameHandle);
2430 AudioComponentCopyName (comp, &itemName);
2433 // if Marc-style fails, do the original way
2434 if (itemName == NULL) {
2435 #ifndef COREAUDIO105
2436 CAComponentDescription comp_desc;
2437 AudioComponentGetDescription (comp, &comp_desc);
2439 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2440 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2441 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2443 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2444 compTypeString, compManufacturerString, compSubTypeString);
2446 if (compTypeString != NULL)
2447 CFRelease(compTypeString);
2448 if (compSubTypeString != NULL)
2449 CFRelease(compSubTypeString);
2450 if (compManufacturerString != NULL)
2451 CFRelease(compManufacturerString);
2454 string str = CFStringRefToStdString(itemName);
2455 string::size_type colon = str.find (':');
2458 name = str.substr (colon+1);
2459 maker = str.substr (0, colon);
2460 strip_whitespace_edges (maker);
2461 strip_whitespace_edges (name);
2465 strip_whitespace_edges (name);
2470 AUPlugin::current_preset() const
2474 CFPropertyListRef propertyList;
2476 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2477 if (unit->GetAUPreset (propertyList) == noErr) {
2478 preset_name = get_preset_name_in_plist (propertyList);
2479 CFRelease(propertyList);
2486 AUPlugin::find_presets ()
2488 vector<string> preset_files;
2490 user_preset_map.clear ();
2492 PluginInfoPtr nfo = get_info();
2493 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2494 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2497 if (preset_files.empty()) {
2498 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2501 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2506 /* make an initial guess at the preset name using the path */
2508 preset_name = Glib::path_get_basename (path);
2509 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2511 /* check that this preset file really matches this plugin
2512 and potentially get the "real" preset name from
2516 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2517 user_preset_map[preset_name] = path;
2518 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2520 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2525 /* now fill the vector<string> with the names we have */
2527 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2528 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2529 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2532 /* add factory presets */
2534 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2535 string const uri = string_compose ("AU2:%1", std::setw(4), std::setfill('0'), i->second);
2536 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2537 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2542 AUPlugin::has_editor () const
2544 // even if the plugin doesn't have its own editor, the AU API can be used
2545 // to create one that looks native.
2549 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2554 type = ARDOUR::AudioUnit;
2558 AUPluginInfo::load (Session& session)
2563 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2564 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2566 if (!comp->IsValid()) {
2567 error << ("AudioUnit: not a valid Component") << endmsg;
2569 plugin.reset (new AUPlugin (session.engine(), session, comp));
2572 AUPluginInfo *aup = new AUPluginInfo (*this);
2573 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2574 plugin->set_info (PluginInfoPtr (aup));
2575 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2579 catch (failed_constructor &err) {
2580 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2581 return PluginPtr ();
2585 std::vector<Plugin::PresetRecord>
2586 AUPluginInfo::get_presets (bool user_only) const
2588 std::vector<Plugin::PresetRecord> p;
2589 boost::shared_ptr<CAComponent> comp;
2592 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2593 if (!comp->IsValid()) {
2594 throw failed_constructor();
2596 } catch (failed_constructor& err) {
2602 if (!preset_search_path_initialized) {
2603 Glib::ustring p = Glib::get_home_dir();
2604 p += "/Library/Audio/Presets:";
2605 p += preset_search_path;
2606 preset_search_path = p;
2607 preset_search_path_initialized = true;
2608 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2611 vector<string> preset_files;
2612 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2614 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2617 preset_name = Glib::path_get_basename (path);
2618 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2619 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2620 p.push_back (Plugin::PresetRecord (path, preset_name));
2634 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2635 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2638 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2639 unit->Uninitialize ();
2642 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2643 unit->Uninitialize ();
2647 unit->Uninitialize ();
2651 CFIndex cnt = CFArrayGetCount (presets);
2652 for (CFIndex i = 0; i < cnt; ++i) {
2653 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2654 string const uri = string_compose ("%1", i);
2655 string name = CFStringRefToStdString (preset->presetName);
2656 p.push_back (Plugin::PresetRecord (uri, name, false));
2658 CFRelease (presets);
2659 unit->Uninitialize ();
2665 AUPluginInfo::au_cache_path ()
2667 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2671 AUPluginInfo::discover (bool scan_only)
2675 /* AU require a CAComponentDescription pointer provided by the OS.
2676 * Ardour only caches port and i/o config. It can't just 'scan' without
2677 * 'discovering' (like we do for VST).
2680 * "Iterate over all plugins. skip the ones where there's no io-cache".
2682 _scan_only = scan_only;
2684 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2685 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2686 // flush RAM cache -- after clear_cache()
2687 cached_info.clear();
2689 // create crash log file
2690 au_start_crashlog ();
2692 PluginInfoList* plugs = new PluginInfoList;
2694 discover_fx (*plugs);
2695 discover_music (*plugs);
2696 discover_generators (*plugs);
2697 discover_instruments (*plugs);
2699 // all fine if we get here
2700 au_remove_crashlog ();
2702 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2708 AUPluginInfo::discover_music (PluginInfoList& plugs)
2710 CAComponentDescription desc;
2711 desc.componentFlags = 0;
2712 desc.componentFlagsMask = 0;
2713 desc.componentSubType = 0;
2714 desc.componentManufacturer = 0;
2715 desc.componentType = kAudioUnitType_MusicEffect;
2717 discover_by_description (plugs, desc);
2721 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2723 CAComponentDescription desc;
2724 desc.componentFlags = 0;
2725 desc.componentFlagsMask = 0;
2726 desc.componentSubType = 0;
2727 desc.componentManufacturer = 0;
2728 desc.componentType = kAudioUnitType_Effect;
2730 discover_by_description (plugs, desc);
2734 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2736 CAComponentDescription desc;
2737 desc.componentFlags = 0;
2738 desc.componentFlagsMask = 0;
2739 desc.componentSubType = 0;
2740 desc.componentManufacturer = 0;
2741 desc.componentType = kAudioUnitType_Generator;
2743 discover_by_description (plugs, desc);
2747 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2749 CAComponentDescription desc;
2750 desc.componentFlags = 0;
2751 desc.componentFlagsMask = 0;
2752 desc.componentSubType = 0;
2753 desc.componentManufacturer = 0;
2754 desc.componentType = kAudioUnitType_MusicDevice;
2756 discover_by_description (plugs, desc);
2761 AUPluginInfo::au_get_crashlog (std::string &msg)
2763 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2764 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2767 std::ifstream ifs(fn.c_str());
2768 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2769 au_remove_crashlog ();
2774 AUPluginInfo::au_start_crashlog ()
2776 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2777 assert(!_crashlog_fd);
2778 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2779 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2780 PBD::error << "Cannot create AU error-log" << fn << "\n";
2781 cerr << "Cannot create AU error-log" << fn << "\n";
2786 AUPluginInfo::au_remove_crashlog ()
2789 ::fclose(_crashlog_fd);
2790 _crashlog_fd = NULL;
2792 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2793 ::g_unlink(fn.c_str());
2794 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2799 AUPluginInfo::au_crashlog (std::string msg)
2801 if (!_crashlog_fd) {
2802 fprintf(stderr, "AU: %s\n", msg.c_str());
2804 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2805 ::fflush(_crashlog_fd);
2810 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2812 ArdourComponent comp = 0;
2813 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2815 comp = ArdourFindNext (NULL, &desc);
2817 while (comp != NULL) {
2818 CAComponentDescription temp;
2820 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2822 AudioComponentGetDescription (comp, &temp);
2824 CFStringRef itemName = NULL;
2827 if (itemName != NULL) CFRelease(itemName);
2828 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2829 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2830 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2831 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2832 compTypeString, compManufacturerString, compSubTypeString);
2833 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2834 if (compTypeString != NULL)
2835 CFRelease(compTypeString);
2836 if (compSubTypeString != NULL)
2837 CFRelease(compSubTypeString);
2838 if (compManufacturerString != NULL)
2839 CFRelease(compManufacturerString);
2842 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2843 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2844 comp = ArdourFindNext (comp, &desc);
2848 bool has_midi_in = false;
2850 AUPluginInfoPtr info (new AUPluginInfo
2851 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2853 /* although apple designed the subtype field to be a "category" indicator,
2854 its really turned into a plugin ID field for a given manufacturer. Hence
2855 there are no categories for AudioUnits. However, to keep the plugins
2856 showing up under "categories", we'll use the "type" as a high level
2859 NOTE: no panners, format converters or i/o AU's for our purposes
2862 switch (info->descriptor->Type()) {
2863 case kAudioUnitType_Panner:
2864 case kAudioUnitType_OfflineEffect:
2865 case kAudioUnitType_FormatConverter:
2866 comp = ArdourFindNext (comp, &desc);
2869 case kAudioUnitType_Output:
2870 info->category = _("Output");
2872 case kAudioUnitType_MusicDevice:
2873 info->category = _("Instrument");
2876 case kAudioUnitType_MusicEffect:
2877 info->category = _("Effect");
2880 case kAudioUnitType_Effect:
2881 info->category = _("Effect");
2883 case kAudioUnitType_Mixer:
2884 info->category = _("Mixer");
2886 case kAudioUnitType_Generator:
2887 info->category = _("Generator");
2890 info->category = _("(Unknown)");
2894 au_blacklist(CFStringRefToStdString(itemName));
2896 get_names (temp, info->name, info->creator);
2898 get_names (comp, info->name, info->creator);
2900 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2901 au_crashlog(string_compose("Plugin: %1", info->name));
2903 info->type = ARDOUR::AudioUnit;
2904 info->unique_id = stringify_descriptor (*info->descriptor);
2906 /* XXX not sure of the best way to handle plugin versioning yet */
2908 CAComponent cacomp (*info->descriptor);
2911 if (cacomp.GetResourceVersion (info->version) != noErr)
2913 if (cacomp.GetVersion (info->version) != noErr)
2919 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2921 info->max_outputs = 0;
2924 /* here we have to map apple's wildcard system to a simple pair
2925 of values. in ::can_do() we use the whole system, but here
2926 we need a single pair of values. XXX probably means we should
2927 remove any use of these values.
2929 for now, if the plugin provides a wildcard, treat it as 1. we really
2930 don't care much, because whether we can handle an i/o configuration
2931 depends upon ::can_support_io_configuration(), not these counts.
2933 they exist because other parts of ardour try to present i/o configuration
2934 info to the user, which should perhaps be revisited.
2937 const vector<pair<int,int> >& ioc (info->cache.io_configs);
2938 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
2939 int32_t possible_out = i->second;
2940 if (possible_out < 0) {
2942 } else if (possible_out > info->max_outputs) {
2943 info->max_outputs = possible_out;
2947 int32_t possible_in = ioc.front().first;
2948 int32_t possible_out = ioc.front().second;
2950 if (possible_in > 0) {
2951 info->n_inputs.set (DataType::AUDIO, possible_in);
2953 info->n_inputs.set (DataType::AUDIO, 1);
2956 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
2958 if (possible_out > 0) {
2959 info->n_outputs.set (DataType::AUDIO, possible_out);
2961 info->n_outputs.set (DataType::AUDIO, 1);
2964 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2965 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2967 plugs.push_back (info);
2970 else if (rv == -1) {
2971 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2974 au_unblacklist(CFStringRefToStdString(itemName));
2975 au_crashlog("Success.");
2976 comp = ArdourFindNext (comp, &desc);
2977 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2979 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2983 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2986 AUPluginCachedInfo& cinfo,
2987 const std::string& name)
2992 /* concatenate unique ID with version to provide a key for cached info lookup.
2993 this ensures we don't get stale information, or should if plugin developers
2994 follow Apple "guidelines".
2997 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
3002 CachedInfoMap::iterator cim = cached_info.find (id);
3004 if (cim != cached_info.end()) {
3005 cinfo = cim->second;
3010 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
3015 AUChannelInfo* channel_info;
3019 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
3023 if (CAAudioUnit::Open (comp, unit) != noErr) {
3029 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
3034 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
3035 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
3040 /* AU is expected to deal with same channel valance in and out */
3041 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
3043 /* CAAudioUnit::GetChannelInfo silently merges bus formats
3044 * check if this was the case and if so, add
3045 * bus configs as incremental options.
3047 Boolean* isWritable = 0;
3048 UInt32 dataSize = 0;
3049 OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
3050 kAudioUnitProperty_SupportedNumChannels,
3051 kAudioUnitScope_Global, 0,
3052 &dataSize, isWritable);
3053 if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
3054 /* incrementally add busses */
3057 for (uint32_t n = 0; n < cnt; ++n) {
3058 in += channel_info[n].inChannels;
3059 out += channel_info[n].outChannels;
3060 cinfo.io_configs.push_back (pair<int,int> (in, out));
3063 /* store each configuration */
3064 for (uint32_t n = 0; n < cnt; ++n) {
3065 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
3066 channel_info[n].outChannels));
3070 free (channel_info);
3073 add_cached_info (id, cinfo);
3074 save_cached_info ();
3080 AUPluginInfo::clear_cache ()
3082 const string& fn = au_cache_path();
3083 if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
3084 ::g_unlink(fn.c_str());
3086 // keep cached_info in RAM until restart or re-scan
3087 cached_info.clear();
3091 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
3093 cached_info[id] = cinfo;
3096 #define AU_CACHE_VERSION "2.0"
3099 AUPluginInfo::save_cached_info ()
3103 node = new XMLNode (X_("AudioUnitPluginCache"));
3104 node->set_property( "version", AU_CACHE_VERSION );
3106 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
3107 XMLNode* parent = new XMLNode (X_("plugin"));
3108 parent->set_property ("id", i->first);
3109 node->add_child_nocopy (*parent);
3111 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
3113 XMLNode* child = new XMLNode (X_("io"));
3115 child->set_property (X_("in"), j->first);
3116 child->set_property (X_("out"), j->second);
3117 parent->add_child_nocopy (*child);
3122 Glib::ustring path = au_cache_path ();
3125 tree.set_root (node);
3127 if (!tree.write (path)) {
3128 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
3129 g_unlink (path.c_str());
3134 AUPluginInfo::load_cached_info ()
3136 Glib::ustring path = au_cache_path ();
3139 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
3143 if ( !tree.read (path) ) {
3144 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
3148 const XMLNode* root (tree.root());
3150 if (root->name() != X_("AudioUnitPluginCache")) {
3154 //initial version has incorrectly stored i/o info, and/or garbage chars.
3155 XMLProperty const * version = root->property(X_("version"));
3156 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
3157 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
3161 cached_info.clear ();
3163 const XMLNodeList children = root->children();
3165 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
3167 const XMLNode* child = *iter;
3169 if (child->name() == X_("plugin")) {
3171 const XMLNode* gchild;
3172 const XMLNodeList gchildren = child->children();
3175 if (!child->get_property (X_("id"), id)) {
3182 string::size_type slash = id.find_last_of ('/');
3184 if (slash == string::npos) {
3188 version = id.substr (slash);
3189 id = id.substr (0, slash);
3190 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3192 if (fixed.empty()) {
3193 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3200 AUPluginCachedInfo cinfo;
3202 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3206 if (gchild->name() == X_("io")) {
3211 if (gchild->get_property (X_("in"), in) && gchild->get_property (X_("out"), out)) {
3212 cinfo.io_configs.push_back (pair<int,int> (in, out));
3217 if (cinfo.io_configs.size()) {
3218 add_cached_info (id, cinfo);
3228 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3232 /* note: OSType is a compiler-implemenation-defined value,
3233 historically a 32 bit integer created with a multi-character
3234 constant such as 'abcd'. It is, fundamentally, an abomination.
3239 s << desc.SubType();
3247 AUPluginInfo::needs_midi_input () const
3249 return is_effect_with_midi_input () || is_instrument ();
3253 AUPluginInfo::is_effect () const
3255 return is_effect_without_midi_input() || is_effect_with_midi_input();
3259 AUPluginInfo::is_effect_without_midi_input () const
3261 return descriptor->IsAUFX();
3265 AUPluginInfo::is_effect_with_midi_input () const
3267 return descriptor->IsAUFM();
3271 AUPluginInfo::is_instrument () const
3273 return descriptor->IsMusicDevice();
3277 AUPluginInfo::is_utility () const
3279 return (descriptor->IsGenerator() || descriptor->componentType == 'aumi');
3280 // kAudioUnitType_MidiProcessor ..looks like we aren't even scanning for these yet?
3284 AUPlugin::set_info (PluginInfoPtr info)
3286 Plugin::set_info (info);
3288 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3289 _has_midi_input = pinfo->needs_midi_input ();
3290 _has_midi_output = false;
3294 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3297 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3299 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3301 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3303 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3307 _parameter_listener_arg = arg;
3309 // listen for latency changes
3310 AudioUnitEvent event;
3311 event.mEventType = kAudioUnitEvent_PropertyChange;
3312 event.mArgument.mProperty.mAudioUnit = unit->AU();
3313 event.mArgument.mProperty.mPropertyID = kAudioUnitProperty_Latency;
3314 event.mArgument.mProperty.mScope = kAudioUnitScope_Global;
3315 event.mArgument.mProperty.mElement = 0;
3317 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3318 PBD::error << "Failed to create latency event listener\n";
3319 // TODO don't cache _current_latency
3326 AUPlugin::listen_to_parameter (uint32_t param_id)
3328 AudioUnitEvent event;
3330 if (!_parameter_listener || param_id >= descriptors.size()) {
3334 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3335 event.mArgument.mParameter.mAudioUnit = unit->AU();
3336 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3337 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3338 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3340 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3344 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3345 event.mArgument.mParameter.mAudioUnit = unit->AU();
3346 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3347 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3348 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3350 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3354 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3355 event.mArgument.mParameter.mAudioUnit = unit->AU();
3356 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3357 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3358 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3360 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3368 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3370 AudioUnitEvent event;
3372 if (!_parameter_listener || param_id >= descriptors.size()) {
3376 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3377 event.mArgument.mParameter.mAudioUnit = unit->AU();
3378 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3379 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3380 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3382 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3386 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3387 event.mArgument.mParameter.mAudioUnit = unit->AU();
3388 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3389 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3390 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3392 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3396 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3397 event.mArgument.mParameter.mAudioUnit = unit->AU();
3398 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3399 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3400 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3402 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3410 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3412 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3416 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3418 if (event->mEventType == kAudioUnitEvent_PropertyChange) {
3419 if (event->mArgument.mProperty.mPropertyID == kAudioUnitProperty_Latency) {
3420 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Latency Change Event %1 <> %2\n", new_value, unit->Latency()));
3421 guint lat = unit->Latency() * _session.sample_rate();
3422 g_atomic_int_set (&_current_latency, lat);
3427 ParameterMap::iterator i;
3429 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3433 switch (event->mEventType) {
3434 case kAudioUnitEvent_BeginParameterChangeGesture:
3435 StartTouch (i->second);
3437 case kAudioUnitEvent_EndParameterChangeGesture:
3438 EndTouch (i->second);
3440 case kAudioUnitEvent_ParameterValueChange:
3441 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3442 means that something else (i.e. the plugin GUI) made the change.
3444 if (preset_holdoff > 0) {
3445 ParameterChangedExternally (i->second, new_value);
3447 Plugin::parameter_changed_externally (i->second, new_value);