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.
27 #include "pbd/transmitter.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30 #include "pbd/whitespace.h"
31 #include "pbd/pathscanner.h"
32 #include "pbd/locale_guard.h"
34 #include <glibmm/thread.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
38 #include "ardour/ardour.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/debug.h"
42 #include "ardour/midi_buffer.h"
43 #include "ardour/filesystem_paths.h"
44 #include "ardour/io.h"
45 #include "ardour/audio_unit.h"
46 #include "ardour/session.h"
47 #include "ardour/tempo.h"
48 #include "ardour/utils.h"
50 #include "appleutility/CAAudioUnit.h"
51 #include "appleutility/CAAUParameter.h"
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreServices/CoreServices.h>
55 #include <AudioUnit/AudioUnit.h>
56 #include <AudioToolbox/AudioUnitUtilities.h>
58 #include <Carbon/Carbon.h>
65 using namespace ARDOUR;
67 #ifndef AU_STATE_SUPPORT
68 static bool seen_get_state_message = false;
69 static bool seen_set_state_message = false;
70 static bool seen_loading_message = false;
71 static bool seen_saving_message = false;
74 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
76 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
77 static string preset_suffix = ".aupreset";
78 static bool preset_search_path_initialized = false;
81 _render_callback(void *userData,
82 AudioUnitRenderActionFlags *ioActionFlags,
83 const AudioTimeStamp *inTimeStamp,
85 UInt32 inNumberFrames,
86 AudioBufferList* ioData)
89 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
95 _get_beat_and_tempo_callback (void* userData,
96 Float64* outCurrentBeat,
97 Float64* outCurrentTempo)
100 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
107 _get_musical_time_location_callback (void * userData,
108 UInt32 * outDeltaSampleOffsetToNextBeat,
109 Float32 * outTimeSig_Numerator,
110 UInt32 * outTimeSig_Denominator,
111 Float64 * outCurrentMeasureDownBeat)
114 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
115 outTimeSig_Numerator,
116 outTimeSig_Denominator,
117 outCurrentMeasureDownBeat);
123 _get_transport_state_callback (void* userData,
124 Boolean* outIsPlaying,
125 Boolean* outTransportStateChanged,
126 Float64* outCurrentSampleInTimeLine,
127 Boolean* outIsCycling,
128 Float64* outCycleStartBeat,
129 Float64* outCycleEndBeat)
132 return ((AUPlugin*)userData)->get_transport_state_callback (
133 outIsPlaying, outTransportStateChanged,
134 outCurrentSampleInTimeLine, outIsCycling,
135 outCycleStartBeat, outCycleEndBeat);
142 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
148 // Convert the property list into XML data.
150 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
153 error << _("Could not create XML version of property list") << endmsg;
157 // Write the XML data to the file.
159 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
161 if (errno == EEXIST) {
162 error << string_compose (_("Preset file %1 exists; not overwriting"),
165 error << string_compose (_("Cannot open preset file %1 (%2)"),
166 path, strerror (errno)) << endmsg;
172 size_t cnt = CFDataGetLength (xmlData);
174 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
185 static CFPropertyListRef
186 load_property_list (Glib::ustring path)
189 CFPropertyListRef propertyList = 0;
191 CFStringRef errorString;
193 // Read the XML file.
195 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
200 off_t len = lseek (fd, 0, SEEK_END);
201 char* buf = new char[len];
202 lseek (fd, 0, SEEK_SET);
204 if (read (fd, buf, len) != len) {
212 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
214 // Reconstitute the dictionary using the XML data.
216 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
218 kCFPropertyListImmutable,
227 //-----------------------------------------------------------------------------
229 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
234 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
236 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
237 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
243 //-----------------------------------------------------------------------------
245 get_preset_name_in_plist (CFPropertyListRef plist)
253 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
254 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
256 CFStringRef str = (CFStringRef) p;
257 int len = CFStringGetLength(str);
259 char local_buffer[len];
260 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
268 //--------------------------------------------------------------------------
269 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
270 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
271 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
272 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
274 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
277 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
278 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
280 // only sub-type and manufacturer IDs need to be equal
283 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
284 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
291 //--------------------------------------------------------------------------
292 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
293 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
294 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
295 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
298 ComponentDescription desc;
300 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
303 // get the ComponentDescription of the input Component
304 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
308 // check if the Component's ComponentDescription matches the input ComponentDescription
309 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
312 //--------------------------------------------------------------------------
313 // determine if 2 ComponentDescriptions are basically equal
314 // (by that, I mean that the important identifying values are compared,
315 // but not the ComponentDescription flags)
316 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
318 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
321 //--------------------------------------------------------------------------
322 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
323 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
325 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
328 //--------------------------------------------------------------------------
329 // determine if a ComponentDescription basically matches that of a particular Component
330 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
332 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
335 //--------------------------------------------------------------------------
336 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
337 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
339 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
343 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
344 : Plugin (engine, session)
346 , unit (new CAAudioUnit)
347 , initialized (false)
348 , _current_block_size (0)
349 , _requires_fixed_size_buffers (false)
354 , frames_processed (0)
355 , _parameter_listener (0)
356 , _parameter_listener_arg (0)
357 , last_transport_rolling (false)
358 , last_transport_speed (0.0)
360 if (!preset_search_path_initialized) {
361 Glib::ustring p = Glib::get_home_dir();
362 p += "/Library/Audio/Presets:";
363 p += preset_search_path;
364 preset_search_path = p;
365 preset_search_path_initialized = true;
372 AUPlugin::AUPlugin (const AUPlugin& other)
374 , comp (other.get_comp())
375 , unit (new CAAudioUnit)
376 , initialized (false)
377 , _current_block_size (0)
379 , _requires_fixed_size_buffers (false)
384 , frames_processed (0)
385 , _parameter_listener (0)
386 , _parameter_listener_arg (0)
392 AUPlugin::~AUPlugin ()
394 if (_parameter_listener) {
395 AUListenerDispose (_parameter_listener);
396 _parameter_listener = 0;
400 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
401 unit->Uninitialize ();
410 AUPlugin::discover_factory_presets ()
417 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
418 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
422 assert (dataSize == sizeof (presets));
424 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
425 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
433 CFIndex cnt = CFArrayGetCount (presets);
435 for (CFIndex i = 0; i < cnt; ++i) {
436 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
438 string name = CFStringRefToStdString (preset->presetName);
439 factory_preset_map[name] = preset->presetNumber;
450 /* these keep track of *configured* channel set up,
451 not potential set ups.
455 output_channels = -1;
458 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
459 err = CAAudioUnit::Open (*(comp.get()), *unit);
461 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
462 throw failed_constructor();
466 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
467 throw failed_constructor ();
470 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
471 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
472 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
473 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
474 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
475 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
477 if (input_elements > 0) {
478 /* setup render callback: the plugin calls this to get input data
481 AURenderCallbackStruct renderCallbackInfo;
483 renderCallbackInfo.inputProc = _render_callback;
484 renderCallbackInfo.inputProcRefCon = this;
486 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
487 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
488 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
489 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
490 throw failed_constructor();
494 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
496 HostCallbackInfo info;
497 memset (&info, 0, sizeof (HostCallbackInfo));
498 info.hostUserData = this;
499 info.beatAndTempoProc = _get_beat_and_tempo_callback;
500 info.musicalTimeLocationProc = _get_musical_time_location_callback;
501 info.transportStateProc = _get_transport_state_callback;
503 //ignore result of this - don't care if the property isn't supported
504 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
505 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
506 kAudioUnitScope_Global,
509 sizeof (HostCallbackInfo));
511 if (set_block_size (_session.get_block_size())) {
512 error << _("AUPlugin: cannot set processing block size") << endmsg;
513 throw failed_constructor();
516 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
517 discover_parameters ();
518 discover_factory_presets ();
520 // Plugin::setup_controls ();
524 AUPlugin::discover_parameters ()
526 /* discover writable parameters */
528 AudioUnitScope scopes[] = {
529 kAudioUnitScope_Global,
530 kAudioUnitScope_Output,
531 kAudioUnitScope_Input
534 descriptors.clear ();
536 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
538 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
540 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
542 AUParameterDescriptor d;
544 d.id = param_info.ParamID (i);
546 const CAAUParameter* param = param_info.GetParamInfo (d.id);
547 const AudioUnitParameterInfo& info (param->ParamInfo());
549 const int len = CFStringGetLength (param->GetName());;
550 char local_buffer[len*2];
551 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
555 d.label = local_buffer;
558 d.scope = param_info.GetScope ();
559 d.element = param_info.GetElement ();
561 /* info.units to consider */
563 kAudioUnitParameterUnit_Generic = 0
564 kAudioUnitParameterUnit_Indexed = 1
565 kAudioUnitParameterUnit_Boolean = 2
566 kAudioUnitParameterUnit_Percent = 3
567 kAudioUnitParameterUnit_Seconds = 4
568 kAudioUnitParameterUnit_SampleFrames = 5
569 kAudioUnitParameterUnit_Phase = 6
570 kAudioUnitParameterUnit_Rate = 7
571 kAudioUnitParameterUnit_Hertz = 8
572 kAudioUnitParameterUnit_Cents = 9
573 kAudioUnitParameterUnit_RelativeSemiTones = 10
574 kAudioUnitParameterUnit_MIDINoteNumber = 11
575 kAudioUnitParameterUnit_MIDIController = 12
576 kAudioUnitParameterUnit_Decibels = 13
577 kAudioUnitParameterUnit_LinearGain = 14
578 kAudioUnitParameterUnit_Degrees = 15
579 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
580 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
581 kAudioUnitParameterUnit_Pan = 18
582 kAudioUnitParameterUnit_Meters = 19
583 kAudioUnitParameterUnit_AbsoluteCents = 20
584 kAudioUnitParameterUnit_Octaves = 21
585 kAudioUnitParameterUnit_BPM = 22
586 kAudioUnitParameterUnit_Beats = 23
587 kAudioUnitParameterUnit_Milliseconds = 24
588 kAudioUnitParameterUnit_Ratio = 25
591 /* info.flags to consider */
595 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
596 kAudioUnitParameterFlag_HasClump = (1L << 20)
597 kAudioUnitParameterFlag_HasName = (1L << 21)
598 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
599 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
600 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
601 kAudioUnitParameterFlag_CanRamp = (1L << 25)
602 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
603 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
604 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
605 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
606 kAudioUnitParameterFlag_IsReadable = (1L << 30)
607 kAudioUnitParameterFlag_IsWritable = (1L << 31)
610 d.lower = info.minValue;
611 d.upper = info.maxValue;
612 d.default_value = info.defaultValue;
614 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
615 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
616 (d.integer_step && ((d.upper - d.lower) == 1.0));
617 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
618 d.automatable = !d.toggled &&
619 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
620 (info.flags & kAudioUnitParameterFlag_IsWritable);
622 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
628 d.min_unbound = 0; // lower is bound
629 d.max_unbound = 0; // upper is bound
631 descriptors.push_back (d);
633 uint32_t last_param = descriptors.size() - 1;
634 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
635 listen_to_parameter (last_param);
642 four_ints_to_four_byte_literal (unsigned char n[4])
644 /* this is actually implementation dependent. sigh. this is what gcc
645 and quite a few others do.
647 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
651 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
653 if (isdigit (id[0])) {
657 /* ID format is xxxx-xxxx-xxxx
658 where x maybe \xNN or a printable character.
660 Split at the '-' and and process each part into an integer.
661 Then put it back together.
665 unsigned char nascent[4];
666 const char* cstr = id.c_str();
667 const char* estr = cstr + id.size();
678 while (*cstr && next_int < 4) {
682 if (estr - cstr < 3) {
684 /* too close to the end for \xNN parsing: treat as literal characters */
692 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
696 memcpy (short_buf, &cstr[2], 2);
697 nascent[in] = strtol (short_buf, NULL, 16);
703 /* treat as literal characters */
717 if (in && (in % 4 == 0)) {
718 /* nascent is ready */
719 n[next_int] = four_ints_to_four_byte_literal (nascent);
723 /* swallow space-hyphen-space */
737 s << n[0] << '-' << n[1] << '-' << n[2];
746 AUPlugin::unique_id () const
748 return AUPluginInfo::stringify_descriptor (comp->Desc());
752 AUPlugin::label () const
754 return _info->name.c_str();
758 AUPlugin::parameter_count () const
760 return descriptors.size();
764 AUPlugin::default_value (uint32_t port)
766 if (port < descriptors.size()) {
767 return descriptors[port].default_value;
774 AUPlugin::signal_latency () const
776 return unit->Latency() * _session.frame_rate();
780 AUPlugin::set_parameter (uint32_t which, float val)
782 if (which >= descriptors.size()) {
786 const AUParameterDescriptor& d (descriptors[which]);
787 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
788 unit->SetParameter (d.id, d.scope, d.element, val);
790 /* tell the world what we did */
792 AudioUnitEvent theEvent;
794 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
795 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
796 theEvent.mArgument.mParameter.mParameterID = d.id;
797 theEvent.mArgument.mParameter.mScope = d.scope;
798 theEvent.mArgument.mParameter.mElement = d.element;
800 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
801 AUEventListenerNotify (NULL, NULL, &theEvent);
803 Plugin::set_parameter (which, val);
807 AUPlugin::get_parameter (uint32_t which) const
810 if (which < descriptors.size()) {
811 const AUParameterDescriptor& d (descriptors[which]);
812 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
813 unit->GetParameter(d.id, d.scope, d.element, val);
819 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
821 if (which < descriptors.size()) {
822 pd = descriptors[which];
829 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
831 if (which < descriptors.size()) {
840 AUPlugin::activate ()
844 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
845 if ((err = unit->Initialize()) != noErr) {
846 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
848 frames_processed = 0;
855 AUPlugin::deactivate ()
857 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
858 unit->Uninitialize ();
865 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
866 unit->GlobalReset ();
870 AUPlugin::requires_fixed_size_buffers() const
872 return _requires_fixed_size_buffers;
877 AUPlugin::set_block_size (pframes_t nframes)
879 bool was_initialized = initialized;
880 UInt32 numFrames = nframes;
887 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
888 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
889 0, &numFrames, sizeof (numFrames))) != noErr) {
890 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
894 if (was_initialized) {
898 _current_block_size = nframes;
904 AUPlugin::configure_io (ChanCount in, ChanCount out)
906 AudioStreamBasicDescription streamFormat;
907 bool was_initialized = initialized;
908 int32_t audio_in = in.n_audio();
909 int32_t audio_out = out.n_audio();
911 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
914 //if we are already running with the requested i/o config, bail out here
915 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
922 streamFormat.mSampleRate = _session.frame_rate();
923 streamFormat.mFormatID = kAudioFormatLinearPCM;
924 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
926 #ifdef __LITTLE_ENDIAN__
929 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
932 streamFormat.mBitsPerChannel = 32;
933 streamFormat.mFramesPerPacket = 1;
935 /* apple says that for non-interleaved data, these
936 values always refer to a single channel.
938 streamFormat.mBytesPerPacket = 4;
939 streamFormat.mBytesPerFrame = 4;
941 streamFormat.mChannelsPerFrame = audio_in;
943 if (set_input_format (streamFormat) != 0) {
947 streamFormat.mChannelsPerFrame = audio_out;
949 if (set_output_format (streamFormat) != 0) {
953 /* reset plugin info to show currently configured state */
955 _info->n_inputs = in;
956 _info->n_outputs = out;
958 if (was_initialized) {
966 AUPlugin::input_streams() const
970 c.set (DataType::AUDIO, 1);
971 c.set (DataType::MIDI, 0);
973 if (input_channels < 0) {
974 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
976 c.set (DataType::AUDIO, input_channels);
977 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
985 AUPlugin::output_streams() const
989 c.set (DataType::AUDIO, 1);
990 c.set (DataType::MIDI, 0);
992 if (output_channels < 0) {
993 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
995 c.set (DataType::AUDIO, output_channels);
996 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1003 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
1005 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1007 int32_t audio_in = in.n_audio();
1010 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1012 /* lets check MIDI first */
1014 if (in.n_midi() > 0) {
1015 if (!_has_midi_input) {
1020 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1022 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1023 name(), io_configs.size(), in, out));
1025 //Ardour expects the plugin to tell it the output
1026 //configuration but AU plugins can have multiple I/O
1027 //configurations in most cases. so first lets see
1028 //if there's a configuration that keeps out==in
1030 audio_out = audio_in;
1032 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1034 int32_t possible_in = i->first;
1035 int32_t possible_out = i->second;
1037 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1038 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1039 possible_in, possible_out,
1042 out.set (DataType::MIDI, 0);
1043 out.set (DataType::AUDIO, audio_out);
1049 /* now allow potentially "imprecise" matches */
1053 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1055 int32_t possible_in = i->first;
1056 int32_t possible_out = i->second;
1058 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1060 if (possible_out == 0) {
1061 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1062 /* XXX surely this is just a send? (e.g. AUNetSend) */
1066 if (possible_in == 0) {
1068 /* instrument plugin, always legal but throws away inputs ...
1071 if (possible_out == -1) {
1072 /* any configuration possible, provide stereo output */
1075 } else if (possible_out == -2) {
1076 /* plugins shouldn't really use (0,-2) but might.
1077 any configuration possible, provide stereo output
1081 } else if (possible_out < -2) {
1082 /* explicitly variable number of outputs, pick maximum */
1083 audio_out = -possible_out;
1086 /* exact number of outputs */
1087 audio_out = possible_out;
1092 if (possible_in == -1) {
1094 /* wildcard for input */
1096 if (possible_out == -1) {
1097 /* out much match in */
1098 audio_out = audio_in;
1100 } else if (possible_out == -2) {
1101 /* any configuration possible, pick matching */
1102 audio_out = audio_in;
1104 } else if (possible_out < -2) {
1105 /* explicitly variable number of outputs, pick maximum */
1106 audio_out = -possible_out;
1109 /* exact number of outputs */
1110 audio_out = possible_out;
1115 if (possible_in == -2) {
1117 if (possible_out == -1) {
1118 /* any configuration possible, pick matching */
1119 audio_out = audio_in;
1121 } else if (possible_out == -2) {
1122 /* plugins shouldn't really use (-2,-2) but might.
1123 interpret as (-1,-1).
1125 audio_out = audio_in;
1127 } else if (possible_out < -2) {
1128 /* explicitly variable number of outputs, pick maximum */
1129 audio_out = -possible_out;
1132 /* exact number of outputs */
1133 audio_out = possible_out;
1138 if (possible_in < -2) {
1140 /* explicit variable number of inputs */
1142 if (audio_in > -possible_in) {
1143 /* request is too large */
1146 if (possible_out == -1) {
1147 /* any output configuration possible, provide stereo out */
1150 } else if (possible_out == -2) {
1151 /* plugins shouldn't really use (<-2,-2) but might.
1152 interpret as (<-2,-1): any configuration possible, provide stereo output
1156 } else if (possible_out < -2) {
1157 /* explicitly variable number of outputs, pick maximum */
1158 audio_out = -possible_out;
1161 /* exact number of outputs */
1162 audio_out = possible_out;
1167 if (possible_in && (possible_in == audio_in)) {
1169 /* exact number of inputs ... must match obviously */
1171 if (possible_out == -1) {
1172 /* any output configuration possible, provide stereo output */
1175 } else if (possible_out == -2) {
1176 /* plugins shouldn't really use (>0,-2) but might.
1177 interpret as (>0,-1):
1178 any output configuration possible, provide stereo output
1182 } else if (possible_out < -2) {
1183 /* explicitly variable number of outputs, pick maximum */
1184 audio_out = -possible_out;
1187 /* exact number of outputs */
1188 audio_out = possible_out;
1200 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1202 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1206 out.set (DataType::MIDI, 0);
1207 out.set (DataType::AUDIO, audio_out);
1213 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1215 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1219 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1221 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1230 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1231 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1237 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1241 for (uint32_t i = 0; i < cnt; ++i) {
1242 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1243 (scope == kAudioUnitScope_Input ? "input" : "output"),
1245 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1246 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1247 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1252 if (scope == kAudioUnitScope_Input) {
1253 input_channels = fmt.mChannelsPerFrame;
1255 output_channels = fmt.mChannelsPerFrame;
1262 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1263 const AudioTimeStamp*,
1265 UInt32 inNumberFrames,
1266 AudioBufferList* ioData)
1268 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1270 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1271 name(), inNumberFrames, ioData->mNumberBuffers));
1273 if (input_maxbuf == 0) {
1274 error << _("AUPlugin: render callback called illegally!") << endmsg;
1275 return kAudioUnitErr_CannotDoInCurrentContext;
1277 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1279 for (uint32_t i = 0; i < limit; ++i) {
1280 ioData->mBuffers[i].mNumberChannels = 1;
1281 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1283 /* we don't use the channel mapping because audiounits are
1284 never replicated. one plugin instance uses all channels/buffers
1285 passed to PluginInsert::connect_and_run()
1288 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1291 cb_offset += inNumberFrames;
1297 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1299 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1301 AudioUnitRenderActionFlags flags = 0;
1305 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1306 unit->GlobalReset();
1307 _last_nframes = nframes;
1310 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1311 name(), input_channels, output_channels, _has_midi_input,
1312 bufs.count(), bufs.available()));
1314 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1315 has the capacity to handle our outputs.
1318 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1320 input_buffers = &bufs;
1321 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1322 input_offset = offset;
1325 buffers->mNumberBuffers = output_channels;
1327 for (int32_t i = 0; i < output_channels; ++i) {
1328 buffers->mBuffers[i].mNumberChannels = 1;
1329 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1330 /* setting this to 0 indicates to the AU that it can provide buffers here
1331 if necessary. if it can process in-place, it will use the buffers provided
1332 as input by ::render_callback() above. no documentation on what setting it
1333 to a non-null value means.
1335 buffers->mBuffers[i].mData = 0;
1338 if (_has_midi_input) {
1340 uint32_t nmidi = bufs.count().n_midi();
1342 for (uint32_t i = 0; i < nmidi; ++i) {
1344 /* one MIDI port/buffer only */
1346 MidiBuffer& m = bufs.get_midi (i);
1348 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1349 Evoral::MIDIEvent<framepos_t> ev (*i);
1351 if (ev.is_channel_event()) {
1352 const uint8_t* b = ev.buffer();
1353 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1354 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1357 /* XXX need to handle sysex and other message types */
1362 /* does this really mean anything ?
1365 ts.mSampleTime = frames_processed;
1366 ts.mFlags = kAudioTimeStampSampleTimeValid;
1368 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1369 // name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1371 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1374 frames_processed += nframes;
1376 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1377 name(), buffers->mNumberBuffers, output_channels));
1379 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1382 for (i = 0; i < limit; ++i) {
1383 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1384 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1385 /* plugin provided its own buffer for output so copy it back to where we want it
1387 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1391 /* now silence any buffers that were passed in but the that the plugin
1392 did not fill/touch/use.
1395 for (;i < output_channels; ++i) {
1396 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1402 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1407 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1408 Float64* outCurrentTempo)
1410 TempoMap& tmap (_session.tempo_map());
1412 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1414 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1415 (and interpretation) of a beat position will be incorrect. So refuse to
1419 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1420 return kAudioUnitErr_CannotDoInCurrentContext;
1423 Timecode::BBT_Time bbt;
1424 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1425 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1427 if (outCurrentBeat) {
1429 beat = metric.meter().divisions_per_bar() * bbt.bars;
1431 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1432 *outCurrentBeat = beat;
1435 if (outCurrentTempo) {
1436 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1444 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1445 Float32* outTimeSig_Numerator,
1446 UInt32* outTimeSig_Denominator,
1447 Float64* outCurrentMeasureDownBeat)
1449 TempoMap& tmap (_session.tempo_map());
1451 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1453 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1454 (and interpretation) of a beat position will be incorrect. So refuse to
1458 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1459 return kAudioUnitErr_CannotDoInCurrentContext;
1462 Timecode::BBT_Time bbt;
1463 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1464 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1466 if (outDeltaSampleOffsetToNextBeat) {
1467 if (bbt.ticks == 0) {
1469 *outDeltaSampleOffsetToNextBeat = 0;
1471 *outDeltaSampleOffsetToNextBeat = (UInt32)
1472 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1473 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1477 if (outTimeSig_Numerator) {
1478 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1480 if (outTimeSig_Denominator) {
1481 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1484 if (outCurrentMeasureDownBeat) {
1486 /* beat for the start of the bar.
1488 2|1|0 -> 1 + divisions_per_bar
1489 3|1|0 -> 1 + (2 * divisions_per_bar)
1493 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1500 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1501 Boolean* outTransportStateChanged,
1502 Float64* outCurrentSampleInTimeLine,
1503 Boolean* outIsCycling,
1504 Float64* outCycleStartBeat,
1505 Float64* outCycleEndBeat)
1510 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1512 rolling = _session.transport_rolling();
1513 speed = _session.transport_speed ();
1516 *outIsPlaying = _session.transport_rolling();
1519 if (outTransportStateChanged) {
1520 if (rolling != last_transport_rolling) {
1521 *outTransportStateChanged = true;
1522 } else if (speed != last_transport_speed) {
1523 *outTransportStateChanged = true;
1525 *outTransportStateChanged = false;
1529 if (outCurrentSampleInTimeLine) {
1530 /* this assumes that the AU can only call this host callback from render context,
1531 where input_offset is valid.
1533 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1537 Location* loc = _session.locations()->auto_loop_location();
1539 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1541 if (*outIsCycling) {
1543 if (outCycleStartBeat || outCycleEndBeat) {
1545 TempoMap& tmap (_session.tempo_map());
1547 /* more than 1 meter means that a simplistic computation (and interpretation) of
1548 a beat position will be incorrect. so refuse to offer the value.
1551 if (tmap.n_meters() > 1) {
1552 return kAudioUnitErr_CannotDoInCurrentContext;
1555 Timecode::BBT_Time bbt;
1557 if (outCycleStartBeat) {
1558 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1559 _session.tempo_map().bbt_time (loc->start(), bbt);
1562 beat = metric.meter().divisions_per_bar() * bbt.bars;
1564 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1566 *outCycleStartBeat = beat;
1569 if (outCycleEndBeat) {
1570 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1571 _session.tempo_map().bbt_time (loc->end(), bbt);
1574 beat = metric.meter().divisions_per_bar() * bbt.bars;
1576 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1578 *outCycleEndBeat = beat;
1584 last_transport_rolling = rolling;
1585 last_transport_speed = speed;
1590 set<Evoral::Parameter>
1591 AUPlugin::automatable() const
1593 set<Evoral::Parameter> automates;
1595 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1596 if (descriptors[i].automatable) {
1597 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1605 AUPlugin::describe_parameter (Evoral::Parameter param)
1607 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1608 return descriptors[param.id()].label;
1615 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1617 // NameValue stuff here
1621 AUPlugin::parameter_is_audio (uint32_t) const
1627 AUPlugin::parameter_is_control (uint32_t) const
1633 AUPlugin::parameter_is_input (uint32_t) const
1639 AUPlugin::parameter_is_output (uint32_t) const
1645 AUPlugin::add_state (XMLNode* root) const
1647 LocaleGuard lg (X_("POSIX"));
1649 #ifdef AU_STATE_SUPPORT
1651 CFPropertyListRef propertyList;
1653 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1654 if (unit->GetAUPreset (propertyList) != noErr) {
1658 // Convert the property list into XML data.
1660 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1663 error << _("Could not create XML version of property list") << endmsg;
1667 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1668 our state node. GACK!
1673 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1675 root->add_child_copy (*t.root());
1679 CFRelease (xmlData);
1680 CFRelease (propertyList);
1682 if (!seen_get_state_message) {
1683 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1686 seen_get_state_message = true;
1692 AUPlugin::set_state(const XMLNode& node, int version)
1694 #ifdef AU_STATE_SUPPORT
1696 CFPropertyListRef propertyList;
1697 LocaleGuard lg (X_("POSIX"));
1699 if (node.name() != state_node_name()) {
1700 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1704 if (node.children().empty()) {
1708 XMLNode* top = node.children().front();
1709 XMLNode* copy = new XMLNode (*top);
1714 const string& xml = t.write_buffer ();
1715 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1716 CFStringRef errorString;
1718 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1720 kCFPropertyListImmutable,
1723 CFRelease (xmlData);
1726 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1727 if (unit->SetAUPreset (propertyList) == noErr) {
1730 /* tell the world */
1732 AudioUnitParameter changedUnit;
1733 changedUnit.mAudioUnit = unit->AU();
1734 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1735 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1737 CFRelease (propertyList);
1740 Plugin::set_state (node, version);
1743 if (!seen_set_state_message) {
1744 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1748 return Plugin::set_state (node, version);
1753 AUPlugin::load_preset (PresetRecord r)
1755 Plugin::load_preset (r);
1757 #ifdef AU_STATE_SUPPORT
1759 CFPropertyListRef propertyList;
1761 UserPresetMap::iterator ux;
1762 FactoryPresetMap::iterator fx;
1764 /* look first in "user" presets */
1766 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1768 if ((propertyList = load_property_list (ux->second)) != 0) {
1769 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1770 if (unit->SetAUPreset (propertyList) == noErr) {
1773 /* tell the world */
1775 AudioUnitParameter changedUnit;
1776 changedUnit.mAudioUnit = unit->AU();
1777 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1778 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1780 CFRelease(propertyList);
1783 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1787 preset.presetNumber = fx->second;
1788 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1790 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1792 if (unit->SetPresentPreset (preset) == 0) {
1795 /* tell the world */
1797 AudioUnitParameter changedUnit;
1798 changedUnit.mAudioUnit = unit->AU();
1799 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1800 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1806 if (!seen_loading_message) {
1807 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1810 seen_loading_message = true;
1817 AUPlugin::do_remove_preset (std::string)
1822 AUPlugin::do_save_preset (string preset_name)
1824 #ifdef AU_STATE_SUPPORT
1825 CFPropertyListRef propertyList;
1826 vector<Glib::ustring> v;
1827 Glib::ustring user_preset_path;
1830 std::string m = maker();
1831 std::string n = name();
1833 strip_whitespace_edges (m);
1834 strip_whitespace_edges (n);
1836 v.push_back (Glib::get_home_dir());
1837 v.push_back ("Library");
1838 v.push_back ("Audio");
1839 v.push_back ("Presets");
1843 user_preset_path = Glib::build_filename (v);
1845 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1846 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1850 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1851 if (unit->GetAUPreset (propertyList) != noErr) {
1855 // add the actual preset name */
1857 v.push_back (preset_name + preset_suffix);
1861 user_preset_path = Glib::build_filename (v);
1863 set_preset_name_in_plist (propertyList, preset_name);
1865 if (save_property_list (propertyList, user_preset_path)) {
1866 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1870 CFRelease(propertyList);
1872 return string ("file:///") + user_preset_path;
1874 if (!seen_saving_message) {
1875 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1878 seen_saving_message = true;
1884 //-----------------------------------------------------------------------------
1885 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1887 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1889 CFNumberRef cfNumber;
1890 SInt32 numberValue = 0;
1891 Boolean dummySuccess;
1893 if (outSuccess == NULL)
1894 outSuccess = &dummySuccess;
1895 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1897 *outSuccess = FALSE;
1901 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1902 if (cfNumber == NULL)
1904 *outSuccess = FALSE;
1907 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1915 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1917 CFDictionaryRef auStateDictionary;
1918 ComponentDescription tempDesc = {0,0,0,0,0};
1919 SInt32 versionValue;
1922 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1925 // the property list for AU state data must be of the dictionary type
1926 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1927 return kAudioUnitErr_InvalidPropertyValue;
1930 auStateDictionary = (CFDictionaryRef)inAUStateData;
1932 // first check to make sure that the version of the AU state data is one that we know understand
1933 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1934 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1937 return kAudioUnitErr_InvalidPropertyValue;
1939 #define kCurrentSavedStateVersion 0
1940 if (versionValue != kCurrentSavedStateVersion) {
1941 return kAudioUnitErr_InvalidPropertyValue;
1944 // grab the ComponentDescription values from the AU state data
1945 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1946 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1947 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1948 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1949 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1950 return kAudioUnitErr_InvalidPropertyValue;
1952 *outComponentDescription = tempDesc;
1957 static bool au_preset_filter (const string& str, void* arg)
1959 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1963 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1967 /* check the preset file path name against this plugin
1968 ID. The idea is that all preset files for this plugin
1969 include "<manufacturer>/<plugin-name>" in their path.
1972 Plugin* p = (Plugin *) arg;
1973 string match = p->maker();
1977 ret = str.find (match) != string::npos;
1980 string m = p->maker ();
1981 string n = p->name ();
1982 strip_whitespace_edges (m);
1983 strip_whitespace_edges (n);
1988 ret = str.find (match) != string::npos;
1996 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1999 CFPropertyListRef plist;
2000 ComponentDescription presetDesc;
2003 plist = load_property_list (pathstr);
2009 // get the ComponentDescription from the AU preset file
2011 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2013 if (status == noErr) {
2014 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2016 /* try to get the preset name from the property list */
2018 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2020 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2024 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2027 char buf[PATH_MAX+1];
2029 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2044 AUPlugin::current_preset() const
2048 #ifdef AU_STATE_SUPPORT
2049 CFPropertyListRef propertyList;
2051 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2052 if (unit->GetAUPreset (propertyList) == noErr) {
2053 preset_name = get_preset_name_in_plist (propertyList);
2054 CFRelease(propertyList);
2061 AUPlugin::find_presets ()
2063 #ifdef AU_STATE_SUPPORT
2064 vector<string*>* preset_files;
2065 PathScanner scanner;
2067 user_preset_map.clear ();
2069 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2071 if (!preset_files) {
2075 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2077 string path = *(*x);
2080 /* make an initial guess at the preset name using the path */
2082 preset_name = Glib::path_get_basename (path);
2083 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2085 /* check that this preset file really matches this plugin
2086 and potentially get the "real" preset name from
2090 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2091 user_preset_map[preset_name] = path;
2097 delete preset_files;
2099 /* now fill the vector<string> with the names we have */
2101 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2102 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2105 /* add factory presets */
2107 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2109 string const uri = string_compose ("%1", _presets.size ());
2110 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2117 AUPlugin::has_editor () const
2119 // even if the plugin doesn't have its own editor, the AU API can be used
2120 // to create one that looks native.
2124 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2127 type = ARDOUR::AudioUnit;
2130 AUPluginInfo::~AUPluginInfo ()
2132 type = ARDOUR::AudioUnit;
2136 AUPluginInfo::load (Session& session)
2141 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2142 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2144 if (!comp->IsValid()) {
2145 error << ("AudioUnit: not a valid Component") << endmsg;
2147 plugin.reset (new AUPlugin (session.engine(), session, comp));
2150 AUPluginInfo *aup = new AUPluginInfo (*this);
2151 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2152 plugin->set_info (PluginInfoPtr (aup));
2153 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2157 catch (failed_constructor &err) {
2158 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2159 return PluginPtr ();
2164 AUPluginInfo::au_cache_path ()
2166 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2170 AUPluginInfo::discover ()
2174 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2175 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2178 PluginInfoList* plugs = new PluginInfoList;
2180 discover_fx (*plugs);
2181 discover_music (*plugs);
2182 discover_generators (*plugs);
2183 discover_instruments (*plugs);
2185 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2191 AUPluginInfo::discover_music (PluginInfoList& plugs)
2193 CAComponentDescription desc;
2194 desc.componentFlags = 0;
2195 desc.componentFlagsMask = 0;
2196 desc.componentSubType = 0;
2197 desc.componentManufacturer = 0;
2198 desc.componentType = kAudioUnitType_MusicEffect;
2200 discover_by_description (plugs, desc);
2204 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2206 CAComponentDescription desc;
2207 desc.componentFlags = 0;
2208 desc.componentFlagsMask = 0;
2209 desc.componentSubType = 0;
2210 desc.componentManufacturer = 0;
2211 desc.componentType = kAudioUnitType_Effect;
2213 discover_by_description (plugs, desc);
2217 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2219 CAComponentDescription desc;
2220 desc.componentFlags = 0;
2221 desc.componentFlagsMask = 0;
2222 desc.componentSubType = 0;
2223 desc.componentManufacturer = 0;
2224 desc.componentType = kAudioUnitType_Generator;
2226 discover_by_description (plugs, desc);
2230 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2232 CAComponentDescription desc;
2233 desc.componentFlags = 0;
2234 desc.componentFlagsMask = 0;
2235 desc.componentSubType = 0;
2236 desc.componentManufacturer = 0;
2237 desc.componentType = kAudioUnitType_MusicDevice;
2239 discover_by_description (plugs, desc);
2243 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2247 comp = FindNextComponent (NULL, &desc);
2249 while (comp != NULL) {
2250 CAComponentDescription temp;
2251 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2253 AUPluginInfoPtr info (new AUPluginInfo
2254 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2256 /* although apple designed the subtype field to be a "category" indicator,
2257 its really turned into a plugin ID field for a given manufacturer. Hence
2258 there are no categories for AudioUnits. However, to keep the plugins
2259 showing up under "categories", we'll use the "type" as a high level
2262 NOTE: no panners, format converters or i/o AU's for our purposes
2265 switch (info->descriptor->Type()) {
2266 case kAudioUnitType_Panner:
2267 case kAudioUnitType_OfflineEffect:
2268 case kAudioUnitType_FormatConverter:
2271 case kAudioUnitType_Output:
2272 info->category = _("AudioUnit Outputs");
2274 case kAudioUnitType_MusicDevice:
2275 info->category = _("AudioUnit Instruments");
2277 case kAudioUnitType_MusicEffect:
2278 info->category = _("AudioUnit MusicEffects");
2280 case kAudioUnitType_Effect:
2281 info->category = _("AudioUnit Effects");
2283 case kAudioUnitType_Mixer:
2284 info->category = _("AudioUnit Mixers");
2286 case kAudioUnitType_Generator:
2287 info->category = _("AudioUnit Generators");
2290 info->category = _("AudioUnit (Unknown)");
2294 AUPluginInfo::get_names (temp, info->name, info->creator);
2296 info->type = ARDOUR::AudioUnit;
2297 info->unique_id = stringify_descriptor (*info->descriptor);
2299 /* XXX not sure of the best way to handle plugin versioning yet
2302 CAComponent cacomp (*info->descriptor);
2304 if (cacomp.GetResourceVersion (info->version) != noErr) {
2308 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2310 /* here we have to map apple's wildcard system to a simple pair
2311 of values. in ::can_do() we use the whole system, but here
2312 we need a single pair of values. XXX probably means we should
2313 remove any use of these values.
2315 for now, if the plugin provides a wildcard, treat it as 1. we really
2316 don't care much, because whether we can handle an i/o configuration
2317 depends upon ::can_support_io_configuration(), not these counts.
2319 they exist because other parts of ardour try to present i/o configuration
2320 info to the user, which should perhaps be revisited.
2323 int32_t possible_in = info->cache.io_configs.front().first;
2324 int32_t possible_out = info->cache.io_configs.front().second;
2326 if (possible_in > 0) {
2327 info->n_inputs.set (DataType::AUDIO, possible_in);
2329 info->n_inputs.set (DataType::AUDIO, 1);
2332 if (possible_out > 0) {
2333 info->n_outputs.set (DataType::AUDIO, possible_out);
2335 info->n_outputs.set (DataType::AUDIO, 1);
2338 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2339 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2341 plugs.push_back (info);
2344 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2347 comp = FindNextComponent (comp, &desc);
2352 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2355 AUPluginCachedInfo& cinfo,
2356 const std::string& name)
2361 /* concatenate unique ID with version to provide a key for cached info lookup.
2362 this ensures we don't get stale information, or should if plugin developers
2363 follow Apple "guidelines".
2366 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2371 CachedInfoMap::iterator cim = cached_info.find (id);
2373 if (cim != cached_info.end()) {
2374 cinfo = cim->second;
2379 AUChannelInfo* channel_info;
2383 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2387 if (CAAudioUnit::Open (comp, unit) != noErr) {
2393 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2398 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2399 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2405 /* no explicit info available, so default to 1in/1out */
2407 /* XXX this is wrong. we should be indicating wildcard values */
2409 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2413 /* store each configuration */
2415 for (uint32_t n = 0; n < cnt; ++n) {
2416 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2417 channel_info[n].outChannels));
2420 free (channel_info);
2423 add_cached_info (id, cinfo);
2424 save_cached_info ();
2430 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2432 cached_info[id] = cinfo;
2435 #define AU_CACHE_VERSION "2.0"
2438 AUPluginInfo::save_cached_info ()
2442 node = new XMLNode (X_("AudioUnitPluginCache"));
2443 node->add_property( "version", AU_CACHE_VERSION );
2445 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2446 XMLNode* parent = new XMLNode (X_("plugin"));
2447 parent->add_property ("id", i->first);
2448 node->add_child_nocopy (*parent);
2450 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2452 XMLNode* child = new XMLNode (X_("io"));
2455 snprintf (buf, sizeof (buf), "%d", j->first);
2456 child->add_property (X_("in"), buf);
2457 snprintf (buf, sizeof (buf), "%d", j->second);
2458 child->add_property (X_("out"), buf);
2459 parent->add_child_nocopy (*child);
2464 Glib::ustring path = au_cache_path ();
2467 tree.set_root (node);
2469 if (!tree.write (path)) {
2470 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2471 unlink (path.c_str());
2476 AUPluginInfo::load_cached_info ()
2478 Glib::ustring path = au_cache_path ();
2481 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2485 if ( !tree.read (path) ) {
2486 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2490 const XMLNode* root (tree.root());
2492 if (root->name() != X_("AudioUnitPluginCache")) {
2496 //initial version has incorrectly stored i/o info, and/or garbage chars.
2497 const XMLProperty* version = root->property(X_("version"));
2498 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2499 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2503 cached_info.clear ();
2505 const XMLNodeList children = root->children();
2507 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2509 const XMLNode* child = *iter;
2511 if (child->name() == X_("plugin")) {
2513 const XMLNode* gchild;
2514 const XMLNodeList gchildren = child->children();
2515 const XMLProperty* prop = child->property (X_("id"));
2521 string id = prop->value();
2525 string::size_type slash = id.find_last_of ('/');
2527 if (slash == string::npos) {
2531 version = id.substr (slash);
2532 id = id.substr (0, slash);
2533 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2535 if (fixed.empty()) {
2536 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2543 AUPluginCachedInfo cinfo;
2545 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2549 if (gchild->name() == X_("io")) {
2553 const XMLProperty* iprop;
2554 const XMLProperty* oprop;
2556 if (((iprop = gchild->property (X_("in"))) != 0) &&
2557 ((oprop = gchild->property (X_("out"))) != 0)) {
2558 in = atoi (iprop->value());
2559 out = atoi (oprop->value());
2561 cinfo.io_configs.push_back (pair<int,int> (in, out));
2566 if (cinfo.io_configs.size()) {
2567 add_cached_info (id, cinfo);
2576 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2578 CFStringRef itemName = NULL;
2580 // Marc Poirier-style item name
2581 CAComponent auComponent (comp_desc);
2582 if (auComponent.IsValid()) {
2583 CAComponentDescription dummydesc;
2584 Handle nameHandle = NewHandle(sizeof(void*));
2585 if (nameHandle != NULL) {
2586 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2588 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2589 if (nameString != NULL) {
2590 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2593 DisposeHandle(nameHandle);
2597 // if Marc-style fails, do the original way
2598 if (itemName == NULL) {
2599 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2600 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2601 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2603 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2604 compTypeString, compManufacturerString, compSubTypeString);
2606 if (compTypeString != NULL)
2607 CFRelease(compTypeString);
2608 if (compSubTypeString != NULL)
2609 CFRelease(compSubTypeString);
2610 if (compManufacturerString != NULL)
2611 CFRelease(compManufacturerString);
2614 string str = CFStringRefToStdString(itemName);
2615 string::size_type colon = str.find (':');
2618 name = str.substr (colon+1);
2619 maker = str.substr (0, colon);
2620 strip_whitespace_edges (maker);
2621 strip_whitespace_edges (name);
2625 strip_whitespace_edges (name);
2630 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2634 /* note: OSType is a compiler-implemenation-defined value,
2635 historically a 32 bit integer created with a multi-character
2636 constant such as 'abcd'. It is, fundamentally, an abomination.
2641 s << desc.SubType();
2649 AUPluginInfo::needs_midi_input ()
2651 return is_effect_with_midi_input () || is_instrument ();
2655 AUPluginInfo::is_effect () const
2657 return is_effect_without_midi_input() || is_effect_with_midi_input();
2661 AUPluginInfo::is_effect_without_midi_input () const
2663 return descriptor->IsAUFX();
2667 AUPluginInfo::is_effect_with_midi_input () const
2669 return descriptor->IsAUFM();
2673 AUPluginInfo::is_instrument () const
2675 return descriptor->IsMusicDevice();
2679 AUPlugin::set_info (PluginInfoPtr info)
2681 Plugin::set_info (info);
2683 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2684 _has_midi_input = pinfo->needs_midi_input ();
2685 _has_midi_output = false;
2689 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2692 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2694 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2696 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2698 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2702 _parameter_listener_arg = arg;
2708 AUPlugin::listen_to_parameter (uint32_t param_id)
2710 AudioUnitEvent event;
2712 if (!_parameter_listener || param_id >= descriptors.size()) {
2716 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2717 event.mArgument.mParameter.mAudioUnit = unit->AU();
2718 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2719 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2720 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2722 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2730 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2732 AudioUnitEvent event;
2734 if (!_parameter_listener || param_id >= descriptors.size()) {
2738 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2739 event.mArgument.mParameter.mAudioUnit = unit->AU();
2740 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2741 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2742 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2744 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2752 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2754 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2758 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2760 ParameterMap::iterator i = parameter_map.find (event->mArgument.mParameter.mParameterID);
2762 if (i != parameter_map.end()) {
2763 ParameterChanged (i->second, new_value);