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/threads.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/route.h"
47 #include "ardour/session.h"
48 #include "ardour/tempo.h"
49 #include "ardour/utils.h"
51 #include "appleutility/CAAudioUnit.h"
52 #include "appleutility/CAAUParameter.h"
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <CoreServices/CoreServices.h>
56 #include <AudioUnit/AudioUnit.h>
57 #include <AudioToolbox/AudioUnitUtilities.h>
59 #include <Carbon/Carbon.h>
66 using namespace ARDOUR;
68 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
70 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
71 static string preset_suffix = ".aupreset";
72 static bool preset_search_path_initialized = false;
75 _render_callback(void *userData,
76 AudioUnitRenderActionFlags *ioActionFlags,
77 const AudioTimeStamp *inTimeStamp,
79 UInt32 inNumberFrames,
80 AudioBufferList* ioData)
83 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
89 _get_beat_and_tempo_callback (void* userData,
90 Float64* outCurrentBeat,
91 Float64* outCurrentTempo)
94 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
101 _get_musical_time_location_callback (void * userData,
102 UInt32 * outDeltaSampleOffsetToNextBeat,
103 Float32 * outTimeSig_Numerator,
104 UInt32 * outTimeSig_Denominator,
105 Float64 * outCurrentMeasureDownBeat)
108 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
109 outTimeSig_Numerator,
110 outTimeSig_Denominator,
111 outCurrentMeasureDownBeat);
117 _get_transport_state_callback (void* userData,
118 Boolean* outIsPlaying,
119 Boolean* outTransportStateChanged,
120 Float64* outCurrentSampleInTimeLine,
121 Boolean* outIsCycling,
122 Float64* outCycleStartBeat,
123 Float64* outCycleEndBeat)
126 return ((AUPlugin*)userData)->get_transport_state_callback (
127 outIsPlaying, outTransportStateChanged,
128 outCurrentSampleInTimeLine, outIsCycling,
129 outCycleStartBeat, outCycleEndBeat);
136 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
142 // Convert the property list into XML data.
144 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
147 error << _("Could not create XML version of property list") << endmsg;
151 // Write the XML data to the file.
153 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
155 if (errno == EEXIST) {
156 error << string_compose (_("Preset file %1 exists; not overwriting"),
159 error << string_compose (_("Cannot open preset file %1 (%2)"),
160 path, strerror (errno)) << endmsg;
166 size_t cnt = CFDataGetLength (xmlData);
168 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
179 static CFPropertyListRef
180 load_property_list (Glib::ustring path)
183 CFPropertyListRef propertyList = 0;
185 CFStringRef errorString;
187 // Read the XML file.
189 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
194 off_t len = lseek (fd, 0, SEEK_END);
195 char* buf = new char[len];
196 lseek (fd, 0, SEEK_SET);
198 if (read (fd, buf, len) != len) {
206 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
208 // Reconstitute the dictionary using the XML data.
210 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
212 kCFPropertyListImmutable,
221 //-----------------------------------------------------------------------------
223 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
228 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
230 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
231 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
237 //-----------------------------------------------------------------------------
239 get_preset_name_in_plist (CFPropertyListRef plist)
247 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
248 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
250 CFStringRef str = (CFStringRef) p;
251 int len = CFStringGetLength(str);
253 char local_buffer[len];
254 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
262 //--------------------------------------------------------------------------
263 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
264 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
265 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
266 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
268 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
271 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
272 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
274 // only sub-type and manufacturer IDs need to be equal
277 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
278 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
285 //--------------------------------------------------------------------------
286 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
287 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
288 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
289 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
292 ComponentDescription desc;
294 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
297 // get the ComponentDescription of the input Component
298 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
302 // check if the Component's ComponentDescription matches the input ComponentDescription
303 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
306 //--------------------------------------------------------------------------
307 // determine if 2 ComponentDescriptions are basically equal
308 // (by that, I mean that the important identifying values are compared,
309 // but not the ComponentDescription flags)
310 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
312 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
315 //--------------------------------------------------------------------------
316 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
317 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
319 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
322 //--------------------------------------------------------------------------
323 // determine if a ComponentDescription basically matches that of a particular Component
324 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
326 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
329 //--------------------------------------------------------------------------
330 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
331 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
333 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
337 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
338 : Plugin (engine, session)
340 , unit (new CAAudioUnit)
341 , initialized (false)
342 , _current_block_size (0)
343 , _requires_fixed_size_buffers (false)
348 , frames_processed (0)
349 , _parameter_listener (0)
350 , _parameter_listener_arg (0)
351 , last_transport_rolling (false)
352 , last_transport_speed (0.0)
354 if (!preset_search_path_initialized) {
355 Glib::ustring p = Glib::get_home_dir();
356 p += "/Library/Audio/Presets:";
357 p += preset_search_path;
358 preset_search_path = p;
359 preset_search_path_initialized = true;
366 AUPlugin::AUPlugin (const AUPlugin& other)
368 , comp (other.get_comp())
369 , unit (new CAAudioUnit)
370 , initialized (false)
371 , _current_block_size (0)
373 , _requires_fixed_size_buffers (false)
378 , frames_processed (0)
379 , _parameter_listener (0)
380 , _parameter_listener_arg (0)
386 AUPlugin::~AUPlugin ()
388 if (_parameter_listener) {
389 AUListenerDispose (_parameter_listener);
390 _parameter_listener = 0;
394 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
395 unit->Uninitialize ();
404 AUPlugin::discover_factory_presets ()
411 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
412 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
416 assert (dataSize == sizeof (presets));
418 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
419 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
427 CFIndex cnt = CFArrayGetCount (presets);
429 for (CFIndex i = 0; i < cnt; ++i) {
430 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
432 string name = CFStringRefToStdString (preset->presetName);
433 factory_preset_map[name] = preset->presetNumber;
444 /* these keep track of *configured* channel set up,
445 not potential set ups.
449 output_channels = -1;
452 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
453 err = CAAudioUnit::Open (*(comp.get()), *unit);
455 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
456 throw failed_constructor();
460 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
461 throw failed_constructor ();
464 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
465 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
466 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
467 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
468 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
469 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
471 if (input_elements > 0) {
472 /* setup render callback: the plugin calls this to get input data
475 AURenderCallbackStruct renderCallbackInfo;
477 renderCallbackInfo.inputProc = _render_callback;
478 renderCallbackInfo.inputProcRefCon = this;
480 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
481 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
482 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
483 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
484 throw failed_constructor();
488 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
490 HostCallbackInfo info;
491 memset (&info, 0, sizeof (HostCallbackInfo));
492 info.hostUserData = this;
493 info.beatAndTempoProc = _get_beat_and_tempo_callback;
494 info.musicalTimeLocationProc = _get_musical_time_location_callback;
495 info.transportStateProc = _get_transport_state_callback;
497 //ignore result of this - don't care if the property isn't supported
498 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
499 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
500 kAudioUnitScope_Global,
503 sizeof (HostCallbackInfo));
505 if (set_block_size (_session.get_block_size())) {
506 error << _("AUPlugin: cannot set processing block size") << endmsg;
507 throw failed_constructor();
510 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
511 discover_parameters ();
512 discover_factory_presets ();
514 // Plugin::setup_controls ();
518 AUPlugin::discover_parameters ()
520 /* discover writable parameters */
522 AudioUnitScope scopes[] = {
523 kAudioUnitScope_Global,
524 kAudioUnitScope_Output,
525 kAudioUnitScope_Input
528 descriptors.clear ();
530 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
532 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
534 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
536 AUParameterDescriptor d;
538 d.id = param_info.ParamID (i);
540 const CAAUParameter* param = param_info.GetParamInfo (d.id);
541 const AudioUnitParameterInfo& info (param->ParamInfo());
543 const int len = CFStringGetLength (param->GetName());;
544 char local_buffer[len*2];
545 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
549 d.label = local_buffer;
552 d.scope = param_info.GetScope ();
553 d.element = param_info.GetElement ();
555 /* info.units to consider */
557 kAudioUnitParameterUnit_Generic = 0
558 kAudioUnitParameterUnit_Indexed = 1
559 kAudioUnitParameterUnit_Boolean = 2
560 kAudioUnitParameterUnit_Percent = 3
561 kAudioUnitParameterUnit_Seconds = 4
562 kAudioUnitParameterUnit_SampleFrames = 5
563 kAudioUnitParameterUnit_Phase = 6
564 kAudioUnitParameterUnit_Rate = 7
565 kAudioUnitParameterUnit_Hertz = 8
566 kAudioUnitParameterUnit_Cents = 9
567 kAudioUnitParameterUnit_RelativeSemiTones = 10
568 kAudioUnitParameterUnit_MIDINoteNumber = 11
569 kAudioUnitParameterUnit_MIDIController = 12
570 kAudioUnitParameterUnit_Decibels = 13
571 kAudioUnitParameterUnit_LinearGain = 14
572 kAudioUnitParameterUnit_Degrees = 15
573 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
574 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
575 kAudioUnitParameterUnit_Pan = 18
576 kAudioUnitParameterUnit_Meters = 19
577 kAudioUnitParameterUnit_AbsoluteCents = 20
578 kAudioUnitParameterUnit_Octaves = 21
579 kAudioUnitParameterUnit_BPM = 22
580 kAudioUnitParameterUnit_Beats = 23
581 kAudioUnitParameterUnit_Milliseconds = 24
582 kAudioUnitParameterUnit_Ratio = 25
585 /* info.flags to consider */
589 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
590 kAudioUnitParameterFlag_HasClump = (1L << 20)
591 kAudioUnitParameterFlag_HasName = (1L << 21)
592 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
593 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
594 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
595 kAudioUnitParameterFlag_CanRamp = (1L << 25)
596 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
597 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
598 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
599 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
600 kAudioUnitParameterFlag_IsReadable = (1L << 30)
601 kAudioUnitParameterFlag_IsWritable = (1L << 31)
604 d.lower = info.minValue;
605 d.upper = info.maxValue;
606 d.default_value = info.defaultValue;
608 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
609 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
610 (d.integer_step && ((d.upper - d.lower) == 1.0));
611 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
612 d.automatable = !d.toggled &&
613 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
614 (info.flags & kAudioUnitParameterFlag_IsWritable);
616 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
622 d.min_unbound = 0; // lower is bound
623 d.max_unbound = 0; // upper is bound
625 descriptors.push_back (d);
627 uint32_t last_param = descriptors.size() - 1;
628 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
629 listen_to_parameter (last_param);
636 four_ints_to_four_byte_literal (unsigned char n[4])
638 /* this is actually implementation dependent. sigh. this is what gcc
639 and quite a few others do.
641 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
645 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
647 if (isdigit (id[0])) {
651 /* ID format is xxxx-xxxx-xxxx
652 where x maybe \xNN or a printable character.
654 Split at the '-' and and process each part into an integer.
655 Then put it back together.
659 unsigned char nascent[4];
660 const char* cstr = id.c_str();
661 const char* estr = cstr + id.size();
672 while (*cstr && next_int < 4) {
676 if (estr - cstr < 3) {
678 /* too close to the end for \xNN parsing: treat as literal characters */
686 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
690 memcpy (short_buf, &cstr[2], 2);
691 nascent[in] = strtol (short_buf, NULL, 16);
697 /* treat as literal characters */
711 if (in && (in % 4 == 0)) {
712 /* nascent is ready */
713 n[next_int] = four_ints_to_four_byte_literal (nascent);
717 /* swallow space-hyphen-space */
731 s << n[0] << '-' << n[1] << '-' << n[2];
740 AUPlugin::unique_id () const
742 return AUPluginInfo::stringify_descriptor (comp->Desc());
746 AUPlugin::label () const
748 return _info->name.c_str();
752 AUPlugin::parameter_count () const
754 return descriptors.size();
758 AUPlugin::default_value (uint32_t port)
760 if (port < descriptors.size()) {
761 return descriptors[port].default_value;
768 AUPlugin::signal_latency () const
770 return unit->Latency() * _session.frame_rate();
774 AUPlugin::set_parameter (uint32_t which, float val)
776 if (which >= descriptors.size()) {
780 if (get_parameter(which) == val) {
784 const AUParameterDescriptor& d (descriptors[which]);
785 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
786 unit->SetParameter (d.id, d.scope, d.element, val);
788 /* tell the world what we did */
790 AudioUnitEvent theEvent;
792 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
793 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
794 theEvent.mArgument.mParameter.mParameterID = d.id;
795 theEvent.mArgument.mParameter.mScope = d.scope;
796 theEvent.mArgument.mParameter.mElement = d.element;
798 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
799 AUEventListenerNotify (NULL, NULL, &theEvent);
801 Plugin::set_parameter (which, val);
805 AUPlugin::get_parameter (uint32_t which) const
808 if (which < descriptors.size()) {
809 const AUParameterDescriptor& d (descriptors[which]);
810 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
811 unit->GetParameter(d.id, d.scope, d.element, val);
817 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
819 if (which < descriptors.size()) {
820 pd = descriptors[which];
827 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
829 if (which < descriptors.size()) {
838 AUPlugin::activate ()
842 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
843 if ((err = unit->Initialize()) != noErr) {
844 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
846 frames_processed = 0;
853 AUPlugin::deactivate ()
855 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
856 unit->Uninitialize ();
863 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
864 unit->GlobalReset ();
868 AUPlugin::requires_fixed_size_buffers() const
870 return _requires_fixed_size_buffers;
875 AUPlugin::set_block_size (pframes_t nframes)
877 bool was_initialized = initialized;
878 UInt32 numFrames = nframes;
885 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
886 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
887 0, &numFrames, sizeof (numFrames))) != noErr) {
888 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
892 if (was_initialized) {
896 _current_block_size = nframes;
902 AUPlugin::configure_io (ChanCount in, ChanCount out)
904 AudioStreamBasicDescription streamFormat;
905 bool was_initialized = initialized;
906 int32_t audio_in = in.n_audio();
907 int32_t audio_out = out.n_audio();
909 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
912 //if we are already running with the requested i/o config, bail out here
913 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
920 streamFormat.mSampleRate = _session.frame_rate();
921 streamFormat.mFormatID = kAudioFormatLinearPCM;
922 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
924 #ifdef __LITTLE_ENDIAN__
927 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
930 streamFormat.mBitsPerChannel = 32;
931 streamFormat.mFramesPerPacket = 1;
933 /* apple says that for non-interleaved data, these
934 values always refer to a single channel.
936 streamFormat.mBytesPerPacket = 4;
937 streamFormat.mBytesPerFrame = 4;
939 streamFormat.mChannelsPerFrame = audio_in;
941 if (set_input_format (streamFormat) != 0) {
945 streamFormat.mChannelsPerFrame = audio_out;
947 if (set_output_format (streamFormat) != 0) {
951 /* reset plugin info to show currently configured state */
953 _info->n_inputs = in;
954 _info->n_outputs = out;
956 if (was_initialized) {
964 AUPlugin::input_streams() const
968 c.set (DataType::AUDIO, 1);
969 c.set (DataType::MIDI, 0);
971 if (input_channels < 0) {
972 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
974 c.set (DataType::AUDIO, input_channels);
975 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
983 AUPlugin::output_streams() const
987 c.set (DataType::AUDIO, 1);
988 c.set (DataType::MIDI, 0);
990 if (output_channels < 0) {
991 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
993 c.set (DataType::AUDIO, output_channels);
994 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1001 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
1003 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1005 int32_t audio_in = in.n_audio();
1008 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1010 /* lets check MIDI first */
1012 if (in.n_midi() > 0) {
1013 if (!_has_midi_input) {
1018 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1020 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1021 name(), io_configs.size(), in, out));
1023 //Ardour expects the plugin to tell it the output
1024 //configuration but AU plugins can have multiple I/O
1025 //configurations in most cases. so first lets see
1026 //if there's a configuration that keeps out==in
1028 audio_out = audio_in;
1030 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1032 int32_t possible_in = i->first;
1033 int32_t possible_out = i->second;
1035 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1036 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1037 possible_in, possible_out,
1040 out.set (DataType::MIDI, 0);
1041 out.set (DataType::AUDIO, audio_out);
1047 /* now allow potentially "imprecise" matches */
1051 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1053 int32_t possible_in = i->first;
1054 int32_t possible_out = i->second;
1056 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1058 if (possible_out == 0) {
1059 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1060 /* XXX surely this is just a send? (e.g. AUNetSend) */
1064 if (possible_in == 0) {
1066 /* instrument plugin, always legal but throws away inputs ...
1069 if (possible_out == -1) {
1070 /* any configuration possible, provide stereo output */
1073 } else if (possible_out == -2) {
1074 /* plugins shouldn't really use (0,-2) but might.
1075 any configuration possible, provide stereo output
1079 } else if (possible_out < -2) {
1080 /* explicitly variable number of outputs.
1082 Since Ardour can handle any configuration,
1083 we have to somehow pick a number.
1085 We'll use the number of inputs
1086 to the master bus, or 2 if there
1089 boost::shared_ptr<Route> master = _session.master_out();
1091 audio_out = master->input()->n_ports().n_audio();
1097 /* exact number of outputs */
1098 audio_out = possible_out;
1103 if (possible_in == -1) {
1105 /* wildcard for input */
1107 if (possible_out == -1) {
1108 /* out much match in */
1109 audio_out = audio_in;
1111 } else if (possible_out == -2) {
1112 /* any configuration possible, pick matching */
1113 audio_out = audio_in;
1115 } else if (possible_out < -2) {
1116 /* explicitly variable number of outputs, pick maximum */
1117 audio_out = -possible_out;
1120 /* exact number of outputs */
1121 audio_out = possible_out;
1126 if (possible_in == -2) {
1128 if (possible_out == -1) {
1129 /* any configuration possible, pick matching */
1130 audio_out = audio_in;
1132 } else if (possible_out == -2) {
1133 /* plugins shouldn't really use (-2,-2) but might.
1134 interpret as (-1,-1).
1136 audio_out = audio_in;
1138 } else if (possible_out < -2) {
1139 /* explicitly variable number of outputs, pick maximum */
1140 audio_out = -possible_out;
1143 /* exact number of outputs */
1144 audio_out = possible_out;
1149 if (possible_in < -2) {
1151 /* explicit variable number of inputs */
1153 if (audio_in > -possible_in) {
1154 /* request is too large */
1158 if (possible_out == -1) {
1159 /* any output configuration possible, provide stereo out */
1162 } else if (possible_out == -2) {
1163 /* plugins shouldn't really use (<-2,-2) but might.
1164 interpret as (<-2,-1): any configuration possible, provide stereo output
1168 } else if (possible_out < -2) {
1169 /* explicitly variable number of outputs.
1171 Since Ardour can handle any configuration,
1172 we have to somehow pick a number.
1174 We'll use the number of inputs
1175 to the master bus, or 2 if there
1178 boost::shared_ptr<Route> master = _session.master_out();
1180 audio_out = master->input()->n_ports().n_audio();
1186 /* exact number of outputs */
1187 audio_out = possible_out;
1192 if (possible_in && (possible_in == audio_in)) {
1194 /* exact number of inputs ... must match obviously */
1196 if (possible_out == -1) {
1197 /* any output configuration possible, provide stereo output */
1200 } else if (possible_out == -2) {
1201 /* plugins shouldn't really use (>0,-2) but might.
1202 interpret as (>0,-1):
1203 any output configuration possible, provide stereo output
1207 } else if (possible_out < -2) {
1208 /* explicitly variable number of outputs, pick maximum */
1209 audio_out = -possible_out;
1212 /* exact number of outputs */
1213 audio_out = possible_out;
1225 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1227 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1231 out.set (DataType::MIDI, 0);
1232 out.set (DataType::AUDIO, audio_out);
1238 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1240 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1244 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1246 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1255 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1256 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1262 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1266 for (uint32_t i = 0; i < cnt; ++i) {
1267 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1268 (scope == kAudioUnitScope_Input ? "input" : "output"),
1270 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1271 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1272 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1277 if (scope == kAudioUnitScope_Input) {
1278 input_channels = fmt.mChannelsPerFrame;
1280 output_channels = fmt.mChannelsPerFrame;
1287 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1288 const AudioTimeStamp*,
1290 UInt32 inNumberFrames,
1291 AudioBufferList* ioData)
1293 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1295 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1296 // name(), inNumberFrames, ioData->mNumberBuffers));
1298 if (input_maxbuf == 0) {
1299 error << _("AUPlugin: render callback called illegally!") << endmsg;
1300 return kAudioUnitErr_CannotDoInCurrentContext;
1302 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1304 for (uint32_t i = 0; i < limit; ++i) {
1305 ioData->mBuffers[i].mNumberChannels = 1;
1306 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1308 /* we don't use the channel mapping because audiounits are
1309 never replicated. one plugin instance uses all channels/buffers
1310 passed to PluginInsert::connect_and_run()
1313 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1316 cb_offset += inNumberFrames;
1322 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1324 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1326 AudioUnitRenderActionFlags flags = 0;
1330 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1331 unit->GlobalReset();
1332 _last_nframes = nframes;
1335 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1336 name(), input_channels, output_channels, _has_midi_input,
1337 bufs.count(), bufs.available()));
1339 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1340 has the capacity to handle our outputs.
1343 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1345 input_buffers = &bufs;
1346 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1347 input_offset = offset;
1350 buffers->mNumberBuffers = output_channels;
1352 for (int32_t i = 0; i < output_channels; ++i) {
1353 buffers->mBuffers[i].mNumberChannels = 1;
1354 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1355 /* setting this to 0 indicates to the AU that it can provide buffers here
1356 if necessary. if it can process in-place, it will use the buffers provided
1357 as input by ::render_callback() above.
1359 a non-null values tells the plugin to render into the buffer pointed
1362 buffers->mBuffers[i].mData = 0;
1365 if (_has_midi_input) {
1367 uint32_t nmidi = bufs.count().n_midi();
1369 for (uint32_t i = 0; i < nmidi; ++i) {
1371 /* one MIDI port/buffer only */
1373 MidiBuffer& m = bufs.get_midi (i);
1375 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1376 Evoral::MIDIEvent<framepos_t> ev (*i);
1378 if (ev.is_channel_event()) {
1379 const uint8_t* b = ev.buffer();
1380 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1381 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1384 /* XXX need to handle sysex and other message types */
1389 /* does this really mean anything ?
1392 ts.mSampleTime = frames_processed;
1393 ts.mFlags = kAudioTimeStampSampleTimeValid;
1395 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1396 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1398 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1401 frames_processed += nframes;
1403 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1404 name(), buffers->mNumberBuffers, output_channels));
1406 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1409 for (i = 0; i < limit; ++i) {
1410 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1411 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1412 /* plugin provided its own buffer for output so copy it back to where we want it
1414 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1418 /* now silence any buffers that were passed in but the that the plugin
1419 did not fill/touch/use.
1422 for (;i < output_channels; ++i) {
1423 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1429 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1434 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1435 Float64* outCurrentTempo)
1437 TempoMap& tmap (_session.tempo_map());
1439 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1441 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1442 (and interpretation) of a beat position will be incorrect. So refuse to
1446 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1447 return kAudioUnitErr_CannotDoInCurrentContext;
1450 Timecode::BBT_Time bbt;
1451 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1452 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1454 if (outCurrentBeat) {
1456 beat = metric.meter().divisions_per_bar() * bbt.bars;
1458 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1459 *outCurrentBeat = beat;
1462 if (outCurrentTempo) {
1463 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1471 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1472 Float32* outTimeSig_Numerator,
1473 UInt32* outTimeSig_Denominator,
1474 Float64* outCurrentMeasureDownBeat)
1476 TempoMap& tmap (_session.tempo_map());
1478 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1480 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1481 (and interpretation) of a beat position will be incorrect. So refuse to
1485 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1486 return kAudioUnitErr_CannotDoInCurrentContext;
1489 Timecode::BBT_Time bbt;
1490 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1491 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1493 if (outDeltaSampleOffsetToNextBeat) {
1494 if (bbt.ticks == 0) {
1496 *outDeltaSampleOffsetToNextBeat = 0;
1498 *outDeltaSampleOffsetToNextBeat = (UInt32)
1499 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1500 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1504 if (outTimeSig_Numerator) {
1505 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1507 if (outTimeSig_Denominator) {
1508 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1511 if (outCurrentMeasureDownBeat) {
1513 /* beat for the start of the bar.
1515 2|1|0 -> 1 + divisions_per_bar
1516 3|1|0 -> 1 + (2 * divisions_per_bar)
1520 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1527 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1528 Boolean* outTransportStateChanged,
1529 Float64* outCurrentSampleInTimeLine,
1530 Boolean* outIsCycling,
1531 Float64* outCycleStartBeat,
1532 Float64* outCycleEndBeat)
1537 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1539 rolling = _session.transport_rolling();
1540 speed = _session.transport_speed ();
1543 *outIsPlaying = _session.transport_rolling();
1546 if (outTransportStateChanged) {
1547 if (rolling != last_transport_rolling) {
1548 *outTransportStateChanged = true;
1549 } else if (speed != last_transport_speed) {
1550 *outTransportStateChanged = true;
1552 *outTransportStateChanged = false;
1556 if (outCurrentSampleInTimeLine) {
1557 /* this assumes that the AU can only call this host callback from render context,
1558 where input_offset is valid.
1560 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1564 Location* loc = _session.locations()->auto_loop_location();
1566 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1568 if (*outIsCycling) {
1570 if (outCycleStartBeat || outCycleEndBeat) {
1572 TempoMap& tmap (_session.tempo_map());
1574 /* more than 1 meter means that a simplistic computation (and interpretation) of
1575 a beat position will be incorrect. so refuse to offer the value.
1578 if (tmap.n_meters() > 1) {
1579 return kAudioUnitErr_CannotDoInCurrentContext;
1582 Timecode::BBT_Time bbt;
1584 if (outCycleStartBeat) {
1585 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1586 _session.tempo_map().bbt_time (loc->start(), bbt);
1589 beat = metric.meter().divisions_per_bar() * bbt.bars;
1591 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1593 *outCycleStartBeat = beat;
1596 if (outCycleEndBeat) {
1597 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1598 _session.tempo_map().bbt_time (loc->end(), bbt);
1601 beat = metric.meter().divisions_per_bar() * bbt.bars;
1603 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1605 *outCycleEndBeat = beat;
1611 last_transport_rolling = rolling;
1612 last_transport_speed = speed;
1617 set<Evoral::Parameter>
1618 AUPlugin::automatable() const
1620 set<Evoral::Parameter> automates;
1622 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1623 if (descriptors[i].automatable) {
1624 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1632 AUPlugin::describe_parameter (Evoral::Parameter param)
1634 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1635 return descriptors[param.id()].label;
1642 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1644 // NameValue stuff here
1648 AUPlugin::parameter_is_audio (uint32_t) const
1654 AUPlugin::parameter_is_control (uint32_t) const
1660 AUPlugin::parameter_is_input (uint32_t) const
1666 AUPlugin::parameter_is_output (uint32_t) const
1672 AUPlugin::add_state (XMLNode* root) const
1674 LocaleGuard lg (X_("POSIX"));
1676 CFPropertyListRef propertyList;
1678 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1679 if (unit->GetAUPreset (propertyList) != noErr) {
1683 // Convert the property list into XML data.
1685 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1688 error << _("Could not create XML version of property list") << endmsg;
1692 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1693 our state node. GACK!
1698 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1700 root->add_child_copy (*t.root());
1704 CFRelease (xmlData);
1705 CFRelease (propertyList);
1709 AUPlugin::set_state(const XMLNode& node, int version)
1712 CFPropertyListRef propertyList;
1713 LocaleGuard lg (X_("POSIX"));
1715 if (node.name() != state_node_name()) {
1716 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1720 if (node.children().empty()) {
1724 XMLNode* top = node.children().front();
1725 XMLNode* copy = new XMLNode (*top);
1730 const string& xml = t.write_buffer ();
1731 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1732 CFStringRef errorString;
1734 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1736 kCFPropertyListImmutable,
1739 CFRelease (xmlData);
1742 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1743 if (unit->SetAUPreset (propertyList) == noErr) {
1746 /* tell the world */
1748 AudioUnitParameter changedUnit;
1749 changedUnit.mAudioUnit = unit->AU();
1750 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1751 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1753 CFRelease (propertyList);
1756 Plugin::set_state (node, version);
1761 AUPlugin::load_preset (PresetRecord r)
1763 Plugin::load_preset (r);
1766 CFPropertyListRef propertyList;
1768 UserPresetMap::iterator ux;
1769 FactoryPresetMap::iterator fx;
1771 /* look first in "user" presets */
1773 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1775 if ((propertyList = load_property_list (ux->second)) != 0) {
1776 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1777 if (unit->SetAUPreset (propertyList) == noErr) {
1780 /* tell the world */
1782 AudioUnitParameter changedUnit;
1783 changedUnit.mAudioUnit = unit->AU();
1784 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1785 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1787 CFRelease(propertyList);
1790 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1794 preset.presetNumber = fx->second;
1795 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1797 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1799 if (unit->SetPresentPreset (preset) == 0) {
1802 /* tell the world */
1804 AudioUnitParameter changedUnit;
1805 changedUnit.mAudioUnit = unit->AU();
1806 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1807 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1815 AUPlugin::do_remove_preset (std::string)
1820 AUPlugin::do_save_preset (string preset_name)
1822 CFPropertyListRef propertyList;
1823 vector<Glib::ustring> v;
1824 Glib::ustring user_preset_path;
1827 std::string m = maker();
1828 std::string n = name();
1830 strip_whitespace_edges (m);
1831 strip_whitespace_edges (n);
1833 v.push_back (Glib::get_home_dir());
1834 v.push_back ("Library");
1835 v.push_back ("Audio");
1836 v.push_back ("Presets");
1840 user_preset_path = Glib::build_filename (v);
1842 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1843 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1847 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1848 if (unit->GetAUPreset (propertyList) != noErr) {
1852 // add the actual preset name */
1854 v.push_back (preset_name + preset_suffix);
1858 user_preset_path = Glib::build_filename (v);
1860 set_preset_name_in_plist (propertyList, preset_name);
1862 if (save_property_list (propertyList, user_preset_path)) {
1863 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1867 CFRelease(propertyList);
1869 return string ("file:///") + user_preset_path;
1872 //-----------------------------------------------------------------------------
1873 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1875 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1877 CFNumberRef cfNumber;
1878 SInt32 numberValue = 0;
1879 Boolean dummySuccess;
1881 if (outSuccess == NULL)
1882 outSuccess = &dummySuccess;
1883 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1885 *outSuccess = FALSE;
1889 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1890 if (cfNumber == NULL)
1892 *outSuccess = FALSE;
1895 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1903 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1905 CFDictionaryRef auStateDictionary;
1906 ComponentDescription tempDesc = {0,0,0,0,0};
1907 SInt32 versionValue;
1910 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1913 // the property list for AU state data must be of the dictionary type
1914 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1915 return kAudioUnitErr_InvalidPropertyValue;
1918 auStateDictionary = (CFDictionaryRef)inAUStateData;
1920 // first check to make sure that the version of the AU state data is one that we know understand
1921 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1922 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1925 return kAudioUnitErr_InvalidPropertyValue;
1927 #define kCurrentSavedStateVersion 0
1928 if (versionValue != kCurrentSavedStateVersion) {
1929 return kAudioUnitErr_InvalidPropertyValue;
1932 // grab the ComponentDescription values from the AU state data
1933 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1934 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1935 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1936 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1937 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1938 return kAudioUnitErr_InvalidPropertyValue;
1940 *outComponentDescription = tempDesc;
1945 static bool au_preset_filter (const string& str, void* arg)
1947 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1951 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1955 /* check the preset file path name against this plugin
1956 ID. The idea is that all preset files for this plugin
1957 include "<manufacturer>/<plugin-name>" in their path.
1960 Plugin* p = (Plugin *) arg;
1961 string match = p->maker();
1965 ret = str.find (match) != string::npos;
1968 string m = p->maker ();
1969 string n = p->name ();
1970 strip_whitespace_edges (m);
1971 strip_whitespace_edges (n);
1976 ret = str.find (match) != string::npos;
1984 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1987 CFPropertyListRef plist;
1988 ComponentDescription presetDesc;
1991 plist = load_property_list (pathstr);
1997 // get the ComponentDescription from the AU preset file
1999 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2001 if (status == noErr) {
2002 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2004 /* try to get the preset name from the property list */
2006 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2008 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2012 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2015 char buf[PATH_MAX+1];
2017 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2032 AUPlugin::current_preset() const
2036 CFPropertyListRef propertyList;
2038 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2039 if (unit->GetAUPreset (propertyList) == noErr) {
2040 preset_name = get_preset_name_in_plist (propertyList);
2041 CFRelease(propertyList);
2048 AUPlugin::find_presets ()
2050 vector<string*>* preset_files;
2051 PathScanner scanner;
2053 user_preset_map.clear ();
2055 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2057 if (!preset_files) {
2061 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2063 string path = *(*x);
2066 /* make an initial guess at the preset name using the path */
2068 preset_name = Glib::path_get_basename (path);
2069 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2071 /* check that this preset file really matches this plugin
2072 and potentially get the "real" preset name from
2076 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2077 user_preset_map[preset_name] = path;
2083 delete preset_files;
2085 /* now fill the vector<string> with the names we have */
2087 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2088 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2091 /* add factory presets */
2093 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2095 string const uri = string_compose ("%1", _presets.size ());
2096 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2101 AUPlugin::has_editor () const
2103 // even if the plugin doesn't have its own editor, the AU API can be used
2104 // to create one that looks native.
2108 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2111 type = ARDOUR::AudioUnit;
2114 AUPluginInfo::~AUPluginInfo ()
2116 type = ARDOUR::AudioUnit;
2120 AUPluginInfo::load (Session& session)
2125 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2126 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2128 if (!comp->IsValid()) {
2129 error << ("AudioUnit: not a valid Component") << endmsg;
2131 plugin.reset (new AUPlugin (session.engine(), session, comp));
2134 AUPluginInfo *aup = new AUPluginInfo (*this);
2135 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2136 plugin->set_info (PluginInfoPtr (aup));
2137 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2141 catch (failed_constructor &err) {
2142 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2143 return PluginPtr ();
2148 AUPluginInfo::au_cache_path ()
2150 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2154 AUPluginInfo::discover ()
2158 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2159 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2162 PluginInfoList* plugs = new PluginInfoList;
2164 discover_fx (*plugs);
2165 discover_music (*plugs);
2166 discover_generators (*plugs);
2167 discover_instruments (*plugs);
2169 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2175 AUPluginInfo::discover_music (PluginInfoList& plugs)
2177 CAComponentDescription desc;
2178 desc.componentFlags = 0;
2179 desc.componentFlagsMask = 0;
2180 desc.componentSubType = 0;
2181 desc.componentManufacturer = 0;
2182 desc.componentType = kAudioUnitType_MusicEffect;
2184 discover_by_description (plugs, desc);
2188 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2190 CAComponentDescription desc;
2191 desc.componentFlags = 0;
2192 desc.componentFlagsMask = 0;
2193 desc.componentSubType = 0;
2194 desc.componentManufacturer = 0;
2195 desc.componentType = kAudioUnitType_Effect;
2197 discover_by_description (plugs, desc);
2201 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2203 CAComponentDescription desc;
2204 desc.componentFlags = 0;
2205 desc.componentFlagsMask = 0;
2206 desc.componentSubType = 0;
2207 desc.componentManufacturer = 0;
2208 desc.componentType = kAudioUnitType_Generator;
2210 discover_by_description (plugs, desc);
2214 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2216 CAComponentDescription desc;
2217 desc.componentFlags = 0;
2218 desc.componentFlagsMask = 0;
2219 desc.componentSubType = 0;
2220 desc.componentManufacturer = 0;
2221 desc.componentType = kAudioUnitType_MusicDevice;
2223 discover_by_description (plugs, desc);
2227 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2231 comp = FindNextComponent (NULL, &desc);
2233 while (comp != NULL) {
2234 CAComponentDescription temp;
2235 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2237 AUPluginInfoPtr info (new AUPluginInfo
2238 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2240 /* although apple designed the subtype field to be a "category" indicator,
2241 its really turned into a plugin ID field for a given manufacturer. Hence
2242 there are no categories for AudioUnits. However, to keep the plugins
2243 showing up under "categories", we'll use the "type" as a high level
2246 NOTE: no panners, format converters or i/o AU's for our purposes
2249 switch (info->descriptor->Type()) {
2250 case kAudioUnitType_Panner:
2251 case kAudioUnitType_OfflineEffect:
2252 case kAudioUnitType_FormatConverter:
2255 case kAudioUnitType_Output:
2256 info->category = _("AudioUnit Outputs");
2258 case kAudioUnitType_MusicDevice:
2259 info->category = _("AudioUnit Instruments");
2261 case kAudioUnitType_MusicEffect:
2262 info->category = _("AudioUnit MusicEffects");
2264 case kAudioUnitType_Effect:
2265 info->category = _("AudioUnit Effects");
2267 case kAudioUnitType_Mixer:
2268 info->category = _("AudioUnit Mixers");
2270 case kAudioUnitType_Generator:
2271 info->category = _("AudioUnit Generators");
2274 info->category = _("AudioUnit (Unknown)");
2278 AUPluginInfo::get_names (temp, info->name, info->creator);
2280 info->type = ARDOUR::AudioUnit;
2281 info->unique_id = stringify_descriptor (*info->descriptor);
2283 /* XXX not sure of the best way to handle plugin versioning yet
2286 CAComponent cacomp (*info->descriptor);
2288 if (cacomp.GetResourceVersion (info->version) != noErr) {
2292 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2294 /* here we have to map apple's wildcard system to a simple pair
2295 of values. in ::can_do() we use the whole system, but here
2296 we need a single pair of values. XXX probably means we should
2297 remove any use of these values.
2299 for now, if the plugin provides a wildcard, treat it as 1. we really
2300 don't care much, because whether we can handle an i/o configuration
2301 depends upon ::can_support_io_configuration(), not these counts.
2303 they exist because other parts of ardour try to present i/o configuration
2304 info to the user, which should perhaps be revisited.
2307 int32_t possible_in = info->cache.io_configs.front().first;
2308 int32_t possible_out = info->cache.io_configs.front().second;
2310 if (possible_in > 0) {
2311 info->n_inputs.set (DataType::AUDIO, possible_in);
2313 info->n_inputs.set (DataType::AUDIO, 1);
2316 if (possible_out > 0) {
2317 info->n_outputs.set (DataType::AUDIO, possible_out);
2319 info->n_outputs.set (DataType::AUDIO, 1);
2322 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2323 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2325 plugs.push_back (info);
2328 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2331 comp = FindNextComponent (comp, &desc);
2336 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2339 AUPluginCachedInfo& cinfo,
2340 const std::string& name)
2345 /* concatenate unique ID with version to provide a key for cached info lookup.
2346 this ensures we don't get stale information, or should if plugin developers
2347 follow Apple "guidelines".
2350 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2355 CachedInfoMap::iterator cim = cached_info.find (id);
2357 if (cim != cached_info.end()) {
2358 cinfo = cim->second;
2363 AUChannelInfo* channel_info;
2367 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2371 if (CAAudioUnit::Open (comp, unit) != noErr) {
2377 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2382 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2383 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2389 /* no explicit info available, so default to 1in/1out */
2391 /* XXX this is wrong. we should be indicating wildcard values */
2393 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2397 /* store each configuration */
2399 for (uint32_t n = 0; n < cnt; ++n) {
2400 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2401 channel_info[n].outChannels));
2404 free (channel_info);
2407 add_cached_info (id, cinfo);
2408 save_cached_info ();
2414 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2416 cached_info[id] = cinfo;
2419 #define AU_CACHE_VERSION "2.0"
2422 AUPluginInfo::save_cached_info ()
2426 node = new XMLNode (X_("AudioUnitPluginCache"));
2427 node->add_property( "version", AU_CACHE_VERSION );
2429 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2430 XMLNode* parent = new XMLNode (X_("plugin"));
2431 parent->add_property ("id", i->first);
2432 node->add_child_nocopy (*parent);
2434 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2436 XMLNode* child = new XMLNode (X_("io"));
2439 snprintf (buf, sizeof (buf), "%d", j->first);
2440 child->add_property (X_("in"), buf);
2441 snprintf (buf, sizeof (buf), "%d", j->second);
2442 child->add_property (X_("out"), buf);
2443 parent->add_child_nocopy (*child);
2448 Glib::ustring path = au_cache_path ();
2451 tree.set_root (node);
2453 if (!tree.write (path)) {
2454 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2455 unlink (path.c_str());
2460 AUPluginInfo::load_cached_info ()
2462 Glib::ustring path = au_cache_path ();
2465 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2469 if ( !tree.read (path) ) {
2470 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2474 const XMLNode* root (tree.root());
2476 if (root->name() != X_("AudioUnitPluginCache")) {
2480 //initial version has incorrectly stored i/o info, and/or garbage chars.
2481 const XMLProperty* version = root->property(X_("version"));
2482 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2483 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2487 cached_info.clear ();
2489 const XMLNodeList children = root->children();
2491 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2493 const XMLNode* child = *iter;
2495 if (child->name() == X_("plugin")) {
2497 const XMLNode* gchild;
2498 const XMLNodeList gchildren = child->children();
2499 const XMLProperty* prop = child->property (X_("id"));
2505 string id = prop->value();
2509 string::size_type slash = id.find_last_of ('/');
2511 if (slash == string::npos) {
2515 version = id.substr (slash);
2516 id = id.substr (0, slash);
2517 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2519 if (fixed.empty()) {
2520 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2527 AUPluginCachedInfo cinfo;
2529 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2533 if (gchild->name() == X_("io")) {
2537 const XMLProperty* iprop;
2538 const XMLProperty* oprop;
2540 if (((iprop = gchild->property (X_("in"))) != 0) &&
2541 ((oprop = gchild->property (X_("out"))) != 0)) {
2542 in = atoi (iprop->value());
2543 out = atoi (oprop->value());
2545 cinfo.io_configs.push_back (pair<int,int> (in, out));
2550 if (cinfo.io_configs.size()) {
2551 add_cached_info (id, cinfo);
2560 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2562 CFStringRef itemName = NULL;
2564 // Marc Poirier-style item name
2565 CAComponent auComponent (comp_desc);
2566 if (auComponent.IsValid()) {
2567 CAComponentDescription dummydesc;
2568 Handle nameHandle = NewHandle(sizeof(void*));
2569 if (nameHandle != NULL) {
2570 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2572 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2573 if (nameString != NULL) {
2574 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2577 DisposeHandle(nameHandle);
2581 // if Marc-style fails, do the original way
2582 if (itemName == NULL) {
2583 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2584 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2585 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2587 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2588 compTypeString, compManufacturerString, compSubTypeString);
2590 if (compTypeString != NULL)
2591 CFRelease(compTypeString);
2592 if (compSubTypeString != NULL)
2593 CFRelease(compSubTypeString);
2594 if (compManufacturerString != NULL)
2595 CFRelease(compManufacturerString);
2598 string str = CFStringRefToStdString(itemName);
2599 string::size_type colon = str.find (':');
2602 name = str.substr (colon+1);
2603 maker = str.substr (0, colon);
2604 strip_whitespace_edges (maker);
2605 strip_whitespace_edges (name);
2609 strip_whitespace_edges (name);
2614 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2618 /* note: OSType is a compiler-implemenation-defined value,
2619 historically a 32 bit integer created with a multi-character
2620 constant such as 'abcd'. It is, fundamentally, an abomination.
2625 s << desc.SubType();
2633 AUPluginInfo::needs_midi_input ()
2635 return is_effect_with_midi_input () || is_instrument ();
2639 AUPluginInfo::is_effect () const
2641 return is_effect_without_midi_input() || is_effect_with_midi_input();
2645 AUPluginInfo::is_effect_without_midi_input () const
2647 return descriptor->IsAUFX();
2651 AUPluginInfo::is_effect_with_midi_input () const
2653 return descriptor->IsAUFM();
2657 AUPluginInfo::is_instrument () const
2659 return descriptor->IsMusicDevice();
2663 AUPlugin::set_info (PluginInfoPtr info)
2665 Plugin::set_info (info);
2667 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2668 _has_midi_input = pinfo->needs_midi_input ();
2669 _has_midi_output = false;
2673 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2676 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2678 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2680 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2682 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2686 _parameter_listener_arg = arg;
2692 AUPlugin::listen_to_parameter (uint32_t param_id)
2694 AudioUnitEvent event;
2696 if (!_parameter_listener || param_id >= descriptors.size()) {
2700 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2701 event.mArgument.mParameter.mAudioUnit = unit->AU();
2702 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2703 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2704 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2706 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2710 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2711 event.mArgument.mParameter.mAudioUnit = unit->AU();
2712 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2713 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2714 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2716 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2720 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2721 event.mArgument.mParameter.mAudioUnit = unit->AU();
2722 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2723 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2724 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2726 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2734 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2736 AudioUnitEvent event;
2738 if (!_parameter_listener || param_id >= descriptors.size()) {
2742 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2743 event.mArgument.mParameter.mAudioUnit = unit->AU();
2744 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2745 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2746 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2748 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2752 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2753 event.mArgument.mParameter.mAudioUnit = unit->AU();
2754 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2755 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2756 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2758 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2762 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2763 event.mArgument.mParameter.mAudioUnit = unit->AU();
2764 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2765 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2766 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2768 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2776 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2778 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2782 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2784 ParameterMap::iterator i;
2786 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
2790 switch (event->mEventType) {
2791 case kAudioUnitEvent_BeginParameterChangeGesture:
2792 StartTouch (i->second);
2794 case kAudioUnitEvent_EndParameterChangeGesture:
2795 EndTouch (i->second);
2797 case kAudioUnitEvent_ParameterValueChange:
2798 ParameterChanged (i->second, new_value);