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/file_utils.h"
32 #include "pbd/locale_guard.h"
34 #include <glibmm/threads.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
37 #include <glib/gstdio.h>
39 #include "ardour/ardour.h"
40 #include "ardour/audioengine.h"
41 #include "ardour/audio_buffer.h"
42 #include "ardour/debug.h"
43 #include "ardour/midi_buffer.h"
44 #include "ardour/filesystem_paths.h"
45 #include "ardour/io.h"
46 #include "ardour/audio_unit.h"
47 #include "ardour/route.h"
48 #include "ardour/session.h"
49 #include "ardour/tempo.h"
50 #include "ardour/utils.h"
52 #include "appleutility/CAAudioUnit.h"
53 #include "appleutility/CAAUParameter.h"
55 #include <CoreFoundation/CoreFoundation.h>
56 #include <CoreServices/CoreServices.h>
57 #include <AudioUnit/AudioUnit.h>
58 #include <AudioToolbox/AudioUnitUtilities.h>
60 #include <Carbon/Carbon.h>
67 using namespace ARDOUR;
69 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
71 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
72 static string preset_suffix = ".aupreset";
73 static bool preset_search_path_initialized = false;
76 _render_callback(void *userData,
77 AudioUnitRenderActionFlags *ioActionFlags,
78 const AudioTimeStamp *inTimeStamp,
80 UInt32 inNumberFrames,
81 AudioBufferList* ioData)
84 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
90 _get_beat_and_tempo_callback (void* userData,
91 Float64* outCurrentBeat,
92 Float64* outCurrentTempo)
95 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
102 _get_musical_time_location_callback (void * userData,
103 UInt32 * outDeltaSampleOffsetToNextBeat,
104 Float32 * outTimeSig_Numerator,
105 UInt32 * outTimeSig_Denominator,
106 Float64 * outCurrentMeasureDownBeat)
109 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
110 outTimeSig_Numerator,
111 outTimeSig_Denominator,
112 outCurrentMeasureDownBeat);
118 _get_transport_state_callback (void* userData,
119 Boolean* outIsPlaying,
120 Boolean* outTransportStateChanged,
121 Float64* outCurrentSampleInTimeLine,
122 Boolean* outIsCycling,
123 Float64* outCycleStartBeat,
124 Float64* outCycleEndBeat)
127 return ((AUPlugin*)userData)->get_transport_state_callback (
128 outIsPlaying, outTransportStateChanged,
129 outCurrentSampleInTimeLine, outIsCycling,
130 outCycleStartBeat, outCycleEndBeat);
137 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
143 // Convert the property list into XML data.
145 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
148 error << _("Could not create XML version of property list") << endmsg;
152 // Write the XML data to the file.
154 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
156 if (errno == EEXIST) {
157 error << string_compose (_("Preset file %1 exists; not overwriting"),
160 error << string_compose (_("Cannot open preset file %1 (%2)"),
161 path, strerror (errno)) << endmsg;
167 size_t cnt = CFDataGetLength (xmlData);
169 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
180 static CFPropertyListRef
181 load_property_list (Glib::ustring path)
184 CFPropertyListRef propertyList = 0;
186 CFStringRef errorString;
188 // Read the XML file.
190 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
195 off_t len = lseek (fd, 0, SEEK_END);
196 char* buf = new char[len];
197 lseek (fd, 0, SEEK_SET);
199 if (read (fd, buf, len) != len) {
207 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
209 // Reconstitute the dictionary using the XML data.
211 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
213 kCFPropertyListImmutable,
222 //-----------------------------------------------------------------------------
224 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
229 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
231 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
232 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
238 //-----------------------------------------------------------------------------
240 get_preset_name_in_plist (CFPropertyListRef plist)
248 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
249 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
251 CFStringRef str = (CFStringRef) p;
252 int len = CFStringGetLength(str);
254 char local_buffer[len];
255 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
263 //--------------------------------------------------------------------------
264 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
265 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
266 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
267 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
269 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
272 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
273 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
275 // only sub-type and manufacturer IDs need to be equal
278 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
279 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
286 //--------------------------------------------------------------------------
287 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
288 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
289 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
290 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
293 ComponentDescription desc;
295 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
298 // get the ComponentDescription of the input Component
299 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
303 // check if the Component's ComponentDescription matches the input ComponentDescription
304 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
307 //--------------------------------------------------------------------------
308 // determine if 2 ComponentDescriptions are basically equal
309 // (by that, I mean that the important identifying values are compared,
310 // but not the ComponentDescription flags)
311 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
313 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
316 //--------------------------------------------------------------------------
317 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
318 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
320 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
323 //--------------------------------------------------------------------------
324 // determine if a ComponentDescription basically matches that of a particular Component
325 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
327 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
330 //--------------------------------------------------------------------------
331 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
332 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
334 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
338 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
339 : Plugin (engine, session)
341 , unit (new CAAudioUnit)
342 , initialized (false)
343 , _current_block_size (0)
344 , _requires_fixed_size_buffers (false)
349 , frames_processed (0)
350 , _parameter_listener (0)
351 , _parameter_listener_arg (0)
352 , last_transport_rolling (false)
353 , last_transport_speed (0.0)
355 if (!preset_search_path_initialized) {
356 Glib::ustring p = Glib::get_home_dir();
357 p += "/Library/Audio/Presets:";
358 p += preset_search_path;
359 preset_search_path = p;
360 preset_search_path_initialized = true;
367 AUPlugin::AUPlugin (const AUPlugin& other)
369 , comp (other.get_comp())
370 , unit (new CAAudioUnit)
371 , initialized (false)
372 , _current_block_size (0)
374 , _requires_fixed_size_buffers (false)
379 , frames_processed (0)
380 , _parameter_listener (0)
381 , _parameter_listener_arg (0)
387 AUPlugin::~AUPlugin ()
389 if (_parameter_listener) {
390 AUListenerDispose (_parameter_listener);
391 _parameter_listener = 0;
395 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
396 unit->Uninitialize ();
405 AUPlugin::discover_factory_presets ()
412 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
413 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
417 assert (dataSize == sizeof (presets));
419 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
420 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
428 CFIndex cnt = CFArrayGetCount (presets);
430 for (CFIndex i = 0; i < cnt; ++i) {
431 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
433 string name = CFStringRefToStdString (preset->presetName);
434 factory_preset_map[name] = preset->presetNumber;
445 /* these keep track of *configured* channel set up,
446 not potential set ups.
450 output_channels = -1;
453 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
454 err = CAAudioUnit::Open (*(comp.get()), *unit);
456 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
457 throw failed_constructor();
461 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
462 throw failed_constructor ();
465 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
466 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
467 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
468 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
469 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
470 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
472 if (input_elements > 0) {
473 /* setup render callback: the plugin calls this to get input data
476 AURenderCallbackStruct renderCallbackInfo;
478 renderCallbackInfo.inputProc = _render_callback;
479 renderCallbackInfo.inputProcRefCon = this;
481 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
482 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
483 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
484 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
485 throw failed_constructor();
489 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
491 HostCallbackInfo info;
492 memset (&info, 0, sizeof (HostCallbackInfo));
493 info.hostUserData = this;
494 info.beatAndTempoProc = _get_beat_and_tempo_callback;
495 info.musicalTimeLocationProc = _get_musical_time_location_callback;
496 info.transportStateProc = _get_transport_state_callback;
498 //ignore result of this - don't care if the property isn't supported
499 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
500 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
501 kAudioUnitScope_Global,
504 sizeof (HostCallbackInfo));
506 if (set_block_size (_session.get_block_size())) {
507 error << _("AUPlugin: cannot set processing block size") << endmsg;
508 throw failed_constructor();
511 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
512 discover_parameters ();
513 discover_factory_presets ();
515 // Plugin::setup_controls ();
519 AUPlugin::discover_parameters ()
521 /* discover writable parameters */
523 AudioUnitScope scopes[] = {
524 kAudioUnitScope_Global,
525 kAudioUnitScope_Output,
526 kAudioUnitScope_Input
529 descriptors.clear ();
531 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
533 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
535 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
537 AUParameterDescriptor d;
539 d.id = param_info.ParamID (i);
541 const CAAUParameter* param = param_info.GetParamInfo (d.id);
542 const AudioUnitParameterInfo& info (param->ParamInfo());
544 const int len = CFStringGetLength (param->GetName());;
545 char local_buffer[len*2];
546 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
550 d.label = local_buffer;
553 d.scope = param_info.GetScope ();
554 d.element = param_info.GetElement ();
556 /* info.units to consider */
558 kAudioUnitParameterUnit_Generic = 0
559 kAudioUnitParameterUnit_Indexed = 1
560 kAudioUnitParameterUnit_Boolean = 2
561 kAudioUnitParameterUnit_Percent = 3
562 kAudioUnitParameterUnit_Seconds = 4
563 kAudioUnitParameterUnit_SampleFrames = 5
564 kAudioUnitParameterUnit_Phase = 6
565 kAudioUnitParameterUnit_Rate = 7
566 kAudioUnitParameterUnit_Hertz = 8
567 kAudioUnitParameterUnit_Cents = 9
568 kAudioUnitParameterUnit_RelativeSemiTones = 10
569 kAudioUnitParameterUnit_MIDINoteNumber = 11
570 kAudioUnitParameterUnit_MIDIController = 12
571 kAudioUnitParameterUnit_Decibels = 13
572 kAudioUnitParameterUnit_LinearGain = 14
573 kAudioUnitParameterUnit_Degrees = 15
574 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
575 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
576 kAudioUnitParameterUnit_Pan = 18
577 kAudioUnitParameterUnit_Meters = 19
578 kAudioUnitParameterUnit_AbsoluteCents = 20
579 kAudioUnitParameterUnit_Octaves = 21
580 kAudioUnitParameterUnit_BPM = 22
581 kAudioUnitParameterUnit_Beats = 23
582 kAudioUnitParameterUnit_Milliseconds = 24
583 kAudioUnitParameterUnit_Ratio = 25
586 /* info.flags to consider */
590 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
591 kAudioUnitParameterFlag_HasClump = (1L << 20)
592 kAudioUnitParameterFlag_HasName = (1L << 21)
593 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
594 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
595 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
596 kAudioUnitParameterFlag_CanRamp = (1L << 25)
597 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
598 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
599 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
600 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
601 kAudioUnitParameterFlag_IsReadable = (1L << 30)
602 kAudioUnitParameterFlag_IsWritable = (1L << 31)
605 d.lower = info.minValue;
606 d.upper = info.maxValue;
607 d.default_value = info.defaultValue;
609 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
610 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
611 (d.integer_step && ((d.upper - d.lower) == 1.0));
612 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
613 d.automatable = !d.toggled &&
614 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
615 (info.flags & kAudioUnitParameterFlag_IsWritable);
617 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
623 d.min_unbound = 0; // lower is bound
624 d.max_unbound = 0; // upper is bound
626 descriptors.push_back (d);
628 uint32_t last_param = descriptors.size() - 1;
629 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
630 listen_to_parameter (last_param);
637 four_ints_to_four_byte_literal (unsigned char n[4])
639 /* this is actually implementation dependent. sigh. this is what gcc
640 and quite a few others do.
642 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
646 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
648 if (isdigit (id[0])) {
652 /* ID format is xxxx-xxxx-xxxx
653 where x maybe \xNN or a printable character.
655 Split at the '-' and and process each part into an integer.
656 Then put it back together.
660 unsigned char nascent[4];
661 const char* cstr = id.c_str();
662 const char* estr = cstr + id.size();
673 while (*cstr && next_int < 4) {
677 if (estr - cstr < 3) {
679 /* too close to the end for \xNN parsing: treat as literal characters */
687 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
691 memcpy (short_buf, &cstr[2], 2);
692 nascent[in] = strtol (short_buf, NULL, 16);
698 /* treat as literal characters */
712 if (in && (in % 4 == 0)) {
713 /* nascent is ready */
714 n[next_int] = four_ints_to_four_byte_literal (nascent);
718 /* swallow space-hyphen-space */
732 s << n[0] << '-' << n[1] << '-' << n[2];
741 AUPlugin::unique_id () const
743 return AUPluginInfo::stringify_descriptor (comp->Desc());
747 AUPlugin::label () const
749 return _info->name.c_str();
753 AUPlugin::parameter_count () const
755 return descriptors.size();
759 AUPlugin::default_value (uint32_t port)
761 if (port < descriptors.size()) {
762 return descriptors[port].default_value;
769 AUPlugin::signal_latency () const
771 return unit->Latency() * _session.frame_rate();
775 AUPlugin::set_parameter (uint32_t which, float val)
777 if (which >= descriptors.size()) {
781 if (get_parameter(which) == val) {
785 const AUParameterDescriptor& d (descriptors[which]);
786 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
787 unit->SetParameter (d.id, d.scope, d.element, val);
789 /* tell the world what we did */
791 AudioUnitEvent theEvent;
793 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
794 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
795 theEvent.mArgument.mParameter.mParameterID = d.id;
796 theEvent.mArgument.mParameter.mScope = d.scope;
797 theEvent.mArgument.mParameter.mElement = d.element;
799 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
800 AUEventListenerNotify (NULL, NULL, &theEvent);
802 Plugin::set_parameter (which, val);
806 AUPlugin::get_parameter (uint32_t which) const
809 if (which < descriptors.size()) {
810 const AUParameterDescriptor& d (descriptors[which]);
811 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
812 unit->GetParameter(d.id, d.scope, d.element, val);
818 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
820 if (which < descriptors.size()) {
821 pd = descriptors[which];
828 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
830 if (which < descriptors.size()) {
839 AUPlugin::activate ()
843 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
844 if ((err = unit->Initialize()) != noErr) {
845 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
847 frames_processed = 0;
854 AUPlugin::deactivate ()
856 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
857 unit->Uninitialize ();
864 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
865 unit->GlobalReset ();
869 AUPlugin::requires_fixed_size_buffers() const
871 return _requires_fixed_size_buffers;
876 AUPlugin::set_block_size (pframes_t nframes)
878 bool was_initialized = initialized;
879 UInt32 numFrames = nframes;
886 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
887 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
888 0, &numFrames, sizeof (numFrames))) != noErr) {
889 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
893 if (was_initialized) {
897 _current_block_size = nframes;
903 AUPlugin::configure_io (ChanCount in, ChanCount out)
905 AudioStreamBasicDescription streamFormat;
906 bool was_initialized = initialized;
907 int32_t audio_in = in.n_audio();
908 int32_t audio_out = out.n_audio();
910 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
913 //if we are already running with the requested i/o config, bail out here
914 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
921 streamFormat.mSampleRate = _session.frame_rate();
922 streamFormat.mFormatID = kAudioFormatLinearPCM;
923 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
925 #ifdef __LITTLE_ENDIAN__
928 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
931 streamFormat.mBitsPerChannel = 32;
932 streamFormat.mFramesPerPacket = 1;
934 /* apple says that for non-interleaved data, these
935 values always refer to a single channel.
937 streamFormat.mBytesPerPacket = 4;
938 streamFormat.mBytesPerFrame = 4;
940 streamFormat.mChannelsPerFrame = audio_in;
942 if (set_input_format (streamFormat) != 0) {
946 streamFormat.mChannelsPerFrame = audio_out;
948 if (set_output_format (streamFormat) != 0) {
952 /* reset plugin info to show currently configured state */
954 _info->n_inputs = in;
955 _info->n_outputs = out;
957 if (was_initialized) {
965 AUPlugin::input_streams() const
969 c.set (DataType::AUDIO, 1);
970 c.set (DataType::MIDI, 0);
972 if (input_channels < 0) {
973 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
975 c.set (DataType::AUDIO, input_channels);
976 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
984 AUPlugin::output_streams() const
988 c.set (DataType::AUDIO, 1);
989 c.set (DataType::MIDI, 0);
991 if (output_channels < 0) {
992 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
994 c.set (DataType::AUDIO, output_channels);
995 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1002 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1004 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1006 int32_t audio_in = in.n_audio();
1009 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1011 /* lets check MIDI first */
1013 if (in.n_midi() > 0) {
1014 if (!_has_midi_input) {
1019 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1021 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1022 name(), io_configs.size(), in, out));
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: %1 in %2 out to match in %3 out %4\n",
1038 possible_in, possible_out,
1041 out.set (DataType::MIDI, 0);
1042 out.set (DataType::AUDIO, audio_out);
1048 /* now allow potentially "imprecise" matches */
1052 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1054 int32_t possible_in = i->first;
1055 int32_t possible_out = i->second;
1057 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1059 if (possible_out == 0) {
1060 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1061 /* XXX surely this is just a send? (e.g. AUNetSend) */
1065 if (possible_in == 0) {
1067 /* instrument plugin, always legal but throws away inputs ...
1070 if (possible_out == -1) {
1071 /* any configuration possible, provide stereo output */
1074 } else if (possible_out == -2) {
1075 /* plugins shouldn't really use (0,-2) but might.
1076 any configuration possible, provide stereo output
1080 } else if (possible_out < -2) {
1081 /* explicitly variable number of outputs.
1083 Since Ardour can handle any configuration,
1084 we have to somehow pick a number.
1086 We'll use the number of inputs
1087 to the master bus, or 2 if there
1090 boost::shared_ptr<Route> master = _session.master_out();
1092 audio_out = master->input()->n_ports().n_audio();
1098 /* exact number of outputs */
1099 audio_out = possible_out;
1104 if (possible_in == -1) {
1106 /* wildcard for input */
1108 if (possible_out == -1) {
1109 /* out much match in */
1110 audio_out = audio_in;
1112 } else if (possible_out == -2) {
1113 /* any configuration possible, pick matching */
1114 audio_out = audio_in;
1116 } else if (possible_out < -2) {
1117 /* explicitly variable number of outputs, pick maximum */
1118 audio_out = -possible_out;
1121 /* exact number of outputs */
1122 audio_out = possible_out;
1127 if (possible_in == -2) {
1129 if (possible_out == -1) {
1130 /* any configuration possible, pick matching */
1131 audio_out = audio_in;
1133 } else if (possible_out == -2) {
1134 /* plugins shouldn't really use (-2,-2) but might.
1135 interpret as (-1,-1).
1137 audio_out = audio_in;
1139 } else if (possible_out < -2) {
1140 /* explicitly variable number of outputs, pick maximum */
1141 audio_out = -possible_out;
1144 /* exact number of outputs */
1145 audio_out = possible_out;
1150 if (possible_in < -2) {
1152 /* explicit variable number of inputs */
1154 if (audio_in > -possible_in) {
1155 /* request is too large */
1159 if (possible_out == -1) {
1160 /* any output configuration possible, provide stereo out */
1163 } else if (possible_out == -2) {
1164 /* plugins shouldn't really use (<-2,-2) but might.
1165 interpret as (<-2,-1): any configuration possible, provide stereo output
1169 } else if (possible_out < -2) {
1170 /* explicitly variable number of outputs.
1172 Since Ardour can handle any configuration,
1173 we have to somehow pick a number.
1175 We'll use the number of inputs
1176 to the master bus, or 2 if there
1179 boost::shared_ptr<Route> master = _session.master_out();
1181 audio_out = master->input()->n_ports().n_audio();
1187 /* exact number of outputs */
1188 audio_out = possible_out;
1193 if (possible_in && (possible_in == audio_in)) {
1195 /* exact number of inputs ... must match obviously */
1197 if (possible_out == -1) {
1198 /* any output configuration possible, provide stereo output */
1201 } else if (possible_out == -2) {
1202 /* plugins shouldn't really use (>0,-2) but might.
1203 interpret as (>0,-1):
1204 any output configuration possible, provide stereo output
1208 } else if (possible_out < -2) {
1209 /* explicitly variable number of outputs, pick maximum */
1210 audio_out = -possible_out;
1213 /* exact number of outputs */
1214 audio_out = possible_out;
1226 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1228 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1232 out.set (DataType::MIDI, 0);
1233 out.set (DataType::AUDIO, audio_out);
1239 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1241 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1245 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1247 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1256 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1257 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1263 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1267 for (uint32_t i = 0; i < cnt; ++i) {
1268 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1269 (scope == kAudioUnitScope_Input ? "input" : "output"),
1271 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1272 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1273 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1278 if (scope == kAudioUnitScope_Input) {
1279 input_channels = fmt.mChannelsPerFrame;
1281 output_channels = fmt.mChannelsPerFrame;
1288 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1289 const AudioTimeStamp*,
1291 UInt32 inNumberFrames,
1292 AudioBufferList* ioData)
1294 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1296 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1297 // name(), inNumberFrames, ioData->mNumberBuffers));
1299 if (input_maxbuf == 0) {
1300 error << _("AUPlugin: render callback called illegally!") << endmsg;
1301 return kAudioUnitErr_CannotDoInCurrentContext;
1303 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1305 for (uint32_t i = 0; i < limit; ++i) {
1306 ioData->mBuffers[i].mNumberChannels = 1;
1307 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1309 /* we don't use the channel mapping because audiounits are
1310 never replicated. one plugin instance uses all channels/buffers
1311 passed to PluginInsert::connect_and_run()
1314 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1317 cb_offset += inNumberFrames;
1323 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1325 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1327 AudioUnitRenderActionFlags flags = 0;
1331 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1332 unit->GlobalReset();
1333 _last_nframes = nframes;
1336 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1337 name(), input_channels, output_channels, _has_midi_input,
1338 bufs.count(), bufs.available()));
1340 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1341 has the capacity to handle our outputs.
1344 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1346 input_buffers = &bufs;
1347 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1348 input_offset = offset;
1351 buffers->mNumberBuffers = output_channels;
1353 for (int32_t i = 0; i < output_channels; ++i) {
1354 buffers->mBuffers[i].mNumberChannels = 1;
1355 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1356 /* setting this to 0 indicates to the AU that it can provide buffers here
1357 if necessary. if it can process in-place, it will use the buffers provided
1358 as input by ::render_callback() above.
1360 a non-null values tells the plugin to render into the buffer pointed
1363 buffers->mBuffers[i].mData = 0;
1366 if (_has_midi_input) {
1368 uint32_t nmidi = bufs.count().n_midi();
1370 for (uint32_t i = 0; i < nmidi; ++i) {
1372 /* one MIDI port/buffer only */
1374 MidiBuffer& m = bufs.get_midi (i);
1376 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1377 Evoral::MIDIEvent<framepos_t> ev (*i);
1379 if (ev.is_channel_event()) {
1380 const uint8_t* b = ev.buffer();
1381 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1382 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1385 /* XXX need to handle sysex and other message types */
1390 /* does this really mean anything ?
1393 ts.mSampleTime = frames_processed;
1394 ts.mFlags = kAudioTimeStampSampleTimeValid;
1396 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1397 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1399 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1402 frames_processed += nframes;
1404 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1405 name(), buffers->mNumberBuffers, output_channels));
1407 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1410 for (i = 0; i < limit; ++i) {
1411 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1412 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1413 /* plugin provided its own buffer for output so copy it back to where we want it
1415 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1419 /* now silence any buffers that were passed in but the that the plugin
1420 did not fill/touch/use.
1423 for (;i < output_channels; ++i) {
1424 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1430 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1435 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1436 Float64* outCurrentTempo)
1438 TempoMap& tmap (_session.tempo_map());
1440 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1442 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1443 (and interpretation) of a beat position will be incorrect. So refuse to
1447 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1448 return kAudioUnitErr_CannotDoInCurrentContext;
1451 Timecode::BBT_Time bbt;
1452 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1453 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1455 if (outCurrentBeat) {
1457 beat = metric.meter().divisions_per_bar() * bbt.bars;
1459 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1460 *outCurrentBeat = beat;
1463 if (outCurrentTempo) {
1464 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1472 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1473 Float32* outTimeSig_Numerator,
1474 UInt32* outTimeSig_Denominator,
1475 Float64* outCurrentMeasureDownBeat)
1477 TempoMap& tmap (_session.tempo_map());
1479 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1481 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1482 (and interpretation) of a beat position will be incorrect. So refuse to
1486 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1487 return kAudioUnitErr_CannotDoInCurrentContext;
1490 Timecode::BBT_Time bbt;
1491 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1492 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1494 if (outDeltaSampleOffsetToNextBeat) {
1495 if (bbt.ticks == 0) {
1497 *outDeltaSampleOffsetToNextBeat = 0;
1499 *outDeltaSampleOffsetToNextBeat = (UInt32)
1500 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1501 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1505 if (outTimeSig_Numerator) {
1506 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1508 if (outTimeSig_Denominator) {
1509 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1512 if (outCurrentMeasureDownBeat) {
1514 /* beat for the start of the bar.
1516 2|1|0 -> 1 + divisions_per_bar
1517 3|1|0 -> 1 + (2 * divisions_per_bar)
1521 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1528 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1529 Boolean* outTransportStateChanged,
1530 Float64* outCurrentSampleInTimeLine,
1531 Boolean* outIsCycling,
1532 Float64* outCycleStartBeat,
1533 Float64* outCycleEndBeat)
1538 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1540 rolling = _session.transport_rolling();
1541 speed = _session.transport_speed ();
1544 *outIsPlaying = _session.transport_rolling();
1547 if (outTransportStateChanged) {
1548 if (rolling != last_transport_rolling) {
1549 *outTransportStateChanged = true;
1550 } else if (speed != last_transport_speed) {
1551 *outTransportStateChanged = true;
1553 *outTransportStateChanged = false;
1557 if (outCurrentSampleInTimeLine) {
1558 /* this assumes that the AU can only call this host callback from render context,
1559 where input_offset is valid.
1561 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1565 Location* loc = _session.locations()->auto_loop_location();
1567 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1569 if (*outIsCycling) {
1571 if (outCycleStartBeat || outCycleEndBeat) {
1573 TempoMap& tmap (_session.tempo_map());
1575 /* more than 1 meter means that a simplistic computation (and interpretation) of
1576 a beat position will be incorrect. so refuse to offer the value.
1579 if (tmap.n_meters() > 1) {
1580 return kAudioUnitErr_CannotDoInCurrentContext;
1583 Timecode::BBT_Time bbt;
1585 if (outCycleStartBeat) {
1586 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1587 _session.tempo_map().bbt_time (loc->start(), bbt);
1590 beat = metric.meter().divisions_per_bar() * bbt.bars;
1592 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1594 *outCycleStartBeat = beat;
1597 if (outCycleEndBeat) {
1598 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1599 _session.tempo_map().bbt_time (loc->end(), bbt);
1602 beat = metric.meter().divisions_per_bar() * bbt.bars;
1604 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1606 *outCycleEndBeat = beat;
1612 last_transport_rolling = rolling;
1613 last_transport_speed = speed;
1618 set<Evoral::Parameter>
1619 AUPlugin::automatable() const
1621 set<Evoral::Parameter> automates;
1623 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1624 if (descriptors[i].automatable) {
1625 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1633 AUPlugin::describe_parameter (Evoral::Parameter param)
1635 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1636 return descriptors[param.id()].label;
1643 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1645 // NameValue stuff here
1649 AUPlugin::parameter_is_audio (uint32_t) const
1655 AUPlugin::parameter_is_control (uint32_t) const
1661 AUPlugin::parameter_is_input (uint32_t) const
1667 AUPlugin::parameter_is_output (uint32_t) const
1673 AUPlugin::add_state (XMLNode* root) const
1675 LocaleGuard lg (X_("POSIX"));
1677 CFPropertyListRef propertyList;
1679 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1680 if (unit->GetAUPreset (propertyList) != noErr) {
1684 // Convert the property list into XML data.
1686 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1689 error << _("Could not create XML version of property list") << endmsg;
1693 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1694 our state node. GACK!
1699 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1701 root->add_child_copy (*t.root());
1705 CFRelease (xmlData);
1706 CFRelease (propertyList);
1710 AUPlugin::set_state(const XMLNode& node, int version)
1713 CFPropertyListRef propertyList;
1714 LocaleGuard lg (X_("POSIX"));
1716 if (node.name() != state_node_name()) {
1717 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1721 #ifndef NO_PLUGIN_STATE
1722 if (node.children().empty()) {
1726 XMLNode* top = node.children().front();
1727 XMLNode* copy = new XMLNode (*top);
1732 const string& xml = t.write_buffer ();
1733 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1734 CFStringRef errorString;
1736 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1738 kCFPropertyListImmutable,
1741 CFRelease (xmlData);
1744 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1745 if (unit->SetAUPreset (propertyList) == noErr) {
1748 /* tell the world */
1750 AudioUnitParameter changedUnit;
1751 changedUnit.mAudioUnit = unit->AU();
1752 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1753 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1755 CFRelease (propertyList);
1759 Plugin::set_state (node, version);
1764 AUPlugin::load_preset (PresetRecord r)
1766 Plugin::load_preset (r);
1769 CFPropertyListRef propertyList;
1771 UserPresetMap::iterator ux;
1772 FactoryPresetMap::iterator fx;
1774 /* look first in "user" presets */
1776 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1778 if ((propertyList = load_property_list (ux->second)) != 0) {
1779 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1780 if (unit->SetAUPreset (propertyList) == noErr) {
1783 /* tell the world */
1785 AudioUnitParameter changedUnit;
1786 changedUnit.mAudioUnit = unit->AU();
1787 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1788 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1790 CFRelease(propertyList);
1793 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1797 preset.presetNumber = fx->second;
1798 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1800 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1802 if (unit->SetPresentPreset (preset) == 0) {
1805 /* tell the world */
1807 AudioUnitParameter changedUnit;
1808 changedUnit.mAudioUnit = unit->AU();
1809 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1810 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1818 AUPlugin::do_remove_preset (std::string)
1823 AUPlugin::do_save_preset (string preset_name)
1825 CFPropertyListRef propertyList;
1826 vector<Glib::ustring> v;
1827 Glib::ustring user_preset_path;
1829 std::string m = maker();
1830 std::string n = name();
1832 strip_whitespace_edges (m);
1833 strip_whitespace_edges (n);
1835 v.push_back (Glib::get_home_dir());
1836 v.push_back ("Library");
1837 v.push_back ("Audio");
1838 v.push_back ("Presets");
1842 user_preset_path = Glib::build_filename (v);
1844 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1845 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1849 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1850 if (unit->GetAUPreset (propertyList) != noErr) {
1854 // add the actual preset name */
1856 v.push_back (preset_name + preset_suffix);
1860 user_preset_path = Glib::build_filename (v);
1862 set_preset_name_in_plist (propertyList, preset_name);
1864 if (save_property_list (propertyList, user_preset_path)) {
1865 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1869 CFRelease(propertyList);
1871 return string ("file:///") + user_preset_path;
1874 //-----------------------------------------------------------------------------
1875 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1877 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1879 CFNumberRef cfNumber;
1880 SInt32 numberValue = 0;
1881 Boolean dummySuccess;
1883 if (outSuccess == NULL)
1884 outSuccess = &dummySuccess;
1885 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1887 *outSuccess = FALSE;
1891 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1892 if (cfNumber == NULL)
1894 *outSuccess = FALSE;
1897 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1905 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1907 CFDictionaryRef auStateDictionary;
1908 ComponentDescription tempDesc = {0,0,0,0,0};
1909 SInt32 versionValue;
1912 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1915 // the property list for AU state data must be of the dictionary type
1916 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1917 return kAudioUnitErr_InvalidPropertyValue;
1920 auStateDictionary = (CFDictionaryRef)inAUStateData;
1922 // first check to make sure that the version of the AU state data is one that we know understand
1923 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1924 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1927 return kAudioUnitErr_InvalidPropertyValue;
1929 #define kCurrentSavedStateVersion 0
1930 if (versionValue != kCurrentSavedStateVersion) {
1931 return kAudioUnitErr_InvalidPropertyValue;
1934 // grab the ComponentDescription values from the AU state data
1935 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1936 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1937 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1938 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1939 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1940 return kAudioUnitErr_InvalidPropertyValue;
1942 *outComponentDescription = tempDesc;
1947 static bool au_preset_filter (const string& str, void* arg)
1949 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1953 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1957 /* check the preset file path name against this plugin
1958 ID. The idea is that all preset files for this plugin
1959 include "<manufacturer>/<plugin-name>" in their path.
1962 Plugin* p = (Plugin *) arg;
1963 string match = p->maker();
1967 ret = str.find (match) != string::npos;
1970 string m = p->maker ();
1971 string n = p->name ();
1972 strip_whitespace_edges (m);
1973 strip_whitespace_edges (n);
1978 ret = str.find (match) != string::npos;
1986 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1989 CFPropertyListRef plist;
1990 ComponentDescription presetDesc;
1993 plist = load_property_list (pathstr);
1999 // get the ComponentDescription from the AU preset file
2001 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2003 if (status == noErr) {
2004 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2006 /* try to get the preset name from the property list */
2008 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2010 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2014 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2017 char buf[PATH_MAX+1];
2019 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2034 AUPlugin::current_preset() const
2038 CFPropertyListRef propertyList;
2040 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2041 if (unit->GetAUPreset (propertyList) == noErr) {
2042 preset_name = get_preset_name_in_plist (propertyList);
2043 CFRelease(propertyList);
2050 AUPlugin::find_presets ()
2052 vector<string> preset_files;
2054 user_preset_map.clear ();
2056 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2058 if (preset_files.empty()) {
2062 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2067 /* make an initial guess at the preset name using the path */
2069 preset_name = Glib::path_get_basename (path);
2070 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2072 /* check that this preset file really matches this plugin
2073 and potentially get the "real" preset name from
2077 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2078 user_preset_map[preset_name] = path;
2083 /* now fill the vector<string> with the names we have */
2085 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2086 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2089 /* add factory presets */
2091 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2093 string const uri = string_compose ("%1", _presets.size ());
2094 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2099 AUPlugin::has_editor () const
2101 // even if the plugin doesn't have its own editor, the AU API can be used
2102 // to create one that looks native.
2106 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2109 type = ARDOUR::AudioUnit;
2112 AUPluginInfo::~AUPluginInfo ()
2114 type = ARDOUR::AudioUnit;
2118 AUPluginInfo::load (Session& session)
2123 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2124 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2126 if (!comp->IsValid()) {
2127 error << ("AudioUnit: not a valid Component") << endmsg;
2129 plugin.reset (new AUPlugin (session.engine(), session, comp));
2132 AUPluginInfo *aup = new AUPluginInfo (*this);
2133 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2134 plugin->set_info (PluginInfoPtr (aup));
2135 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2139 catch (failed_constructor &err) {
2140 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2141 return PluginPtr ();
2146 AUPluginInfo::au_cache_path ()
2148 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2152 AUPluginInfo::discover ()
2156 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2157 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2160 PluginInfoList* plugs = new PluginInfoList;
2162 discover_fx (*plugs);
2163 discover_music (*plugs);
2164 discover_generators (*plugs);
2165 discover_instruments (*plugs);
2167 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2173 AUPluginInfo::discover_music (PluginInfoList& plugs)
2175 CAComponentDescription desc;
2176 desc.componentFlags = 0;
2177 desc.componentFlagsMask = 0;
2178 desc.componentSubType = 0;
2179 desc.componentManufacturer = 0;
2180 desc.componentType = kAudioUnitType_MusicEffect;
2182 discover_by_description (plugs, desc);
2186 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2188 CAComponentDescription desc;
2189 desc.componentFlags = 0;
2190 desc.componentFlagsMask = 0;
2191 desc.componentSubType = 0;
2192 desc.componentManufacturer = 0;
2193 desc.componentType = kAudioUnitType_Effect;
2195 discover_by_description (plugs, desc);
2199 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2201 CAComponentDescription desc;
2202 desc.componentFlags = 0;
2203 desc.componentFlagsMask = 0;
2204 desc.componentSubType = 0;
2205 desc.componentManufacturer = 0;
2206 desc.componentType = kAudioUnitType_Generator;
2208 discover_by_description (plugs, desc);
2212 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2214 CAComponentDescription desc;
2215 desc.componentFlags = 0;
2216 desc.componentFlagsMask = 0;
2217 desc.componentSubType = 0;
2218 desc.componentManufacturer = 0;
2219 desc.componentType = kAudioUnitType_MusicDevice;
2221 discover_by_description (plugs, desc);
2225 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2229 comp = FindNextComponent (NULL, &desc);
2231 while (comp != NULL) {
2232 CAComponentDescription temp;
2233 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2235 AUPluginInfoPtr info (new AUPluginInfo
2236 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2238 /* although apple designed the subtype field to be a "category" indicator,
2239 its really turned into a plugin ID field for a given manufacturer. Hence
2240 there are no categories for AudioUnits. However, to keep the plugins
2241 showing up under "categories", we'll use the "type" as a high level
2244 NOTE: no panners, format converters or i/o AU's for our purposes
2247 switch (info->descriptor->Type()) {
2248 case kAudioUnitType_Panner:
2249 case kAudioUnitType_OfflineEffect:
2250 case kAudioUnitType_FormatConverter:
2253 case kAudioUnitType_Output:
2254 info->category = _("AudioUnit Outputs");
2256 case kAudioUnitType_MusicDevice:
2257 info->category = _("AudioUnit Instruments");
2259 case kAudioUnitType_MusicEffect:
2260 info->category = _("AudioUnit MusicEffects");
2262 case kAudioUnitType_Effect:
2263 info->category = _("AudioUnit Effects");
2265 case kAudioUnitType_Mixer:
2266 info->category = _("AudioUnit Mixers");
2268 case kAudioUnitType_Generator:
2269 info->category = _("AudioUnit Generators");
2272 info->category = _("AudioUnit (Unknown)");
2276 AUPluginInfo::get_names (temp, info->name, info->creator);
2277 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2279 info->type = ARDOUR::AudioUnit;
2280 info->unique_id = stringify_descriptor (*info->descriptor);
2282 /* XXX not sure of the best way to handle plugin versioning yet
2285 CAComponent cacomp (*info->descriptor);
2287 if (cacomp.GetResourceVersion (info->version) != noErr) {
2291 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2293 /* here we have to map apple's wildcard system to a simple pair
2294 of values. in ::can_do() we use the whole system, but here
2295 we need a single pair of values. XXX probably means we should
2296 remove any use of these values.
2298 for now, if the plugin provides a wildcard, treat it as 1. we really
2299 don't care much, because whether we can handle an i/o configuration
2300 depends upon ::can_support_io_configuration(), not these counts.
2302 they exist because other parts of ardour try to present i/o configuration
2303 info to the user, which should perhaps be revisited.
2306 int32_t possible_in = info->cache.io_configs.front().first;
2307 int32_t possible_out = info->cache.io_configs.front().second;
2309 if (possible_in > 0) {
2310 info->n_inputs.set (DataType::AUDIO, possible_in);
2312 info->n_inputs.set (DataType::AUDIO, 1);
2315 if (possible_out > 0) {
2316 info->n_outputs.set (DataType::AUDIO, possible_out);
2318 info->n_outputs.set (DataType::AUDIO, 1);
2321 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2322 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2324 plugs.push_back (info);
2327 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2330 comp = FindNextComponent (comp, &desc);
2335 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2338 AUPluginCachedInfo& cinfo,
2339 const std::string& name)
2344 /* concatenate unique ID with version to provide a key for cached info lookup.
2345 this ensures we don't get stale information, or should if plugin developers
2346 follow Apple "guidelines".
2349 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2354 CachedInfoMap::iterator cim = cached_info.find (id);
2356 if (cim != cached_info.end()) {
2357 cinfo = cim->second;
2362 AUChannelInfo* channel_info;
2366 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2370 if (CAAudioUnit::Open (comp, unit) != noErr) {
2376 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2381 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2382 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2388 /* no explicit info available, so default to 1in/1out */
2390 /* XXX this is wrong. we should be indicating wildcard values */
2392 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2396 /* store each configuration */
2398 for (uint32_t n = 0; n < cnt; ++n) {
2399 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2400 channel_info[n].outChannels));
2403 free (channel_info);
2406 add_cached_info (id, cinfo);
2407 save_cached_info ();
2413 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2415 cached_info[id] = cinfo;
2418 #define AU_CACHE_VERSION "2.0"
2421 AUPluginInfo::save_cached_info ()
2425 node = new XMLNode (X_("AudioUnitPluginCache"));
2426 node->add_property( "version", AU_CACHE_VERSION );
2428 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2429 XMLNode* parent = new XMLNode (X_("plugin"));
2430 parent->add_property ("id", i->first);
2431 node->add_child_nocopy (*parent);
2433 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2435 XMLNode* child = new XMLNode (X_("io"));
2438 snprintf (buf, sizeof (buf), "%d", j->first);
2439 child->add_property (X_("in"), buf);
2440 snprintf (buf, sizeof (buf), "%d", j->second);
2441 child->add_property (X_("out"), buf);
2442 parent->add_child_nocopy (*child);
2447 Glib::ustring path = au_cache_path ();
2450 tree.set_root (node);
2452 if (!tree.write (path)) {
2453 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2454 g_unlink (path.c_str());
2459 AUPluginInfo::load_cached_info ()
2461 Glib::ustring path = au_cache_path ();
2464 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2468 if ( !tree.read (path) ) {
2469 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2473 const XMLNode* root (tree.root());
2475 if (root->name() != X_("AudioUnitPluginCache")) {
2479 //initial version has incorrectly stored i/o info, and/or garbage chars.
2480 const XMLProperty* version = root->property(X_("version"));
2481 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2482 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2486 cached_info.clear ();
2488 const XMLNodeList children = root->children();
2490 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2492 const XMLNode* child = *iter;
2494 if (child->name() == X_("plugin")) {
2496 const XMLNode* gchild;
2497 const XMLNodeList gchildren = child->children();
2498 const XMLProperty* prop = child->property (X_("id"));
2504 string id = prop->value();
2508 string::size_type slash = id.find_last_of ('/');
2510 if (slash == string::npos) {
2514 version = id.substr (slash);
2515 id = id.substr (0, slash);
2516 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2518 if (fixed.empty()) {
2519 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2526 AUPluginCachedInfo cinfo;
2528 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2532 if (gchild->name() == X_("io")) {
2536 const XMLProperty* iprop;
2537 const XMLProperty* oprop;
2539 if (((iprop = gchild->property (X_("in"))) != 0) &&
2540 ((oprop = gchild->property (X_("out"))) != 0)) {
2541 in = atoi (iprop->value());
2542 out = atoi (oprop->value());
2544 cinfo.io_configs.push_back (pair<int,int> (in, out));
2549 if (cinfo.io_configs.size()) {
2550 add_cached_info (id, cinfo);
2559 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2561 CFStringRef itemName = NULL;
2563 // Marc Poirier-style item name
2564 CAComponent auComponent (comp_desc);
2565 if (auComponent.IsValid()) {
2566 CAComponentDescription dummydesc;
2567 Handle nameHandle = NewHandle(sizeof(void*));
2568 if (nameHandle != NULL) {
2569 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2571 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2572 if (nameString != NULL) {
2573 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2576 DisposeHandle(nameHandle);
2580 // if Marc-style fails, do the original way
2581 if (itemName == NULL) {
2582 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2583 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2584 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2586 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2587 compTypeString, compManufacturerString, compSubTypeString);
2589 if (compTypeString != NULL)
2590 CFRelease(compTypeString);
2591 if (compSubTypeString != NULL)
2592 CFRelease(compSubTypeString);
2593 if (compManufacturerString != NULL)
2594 CFRelease(compManufacturerString);
2597 string str = CFStringRefToStdString(itemName);
2598 string::size_type colon = str.find (':');
2601 name = str.substr (colon+1);
2602 maker = str.substr (0, colon);
2603 strip_whitespace_edges (maker);
2604 strip_whitespace_edges (name);
2608 strip_whitespace_edges (name);
2613 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2617 /* note: OSType is a compiler-implemenation-defined value,
2618 historically a 32 bit integer created with a multi-character
2619 constant such as 'abcd'. It is, fundamentally, an abomination.
2624 s << desc.SubType();
2632 AUPluginInfo::needs_midi_input ()
2634 return is_effect_with_midi_input () || is_instrument ();
2638 AUPluginInfo::is_effect () const
2640 return is_effect_without_midi_input() || is_effect_with_midi_input();
2644 AUPluginInfo::is_effect_without_midi_input () const
2646 return descriptor->IsAUFX();
2650 AUPluginInfo::is_effect_with_midi_input () const
2652 return descriptor->IsAUFM();
2656 AUPluginInfo::is_instrument () const
2658 return descriptor->IsMusicDevice();
2662 AUPlugin::set_info (PluginInfoPtr info)
2664 Plugin::set_info (info);
2666 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2667 _has_midi_input = pinfo->needs_midi_input ();
2668 _has_midi_output = false;
2672 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2675 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2677 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2679 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2681 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2685 _parameter_listener_arg = arg;
2691 AUPlugin::listen_to_parameter (uint32_t param_id)
2693 AudioUnitEvent event;
2695 if (!_parameter_listener || param_id >= descriptors.size()) {
2699 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2700 event.mArgument.mParameter.mAudioUnit = unit->AU();
2701 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2702 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2703 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2705 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2709 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2710 event.mArgument.mParameter.mAudioUnit = unit->AU();
2711 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2712 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2713 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2715 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2719 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2720 event.mArgument.mParameter.mAudioUnit = unit->AU();
2721 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2722 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2723 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2725 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2733 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2735 AudioUnitEvent event;
2737 if (!_parameter_listener || param_id >= descriptors.size()) {
2741 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2742 event.mArgument.mParameter.mAudioUnit = unit->AU();
2743 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2744 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2745 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2747 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2751 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2752 event.mArgument.mParameter.mAudioUnit = unit->AU();
2753 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2754 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2755 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2757 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2761 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2762 event.mArgument.mParameter.mAudioUnit = unit->AU();
2763 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2764 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2765 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2767 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2775 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2777 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2781 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2783 ParameterMap::iterator i;
2785 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
2789 switch (event->mEventType) {
2790 case kAudioUnitEvent_BeginParameterChangeGesture:
2791 StartTouch (i->second);
2793 case kAudioUnitEvent_EndParameterChangeGesture:
2794 EndTouch (i->second);
2796 case kAudioUnitEvent_ParameterValueChange:
2797 ParameterChanged (i->second, new_value);