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\n", name(), io_configs.size()));
1024 //Ardour expects the plugin to tell it the output
1025 //configuration but AU plugins can have multiple I/O
1026 //configurations in most cases. so first lets see
1027 //if there's a configuration that keeps out==in
1029 audio_out = audio_in;
1031 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1033 int32_t possible_in = i->first;
1034 int32_t possible_out = i->second;
1036 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1037 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1042 /* now allow potentially "imprecise" matches */
1046 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1048 int32_t possible_in = i->first;
1049 int32_t possible_out = i->second;
1051 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1053 if (possible_out == 0) {
1054 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1055 /* XXX surely this is just a send? (e.g. AUNetSend) */
1059 if (possible_in == 0) {
1061 /* instrument plugin, always legal but throws away inputs ...
1064 if (possible_out == -1) {
1065 /* any configuration possible, provide stereo output */
1068 } else if (possible_out == -2) {
1069 /* plugins shouldn't really use (0,-2) but might.
1070 any configuration possible, provide stereo output
1074 } else if (possible_out < -2) {
1075 /* explicitly variable number of outputs, pick maximum */
1076 audio_out = -possible_out;
1079 /* exact number of outputs */
1080 audio_out = possible_out;
1085 if (possible_in == -1) {
1087 /* wildcard for input */
1089 if (possible_out == -1) {
1090 /* out much match in */
1091 audio_out = audio_in;
1093 } else if (possible_out == -2) {
1094 /* any configuration possible, pick matching */
1095 audio_out = audio_in;
1097 } else if (possible_out < -2) {
1098 /* explicitly variable number of outputs, pick maximum */
1099 audio_out = -possible_out;
1102 /* exact number of outputs */
1103 audio_out = possible_out;
1108 if (possible_in == -2) {
1110 if (possible_out == -1) {
1111 /* any configuration possible, pick matching */
1112 audio_out = audio_in;
1114 } else if (possible_out == -2) {
1115 /* plugins shouldn't really use (-2,-2) but might.
1116 interpret as (-1,-1).
1118 audio_out = audio_in;
1120 } else if (possible_out < -2) {
1121 /* explicitly variable number of outputs, pick maximum */
1122 audio_out = -possible_out;
1125 /* exact number of outputs */
1126 audio_out = possible_out;
1131 if (possible_in < -2) {
1133 /* explicit variable number of inputs */
1135 if (audio_in > -possible_in) {
1136 /* request is too large */
1139 if (possible_out == -1) {
1140 /* any output configuration possible, provide stereo out */
1143 } else if (possible_out == -2) {
1144 /* plugins shouldn't really use (<-2,-2) but might.
1145 interpret as (<-2,-1): any configuration possible, provide stereo output
1149 } else if (possible_out < -2) {
1150 /* explicitly variable number of outputs, pick maximum */
1151 audio_out = -possible_out;
1154 /* exact number of outputs */
1155 audio_out = possible_out;
1160 if (possible_in && (possible_in == audio_in)) {
1162 /* exact number of inputs ... must match obviously */
1164 if (possible_out == -1) {
1165 /* any output configuration possible, provide stereo output */
1168 } else if (possible_out == -2) {
1169 /* plugins shouldn't really use (>0,-2) but might.
1170 interpret as (>0,-1):
1171 any output configuration possible, provide stereo output
1175 } else if (possible_out < -2) {
1176 /* explicitly variable number of outputs, pick maximum */
1177 audio_out = -possible_out;
1180 /* exact number of outputs */
1181 audio_out = possible_out;
1193 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1195 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1199 out.set (DataType::MIDI, 0);
1200 out.set (DataType::AUDIO, audio_out);
1206 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1208 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1212 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1214 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1223 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1224 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1230 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1234 for (uint32_t i = 0; i < cnt; ++i) {
1235 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1236 (scope == kAudioUnitScope_Input ? "input" : "output"),
1238 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1239 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1240 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1245 if (scope == kAudioUnitScope_Input) {
1246 input_channels = fmt.mChannelsPerFrame;
1248 output_channels = fmt.mChannelsPerFrame;
1255 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1256 const AudioTimeStamp*,
1258 UInt32 inNumberFrames,
1259 AudioBufferList* ioData)
1261 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1263 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1264 name(), inNumberFrames, ioData->mNumberBuffers));
1266 if (input_maxbuf == 0) {
1267 error << _("AUPlugin: render callback called illegally!") << endmsg;
1268 return kAudioUnitErr_CannotDoInCurrentContext;
1270 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1272 for (uint32_t i = 0; i < limit; ++i) {
1273 ioData->mBuffers[i].mNumberChannels = 1;
1274 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1276 /* we don't use the channel mapping because audiounits are
1277 never replicated. one plugin instance uses all channels/buffers
1278 passed to PluginInsert::connect_and_run()
1281 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1284 cb_offset += inNumberFrames;
1290 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1292 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1294 AudioUnitRenderActionFlags flags = 0;
1298 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1299 unit->GlobalReset();
1300 _last_nframes = nframes;
1303 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1304 has the capacity to handle our outputs.
1306 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1308 input_buffers = &bufs;
1309 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1310 input_offset = offset;
1313 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1314 name(), input_channels, output_channels, _has_midi_input,
1315 bufs.count(), bufs.available()));
1317 buffers->mNumberBuffers = output_channels;
1319 for (int32_t i = 0; i < output_channels; ++i) {
1320 buffers->mBuffers[i].mNumberChannels = 1;
1321 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1322 /* setting this to 0 indicates to the AU that it can provide buffers here
1323 if necessary. if it can process in-place, it will use the buffers provided
1324 as input by ::render_callback() above. no documentation on what setting it
1325 to a non-null value means.
1327 buffers->mBuffers[i].mData = 0;
1330 if (_has_midi_input) {
1332 uint32_t nmidi = bufs.count().n_midi();
1334 for (uint32_t i = 0; i < nmidi; ++i) {
1336 /* one MIDI port/buffer only */
1338 MidiBuffer& m = bufs.get_midi (i);
1340 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1341 Evoral::MIDIEvent<framepos_t> ev (*i);
1343 if (ev.is_channel_event()) {
1344 const uint8_t* b = ev.buffer();
1345 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1346 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1349 /* XXX need to handle sysex and other message types */
1354 /* does this really mean anything ?
1357 ts.mSampleTime = frames_processed;
1358 ts.mFlags = kAudioTimeStampSampleTimeValid;
1360 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1361 // name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1363 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1366 frames_processed += nframes;
1368 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1369 name(), buffers->mNumberBuffers, output_channels));
1371 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1374 for (i = 0; i < limit; ++i) {
1375 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1376 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1377 /* plugin provided its own buffer for output so copy it back to where we want it
1379 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1383 /* now silence any buffers that were passed in but the that the plugin
1384 did not fill/touch/use.
1387 for (;i < output_channels; ++i) {
1388 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1394 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1399 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1400 Float64* outCurrentTempo)
1402 TempoMap& tmap (_session.tempo_map());
1404 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1406 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1407 (and interpretation) of a beat position will be incorrect. So refuse to
1411 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1412 return kAudioUnitErr_CannotDoInCurrentContext;
1415 Timecode::BBT_Time bbt;
1416 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1417 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1419 if (outCurrentBeat) {
1421 beat = metric.meter().divisions_per_bar() * bbt.bars;
1423 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1424 *outCurrentBeat = beat;
1427 if (outCurrentTempo) {
1428 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1436 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1437 Float32* outTimeSig_Numerator,
1438 UInt32* outTimeSig_Denominator,
1439 Float64* outCurrentMeasureDownBeat)
1441 TempoMap& tmap (_session.tempo_map());
1443 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1445 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1446 (and interpretation) of a beat position will be incorrect. So refuse to
1450 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1451 return kAudioUnitErr_CannotDoInCurrentContext;
1454 Timecode::BBT_Time bbt;
1455 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1456 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1458 if (outDeltaSampleOffsetToNextBeat) {
1459 if (bbt.ticks == 0) {
1461 *outDeltaSampleOffsetToNextBeat = 0;
1463 *outDeltaSampleOffsetToNextBeat = (UInt32)
1464 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1465 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1469 if (outTimeSig_Numerator) {
1470 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1472 if (outTimeSig_Denominator) {
1473 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1476 if (outCurrentMeasureDownBeat) {
1478 /* beat for the start of the bar.
1480 2|1|0 -> 1 + divisions_per_bar
1481 3|1|0 -> 1 + (2 * divisions_per_bar)
1485 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1492 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1493 Boolean* outTransportStateChanged,
1494 Float64* outCurrentSampleInTimeLine,
1495 Boolean* outIsCycling,
1496 Float64* outCycleStartBeat,
1497 Float64* outCycleEndBeat)
1502 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1504 rolling = _session.transport_rolling();
1505 speed = _session.transport_speed ();
1508 *outIsPlaying = _session.transport_rolling();
1511 if (outTransportStateChanged) {
1512 if (rolling != last_transport_rolling) {
1513 *outTransportStateChanged = true;
1514 } else if (speed != last_transport_speed) {
1515 *outTransportStateChanged = true;
1517 *outTransportStateChanged = false;
1521 if (outCurrentSampleInTimeLine) {
1522 /* this assumes that the AU can only call this host callback from render context,
1523 where input_offset is valid.
1525 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1529 Location* loc = _session.locations()->auto_loop_location();
1531 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1533 if (*outIsCycling) {
1535 if (outCycleStartBeat || outCycleEndBeat) {
1537 TempoMap& tmap (_session.tempo_map());
1539 /* more than 1 meter means that a simplistic computation (and interpretation) of
1540 a beat position will be incorrect. so refuse to offer the value.
1543 if (tmap.n_meters() > 1) {
1544 return kAudioUnitErr_CannotDoInCurrentContext;
1547 Timecode::BBT_Time bbt;
1549 if (outCycleStartBeat) {
1550 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1551 _session.tempo_map().bbt_time (loc->start(), bbt);
1554 beat = metric.meter().divisions_per_bar() * bbt.bars;
1556 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1558 *outCycleStartBeat = beat;
1561 if (outCycleEndBeat) {
1562 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1563 _session.tempo_map().bbt_time (loc->end(), bbt);
1566 beat = metric.meter().divisions_per_bar() * bbt.bars;
1568 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1570 *outCycleEndBeat = beat;
1576 last_transport_rolling = rolling;
1577 last_transport_speed = speed;
1582 set<Evoral::Parameter>
1583 AUPlugin::automatable() const
1585 set<Evoral::Parameter> automates;
1587 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1588 if (descriptors[i].automatable) {
1589 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1597 AUPlugin::describe_parameter (Evoral::Parameter param)
1599 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1600 return descriptors[param.id()].label;
1607 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1609 // NameValue stuff here
1613 AUPlugin::parameter_is_audio (uint32_t) const
1619 AUPlugin::parameter_is_control (uint32_t) const
1625 AUPlugin::parameter_is_input (uint32_t) const
1631 AUPlugin::parameter_is_output (uint32_t) const
1637 AUPlugin::add_state (XMLNode* root) const
1639 LocaleGuard lg (X_("POSIX"));
1641 #ifdef AU_STATE_SUPPORT
1643 CFPropertyListRef propertyList;
1645 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1646 if (unit->GetAUPreset (propertyList) != noErr) {
1650 // Convert the property list into XML data.
1652 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1655 error << _("Could not create XML version of property list") << endmsg;
1659 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1660 our state node. GACK!
1665 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1667 root->add_child_copy (*t.root());
1671 CFRelease (xmlData);
1672 CFRelease (propertyList);
1674 if (!seen_get_state_message) {
1675 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1678 seen_get_state_message = true;
1684 AUPlugin::set_state(const XMLNode& node, int version)
1686 #ifdef AU_STATE_SUPPORT
1688 CFPropertyListRef propertyList;
1689 LocaleGuard lg (X_("POSIX"));
1691 if (node.name() != state_node_name()) {
1692 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1696 if (node.children().empty()) {
1700 XMLNode* top = node.children().front();
1701 XMLNode* copy = new XMLNode (*top);
1706 const string& xml = t.write_buffer ();
1707 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1708 CFStringRef errorString;
1710 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1712 kCFPropertyListImmutable,
1715 CFRelease (xmlData);
1718 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1719 if (unit->SetAUPreset (propertyList) == noErr) {
1722 /* tell the world */
1724 AudioUnitParameter changedUnit;
1725 changedUnit.mAudioUnit = unit->AU();
1726 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1727 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1729 CFRelease (propertyList);
1732 Plugin::set_state (node, version);
1735 if (!seen_set_state_message) {
1736 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1740 return Plugin::set_state (node, version);
1745 AUPlugin::load_preset (PresetRecord r)
1747 Plugin::load_preset (r);
1749 #ifdef AU_STATE_SUPPORT
1751 CFPropertyListRef propertyList;
1753 UserPresetMap::iterator ux;
1754 FactoryPresetMap::iterator fx;
1756 /* look first in "user" presets */
1758 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1760 if ((propertyList = load_property_list (ux->second)) != 0) {
1761 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1762 if (unit->SetAUPreset (propertyList) == noErr) {
1765 /* tell the world */
1767 AudioUnitParameter changedUnit;
1768 changedUnit.mAudioUnit = unit->AU();
1769 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1770 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1772 CFRelease(propertyList);
1775 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1779 preset.presetNumber = fx->second;
1780 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1782 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1784 if (unit->SetPresentPreset (preset) == 0) {
1787 /* tell the world */
1789 AudioUnitParameter changedUnit;
1790 changedUnit.mAudioUnit = unit->AU();
1791 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1792 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1798 if (!seen_loading_message) {
1799 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1802 seen_loading_message = true;
1809 AUPlugin::do_remove_preset (std::string)
1814 AUPlugin::do_save_preset (string preset_name)
1816 #ifdef AU_STATE_SUPPORT
1817 CFPropertyListRef propertyList;
1818 vector<Glib::ustring> v;
1819 Glib::ustring user_preset_path;
1822 std::string m = maker();
1823 std::string n = name();
1825 strip_whitespace_edges (m);
1826 strip_whitespace_edges (n);
1828 v.push_back (Glib::get_home_dir());
1829 v.push_back ("Library");
1830 v.push_back ("Audio");
1831 v.push_back ("Presets");
1835 user_preset_path = Glib::build_filename (v);
1837 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1838 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1842 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1843 if (unit->GetAUPreset (propertyList) != noErr) {
1847 // add the actual preset name */
1849 v.push_back (preset_name + preset_suffix);
1853 user_preset_path = Glib::build_filename (v);
1855 set_preset_name_in_plist (propertyList, preset_name);
1857 if (save_property_list (propertyList, user_preset_path)) {
1858 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1862 CFRelease(propertyList);
1864 return string ("file:///") + user_preset_path;
1866 if (!seen_saving_message) {
1867 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1870 seen_saving_message = true;
1876 //-----------------------------------------------------------------------------
1877 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1879 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1881 CFNumberRef cfNumber;
1882 SInt32 numberValue = 0;
1883 Boolean dummySuccess;
1885 if (outSuccess == NULL)
1886 outSuccess = &dummySuccess;
1887 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1889 *outSuccess = FALSE;
1893 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1894 if (cfNumber == NULL)
1896 *outSuccess = FALSE;
1899 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1907 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1909 CFDictionaryRef auStateDictionary;
1910 ComponentDescription tempDesc = {0,0,0,0,0};
1911 SInt32 versionValue;
1914 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1917 // the property list for AU state data must be of the dictionary type
1918 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1919 return kAudioUnitErr_InvalidPropertyValue;
1922 auStateDictionary = (CFDictionaryRef)inAUStateData;
1924 // first check to make sure that the version of the AU state data is one that we know understand
1925 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1926 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1929 return kAudioUnitErr_InvalidPropertyValue;
1931 #define kCurrentSavedStateVersion 0
1932 if (versionValue != kCurrentSavedStateVersion) {
1933 return kAudioUnitErr_InvalidPropertyValue;
1936 // grab the ComponentDescription values from the AU state data
1937 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1938 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1939 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1940 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1941 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1942 return kAudioUnitErr_InvalidPropertyValue;
1944 *outComponentDescription = tempDesc;
1949 static bool au_preset_filter (const string& str, void* arg)
1951 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1955 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1959 /* check the preset file path name against this plugin
1960 ID. The idea is that all preset files for this plugin
1961 include "<manufacturer>/<plugin-name>" in their path.
1964 Plugin* p = (Plugin *) arg;
1965 string match = p->maker();
1969 ret = str.find (match) != string::npos;
1972 string m = p->maker ();
1973 string n = p->name ();
1974 strip_whitespace_edges (m);
1975 strip_whitespace_edges (n);
1980 ret = str.find (match) != string::npos;
1988 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1991 CFPropertyListRef plist;
1992 ComponentDescription presetDesc;
1995 plist = load_property_list (pathstr);
2001 // get the ComponentDescription from the AU preset file
2003 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2005 if (status == noErr) {
2006 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2008 /* try to get the preset name from the property list */
2010 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2012 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2016 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2019 char buf[PATH_MAX+1];
2021 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2036 AUPlugin::current_preset() const
2040 #ifdef AU_STATE_SUPPORT
2041 CFPropertyListRef propertyList;
2043 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2044 if (unit->GetAUPreset (propertyList) == noErr) {
2045 preset_name = get_preset_name_in_plist (propertyList);
2046 CFRelease(propertyList);
2053 AUPlugin::find_presets ()
2055 #ifdef AU_STATE_SUPPORT
2056 vector<string*>* preset_files;
2057 PathScanner scanner;
2059 user_preset_map.clear ();
2061 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2063 if (!preset_files) {
2067 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2069 string path = *(*x);
2072 /* make an initial guess at the preset name using the path */
2074 preset_name = Glib::path_get_basename (path);
2075 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2077 /* check that this preset file really matches this plugin
2078 and potentially get the "real" preset name from
2082 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2083 user_preset_map[preset_name] = path;
2089 delete preset_files;
2091 /* now fill the vector<string> with the names we have */
2093 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2094 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2097 /* add factory presets */
2099 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2101 string const uri = string_compose ("%1", _presets.size ());
2102 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first)));
2109 AUPlugin::has_editor () const
2111 // even if the plugin doesn't have its own editor, the AU API can be used
2112 // to create one that looks native.
2116 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2119 type = ARDOUR::AudioUnit;
2122 AUPluginInfo::~AUPluginInfo ()
2124 type = ARDOUR::AudioUnit;
2128 AUPluginInfo::load (Session& session)
2133 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2134 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2136 if (!comp->IsValid()) {
2137 error << ("AudioUnit: not a valid Component") << endmsg;
2139 plugin.reset (new AUPlugin (session.engine(), session, comp));
2142 AUPluginInfo *aup = new AUPluginInfo (*this);
2143 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2144 plugin->set_info (PluginInfoPtr (aup));
2145 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2149 catch (failed_constructor &err) {
2150 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2151 return PluginPtr ();
2156 AUPluginInfo::au_cache_path ()
2158 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2162 AUPluginInfo::discover ()
2166 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2167 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2170 PluginInfoList* plugs = new PluginInfoList;
2172 discover_fx (*plugs);
2173 discover_music (*plugs);
2174 discover_generators (*plugs);
2175 discover_instruments (*plugs);
2177 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2183 AUPluginInfo::discover_music (PluginInfoList& plugs)
2185 CAComponentDescription desc;
2186 desc.componentFlags = 0;
2187 desc.componentFlagsMask = 0;
2188 desc.componentSubType = 0;
2189 desc.componentManufacturer = 0;
2190 desc.componentType = kAudioUnitType_MusicEffect;
2192 discover_by_description (plugs, desc);
2196 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2198 CAComponentDescription desc;
2199 desc.componentFlags = 0;
2200 desc.componentFlagsMask = 0;
2201 desc.componentSubType = 0;
2202 desc.componentManufacturer = 0;
2203 desc.componentType = kAudioUnitType_Effect;
2205 discover_by_description (plugs, desc);
2209 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2211 CAComponentDescription desc;
2212 desc.componentFlags = 0;
2213 desc.componentFlagsMask = 0;
2214 desc.componentSubType = 0;
2215 desc.componentManufacturer = 0;
2216 desc.componentType = kAudioUnitType_Generator;
2218 discover_by_description (plugs, desc);
2222 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2224 CAComponentDescription desc;
2225 desc.componentFlags = 0;
2226 desc.componentFlagsMask = 0;
2227 desc.componentSubType = 0;
2228 desc.componentManufacturer = 0;
2229 desc.componentType = kAudioUnitType_MusicDevice;
2231 discover_by_description (plugs, desc);
2235 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2239 comp = FindNextComponent (NULL, &desc);
2241 while (comp != NULL) {
2242 CAComponentDescription temp;
2243 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2245 AUPluginInfoPtr info (new AUPluginInfo
2246 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2248 /* although apple designed the subtype field to be a "category" indicator,
2249 its really turned into a plugin ID field for a given manufacturer. Hence
2250 there are no categories for AudioUnits. However, to keep the plugins
2251 showing up under "categories", we'll use the "type" as a high level
2254 NOTE: no panners, format converters or i/o AU's for our purposes
2257 switch (info->descriptor->Type()) {
2258 case kAudioUnitType_Panner:
2259 case kAudioUnitType_OfflineEffect:
2260 case kAudioUnitType_FormatConverter:
2263 case kAudioUnitType_Output:
2264 info->category = _("AudioUnit Outputs");
2266 case kAudioUnitType_MusicDevice:
2267 info->category = _("AudioUnit Instruments");
2269 case kAudioUnitType_MusicEffect:
2270 info->category = _("AudioUnit MusicEffects");
2272 case kAudioUnitType_Effect:
2273 info->category = _("AudioUnit Effects");
2275 case kAudioUnitType_Mixer:
2276 info->category = _("AudioUnit Mixers");
2278 case kAudioUnitType_Generator:
2279 info->category = _("AudioUnit Generators");
2282 info->category = _("AudioUnit (Unknown)");
2286 AUPluginInfo::get_names (temp, info->name, info->creator);
2288 info->type = ARDOUR::AudioUnit;
2289 info->unique_id = stringify_descriptor (*info->descriptor);
2291 /* XXX not sure of the best way to handle plugin versioning yet
2294 CAComponent cacomp (*info->descriptor);
2296 if (cacomp.GetResourceVersion (info->version) != noErr) {
2300 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2302 /* here we have to map apple's wildcard system to a simple pair
2303 of values. in ::can_do() we use the whole system, but here
2304 we need a single pair of values. XXX probably means we should
2305 remove any use of these values.
2307 for now, if the plugin provides a wildcard, treat it as 1. we really
2308 don't care much, because whether we can handle an i/o configuration
2309 depends upon ::can_support_io_configuration(), not these counts.
2311 they exist because other parts of ardour try to present i/o configuration
2312 info to the user, which should perhaps be revisited.
2315 int32_t possible_in = info->cache.io_configs.front().first;
2316 int32_t possible_out = info->cache.io_configs.front().second;
2318 if (possible_in > 0) {
2319 info->n_inputs.set (DataType::AUDIO, possible_in);
2321 info->n_inputs.set (DataType::AUDIO, 1);
2324 if (possible_out > 0) {
2325 info->n_outputs.set (DataType::AUDIO, possible_out);
2327 info->n_outputs.set (DataType::AUDIO, 1);
2330 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2331 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2333 plugs.push_back (info);
2336 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2339 comp = FindNextComponent (comp, &desc);
2344 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2347 AUPluginCachedInfo& cinfo,
2348 const std::string& name)
2353 /* concatenate unique ID with version to provide a key for cached info lookup.
2354 this ensures we don't get stale information, or should if plugin developers
2355 follow Apple "guidelines".
2358 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2363 CachedInfoMap::iterator cim = cached_info.find (id);
2365 if (cim != cached_info.end()) {
2366 cinfo = cim->second;
2371 AUChannelInfo* channel_info;
2375 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2379 if (CAAudioUnit::Open (comp, unit) != noErr) {
2385 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2390 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2391 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2397 /* no explicit info available, so default to 1in/1out */
2399 /* XXX this is wrong. we should be indicating wildcard values */
2401 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2405 /* store each configuration */
2407 for (uint32_t n = 0; n < cnt; ++n) {
2408 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2409 channel_info[n].outChannels));
2412 free (channel_info);
2415 add_cached_info (id, cinfo);
2416 save_cached_info ();
2422 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2424 cached_info[id] = cinfo;
2427 #define AU_CACHE_VERSION "2.0"
2430 AUPluginInfo::save_cached_info ()
2434 node = new XMLNode (X_("AudioUnitPluginCache"));
2435 node->add_property( "version", AU_CACHE_VERSION );
2437 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2438 XMLNode* parent = new XMLNode (X_("plugin"));
2439 parent->add_property ("id", i->first);
2440 node->add_child_nocopy (*parent);
2442 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2444 XMLNode* child = new XMLNode (X_("io"));
2447 snprintf (buf, sizeof (buf), "%d", j->first);
2448 child->add_property (X_("in"), buf);
2449 snprintf (buf, sizeof (buf), "%d", j->second);
2450 child->add_property (X_("out"), buf);
2451 parent->add_child_nocopy (*child);
2456 Glib::ustring path = au_cache_path ();
2459 tree.set_root (node);
2461 if (!tree.write (path)) {
2462 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2463 unlink (path.c_str());
2468 AUPluginInfo::load_cached_info ()
2470 Glib::ustring path = au_cache_path ();
2473 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2477 if ( !tree.read (path) ) {
2478 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2482 const XMLNode* root (tree.root());
2484 if (root->name() != X_("AudioUnitPluginCache")) {
2488 //initial version has incorrectly stored i/o info, and/or garbage chars.
2489 const XMLProperty* version = root->property(X_("version"));
2490 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2491 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2495 cached_info.clear ();
2497 const XMLNodeList children = root->children();
2499 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2501 const XMLNode* child = *iter;
2503 if (child->name() == X_("plugin")) {
2505 const XMLNode* gchild;
2506 const XMLNodeList gchildren = child->children();
2507 const XMLProperty* prop = child->property (X_("id"));
2513 string id = prop->value();
2517 string::size_type slash = id.find_last_of ('/');
2519 if (slash == string::npos) {
2523 version = id.substr (slash);
2524 id = id.substr (0, slash);
2525 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2527 if (fixed.empty()) {
2528 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2535 AUPluginCachedInfo cinfo;
2537 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2541 if (gchild->name() == X_("io")) {
2545 const XMLProperty* iprop;
2546 const XMLProperty* oprop;
2548 if (((iprop = gchild->property (X_("in"))) != 0) &&
2549 ((oprop = gchild->property (X_("out"))) != 0)) {
2550 in = atoi (iprop->value());
2551 out = atoi (oprop->value());
2553 cinfo.io_configs.push_back (pair<int,int> (in, out));
2558 if (cinfo.io_configs.size()) {
2559 add_cached_info (id, cinfo);
2568 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2570 CFStringRef itemName = NULL;
2572 // Marc Poirier-style item name
2573 CAComponent auComponent (comp_desc);
2574 if (auComponent.IsValid()) {
2575 CAComponentDescription dummydesc;
2576 Handle nameHandle = NewHandle(sizeof(void*));
2577 if (nameHandle != NULL) {
2578 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2580 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2581 if (nameString != NULL) {
2582 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2585 DisposeHandle(nameHandle);
2589 // if Marc-style fails, do the original way
2590 if (itemName == NULL) {
2591 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2592 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2593 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2595 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2596 compTypeString, compManufacturerString, compSubTypeString);
2598 if (compTypeString != NULL)
2599 CFRelease(compTypeString);
2600 if (compSubTypeString != NULL)
2601 CFRelease(compSubTypeString);
2602 if (compManufacturerString != NULL)
2603 CFRelease(compManufacturerString);
2606 string str = CFStringRefToStdString(itemName);
2607 string::size_type colon = str.find (':');
2610 name = str.substr (colon+1);
2611 maker = str.substr (0, colon);
2612 strip_whitespace_edges (maker);
2613 strip_whitespace_edges (name);
2617 strip_whitespace_edges (name);
2622 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2626 /* note: OSType is a compiler-implemenation-defined value,
2627 historically a 32 bit integer created with a multi-character
2628 constant such as 'abcd'. It is, fundamentally, an abomination.
2633 s << desc.SubType();
2641 AUPluginInfo::needs_midi_input ()
2643 return is_effect_with_midi_input () || is_instrument ();
2647 AUPluginInfo::is_effect () const
2649 return is_effect_without_midi_input() || is_effect_with_midi_input();
2653 AUPluginInfo::is_effect_without_midi_input () const
2655 return descriptor->IsAUFX();
2659 AUPluginInfo::is_effect_with_midi_input () const
2661 return descriptor->IsAUFM();
2665 AUPluginInfo::is_instrument () const
2667 return descriptor->IsMusicDevice();
2671 AUPlugin::set_info (PluginInfoPtr info)
2673 Plugin::set_info (info);
2675 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2676 _has_midi_input = pinfo->needs_midi_input ();
2677 _has_midi_output = false;
2681 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2684 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2686 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2688 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2690 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2694 _parameter_listener_arg = arg;
2700 AUPlugin::listen_to_parameter (uint32_t param_id)
2702 AudioUnitEvent event;
2704 if (!_parameter_listener || param_id >= descriptors.size()) {
2708 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2709 event.mArgument.mParameter.mAudioUnit = unit->AU();
2710 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2711 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2712 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2714 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2722 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2724 AudioUnitEvent event;
2726 if (!_parameter_listener || param_id >= descriptors.size()) {
2730 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2731 event.mArgument.mParameter.mAudioUnit = unit->AU();
2732 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2733 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2734 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2736 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2744 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2746 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2750 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2752 ParameterMap::iterator i = parameter_map.find (event->mArgument.mParameter.mParameterID);
2754 if (i != parameter_map.end()) {
2755 ParameterChanged (i->second, new_value);