2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include "pbd/gstdio_compat.h"
29 #include "pbd/transmitter.h"
30 #include "pbd/xml++.h"
31 #include "pbd/convert.h"
32 #include "pbd/whitespace.h"
33 #include "pbd/file_utils.h"
34 #include "pbd/locale_guard.h"
36 #include <glibmm/threads.h>
37 #include <glibmm/fileutils.h>
38 #include <glibmm/miscutils.h>
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/debug.h"
44 #include "ardour/midi_buffer.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/audio_unit.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
53 #include "CAAudioUnit.h"
54 #include "CAAUParameter.h"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
61 #include <Carbon/Carbon.h>
65 #define ArdourComponent Component
66 #define ArdourDescription ComponentDescription
67 #define ArdourFindNext FindNextComponent
69 #define ArdourComponent AudioComponent
70 #define ArdourDescription AudioComponentDescription
71 #define ArdourFindNext AudioComponentFindNext
78 using namespace ARDOUR;
80 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
82 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
83 static string preset_suffix = ".aupreset";
84 static bool preset_search_path_initialized = false;
85 FILE * AUPluginInfo::_crashlog_fd = NULL;
86 bool AUPluginInfo::_scan_only = true;
89 static void au_blacklist (std::string id)
91 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
92 FILE * blacklist_fd = NULL;
93 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
94 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
97 assert(id.find("\n") == string::npos);
98 fprintf(blacklist_fd, "%s\n", id.c_str());
99 ::fclose(blacklist_fd);
102 static void au_unblacklist (std::string id)
104 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
105 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
106 PBD::warning << "Expected Blacklist file does not exist.\n";
112 std::ifstream ifs(fn.c_str());
113 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
116 ::g_unlink (fn.c_str());
118 assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
119 assert(id.find("\n") == string::npos);
121 id += "\n"; // add separator
122 const size_t rpl = bl.find(id);
123 if (rpl != string::npos) {
124 bl.replace(rpl, id.size(), "");
130 FILE * blacklist_fd = NULL;
131 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
132 PBD::error << "Cannot open AU blacklist.\n";
135 fprintf(blacklist_fd, "%s", bl.c_str());
136 ::fclose(blacklist_fd);
139 static bool is_blacklisted (std::string id)
141 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
142 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
146 std::ifstream ifs(fn.c_str());
147 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
149 assert(id.find("\n") == string::npos);
151 id += "\n"; // add separator
152 const size_t rpl = bl.find(id);
153 if (rpl != string::npos) {
162 _render_callback(void *userData,
163 AudioUnitRenderActionFlags *ioActionFlags,
164 const AudioTimeStamp *inTimeStamp,
166 UInt32 inNumberFrames,
167 AudioBufferList* ioData)
170 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
176 _get_beat_and_tempo_callback (void* userData,
177 Float64* outCurrentBeat,
178 Float64* outCurrentTempo)
181 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
188 _get_musical_time_location_callback (void * userData,
189 UInt32 * outDeltaSampleOffsetToNextBeat,
190 Float32 * outTimeSig_Numerator,
191 UInt32 * outTimeSig_Denominator,
192 Float64 * outCurrentMeasureDownBeat)
195 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
196 outTimeSig_Numerator,
197 outTimeSig_Denominator,
198 outCurrentMeasureDownBeat);
204 _get_transport_state_callback (void* userData,
205 Boolean* outIsPlaying,
206 Boolean* outTransportStateChanged,
207 Float64* outCurrentSampleInTimeLine,
208 Boolean* outIsCycling,
209 Float64* outCycleStartBeat,
210 Float64* outCycleEndBeat)
213 return ((AUPlugin*)userData)->get_transport_state_callback (
214 outIsPlaying, outTransportStateChanged,
215 outCurrentSampleInTimeLine, outIsCycling,
216 outCycleStartBeat, outCycleEndBeat);
223 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
229 // Convert the property list into XML data.
231 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
234 error << _("Could not create XML version of property list") << endmsg;
238 // Write the XML data to the file.
240 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
242 if (errno == EEXIST) {
243 error << string_compose (_("Preset file %1 exists; not overwriting"),
246 error << string_compose (_("Cannot open preset file %1 (%2)"),
247 path, strerror (errno)) << endmsg;
253 size_t cnt = CFDataGetLength (xmlData);
255 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
266 static CFPropertyListRef
267 load_property_list (Glib::ustring path)
270 CFPropertyListRef propertyList = 0;
272 CFStringRef errorString;
274 // Read the XML file.
276 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
281 off_t len = lseek (fd, 0, SEEK_END);
282 char* buf = new char[len];
283 lseek (fd, 0, SEEK_SET);
285 if (read (fd, buf, len) != len) {
293 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
295 // Reconstitute the dictionary using the XML data.
297 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
299 kCFPropertyListImmutable,
308 //-----------------------------------------------------------------------------
310 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
315 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
317 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
318 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
324 //-----------------------------------------------------------------------------
326 get_preset_name_in_plist (CFPropertyListRef plist)
334 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
335 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
337 CFStringRef str = (CFStringRef) p;
338 int len = CFStringGetLength(str);
340 char local_buffer[len];
341 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
349 //--------------------------------------------------------------------------
350 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
351 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
352 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
353 Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
355 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
358 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
359 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
361 // only sub-type and manufacturer IDs need to be equal
364 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
365 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
372 //--------------------------------------------------------------------------
373 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
374 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
375 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
376 Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
379 ArdourDescription desc;
381 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
384 // get the ComponentDescription of the input Component
386 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
388 status = AudioComponentGetDescription (inComponent, &desc);
393 // check if the Component's ComponentDescription matches the input ComponentDescription
394 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
397 //--------------------------------------------------------------------------
398 // determine if 2 ComponentDescriptions are basically equal
399 // (by that, I mean that the important identifying values are compared,
400 // but not the ComponentDescription flags)
401 Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
403 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
406 //--------------------------------------------------------------------------
407 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
408 Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
410 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
413 //--------------------------------------------------------------------------
414 // determine if a ComponentDescription basically matches that of a particular Component
415 Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
417 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
420 //--------------------------------------------------------------------------
421 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
422 Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
424 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
428 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
429 : Plugin (engine, session)
431 , unit (new CAAudioUnit)
432 , initialized (false)
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 , frames_processed (0)
449 , audio_input_cnt (0)
450 , _parameter_listener (0)
451 , _parameter_listener_arg (0)
452 , transport_frame (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 , frames_processed (0)
490 , _parameter_listener (0)
491 , _parameter_listener_arg (0)
492 , transport_frame (0)
493 , transport_speed (0)
494 , last_transport_speed (0.0)
498 for (size_t i = 0; i < descriptors.size(); ++i) {
499 set_parameter (i, other.get_parameter (i));
503 AUPlugin::~AUPlugin ()
505 if (_parameter_listener) {
506 AUListenerDispose (_parameter_listener);
507 _parameter_listener = 0;
511 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
512 unit->Uninitialize ();
522 AUPlugin::discover_factory_presets ()
529 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
530 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
534 assert (dataSize == sizeof (presets));
536 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
537 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
545 CFIndex cnt = CFArrayGetCount (presets);
547 for (CFIndex i = 0; i < cnt; ++i) {
548 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
550 string name = CFStringRefToStdString (preset->presetName);
551 factory_preset_map[name] = preset->presetNumber;
552 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
562 CFStringRef itemName;
564 /* these keep track of *configured* channel set up,
565 not potential set ups.
569 output_channels = -1;
571 CAComponentDescription temp;
573 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
575 AudioComponentGetDescription (comp.get()->Comp(), &temp);
577 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
578 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
579 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
580 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
581 compTypeString, compManufacturerString, compSubTypeString);
582 if (compTypeString != NULL) CFRelease(compTypeString);
583 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
584 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
587 au_blacklist(CFStringRefToStdString(itemName));
590 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
591 err = CAAudioUnit::Open (*(comp.get()), *unit);
593 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
594 throw failed_constructor();
598 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
599 throw failed_constructor ();
602 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
603 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
604 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
605 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
606 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
607 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
609 cb_offsets = (framecnt_t*) calloc (input_elements, sizeof(framecnt_t));
610 bus_inputs = (uint32_t*) calloc (input_elements, sizeof(uint32_t));
611 bus_outputs = (uint32_t*) calloc (output_elements, sizeof(uint32_t));
613 for (size_t i = 0; i < output_elements; ++i) {
614 unit->Reset (kAudioUnitScope_Output, i);
615 AudioStreamBasicDescription fmt;
616 err = unit->GetFormat (kAudioUnitScope_Output, i, fmt);
618 bus_outputs[i] = fmt.mChannelsPerFrame;
621 UInt32 sz = sizeof (CFStringRef);
622 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Output,
623 i, &name, &sz) == noErr
625 _bus_name_out.push_back (CFStringRefToStdString (name));
628 _bus_name_out.push_back (string_compose ("Audio-Bus %1", i));
632 for (size_t i = 0; i < input_elements; ++i) {
633 unit->Reset (kAudioUnitScope_Input, i);
634 AudioStreamBasicDescription fmt;
635 err = unit->GetFormat (kAudioUnitScope_Input, i, fmt);
637 bus_inputs[i] = fmt.mChannelsPerFrame;
640 UInt32 sz = sizeof (CFStringRef);
641 if (AudioUnitGetProperty (unit->AU(), kAudioUnitProperty_ElementName, kAudioUnitScope_Input,
642 i, &name, &sz) == noErr
644 _bus_name_in.push_back (CFStringRefToStdString (name));
647 _bus_name_in.push_back (string_compose ("Audio-Bus %1", i));
651 for (size_t i = 0; i < input_elements; ++i) {
652 /* setup render callback: the plugin calls this to get input data */
653 AURenderCallbackStruct renderCallbackInfo;
654 renderCallbackInfo.inputProc = _render_callback;
655 renderCallbackInfo.inputProcRefCon = this;
656 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
657 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
658 i, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
659 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
660 throw failed_constructor();
664 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
666 HostCallbackInfo info;
667 memset (&info, 0, sizeof (HostCallbackInfo));
668 info.hostUserData = this;
669 info.beatAndTempoProc = _get_beat_and_tempo_callback;
670 info.musicalTimeLocationProc = _get_musical_time_location_callback;
671 info.transportStateProc = _get_transport_state_callback;
673 //ignore result of this - don't care if the property isn't supported
674 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
675 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
676 kAudioUnitScope_Global,
679 sizeof (HostCallbackInfo));
681 if (set_block_size (_session.get_block_size())) {
682 error << _("AUPlugin: cannot set processing block size") << endmsg;
683 throw failed_constructor();
686 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
687 discover_parameters ();
688 discover_factory_presets ();
690 // Plugin::setup_controls ();
692 au_unblacklist(CFStringRefToStdString(itemName));
693 if (itemName != NULL) CFRelease(itemName);
697 AUPlugin::discover_parameters ()
699 /* discover writable parameters */
701 AudioUnitScope scopes[] = {
702 kAudioUnitScope_Global,
703 kAudioUnitScope_Output,
704 kAudioUnitScope_Input
707 descriptors.clear ();
709 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
711 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
713 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
715 AUParameterDescriptor d;
717 d.id = param_info.ParamID (i);
719 const CAAUParameter* param = param_info.GetParamInfo (d.id);
720 const AudioUnitParameterInfo& info (param->ParamInfo());
722 const int len = CFStringGetLength (param->GetName());
723 char local_buffer[len*2];
724 Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
728 d.label = local_buffer;
731 d.scope = param_info.GetScope ();
732 d.element = param_info.GetElement ();
734 /* info.units to consider */
736 kAudioUnitParameterUnit_Generic = 0
737 kAudioUnitParameterUnit_Indexed = 1
738 kAudioUnitParameterUnit_Boolean = 2
739 kAudioUnitParameterUnit_Percent = 3
740 kAudioUnitParameterUnit_Seconds = 4
741 kAudioUnitParameterUnit_SampleFrames = 5
742 kAudioUnitParameterUnit_Phase = 6
743 kAudioUnitParameterUnit_Rate = 7
744 kAudioUnitParameterUnit_Hertz = 8
745 kAudioUnitParameterUnit_Cents = 9
746 kAudioUnitParameterUnit_RelativeSemiTones = 10
747 kAudioUnitParameterUnit_MIDINoteNumber = 11
748 kAudioUnitParameterUnit_MIDIController = 12
749 kAudioUnitParameterUnit_Decibels = 13
750 kAudioUnitParameterUnit_LinearGain = 14
751 kAudioUnitParameterUnit_Degrees = 15
752 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
753 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
754 kAudioUnitParameterUnit_Pan = 18
755 kAudioUnitParameterUnit_Meters = 19
756 kAudioUnitParameterUnit_AbsoluteCents = 20
757 kAudioUnitParameterUnit_Octaves = 21
758 kAudioUnitParameterUnit_BPM = 22
759 kAudioUnitParameterUnit_Beats = 23
760 kAudioUnitParameterUnit_Milliseconds = 24
761 kAudioUnitParameterUnit_Ratio = 25
764 /* info.flags to consider */
768 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
769 kAudioUnitParameterFlag_HasClump = (1L << 20)
770 kAudioUnitParameterFlag_HasName = (1L << 21)
771 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
772 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
773 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
774 kAudioUnitParameterFlag_CanRamp = (1L << 25)
775 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
776 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
777 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
778 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
779 kAudioUnitParameterFlag_IsReadable = (1L << 30)
780 kAudioUnitParameterFlag_IsWritable = (1L << 31)
783 d.lower = info.minValue;
784 d.upper = info.maxValue;
785 d.normal = info.defaultValue;
787 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
788 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
789 (d.integer_step && ((d.upper - d.lower) == 1.0));
790 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
791 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
792 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
793 (info.flags & kAudioUnitParameterFlag_IsWritable);
795 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
796 d.au_unit = info.unit;
798 case kAudioUnitParameterUnit_Decibels:
799 d.unit = ParameterDescriptor::DB;
801 case kAudioUnitParameterUnit_MIDINoteNumber:
802 d.unit = ParameterDescriptor::MIDI_NOTE;
804 case kAudioUnitParameterUnit_Hertz:
805 d.unit = ParameterDescriptor::HZ;
809 d.min_unbound = 0; // lower is bound
810 d.max_unbound = 0; // upper is bound
813 descriptors.push_back (d);
815 uint32_t last_param = descriptors.size() - 1;
816 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
817 listen_to_parameter (last_param);
824 four_ints_to_four_byte_literal (unsigned char n[4])
826 /* this is actually implementation dependent. sigh. this is what gcc
827 and quite a few others do.
829 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
833 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
835 if (isdigit (id[0])) {
839 /* ID format is xxxx-xxxx-xxxx
840 where x maybe \xNN or a printable character.
842 Split at the '-' and and process each part into an integer.
843 Then put it back together.
847 unsigned char nascent[4];
848 const char* cstr = id.c_str();
849 const char* estr = cstr + id.size();
860 while (*cstr && next_int < 4) {
864 if (estr - cstr < 3) {
866 /* too close to the end for \xNN parsing: treat as literal characters */
874 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
878 memcpy (short_buf, &cstr[2], 2);
879 nascent[in] = strtol (short_buf, NULL, 16);
885 /* treat as literal characters */
899 if (in && (in % 4 == 0)) {
900 /* nascent is ready */
901 n[next_int] = four_ints_to_four_byte_literal (nascent);
905 /* swallow space-hyphen-space */
919 s << n[0] << '-' << n[1] << '-' << n[2];
928 AUPlugin::unique_id () const
930 return AUPluginInfo::stringify_descriptor (comp->Desc());
934 AUPlugin::label () const
936 return _info->name.c_str();
940 AUPlugin::parameter_count () const
942 return descriptors.size();
946 AUPlugin::default_value (uint32_t port)
948 if (port < descriptors.size()) {
949 return descriptors[port].normal;
956 AUPlugin::signal_latency () const
958 guint lat = g_atomic_int_get (&_current_latency);;
959 if (lat == UINT_MAX) {
960 lat = unit->Latency() * _session.frame_rate();
961 g_atomic_int_set (&_current_latency, lat);
967 AUPlugin::set_parameter (uint32_t which, float val)
969 if (which >= descriptors.size()) {
973 if (get_parameter(which) == val) {
977 const AUParameterDescriptor& d (descriptors[which]);
978 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
979 unit->SetParameter (d.id, d.scope, d.element, val);
981 /* tell the world what we did */
983 AudioUnitEvent theEvent;
985 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
986 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
987 theEvent.mArgument.mParameter.mParameterID = d.id;
988 theEvent.mArgument.mParameter.mScope = d.scope;
989 theEvent.mArgument.mParameter.mElement = d.element;
991 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
992 /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
993 AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
995 Plugin::set_parameter (which, val);
999 AUPlugin::get_parameter (uint32_t which) const
1002 if (which < descriptors.size()) {
1003 const AUParameterDescriptor& d (descriptors[which]);
1004 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
1005 unit->GetParameter(d.id, d.scope, d.element, val);
1011 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
1013 if (which < descriptors.size()) {
1014 pd = descriptors[which];
1021 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
1023 if (which < descriptors.size()) {
1032 AUPlugin::activate ()
1036 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
1037 if ((err = unit->Initialize()) != noErr) {
1038 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
1040 frames_processed = 0;
1047 AUPlugin::deactivate ()
1049 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
1050 unit->Uninitialize ();
1051 initialized = false;
1057 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
1058 unit->GlobalReset ();
1062 AUPlugin::requires_fixed_size_buffers() const
1064 return _requires_fixed_size_buffers;
1069 AUPlugin::set_block_size (pframes_t nframes)
1071 bool was_initialized = initialized;
1072 UInt32 numFrames = nframes;
1079 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
1080 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
1081 0, &numFrames, sizeof (numFrames))) != noErr) {
1082 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
1086 if (was_initialized) {
1094 AUPlugin::configure_io (ChanCount in, ChanCount out)
1096 AudioStreamBasicDescription streamFormat;
1097 bool was_initialized = initialized;
1098 int32_t audio_out = out.n_audio();
1099 if (audio_input_cnt > 0) {
1100 in.set (DataType::AUDIO, audio_input_cnt);
1102 const int32_t audio_in = in.n_audio();
1104 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1107 //if we are already running with the requested i/o config, bail out here
1108 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1115 streamFormat.mSampleRate = _session.frame_rate();
1116 streamFormat.mFormatID = kAudioFormatLinearPCM;
1117 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1119 #ifdef __LITTLE_ENDIAN__
1122 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1125 streamFormat.mBitsPerChannel = 32;
1126 streamFormat.mFramesPerPacket = 1;
1128 /* apple says that for non-interleaved data, these
1129 * values always refer to a single channel.
1131 streamFormat.mBytesPerPacket = 4;
1132 streamFormat.mBytesPerFrame = 4;
1134 configured_input_busses = 0;
1135 configured_output_busses = 0;
1137 for (size_t i = 0; i < output_elements; ++i) {
1138 unit->Reset (kAudioUnitScope_Output, i);
1140 for (size_t i = 0; i < input_elements; ++i) {
1141 unit->Reset (kAudioUnitScope_Input, i);
1144 /* now assign the channels to available busses */
1145 uint32_t used_in = 0;
1146 uint32_t used_out = 0;
1148 if (variable_inputs || input_elements == 1) {
1149 // we only ever use the first bus
1150 if (input_elements > 1) {
1151 warning << string_compose (_("AU %1 has multiple input busses and variable port count."), name()) << endmsg;
1153 streamFormat.mChannelsPerFrame = audio_in;
1154 if (set_stream_format (kAudioUnitScope_Input, 0, streamFormat) != 0) {
1157 configured_input_busses = 1;
1160 configured_input_busses = 0;
1161 uint32_t remain = audio_in;
1162 for (uint32_t bus = 0; remain > 0 && bus < input_elements; ++bus) {
1163 uint32_t cnt = std::min (remain, bus_inputs[bus]);
1164 if (cnt == 0) { continue; }
1165 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure input bus: %2 chn: %3", name(), bus, cnt));
1167 streamFormat.mChannelsPerFrame = cnt;
1168 if (set_stream_format (kAudioUnitScope_Input, bus, streamFormat) != 0) {
1172 ++configured_input_busses;
1177 if (variable_outputs || output_elements == 1) {
1178 if (output_elements > 1) {
1179 warning << string_compose (_("AU %1 has multiple output busses and variable port count."), name()) << endmsg;
1182 streamFormat.mChannelsPerFrame = audio_out;
1183 if (set_stream_format (kAudioUnitScope_Output, 0, streamFormat) != 0) {
1186 configured_output_busses = 1;
1187 used_out = audio_out;
1189 uint32_t remain = audio_out;
1190 configured_output_busses = 0;
1191 for (uint32_t bus = 0; remain > 0 && bus < output_elements; ++bus) {
1192 uint32_t cnt = std::min (remain, bus_outputs[bus]);
1193 if (cnt == 0) { continue; }
1194 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 configure output bus: %2 chn: %3", name(), bus, cnt));
1195 streamFormat.mChannelsPerFrame = cnt;
1196 if (set_stream_format (kAudioUnitScope_Output, bus, streamFormat) != 0) {
1201 ++configured_output_busses;
1206 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1207 used_out * sizeof(::AudioBuffer));
1209 input_channels = used_in;
1210 output_channels = used_out;
1211 /* reset plugin info to show currently configured state */
1213 _info->n_inputs = ChanCount (DataType::AUDIO, used_in) + ChanCount (DataType::MIDI, _has_midi_input ? 1 : 0);
1214 _info->n_outputs = ChanCount (DataType::AUDIO, used_out);
1216 if (was_initialized) {
1224 AUPlugin::input_streams() const
1227 if (input_channels < 0) {
1228 // force PluginIoReConfigure -- see also commit msg e38eb06
1229 c.set (DataType::AUDIO, 0);
1230 c.set (DataType::MIDI, 0);
1232 c.set (DataType::AUDIO, input_channels);
1233 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1240 AUPlugin::output_streams() const
1243 if (output_channels < 0) {
1244 // force PluginIoReConfigure - see also commit msg e38eb06
1245 c.set (DataType::AUDIO, 0);
1246 c.set (DataType::MIDI, 0);
1248 c.set (DataType::AUDIO, output_channels);
1249 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1255 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out, ChanCount* imprecise)
1257 _output_configs.clear ();
1258 const int32_t audio_in = in.n_audio();
1259 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1261 /* lets check MIDI first */
1263 if (in.n_midi() > 0 && !_has_midi_input && !imprecise) {
1267 vector<pair<int,int> > io_configs = pinfo->cache.io_configs;
1269 if (input_elements > 1) {
1270 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1271 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1272 int32_t possible_in = i->first;
1273 int32_t possible_out = i->second;
1274 if (possible_in < 1 || possible_out < 1) {
1277 for (uint32_t i = 1; i < input_elements; ++i) {
1278 // can't use up-to bus_inputs[]
1279 // waves' SC-C6(s) for example fails to configure with only 1 input
1281 io_configs.push_back (pair<int,int> (possible_in + bus_inputs[i], possible_out));
1286 if (output_elements > 1) {
1287 const vector<pair<int,int> >& ioc (pinfo->cache.io_configs);
1288 for (vector<pair<int,int> >::const_iterator i = ioc.begin(); i != ioc.end(); ++i) {
1289 int32_t possible_in = i->first;
1290 int32_t possible_out = i->second;
1291 if (possible_in < 1 || possible_out < 1) {
1294 for (uint32_t i = 1; i < output_elements; ++i) {
1295 int32_t c = bus_outputs[i];
1296 for (uint32_t j = 1; j < i; ++j) {
1297 c += bus_outputs [j];
1299 io_configs.push_back (pair<int,int> (possible_in, possible_out + c));
1304 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1305 name(), io_configs.size(), in, out));
1308 printf ("AU I/O Configs %s %d\n", name(), io_configs.size());
1309 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1310 printf ("- I/O %d / %d\n", i->first, i->second);
1314 // preferred setting (provided by plugin_insert)
1315 const int preferred_out = out.n_audio ();
1317 bool exact_match = false;
1319 /* kAudioUnitProperty_SupportedNumChannels
1320 * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
1322 * - both fields are -1
1323 * e.g. inChannels = -1 outChannels = -1
1324 * This is the default case. Any number of input and output channels, as long as the numbers match
1326 * - one field is -1, the other field is positive
1327 * e.g. inChannels = -1 outChannels = 2
1328 * Any number of input channels, exactly two output channels
1330 * - one field is -1, the other field is -2
1331 * e.g. inChannels = -1 outChannels = -2
1332 * Any number of input channels, any number of output channels
1334 * - both fields have non-negative values
1335 * e.g. inChannels = 2 outChannels = 6
1336 * Exactly two input channels, exactly six output channels
1337 * e.g. inChannels = 0 outChannels = 2
1338 * No input channels, exactly two output channels (such as for an instrument unit with stereo output)
1340 * - both fields have negative values, neither of which is –1 or –2
1341 * e.g. inChannels = -4 outChannels = -8
1342 * Up to four input channels and up to eight output channels
1345 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1347 int32_t possible_in = i->first;
1348 int32_t possible_out = i->second;
1350 if ((possible_in == audio_in) && (possible_out == preferred_out)) {
1351 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1352 possible_in, possible_out,
1356 _output_configs.insert (preferred_out);
1363 /* now allow potentially "imprecise" matches */
1364 int32_t audio_out = -1;
1365 float penalty = 9999;
1366 int used_possible_in = 0;
1367 #if defined (__clang__)
1368 # pragma clang diagnostic push
1369 # pragma clang diagnostic ignored "-Wtautological-compare"
1372 #define FOUNDCFG(nch) { \
1373 float p = fabsf ((float)(nch) - preferred_out); \
1374 _output_configs.insert (nch); \
1375 if ((nch) > preferred_out) { p *= 1.1; } \
1376 if (p < penalty) { \
1377 used_possible_in = possible_in; \
1378 audio_out = (nch); \
1381 variable_inputs = possible_in < 0; \
1382 variable_outputs = possible_out < 0; \
1386 #define ANYTHINGGOES \
1387 _output_configs.insert (0);
1389 #define UPTO(nch) { \
1390 for (int n = 1; n <= nch; ++n) { \
1391 _output_configs.insert (n); \
1395 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1397 int32_t possible_in = i->first;
1398 int32_t possible_out = i->second;
1400 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1402 if (possible_out == 0) {
1403 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1404 /* XXX surely this is just a send? (e.g. AUNetSend) */
1408 if (possible_in == 0) {
1409 /* no inputs, generators & instruments */
1410 if (possible_out == -1) {
1411 /* any configuration possible, provide stereo output */
1412 FOUNDCFG (preferred_out);
1414 } else if (possible_out == -2) {
1415 /* invalid, should be (0, -1) */
1416 FOUNDCFG (preferred_out);
1418 } else if (possible_out < -2) {
1419 /* variable number of outputs up to -N, */
1420 FOUNDCFG (min (-possible_out, preferred_out));
1421 UPTO (-possible_out);
1423 /* exact number of outputs */
1424 FOUNDCFG (possible_out);
1428 if (possible_in == -1) {
1429 /* wildcard for input */
1430 if (possible_out == -1) {
1431 /* out must match in */
1432 FOUNDCFG (audio_in);
1433 } else if (possible_out == -2) {
1434 /* any configuration possible, pick matching */
1435 FOUNDCFG (preferred_out);
1437 } else if (possible_out < -2) {
1438 /* explicitly variable number of outputs, pick maximum */
1439 FOUNDCFG (max (-possible_out, preferred_out));
1440 /* and try min, too, in case the penalty is lower */
1441 FOUNDCFG (min (-possible_out, preferred_out));
1442 UPTO (-possible_out)
1444 /* exact number of outputs */
1445 FOUNDCFG (possible_out);
1449 if (possible_in == -2) {
1450 if (possible_out == -1) {
1451 /* any configuration possible, pick matching */
1452 FOUNDCFG (preferred_out);
1454 } else if (possible_out == -2) {
1455 /* invalid. interpret as (-1, -1) */
1456 FOUNDCFG (preferred_out);
1458 } else if (possible_out < -2) {
1459 /* invalid, interpret as (<-2, <-2)
1460 * variable number of outputs up to -N, */
1461 FOUNDCFG (min (-possible_out, preferred_out));
1462 UPTO (-possible_out)
1464 /* exact number of outputs */
1465 FOUNDCFG (possible_out);
1469 if (possible_in < -2) {
1470 /* explicit variable number of inputs */
1471 if (audio_in > -possible_in && imprecise != NULL) {
1472 // hide inputs ports
1473 imprecise->set (DataType::AUDIO, -possible_in);
1476 if (audio_in > -possible_in && imprecise == NULL) {
1477 /* request is too large */
1478 } else if (possible_out == -1) {
1479 /* any output configuration possible */
1480 FOUNDCFG (preferred_out);
1482 } else if (possible_out == -2) {
1483 /* invalid. interpret as (<-2, -1) */
1484 FOUNDCFG (preferred_out);
1486 } else if (possible_out < -2) {
1487 /* variable number of outputs up to -N, */
1488 FOUNDCFG (min (-possible_out, preferred_out));
1489 UPTO (-possible_out)
1491 /* exact number of outputs */
1492 FOUNDCFG (possible_out);
1496 if (possible_in && (possible_in == audio_in)) {
1497 /* exact number of inputs ... must match obviously */
1498 if (possible_out == -1) {
1499 /* any output configuration possible */
1500 FOUNDCFG (preferred_out);
1502 } else if (possible_out == -2) {
1503 /* plugins shouldn't really use (>0,-2), interpret as (>0,-1) */
1504 FOUNDCFG (preferred_out);
1506 } else if (possible_out < -2) {
1507 /* > 0, < -2 is not specified
1508 * interpret as up to -N */
1509 FOUNDCFG (min (-possible_out, preferred_out));
1510 UPTO (-possible_out)
1512 /* exact number of outputs */
1513 FOUNDCFG (possible_out);
1518 if (!found && imprecise) {
1520 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1521 int32_t possible_in = i->first;
1522 int32_t possible_out = i->second;
1524 assert (possible_in > 0); // all other cases will have been matched above
1525 assert (possible_out !=0 || possible_in !=0); // already handled above
1527 imprecise->set (DataType::AUDIO, possible_in);
1528 if (possible_out == -1 || possible_out == -2) {
1530 } else if (possible_out < -2) {
1531 /* explicitly variable number of outputs, pick maximum */
1532 FOUNDCFG (min (-possible_out, preferred_out));
1534 /* exact number of outputs */
1535 FOUNDCFG (possible_out);
1537 // ideally we'll also find the closest, best matching
1538 // input configuration with minimal output penalty...
1543 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1548 out.set (DataType::MIDI, 0); // currently always zero
1549 out.set (DataType::AUDIO, preferred_out);
1551 if (used_possible_in < -2 && audio_in == 0) {
1552 // input-port count cannot be zero, use as many ports
1553 // as outputs, but at most abs(possible_in)
1554 audio_input_cnt = max (1, min (audio_out, -used_possible_in));
1556 out.set (DataType::MIDI, 0); /// XXX
1557 out.set (DataType::AUDIO, audio_out);
1559 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1561 #if defined (__clang__)
1562 # pragma clang diagnostic pop
1568 AUPlugin::set_stream_format (int scope, uint32_t bus, AudioStreamBasicDescription& fmt)
1572 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1573 (scope == kAudioUnitScope_Input ? "input" : "output"),
1575 if ((result = unit->SetFormat (scope, bus, fmt)) != 0) {
1576 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1577 (scope == kAudioUnitScope_Input ? "input" : "output"), bus, result) << endmsg;
1584 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1585 const AudioTimeStamp*,
1587 UInt32 inNumberFrames,
1588 AudioBufferList* ioData)
1590 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1592 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bus %3 bufs %4\n",
1593 // name(), inNumberFrames, bus, ioData->mNumberBuffers));
1595 if (input_maxbuf == 0) {
1596 DEBUG_TRACE (DEBUG::AudioUnits, "AUPlugin: render callback called illegally!");
1597 error << _("AUPlugin: render callback called illegally!") << endmsg;
1598 return kAudioUnitErr_CannotDoInCurrentContext;
1601 assert (bus < input_elements);
1602 uint32_t busoff = 0;
1603 for (uint32_t i = 0; i < bus; ++i) {
1604 busoff += bus_inputs[i];
1607 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1609 ChanCount bufs_count (DataType::AUDIO, 1);
1610 BufferSet& silent_bufs = _session.get_silent_buffers(bufs_count);
1612 /* apply bus offsets */
1614 for (uint32_t i = 0; i < limit; ++i) {
1615 ioData->mBuffers[i].mNumberChannels = 1;
1616 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1619 uint32_t idx = input_map->get (DataType::AUDIO, i + busoff, &valid);
1621 ioData->mBuffers[i].mData = input_buffers->get_audio (idx).data (cb_offsets[bus] + input_offset);
1623 ioData->mBuffers[i].mData = silent_bufs.get_audio(0).data (cb_offsets[bus] + input_offset);
1626 cb_offsets[bus] += inNumberFrames;
1631 AUPlugin::connect_and_run (BufferSet& bufs,
1632 framepos_t start, framepos_t end, double speed,
1633 ChanMapping in_map, ChanMapping out_map,
1634 pframes_t nframes, framecnt_t offset)
1636 Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
1638 transport_frame = start;
1639 transport_speed = speed;
1641 AudioUnitRenderActionFlags flags = 0;
1645 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1646 unit->GlobalReset();
1647 _last_nframes = nframes;
1650 /* test if we can run in-place; only compare audio buffers */
1651 bool inplace = true; // TODO check plugin-insert in-place ?
1652 ChanMapping::Mappings inmap (in_map.mappings ());
1653 ChanMapping::Mappings outmap (out_map.mappings ());
1654 if (outmap[DataType::AUDIO].size () == 0) {
1657 if (inmap[DataType::AUDIO].size() > 0 && inmap != outmap) {
1661 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",
1662 name(), input_channels, output_channels, _has_midi_input,
1663 bufs.count(), bufs.available(),
1664 configured_input_busses, configured_output_busses, inplace, variable_inputs, variable_outputs));
1666 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1667 * has the capacity to handle our outputs.
1670 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1672 input_buffers = &bufs;
1673 input_map = &in_map;
1674 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1675 input_offset = offset;
1676 for (size_t i = 0; i < input_elements; ++i) {
1680 ChanCount bufs_count (DataType::AUDIO, 1);
1681 BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
1683 if (_has_midi_input) {
1684 uint32_t nmidi = bufs.count().n_midi();
1685 for (uint32_t i = 0; i < nmidi; ++i) {
1686 /* one MIDI port/buffer only */
1687 MidiBuffer& m = bufs.get_midi (i);
1688 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1689 Evoral::Event<framepos_t> ev (*i);
1690 if (ev.is_channel_event()) {
1691 const uint8_t* b = ev.buffer();
1692 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1693 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1695 /* XXX need to handle sysex and other message types */
1700 assert (input_maxbuf < 512);
1701 std::bitset<512> used_outputs;
1704 uint32_t busoff = 0;
1705 uint32_t remain = output_channels;
1706 for (uint32_t bus = 0; remain > 0 && bus < configured_output_busses; ++bus) {
1708 if (variable_outputs || (output_elements == configured_output_busses && configured_output_busses == 1)) {
1709 cnt = output_channels;
1711 cnt = std::min (remain, bus_outputs[bus]);
1715 buffers->mNumberBuffers = cnt;
1717 for (uint32_t i = 0; i < cnt; ++i) {
1718 buffers->mBuffers[i].mNumberChannels = 1;
1719 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1720 /* setting this to 0 indicates to the AU that it can provide buffers here
1721 * if necessary. if it can process in-place, it will use the buffers provided
1722 * as input by ::render_callback() above.
1724 * a non-null values tells the plugin to render into the buffer pointed
1728 buffers->mBuffers[i].mData = 0;
1731 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1733 buffers->mBuffers[i].mData = bufs.get_audio (idx).data (offset);
1735 buffers->mBuffers[i].mData = scratch_bufs.get_audio(0).data(offset);
1740 /* does this really mean anything ? */
1741 ts.mSampleTime = frames_processed;
1742 ts.mFlags = kAudioTimeStampSampleTimeValid;
1744 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 bus=%5 buffers=%6\n",
1745 name(), flags, frames_processed, nframes, bus, buffers->mNumberBuffers));
1747 if ((err = unit->Render (&flags, &ts, bus, nframes, buffers)) == noErr) {
1749 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1750 name(), buffers->mNumberBuffers, output_channels));
1752 uint32_t limit = std::min ((uint32_t) buffers->mNumberBuffers, cnt);
1753 for (uint32_t i = 0; i < limit; ++i) {
1755 uint32_t idx = out_map.get (DataType::AUDIO, i + busoff, &valid);
1756 if (!valid) continue;
1757 used_outputs.set (i + busoff);
1758 Sample* expected_buffer_address = bufs.get_audio (idx).data (offset);
1759 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1760 /* plugin provided its own buffer for output so copy it back to where we want it */
1761 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1765 DEBUG_TRACE (DEBUG::AudioUnits, string_compose (_("AU: render error for %1, bus %2 status = %3\n"), name(), bus, err));
1766 error << string_compose (_("AU: render error for %1, bus %2 status = %3"), name(), bus, err) << endmsg;
1772 busoff += bus_outputs[bus];
1775 /* now silence any buffers that were passed in but the that the plugin
1776 * did not fill/touch/use.
1778 * TODO: optimize, when plugin-insert is processing in-place
1779 * unconnected buffers are (also) cleared there.
1781 for (uint32_t i = 0; i < input_maxbuf; ++i) {
1782 if (used_outputs.test (i)) { continue; }
1784 uint32_t idx = out_map.get (DataType::AUDIO, i, &valid);
1785 if (!valid) continue;
1786 memset (bufs.get_audio (idx).data (offset), 0, nframes * sizeof (Sample));
1792 frames_processed += nframes;
1799 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1800 Float64* outCurrentTempo)
1802 TempoMap& tmap (_session.tempo_map());
1804 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1806 if (outCurrentBeat) {
1807 *outCurrentBeat = tmap.quarter_note_at_frame (transport_frame + input_offset);
1810 if (outCurrentTempo) {
1811 *outCurrentTempo = tmap.tempo_at_frame (transport_frame + input_offset).quarter_notes_per_minute();
1819 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1820 Float32* outTimeSig_Numerator,
1821 UInt32* outTimeSig_Denominator,
1822 Float64* outCurrentMeasureDownBeat)
1824 TempoMap& tmap (_session.tempo_map());
1826 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1828 TempoMetric metric = tmap.metric_at (transport_frame + input_offset);
1829 Timecode::BBT_Time bbt = _session.tempo_map().bbt_at_frame (transport_frame + input_offset);
1831 if (outDeltaSampleOffsetToNextBeat) {
1832 if (bbt.ticks == 0) {
1834 *outDeltaSampleOffsetToNextBeat = 0;
1836 double const next_beat = ceil (tmap.quarter_note_at_frame (transport_frame + input_offset));
1837 framepos_t const next_beat_frame = tmap.frame_at_quarter_note (next_beat);
1839 *outDeltaSampleOffsetToNextBeat = next_beat_frame - (transport_frame + input_offset);
1843 if (outTimeSig_Numerator) {
1844 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1846 if (outTimeSig_Denominator) {
1847 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1850 if (outCurrentMeasureDownBeat) {
1852 /* beat for the start of the bar.
1854 2|1|0 -> 1 + divisions_per_bar
1855 3|1|0 -> 1 + (2 * divisions_per_bar)
1861 *outCurrentMeasureDownBeat = tmap.quarter_note_at_bbt (bbt);
1868 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1869 Boolean* outTransportStateChanged,
1870 Float64* outCurrentSampleInTimeLine,
1871 Boolean* outIsCycling,
1872 Float64* outCycleStartBeat,
1873 Float64* outCycleEndBeat)
1875 const bool rolling = (transport_speed != 0);
1876 const bool last_transport_rolling = (last_transport_speed != 0);
1878 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1882 *outIsPlaying = rolling;
1885 if (outTransportStateChanged) {
1886 if (rolling != last_transport_rolling) {
1887 *outTransportStateChanged = true;
1888 } else if (transport_speed != last_transport_speed) {
1889 *outTransportStateChanged = true;
1891 *outTransportStateChanged = false;
1895 if (outCurrentSampleInTimeLine) {
1896 /* this assumes that the AU can only call this host callback from render context,
1897 where input_offset is valid.
1899 *outCurrentSampleInTimeLine = transport_frame + input_offset;
1903 // TODO check bounce-processing
1904 Location* loc = _session.locations()->auto_loop_location();
1906 *outIsCycling = (loc && rolling && _session.get_play_loop());
1908 if (*outIsCycling) {
1910 if (outCycleStartBeat || outCycleEndBeat) {
1912 TempoMap& tmap (_session.tempo_map());
1914 Timecode::BBT_Time bbt;
1916 if (outCycleStartBeat) {
1917 *outCycleStartBeat = tmap.quarter_note_at_frame (loc->start() + input_offset);
1920 if (outCycleEndBeat) {
1921 *outCycleEndBeat = tmap.quarter_note_at_frame (loc->end() + input_offset);
1927 last_transport_speed = transport_speed;
1932 set<Evoral::Parameter>
1933 AUPlugin::automatable() const
1935 set<Evoral::Parameter> automates;
1937 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1938 if (descriptors[i].automatable) {
1939 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1946 Plugin::IOPortDescription
1947 AUPlugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
1949 std::stringstream ss;
1951 case DataType::AUDIO:
1953 case DataType::MIDI:
1961 std::string busname;
1963 if (dt == DataType::AUDIO) {
1966 for (uint32_t bus = 0; bus < input_elements; ++bus) {
1967 if (pid < bus_inputs[bus]) {
1969 ss << _bus_name_in[bus];
1970 ss << " / Bus " << (1 + bus);
1971 busname = _bus_name_in[bus];
1974 pid -= bus_inputs[bus];
1979 for (uint32_t bus = 0; bus < output_elements; ++bus) {
1980 if (pid < bus_outputs[bus]) {
1982 ss << _bus_name_out[bus];
1983 ss << " / Bus " << (1 + bus);
1984 busname = _bus_name_out[bus];
1987 pid -= bus_outputs[bus];
1993 ss << " " << _("In") << " ";
1995 ss << " " << _("Out") << " ";
2000 Plugin::IOPortDescription iod (ss.str());
2001 if (!busname.empty()) {
2002 iod.group_name = busname;
2003 iod.group_channel = id;
2009 AUPlugin::describe_parameter (Evoral::Parameter param)
2011 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
2012 return descriptors[param.id()].label;
2019 AUPlugin::print_parameter (uint32_t param, char* buf, uint32_t len) const
2021 // NameValue stuff here
2023 if (param < parameter_count()) {
2024 snprintf (buf, len, "%.3f", get_parameter (param));
2032 AUPlugin::parameter_is_audio (uint32_t) const
2038 AUPlugin::parameter_is_control (uint32_t param) const
2040 assert(param < descriptors.size());
2041 if (descriptors[param].automatable) {
2042 /* corrently ardour expects all controls to be automatable
2043 * IOW ardour GUI elements mandate an Evoral::Parameter
2044 * for all input+control ports.
2052 AUPlugin::parameter_is_input (uint32_t param) const
2054 /* AU params that are both readable and writeable,
2055 * are listed in kAudioUnitScope_Global
2057 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
2061 AUPlugin::parameter_is_output (uint32_t param) const
2063 assert(param < descriptors.size());
2064 // TODO check if ardour properly handles ports
2065 // that report is_input + is_output == true
2066 // -> add || descriptors[param].scope == kAudioUnitScope_Global
2067 return (descriptors[param].scope == kAudioUnitScope_Output);
2071 AUPlugin::add_state (XMLNode* root) const
2075 CFPropertyListRef propertyList;
2077 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
2078 if (unit->GetAUPreset (propertyList) != noErr) {
2082 // Convert the property list into XML data.
2084 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
2087 error << _("Could not create XML version of property list") << endmsg;
2091 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
2092 our state node. GACK!
2097 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
2099 root->add_child_copy (*t.root());
2103 CFRelease (xmlData);
2104 CFRelease (propertyList);
2108 AUPlugin::set_state(const XMLNode& node, int version)
2111 CFPropertyListRef propertyList;
2114 if (node.name() != state_node_name()) {
2115 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
2119 #ifndef NO_PLUGIN_STATE
2120 if (node.children().empty()) {
2124 XMLNode* top = node.children().front();
2125 XMLNode* copy = new XMLNode (*top);
2130 const string& xml = t.write_buffer ();
2131 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
2132 CFStringRef errorString;
2134 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
2136 kCFPropertyListImmutable,
2139 CFRelease (xmlData);
2142 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
2143 if (unit->SetAUPreset (propertyList) == noErr) {
2146 /* tell the world */
2148 AudioUnitParameter changedUnit;
2149 changedUnit.mAudioUnit = unit->AU();
2150 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2151 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2153 CFRelease (propertyList);
2157 Plugin::set_state (node, version);
2162 AUPlugin::load_preset (PresetRecord r)
2164 Plugin::load_preset (r);
2167 CFPropertyListRef propertyList;
2169 UserPresetMap::iterator ux;
2170 FactoryPresetMap::iterator fx;
2172 /* look first in "user" presets */
2174 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
2176 if ((propertyList = load_property_list (ux->second)) != 0) {
2177 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
2178 if (unit->SetAUPreset (propertyList) == noErr) {
2181 /* tell the world */
2183 AudioUnitParameter changedUnit;
2184 changedUnit.mAudioUnit = unit->AU();
2185 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2186 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2188 CFRelease(propertyList);
2191 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
2195 preset.presetNumber = fx->second;
2196 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
2198 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
2200 if (unit->SetPresentPreset (preset) == 0) {
2203 /* tell the world */
2205 AudioUnitParameter changedUnit;
2206 changedUnit.mAudioUnit = unit->AU();
2207 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
2208 AUParameterListenerNotify (NULL, NULL, &changedUnit);
2216 AUPlugin::do_remove_preset (std::string)
2221 AUPlugin::do_save_preset (string preset_name)
2223 CFPropertyListRef propertyList;
2224 vector<Glib::ustring> v;
2225 Glib::ustring user_preset_path;
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");
2240 user_preset_path = Glib::build_filename (v);
2242 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
2243 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
2247 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
2248 if (unit->GetAUPreset (propertyList) != noErr) {
2252 // add the actual preset name */
2254 v.push_back (preset_name + preset_suffix);
2258 user_preset_path = Glib::build_filename (v);
2260 set_preset_name_in_plist (propertyList, preset_name);
2262 if (save_property_list (propertyList, user_preset_path)) {
2263 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
2267 CFRelease(propertyList);
2269 user_preset_map[preset_name] = user_preset_path;;
2271 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
2273 return string ("file:///") + user_preset_path;
2276 //-----------------------------------------------------------------------------
2277 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
2279 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
2281 CFNumberRef cfNumber;
2282 SInt32 numberValue = 0;
2283 Boolean dummySuccess;
2285 if (outSuccess == NULL)
2286 outSuccess = &dummySuccess;
2287 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2289 *outSuccess = FALSE;
2293 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2294 if (cfNumber == NULL)
2296 *outSuccess = FALSE;
2299 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2307 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
2309 CFDictionaryRef auStateDictionary;
2310 ArdourDescription tempDesc = {0,0,0,0,0};
2311 SInt32 versionValue;
2314 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2317 // the property list for AU state data must be of the dictionary type
2318 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2319 return kAudioUnitErr_InvalidPropertyValue;
2322 auStateDictionary = (CFDictionaryRef)inAUStateData;
2324 // first check to make sure that the version of the AU state data is one that we know understand
2325 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2326 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2329 return kAudioUnitErr_InvalidPropertyValue;
2331 #define kCurrentSavedStateVersion 0
2332 if (versionValue != kCurrentSavedStateVersion) {
2333 return kAudioUnitErr_InvalidPropertyValue;
2336 // grab the ComponentDescription values from the AU state data
2337 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2338 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2339 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2340 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2341 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2342 return kAudioUnitErr_InvalidPropertyValue;
2344 *outComponentDescription = tempDesc;
2349 static bool au_preset_filter (const string& str, void* arg)
2351 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2355 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2359 /* check the preset file path name against this plugin
2360 ID. The idea is that all preset files for this plugin
2361 include "<manufacturer>/<plugin-name>" in their path.
2364 AUPluginInfo* p = (AUPluginInfo *) arg;
2365 string match = p->creator;
2369 ret = str.find (match) != string::npos;
2372 string m = p->creator;
2374 strip_whitespace_edges (m);
2375 strip_whitespace_edges (n);
2380 ret = str.find (match) != string::npos;
2388 check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
2391 CFPropertyListRef plist;
2392 ArdourDescription presetDesc;
2395 plist = load_property_list (pathstr);
2401 // get the ComponentDescription from the AU preset file
2403 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2405 if (status == noErr) {
2406 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2408 /* try to get the preset name from the property list */
2410 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2412 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2416 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2419 char buf[PATH_MAX+1];
2421 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2438 get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2440 get_names (ArdourComponent& comp, std::string& name, std::string& maker)
2443 CFStringRef itemName = NULL;
2444 // Marc Poirier-style item name
2446 CAComponent auComponent (comp_desc);
2447 if (auComponent.IsValid()) {
2448 CAComponentDescription dummydesc;
2449 Handle nameHandle = NewHandle(sizeof(void*));
2450 if (nameHandle != NULL) {
2451 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2453 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2454 if (nameString != NULL) {
2455 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2458 DisposeHandle(nameHandle);
2463 AudioComponentCopyName (comp, &itemName);
2466 // if Marc-style fails, do the original way
2467 if (itemName == NULL) {
2468 #ifndef COREAUDIO105
2469 CAComponentDescription comp_desc;
2470 AudioComponentGetDescription (comp, &comp_desc);
2472 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2473 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2474 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2476 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2477 compTypeString, compManufacturerString, compSubTypeString);
2479 if (compTypeString != NULL)
2480 CFRelease(compTypeString);
2481 if (compSubTypeString != NULL)
2482 CFRelease(compSubTypeString);
2483 if (compManufacturerString != NULL)
2484 CFRelease(compManufacturerString);
2487 string str = CFStringRefToStdString(itemName);
2488 string::size_type colon = str.find (':');
2491 name = str.substr (colon+1);
2492 maker = str.substr (0, colon);
2493 strip_whitespace_edges (maker);
2494 strip_whitespace_edges (name);
2498 strip_whitespace_edges (name);
2503 AUPlugin::current_preset() const
2507 CFPropertyListRef propertyList;
2509 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2510 if (unit->GetAUPreset (propertyList) == noErr) {
2511 preset_name = get_preset_name_in_plist (propertyList);
2512 CFRelease(propertyList);
2519 AUPlugin::find_presets ()
2521 vector<string> preset_files;
2523 user_preset_map.clear ();
2525 PluginInfoPtr nfo = get_info();
2526 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
2527 boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
2530 if (preset_files.empty()) {
2531 DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
2534 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2539 /* make an initial guess at the preset name using the path */
2541 preset_name = Glib::path_get_basename (path);
2542 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2544 /* check that this preset file really matches this plugin
2545 and potentially get the "real" preset name from
2549 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2550 user_preset_map[preset_name] = path;
2551 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
2553 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
2558 /* now fill the vector<string> with the names we have */
2560 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2561 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2562 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
2565 /* add factory presets */
2567 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2568 /* XXX: dubious -- deleting & re-adding a preset -> same URI
2569 * good that we don't support deleting AU presets :)
2571 string const uri = PBD::to_string<uint32_t> (_presets.size ());
2572 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
2573 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
2578 AUPlugin::has_editor () const
2580 // even if the plugin doesn't have its own editor, the AU API can be used
2581 // to create one that looks native.
2585 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2589 type = ARDOUR::AudioUnit;
2592 AUPluginInfo::~AUPluginInfo ()
2594 type = ARDOUR::AudioUnit;
2598 AUPluginInfo::load (Session& session)
2603 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2604 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2606 if (!comp->IsValid()) {
2607 error << ("AudioUnit: not a valid Component") << endmsg;
2609 plugin.reset (new AUPlugin (session.engine(), session, comp));
2612 AUPluginInfo *aup = new AUPluginInfo (*this);
2613 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2614 plugin->set_info (PluginInfoPtr (aup));
2615 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2619 catch (failed_constructor &err) {
2620 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2621 return PluginPtr ();
2625 std::vector<Plugin::PresetRecord>
2626 AUPluginInfo::get_presets (bool user_only) const
2628 std::vector<Plugin::PresetRecord> p;
2629 boost::shared_ptr<CAComponent> comp;
2630 #ifndef NO_PLUGIN_STATE
2632 comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
2633 if (!comp->IsValid()) {
2634 throw failed_constructor();
2636 } catch (failed_constructor& err) {
2642 if (!preset_search_path_initialized) {
2643 Glib::ustring p = Glib::get_home_dir();
2644 p += "/Library/Audio/Presets:";
2645 p += preset_search_path;
2646 preset_search_path = p;
2647 preset_search_path_initialized = true;
2648 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
2651 vector<string> preset_files;
2652 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
2654 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2657 preset_name = Glib::path_get_basename (path);
2658 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2659 if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
2660 p.push_back (Plugin::PresetRecord (path, preset_name));
2674 boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
2675 if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
2678 if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
2679 unit->Uninitialize ();
2682 if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
2683 unit->Uninitialize ();
2687 unit->Uninitialize ();
2691 CFIndex cnt = CFArrayGetCount (presets);
2692 for (CFIndex i = 0; i < cnt; ++i) {
2693 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
2694 string const uri = string_compose ("%1", i);
2695 string name = CFStringRefToStdString (preset->presetName);
2696 p.push_back (Plugin::PresetRecord (uri, name, false));
2698 CFRelease (presets);
2699 unit->Uninitialize ();
2701 #endif // NO_PLUGIN_STATE
2706 AUPluginInfo::au_cache_path ()
2708 return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
2712 AUPluginInfo::discover (bool scan_only)
2716 /* AU require a CAComponentDescription pointer provided by the OS.
2717 * Ardour only caches port and i/o config. It can't just 'scan' without
2718 * 'discovering' (like we do for VST).
2721 * "Iterate over all plugins. skip the ones where there's no io-cache".
2723 _scan_only = scan_only;
2725 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2726 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2727 // flush RAM cache -- after clear_cache()
2728 cached_info.clear();
2730 // create crash log file
2731 au_start_crashlog ();
2733 PluginInfoList* plugs = new PluginInfoList;
2735 discover_fx (*plugs);
2736 discover_music (*plugs);
2737 discover_generators (*plugs);
2738 discover_instruments (*plugs);
2740 // all fine if we get here
2741 au_remove_crashlog ();
2743 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2749 AUPluginInfo::discover_music (PluginInfoList& plugs)
2751 CAComponentDescription desc;
2752 desc.componentFlags = 0;
2753 desc.componentFlagsMask = 0;
2754 desc.componentSubType = 0;
2755 desc.componentManufacturer = 0;
2756 desc.componentType = kAudioUnitType_MusicEffect;
2758 discover_by_description (plugs, desc);
2762 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2764 CAComponentDescription desc;
2765 desc.componentFlags = 0;
2766 desc.componentFlagsMask = 0;
2767 desc.componentSubType = 0;
2768 desc.componentManufacturer = 0;
2769 desc.componentType = kAudioUnitType_Effect;
2771 discover_by_description (plugs, desc);
2775 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2777 CAComponentDescription desc;
2778 desc.componentFlags = 0;
2779 desc.componentFlagsMask = 0;
2780 desc.componentSubType = 0;
2781 desc.componentManufacturer = 0;
2782 desc.componentType = kAudioUnitType_Generator;
2784 discover_by_description (plugs, desc);
2788 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2790 CAComponentDescription desc;
2791 desc.componentFlags = 0;
2792 desc.componentFlagsMask = 0;
2793 desc.componentSubType = 0;
2794 desc.componentManufacturer = 0;
2795 desc.componentType = kAudioUnitType_MusicDevice;
2797 discover_by_description (plugs, desc);
2802 AUPluginInfo::au_get_crashlog (std::string &msg)
2804 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2805 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2808 std::ifstream ifs(fn.c_str());
2809 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2810 au_remove_crashlog ();
2815 AUPluginInfo::au_start_crashlog ()
2817 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2818 assert(!_crashlog_fd);
2819 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2820 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2821 PBD::error << "Cannot create AU error-log" << fn << "\n";
2822 cerr << "Cannot create AU error-log" << fn << "\n";
2827 AUPluginInfo::au_remove_crashlog ()
2830 ::fclose(_crashlog_fd);
2831 _crashlog_fd = NULL;
2833 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2834 ::g_unlink(fn.c_str());
2835 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2840 AUPluginInfo::au_crashlog (std::string msg)
2842 if (!_crashlog_fd) {
2843 fprintf(stderr, "AU: %s\n", msg.c_str());
2845 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2846 ::fflush(_crashlog_fd);
2851 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2853 ArdourComponent comp = 0;
2854 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2856 comp = ArdourFindNext (NULL, &desc);
2858 while (comp != NULL) {
2859 CAComponentDescription temp;
2861 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2863 AudioComponentGetDescription (comp, &temp);
2865 CFStringRef itemName = NULL;
2868 if (itemName != NULL) CFRelease(itemName);
2869 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2870 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2871 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2872 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2873 compTypeString, compManufacturerString, compSubTypeString);
2874 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2875 if (compTypeString != NULL)
2876 CFRelease(compTypeString);
2877 if (compSubTypeString != NULL)
2878 CFRelease(compSubTypeString);
2879 if (compManufacturerString != NULL)
2880 CFRelease(compManufacturerString);
2883 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2884 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2885 comp = ArdourFindNext (comp, &desc);
2889 bool has_midi_in = false;
2891 AUPluginInfoPtr info (new AUPluginInfo
2892 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2894 /* although apple designed the subtype field to be a "category" indicator,
2895 its really turned into a plugin ID field for a given manufacturer. Hence
2896 there are no categories for AudioUnits. However, to keep the plugins
2897 showing up under "categories", we'll use the "type" as a high level
2900 NOTE: no panners, format converters or i/o AU's for our purposes
2903 switch (info->descriptor->Type()) {
2904 case kAudioUnitType_Panner:
2905 case kAudioUnitType_OfflineEffect:
2906 case kAudioUnitType_FormatConverter:
2907 comp = ArdourFindNext (comp, &desc);
2910 case kAudioUnitType_Output:
2911 info->category = _("AudioUnit Output");
2913 case kAudioUnitType_MusicDevice:
2914 info->category = _("Instrument");
2917 case kAudioUnitType_MusicEffect:
2918 info->category = _("Music Effect");
2921 case kAudioUnitType_Effect:
2922 info->category = _("Effect");
2924 case kAudioUnitType_Mixer:
2925 info->category = _("Mixer");
2927 case kAudioUnitType_Generator:
2928 info->category = _("Generator");
2931 info->category = _("AudioUnit (Unknown)");
2935 au_blacklist(CFStringRefToStdString(itemName));
2937 get_names (temp, info->name, info->creator);
2939 get_names (comp, info->name, info->creator);
2941 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2942 au_crashlog(string_compose("Plugin: %1", info->name));
2944 info->type = ARDOUR::AudioUnit;
2945 info->unique_id = stringify_descriptor (*info->descriptor);
2947 /* XXX not sure of the best way to handle plugin versioning yet */
2949 CAComponent cacomp (*info->descriptor);
2952 if (cacomp.GetResourceVersion (info->version) != noErr)
2954 if (cacomp.GetVersion (info->version) != noErr)
2960 const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
2963 /* here we have to map apple's wildcard system to a simple pair
2964 of values. in ::can_do() we use the whole system, but here
2965 we need a single pair of values. XXX probably means we should
2966 remove any use of these values.
2968 for now, if the plugin provides a wildcard, treat it as 1. we really
2969 don't care much, because whether we can handle an i/o configuration
2970 depends upon ::can_support_io_configuration(), not these counts.
2972 they exist because other parts of ardour try to present i/o configuration
2973 info to the user, which should perhaps be revisited.
2976 int32_t possible_in = info->cache.io_configs.front().first;
2977 int32_t possible_out = info->cache.io_configs.front().second;
2979 if (possible_in > 0) {
2980 info->n_inputs.set (DataType::AUDIO, possible_in);
2982 info->n_inputs.set (DataType::AUDIO, 1);
2985 info->n_inputs.set (DataType::MIDI, has_midi_in ? 1 : 0);
2987 if (possible_out > 0) {
2988 info->n_outputs.set (DataType::AUDIO, possible_out);
2990 info->n_outputs.set (DataType::AUDIO, 1);
2993 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2994 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2996 plugs.push_back (info);
2999 else if (rv == -1) {
3000 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
3003 au_unblacklist(CFStringRefToStdString(itemName));
3004 au_crashlog("Success.");
3005 comp = ArdourFindNext (comp, &desc);
3006 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
3008 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
3012 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
3015 AUPluginCachedInfo& cinfo,
3016 const std::string& name)
3021 /* concatenate unique ID with version to provide a key for cached info lookup.
3022 this ensures we don't get stale information, or should if plugin developers
3023 follow Apple "guidelines".
3026 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
3031 CachedInfoMap::iterator cim = cached_info.find (id);
3033 if (cim != cached_info.end()) {
3034 cinfo = cim->second;
3039 PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
3044 AUChannelInfo* channel_info;
3048 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
3052 if (CAAudioUnit::Open (comp, unit) != noErr) {
3058 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
3063 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
3064 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
3069 /* AU is expected to deal with same channel valance in and out */
3070 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
3072 /* CAAudioUnit::GetChannelInfo silently merges bus formats
3073 * check if this was the case and if so, add
3074 * bus configs as incremental options.
3076 Boolean* isWritable = 0;
3077 UInt32 dataSize = 0;
3078 OSStatus result = AudioUnitGetPropertyInfo (unit.AU(),
3079 kAudioUnitProperty_SupportedNumChannels,
3080 kAudioUnitScope_Global, 0,
3081 &dataSize, isWritable);
3082 if (result != noErr && (comp.Desc().IsGenerator() || comp.Desc().IsMusicDevice())) {
3083 /* incrementally add busses */
3086 for (uint32_t n = 0; n < cnt; ++n) {
3087 in += channel_info[n].inChannels;
3088 out += channel_info[n].outChannels;
3089 cinfo.io_configs.push_back (pair<int,int> (in, out));
3092 /* store each configuration */
3093 for (uint32_t n = 0; n < cnt; ++n) {
3094 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
3095 channel_info[n].outChannels));
3099 free (channel_info);
3102 add_cached_info (id, cinfo);
3103 save_cached_info ();
3109 AUPluginInfo::clear_cache ()
3111 const string& fn = au_cache_path();
3112 if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
3113 ::g_unlink(fn.c_str());
3115 // keep cached_info in RAM until restart or re-scan
3116 cached_info.clear();
3120 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
3122 cached_info[id] = cinfo;
3125 #define AU_CACHE_VERSION "2.0"
3128 AUPluginInfo::save_cached_info ()
3132 node = new XMLNode (X_("AudioUnitPluginCache"));
3133 node->set_property( "version", AU_CACHE_VERSION );
3135 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
3136 XMLNode* parent = new XMLNode (X_("plugin"));
3137 parent->set_property ("id", i->first);
3138 node->add_child_nocopy (*parent);
3140 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
3142 XMLNode* child = new XMLNode (X_("io"));
3144 child->set_property (X_("in"), j->first);
3145 child->set_property (X_("out"), j->second);
3146 parent->add_child_nocopy (*child);
3151 Glib::ustring path = au_cache_path ();
3154 tree.set_root (node);
3156 if (!tree.write (path)) {
3157 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
3158 g_unlink (path.c_str());
3163 AUPluginInfo::load_cached_info ()
3165 Glib::ustring path = au_cache_path ();
3168 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
3172 if ( !tree.read (path) ) {
3173 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
3177 const XMLNode* root (tree.root());
3179 if (root->name() != X_("AudioUnitPluginCache")) {
3183 //initial version has incorrectly stored i/o info, and/or garbage chars.
3184 XMLProperty const * version = root->property(X_("version"));
3185 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
3186 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
3190 cached_info.clear ();
3192 const XMLNodeList children = root->children();
3194 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
3196 const XMLNode* child = *iter;
3198 if (child->name() == X_("plugin")) {
3200 const XMLNode* gchild;
3201 const XMLNodeList gchildren = child->children();
3204 if (!child->get_property (X_("id"), id)) {
3211 string::size_type slash = id.find_last_of ('/');
3213 if (slash == string::npos) {
3217 version = id.substr (slash);
3218 id = id.substr (0, slash);
3219 fixed = AUPlugin::maybe_fix_broken_au_id (id);
3221 if (fixed.empty()) {
3222 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
3229 AUPluginCachedInfo cinfo;
3231 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
3235 if (gchild->name() == X_("io")) {
3240 if (gchild->get_property (X_("in"), in) && gchild->get_property (X_("out"), out)) {
3241 cinfo.io_configs.push_back (pair<int,int> (in, out));
3246 if (cinfo.io_configs.size()) {
3247 add_cached_info (id, cinfo);
3257 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
3261 /* note: OSType is a compiler-implemenation-defined value,
3262 historically a 32 bit integer created with a multi-character
3263 constant such as 'abcd'. It is, fundamentally, an abomination.
3268 s << desc.SubType();
3276 AUPluginInfo::needs_midi_input () const
3278 return is_effect_with_midi_input () || is_instrument ();
3282 AUPluginInfo::is_effect () const
3284 return is_effect_without_midi_input() || is_effect_with_midi_input();
3288 AUPluginInfo::is_effect_without_midi_input () const
3290 return descriptor->IsAUFX();
3294 AUPluginInfo::is_effect_with_midi_input () const
3296 return descriptor->IsAUFM();
3300 AUPluginInfo::is_instrument () const
3302 return descriptor->IsMusicDevice();
3306 AUPlugin::set_info (PluginInfoPtr info)
3308 Plugin::set_info (info);
3310 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
3311 _has_midi_input = pinfo->needs_midi_input ();
3312 _has_midi_output = false;
3316 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
3319 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
3321 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
3323 CFStringRef loop_mode = kCFRunLoopDefaultMode;
3325 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
3329 _parameter_listener_arg = arg;
3331 // listen for latency changes
3332 AudioUnitEvent event;
3333 event.mEventType = kAudioUnitEvent_PropertyChange;
3334 event.mArgument.mProperty.mAudioUnit = unit->AU();
3335 event.mArgument.mProperty.mPropertyID = kAudioUnitProperty_Latency;
3336 event.mArgument.mProperty.mScope = kAudioUnitScope_Global;
3337 event.mArgument.mProperty.mElement = 0;
3339 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3340 PBD::error << "Failed to create latency event listener\n";
3341 // TODO don't cache _current_latency
3348 AUPlugin::listen_to_parameter (uint32_t param_id)
3350 AudioUnitEvent event;
3352 if (!_parameter_listener || param_id >= descriptors.size()) {
3356 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3357 event.mArgument.mParameter.mAudioUnit = unit->AU();
3358 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3359 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3360 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3362 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3366 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3367 event.mArgument.mParameter.mAudioUnit = unit->AU();
3368 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3369 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3370 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3372 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3376 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
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 (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3390 AUPlugin::end_listen_to_parameter (uint32_t param_id)
3392 AudioUnitEvent event;
3394 if (!_parameter_listener || param_id >= descriptors.size()) {
3398 event.mEventType = kAudioUnitEvent_ParameterValueChange;
3399 event.mArgument.mParameter.mAudioUnit = unit->AU();
3400 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3401 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3402 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3404 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3408 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
3409 event.mArgument.mParameter.mAudioUnit = unit->AU();
3410 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3411 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3412 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3414 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3418 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
3419 event.mArgument.mParameter.mAudioUnit = unit->AU();
3420 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
3421 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
3422 event.mArgument.mParameter.mElement = descriptors[param_id].element;
3424 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
3432 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
3434 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
3438 AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
3440 if (event->mEventType == kAudioUnitEvent_PropertyChange) {
3441 if (event->mArgument.mProperty.mPropertyID == kAudioUnitProperty_Latency) {
3442 DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Latency Change Event %1 <> %2\n", new_value, unit->Latency()));
3443 guint lat = unit->Latency() * _session.frame_rate();
3444 g_atomic_int_set (&_current_latency, lat);
3449 ParameterMap::iterator i;
3451 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
3455 switch (event->mEventType) {
3456 case kAudioUnitEvent_BeginParameterChangeGesture:
3457 StartTouch (i->second);
3459 case kAudioUnitEvent_EndParameterChangeGesture:
3460 EndTouch (i->second);
3462 case kAudioUnitEvent_ParameterValueChange:
3463 /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
3464 means that something else (i.e. the plugin GUI) made the change.
3466 ParameterChangedExternally (i->second, new_value);