2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "pbd/transmitter.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30 #include "pbd/whitespace.h"
31 #include "pbd/pathscanner.h"
32 #include "pbd/locale_guard.h"
34 #include <glibmm/thread.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
38 #include "ardour/ardour.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/debug.h"
42 #include "ardour/midi_buffer.h"
43 #include "ardour/filesystem_paths.h"
44 #include "ardour/io.h"
45 #include "ardour/audio_unit.h"
46 #include "ardour/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 #ifndef AU_STATE_SUPPORT
69 static bool seen_get_state_message = false;
70 static bool seen_set_state_message = false;
71 static bool seen_loading_message = false;
72 static bool seen_saving_message = false;
75 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
77 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
78 static string preset_suffix = ".aupreset";
79 static bool preset_search_path_initialized = false;
82 _render_callback(void *userData,
83 AudioUnitRenderActionFlags *ioActionFlags,
84 const AudioTimeStamp *inTimeStamp,
86 UInt32 inNumberFrames,
87 AudioBufferList* ioData)
90 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
96 _get_beat_and_tempo_callback (void* userData,
97 Float64* outCurrentBeat,
98 Float64* outCurrentTempo)
101 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
108 _get_musical_time_location_callback (void * userData,
109 UInt32 * outDeltaSampleOffsetToNextBeat,
110 Float32 * outTimeSig_Numerator,
111 UInt32 * outTimeSig_Denominator,
112 Float64 * outCurrentMeasureDownBeat)
115 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
116 outTimeSig_Numerator,
117 outTimeSig_Denominator,
118 outCurrentMeasureDownBeat);
124 _get_transport_state_callback (void* userData,
125 Boolean* outIsPlaying,
126 Boolean* outTransportStateChanged,
127 Float64* outCurrentSampleInTimeLine,
128 Boolean* outIsCycling,
129 Float64* outCycleStartBeat,
130 Float64* outCycleEndBeat)
133 return ((AUPlugin*)userData)->get_transport_state_callback (
134 outIsPlaying, outTransportStateChanged,
135 outCurrentSampleInTimeLine, outIsCycling,
136 outCycleStartBeat, outCycleEndBeat);
143 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
149 // Convert the property list into XML data.
151 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
154 error << _("Could not create XML version of property list") << endmsg;
158 // Write the XML data to the file.
160 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
162 if (errno == EEXIST) {
163 error << string_compose (_("Preset file %1 exists; not overwriting"),
166 error << string_compose (_("Cannot open preset file %1 (%2)"),
167 path, strerror (errno)) << endmsg;
173 size_t cnt = CFDataGetLength (xmlData);
175 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
186 static CFPropertyListRef
187 load_property_list (Glib::ustring path)
190 CFPropertyListRef propertyList = 0;
192 CFStringRef errorString;
194 // Read the XML file.
196 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
201 off_t len = lseek (fd, 0, SEEK_END);
202 char* buf = new char[len];
203 lseek (fd, 0, SEEK_SET);
205 if (read (fd, buf, len) != len) {
213 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
215 // Reconstitute the dictionary using the XML data.
217 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
219 kCFPropertyListImmutable,
228 //-----------------------------------------------------------------------------
230 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
235 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
237 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
238 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
244 //-----------------------------------------------------------------------------
246 get_preset_name_in_plist (CFPropertyListRef plist)
254 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
255 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
257 CFStringRef str = (CFStringRef) p;
258 int len = CFStringGetLength(str);
260 char local_buffer[len];
261 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
269 //--------------------------------------------------------------------------
270 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
271 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
272 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
273 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
275 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
278 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
279 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
281 // only sub-type and manufacturer IDs need to be equal
284 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
285 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
292 //--------------------------------------------------------------------------
293 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
294 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
295 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
296 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
299 ComponentDescription desc;
301 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
304 // get the ComponentDescription of the input Component
305 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
309 // check if the Component's ComponentDescription matches the input ComponentDescription
310 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
313 //--------------------------------------------------------------------------
314 // determine if 2 ComponentDescriptions are basically equal
315 // (by that, I mean that the important identifying values are compared,
316 // but not the ComponentDescription flags)
317 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
319 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
322 //--------------------------------------------------------------------------
323 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
324 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
326 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
329 //--------------------------------------------------------------------------
330 // determine if a ComponentDescription basically matches that of a particular Component
331 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
333 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
336 //--------------------------------------------------------------------------
337 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
338 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
340 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
344 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
345 : Plugin (engine, session)
347 , unit (new CAAudioUnit)
348 , initialized (false)
349 , _current_block_size (0)
350 , _requires_fixed_size_buffers (false)
355 , frames_processed (0)
356 , _parameter_listener (0)
357 , _parameter_listener_arg (0)
358 , last_transport_rolling (false)
359 , last_transport_speed (0.0)
361 if (!preset_search_path_initialized) {
362 Glib::ustring p = Glib::get_home_dir();
363 p += "/Library/Audio/Presets:";
364 p += preset_search_path;
365 preset_search_path = p;
366 preset_search_path_initialized = true;
373 AUPlugin::AUPlugin (const AUPlugin& other)
375 , comp (other.get_comp())
376 , unit (new CAAudioUnit)
377 , initialized (false)
378 , _current_block_size (0)
380 , _requires_fixed_size_buffers (false)
385 , frames_processed (0)
386 , _parameter_listener (0)
387 , _parameter_listener_arg (0)
393 AUPlugin::~AUPlugin ()
395 if (_parameter_listener) {
396 AUListenerDispose (_parameter_listener);
397 _parameter_listener = 0;
401 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
402 unit->Uninitialize ();
411 AUPlugin::discover_factory_presets ()
418 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
419 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
423 assert (dataSize == sizeof (presets));
425 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
426 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
434 CFIndex cnt = CFArrayGetCount (presets);
436 for (CFIndex i = 0; i < cnt; ++i) {
437 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
439 string name = CFStringRefToStdString (preset->presetName);
440 factory_preset_map[name] = preset->presetNumber;
451 /* these keep track of *configured* channel set up,
452 not potential set ups.
456 output_channels = -1;
459 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
460 err = CAAudioUnit::Open (*(comp.get()), *unit);
462 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
463 throw failed_constructor();
467 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
468 throw failed_constructor ();
471 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
472 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
473 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
474 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
475 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
476 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
478 if (input_elements > 0) {
479 /* setup render callback: the plugin calls this to get input data
482 AURenderCallbackStruct renderCallbackInfo;
484 renderCallbackInfo.inputProc = _render_callback;
485 renderCallbackInfo.inputProcRefCon = this;
487 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
488 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
489 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
490 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
491 throw failed_constructor();
495 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
497 HostCallbackInfo info;
498 memset (&info, 0, sizeof (HostCallbackInfo));
499 info.hostUserData = this;
500 info.beatAndTempoProc = _get_beat_and_tempo_callback;
501 info.musicalTimeLocationProc = _get_musical_time_location_callback;
502 info.transportStateProc = _get_transport_state_callback;
504 //ignore result of this - don't care if the property isn't supported
505 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
506 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
507 kAudioUnitScope_Global,
510 sizeof (HostCallbackInfo));
512 if (set_block_size (_session.get_block_size())) {
513 error << _("AUPlugin: cannot set processing block size") << endmsg;
514 throw failed_constructor();
517 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
518 discover_parameters ();
519 discover_factory_presets ();
521 // Plugin::setup_controls ();
525 AUPlugin::discover_parameters ()
527 /* discover writable parameters */
529 AudioUnitScope scopes[] = {
530 kAudioUnitScope_Global,
531 kAudioUnitScope_Output,
532 kAudioUnitScope_Input
535 descriptors.clear ();
537 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
539 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
541 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
543 AUParameterDescriptor d;
545 d.id = param_info.ParamID (i);
547 const CAAUParameter* param = param_info.GetParamInfo (d.id);
548 const AudioUnitParameterInfo& info (param->ParamInfo());
550 const int len = CFStringGetLength (param->GetName());;
551 char local_buffer[len*2];
552 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
556 d.label = local_buffer;
559 d.scope = param_info.GetScope ();
560 d.element = param_info.GetElement ();
562 /* info.units to consider */
564 kAudioUnitParameterUnit_Generic = 0
565 kAudioUnitParameterUnit_Indexed = 1
566 kAudioUnitParameterUnit_Boolean = 2
567 kAudioUnitParameterUnit_Percent = 3
568 kAudioUnitParameterUnit_Seconds = 4
569 kAudioUnitParameterUnit_SampleFrames = 5
570 kAudioUnitParameterUnit_Phase = 6
571 kAudioUnitParameterUnit_Rate = 7
572 kAudioUnitParameterUnit_Hertz = 8
573 kAudioUnitParameterUnit_Cents = 9
574 kAudioUnitParameterUnit_RelativeSemiTones = 10
575 kAudioUnitParameterUnit_MIDINoteNumber = 11
576 kAudioUnitParameterUnit_MIDIController = 12
577 kAudioUnitParameterUnit_Decibels = 13
578 kAudioUnitParameterUnit_LinearGain = 14
579 kAudioUnitParameterUnit_Degrees = 15
580 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
581 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
582 kAudioUnitParameterUnit_Pan = 18
583 kAudioUnitParameterUnit_Meters = 19
584 kAudioUnitParameterUnit_AbsoluteCents = 20
585 kAudioUnitParameterUnit_Octaves = 21
586 kAudioUnitParameterUnit_BPM = 22
587 kAudioUnitParameterUnit_Beats = 23
588 kAudioUnitParameterUnit_Milliseconds = 24
589 kAudioUnitParameterUnit_Ratio = 25
592 /* info.flags to consider */
596 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
597 kAudioUnitParameterFlag_HasClump = (1L << 20)
598 kAudioUnitParameterFlag_HasName = (1L << 21)
599 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
600 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
601 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
602 kAudioUnitParameterFlag_CanRamp = (1L << 25)
603 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
604 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
605 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
606 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
607 kAudioUnitParameterFlag_IsReadable = (1L << 30)
608 kAudioUnitParameterFlag_IsWritable = (1L << 31)
611 d.lower = info.minValue;
612 d.upper = info.maxValue;
613 d.default_value = info.defaultValue;
615 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
616 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
617 (d.integer_step && ((d.upper - d.lower) == 1.0));
618 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
619 d.automatable = !d.toggled &&
620 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
621 (info.flags & kAudioUnitParameterFlag_IsWritable);
623 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
629 d.min_unbound = 0; // lower is bound
630 d.max_unbound = 0; // upper is bound
632 descriptors.push_back (d);
634 uint32_t last_param = descriptors.size() - 1;
635 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
636 listen_to_parameter (last_param);
643 four_ints_to_four_byte_literal (unsigned char n[4])
645 /* this is actually implementation dependent. sigh. this is what gcc
646 and quite a few others do.
648 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
652 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
654 if (isdigit (id[0])) {
658 /* ID format is xxxx-xxxx-xxxx
659 where x maybe \xNN or a printable character.
661 Split at the '-' and and process each part into an integer.
662 Then put it back together.
666 unsigned char nascent[4];
667 const char* cstr = id.c_str();
668 const char* estr = cstr + id.size();
679 while (*cstr && next_int < 4) {
683 if (estr - cstr < 3) {
685 /* too close to the end for \xNN parsing: treat as literal characters */
693 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
697 memcpy (short_buf, &cstr[2], 2);
698 nascent[in] = strtol (short_buf, NULL, 16);
704 /* treat as literal characters */
718 if (in && (in % 4 == 0)) {
719 /* nascent is ready */
720 n[next_int] = four_ints_to_four_byte_literal (nascent);
724 /* swallow space-hyphen-space */
738 s << n[0] << '-' << n[1] << '-' << n[2];
747 AUPlugin::unique_id () const
749 return AUPluginInfo::stringify_descriptor (comp->Desc());
753 AUPlugin::label () const
755 return _info->name.c_str();
759 AUPlugin::parameter_count () const
761 return descriptors.size();
765 AUPlugin::default_value (uint32_t port)
767 if (port < descriptors.size()) {
768 return descriptors[port].default_value;
775 AUPlugin::signal_latency () const
777 return unit->Latency() * _session.frame_rate();
781 AUPlugin::set_parameter (uint32_t which, float val)
783 if (which >= descriptors.size()) {
787 const AUParameterDescriptor& d (descriptors[which]);
788 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
789 unit->SetParameter (d.id, d.scope, d.element, val);
791 /* tell the world what we did */
793 AudioUnitEvent theEvent;
795 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
796 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
797 theEvent.mArgument.mParameter.mParameterID = d.id;
798 theEvent.mArgument.mParameter.mScope = d.scope;
799 theEvent.mArgument.mParameter.mElement = d.element;
801 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
802 AUEventListenerNotify (NULL, NULL, &theEvent);
804 Plugin::set_parameter (which, val);
808 AUPlugin::get_parameter (uint32_t which) const
811 if (which < descriptors.size()) {
812 const AUParameterDescriptor& d (descriptors[which]);
813 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
814 unit->GetParameter(d.id, d.scope, d.element, val);
820 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
822 if (which < descriptors.size()) {
823 pd = descriptors[which];
830 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
832 if (which < descriptors.size()) {
841 AUPlugin::activate ()
845 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
846 if ((err = unit->Initialize()) != noErr) {
847 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
849 frames_processed = 0;
856 AUPlugin::deactivate ()
858 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
859 unit->Uninitialize ();
866 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
867 unit->GlobalReset ();
871 AUPlugin::requires_fixed_size_buffers() const
873 return _requires_fixed_size_buffers;
878 AUPlugin::set_block_size (pframes_t nframes)
880 bool was_initialized = initialized;
881 UInt32 numFrames = nframes;
888 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
889 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
890 0, &numFrames, sizeof (numFrames))) != noErr) {
891 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
895 if (was_initialized) {
899 _current_block_size = nframes;
905 AUPlugin::configure_io (ChanCount in, ChanCount out)
907 AudioStreamBasicDescription streamFormat;
908 bool was_initialized = initialized;
909 int32_t audio_in = in.n_audio();
910 int32_t audio_out = out.n_audio();
912 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
915 //if we are already running with the requested i/o config, bail out here
916 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
923 streamFormat.mSampleRate = _session.frame_rate();
924 streamFormat.mFormatID = kAudioFormatLinearPCM;
925 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
927 #ifdef __LITTLE_ENDIAN__
930 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
933 streamFormat.mBitsPerChannel = 32;
934 streamFormat.mFramesPerPacket = 1;
936 /* apple says that for non-interleaved data, these
937 values always refer to a single channel.
939 streamFormat.mBytesPerPacket = 4;
940 streamFormat.mBytesPerFrame = 4;
942 streamFormat.mChannelsPerFrame = audio_in;
944 if (set_input_format (streamFormat) != 0) {
948 streamFormat.mChannelsPerFrame = audio_out;
950 if (set_output_format (streamFormat) != 0) {
954 /* reset plugin info to show currently configured state */
956 _info->n_inputs = in;
957 _info->n_outputs = out;
959 if (was_initialized) {
967 AUPlugin::input_streams() const
971 c.set (DataType::AUDIO, 1);
972 c.set (DataType::MIDI, 0);
974 if (input_channels < 0) {
975 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
977 c.set (DataType::AUDIO, input_channels);
978 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
986 AUPlugin::output_streams() const
990 c.set (DataType::AUDIO, 1);
991 c.set (DataType::MIDI, 0);
993 if (output_channels < 0) {
994 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
996 c.set (DataType::AUDIO, output_channels);
997 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1004 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
1006 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1008 int32_t audio_in = in.n_audio();
1011 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1013 /* lets check MIDI first */
1015 if (in.n_midi() > 0) {
1016 if (!_has_midi_input) {
1021 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1023 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1024 name(), io_configs.size(), in, out));
1026 //Ardour expects the plugin to tell it the output
1027 //configuration but AU plugins can have multiple I/O
1028 //configurations in most cases. so first lets see
1029 //if there's a configuration that keeps out==in
1031 audio_out = audio_in;
1033 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1035 int32_t possible_in = i->first;
1036 int32_t possible_out = i->second;
1038 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1039 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1040 possible_in, possible_out,
1043 out.set (DataType::MIDI, 0);
1044 out.set (DataType::AUDIO, audio_out);
1050 /* now allow potentially "imprecise" matches */
1054 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1056 int32_t possible_in = i->first;
1057 int32_t possible_out = i->second;
1059 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1061 if (possible_out == 0) {
1062 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1063 /* XXX surely this is just a send? (e.g. AUNetSend) */
1067 if (possible_in == 0) {
1069 /* instrument plugin, always legal but throws away inputs ...
1072 if (possible_out == -1) {
1073 /* any configuration possible, provide stereo output */
1076 } else if (possible_out == -2) {
1077 /* plugins shouldn't really use (0,-2) but might.
1078 any configuration possible, provide stereo output
1082 } else if (possible_out < -2) {
1083 /* explicitly variable number of outputs.
1085 Since Ardour can handle any configuration,
1086 we have to somehow pick a number.
1088 We'll use the number of inputs
1089 to the master bus, or 2 if there
1092 boost::shared_ptr<Route> master = _session.master_out();
1094 audio_out = master->input()->n_ports().n_audio();
1100 /* exact number of outputs */
1101 audio_out = possible_out;
1106 if (possible_in == -1) {
1108 /* wildcard for input */
1110 if (possible_out == -1) {
1111 /* out much match in */
1112 audio_out = audio_in;
1114 } else if (possible_out == -2) {
1115 /* any configuration possible, pick matching */
1116 audio_out = audio_in;
1118 } else if (possible_out < -2) {
1119 /* explicitly variable number of outputs, pick maximum */
1120 audio_out = -possible_out;
1123 /* exact number of outputs */
1124 audio_out = possible_out;
1129 if (possible_in == -2) {
1131 if (possible_out == -1) {
1132 /* any configuration possible, pick matching */
1133 audio_out = audio_in;
1135 } else if (possible_out == -2) {
1136 /* plugins shouldn't really use (-2,-2) but might.
1137 interpret as (-1,-1).
1139 audio_out = audio_in;
1141 } else if (possible_out < -2) {
1142 /* explicitly variable number of outputs, pick maximum */
1143 audio_out = -possible_out;
1146 /* exact number of outputs */
1147 audio_out = possible_out;
1152 if (possible_in < -2) {
1154 /* explicit variable number of inputs */
1156 if (audio_in > -possible_in) {
1157 /* request is too large */
1161 if (possible_out == -1) {
1162 /* any output configuration possible, provide stereo out */
1165 } else if (possible_out == -2) {
1166 /* plugins shouldn't really use (<-2,-2) but might.
1167 interpret as (<-2,-1): any configuration possible, provide stereo output
1171 } else if (possible_out < -2) {
1172 /* explicitly variable number of outputs.
1174 Since Ardour can handle any configuration,
1175 we have to somehow pick a number.
1177 We'll use the number of inputs
1178 to the master bus, or 2 if there
1181 boost::shared_ptr<Route> master = _session.master_out();
1183 audio_out = master->input()->n_ports().n_audio();
1189 /* exact number of outputs */
1190 audio_out = possible_out;
1195 if (possible_in && (possible_in == audio_in)) {
1197 /* exact number of inputs ... must match obviously */
1199 if (possible_out == -1) {
1200 /* any output configuration possible, provide stereo output */
1203 } else if (possible_out == -2) {
1204 /* plugins shouldn't really use (>0,-2) but might.
1205 interpret as (>0,-1):
1206 any output configuration possible, provide stereo output
1210 } else if (possible_out < -2) {
1211 /* explicitly variable number of outputs, pick maximum */
1212 audio_out = -possible_out;
1215 /* exact number of outputs */
1216 audio_out = possible_out;
1228 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1230 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1234 out.set (DataType::MIDI, 0);
1235 out.set (DataType::AUDIO, audio_out);
1241 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1243 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1247 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1249 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1258 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1259 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1265 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1269 for (uint32_t i = 0; i < cnt; ++i) {
1270 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1271 (scope == kAudioUnitScope_Input ? "input" : "output"),
1273 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1274 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1275 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1280 if (scope == kAudioUnitScope_Input) {
1281 input_channels = fmt.mChannelsPerFrame;
1283 output_channels = fmt.mChannelsPerFrame;
1290 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1291 const AudioTimeStamp*,
1293 UInt32 inNumberFrames,
1294 AudioBufferList* ioData)
1296 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1298 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1299 name(), inNumberFrames, ioData->mNumberBuffers));
1301 if (input_maxbuf == 0) {
1302 error << _("AUPlugin: render callback called illegally!") << endmsg;
1303 return kAudioUnitErr_CannotDoInCurrentContext;
1305 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1307 for (uint32_t i = 0; i < limit; ++i) {
1308 ioData->mBuffers[i].mNumberChannels = 1;
1309 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1311 /* we don't use the channel mapping because audiounits are
1312 never replicated. one plugin instance uses all channels/buffers
1313 passed to PluginInsert::connect_and_run()
1316 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1319 cb_offset += inNumberFrames;
1325 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1327 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1329 AudioUnitRenderActionFlags flags = 0;
1333 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1334 unit->GlobalReset();
1335 _last_nframes = nframes;
1338 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1339 name(), input_channels, output_channels, _has_midi_input,
1340 bufs.count(), bufs.available()));
1342 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1343 has the capacity to handle our outputs.
1346 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1348 input_buffers = &bufs;
1349 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1350 input_offset = offset;
1353 buffers->mNumberBuffers = output_channels;
1355 for (int32_t i = 0; i < output_channels; ++i) {
1356 buffers->mBuffers[i].mNumberChannels = 1;
1357 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1358 /* setting this to 0 indicates to the AU that it can provide buffers here
1359 if necessary. if it can process in-place, it will use the buffers provided
1360 as input by ::render_callback() above.
1362 a non-null values tells the plugin to render into the buffer pointed
1365 buffers->mBuffers[i].mData = 0;
1368 if (_has_midi_input) {
1370 uint32_t nmidi = bufs.count().n_midi();
1372 for (uint32_t i = 0; i < nmidi; ++i) {
1374 /* one MIDI port/buffer only */
1376 MidiBuffer& m = bufs.get_midi (i);
1378 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1379 Evoral::MIDIEvent<framepos_t> ev (*i);
1381 if (ev.is_channel_event()) {
1382 const uint8_t* b = ev.buffer();
1383 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1384 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1387 /* XXX need to handle sysex and other message types */
1392 /* does this really mean anything ?
1395 ts.mSampleTime = frames_processed;
1396 ts.mFlags = kAudioTimeStampSampleTimeValid;
1398 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1399 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1401 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1404 frames_processed += nframes;
1406 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1407 name(), buffers->mNumberBuffers, output_channels));
1409 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1412 for (i = 0; i < limit; ++i) {
1413 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1414 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1415 /* plugin provided its own buffer for output so copy it back to where we want it
1417 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1421 /* now silence any buffers that were passed in but the that the plugin
1422 did not fill/touch/use.
1425 for (;i < output_channels; ++i) {
1426 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1432 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1437 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1438 Float64* outCurrentTempo)
1440 TempoMap& tmap (_session.tempo_map());
1442 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1444 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1445 (and interpretation) of a beat position will be incorrect. So refuse to
1449 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1450 return kAudioUnitErr_CannotDoInCurrentContext;
1453 Timecode::BBT_Time bbt;
1454 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1455 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1457 if (outCurrentBeat) {
1459 beat = metric.meter().divisions_per_bar() * bbt.bars;
1461 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1462 *outCurrentBeat = beat;
1465 if (outCurrentTempo) {
1466 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1474 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1475 Float32* outTimeSig_Numerator,
1476 UInt32* outTimeSig_Denominator,
1477 Float64* outCurrentMeasureDownBeat)
1479 TempoMap& tmap (_session.tempo_map());
1481 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1483 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1484 (and interpretation) of a beat position will be incorrect. So refuse to
1488 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1489 return kAudioUnitErr_CannotDoInCurrentContext;
1492 Timecode::BBT_Time bbt;
1493 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1494 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1496 if (outDeltaSampleOffsetToNextBeat) {
1497 if (bbt.ticks == 0) {
1499 *outDeltaSampleOffsetToNextBeat = 0;
1501 *outDeltaSampleOffsetToNextBeat = (UInt32)
1502 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1503 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1507 if (outTimeSig_Numerator) {
1508 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1510 if (outTimeSig_Denominator) {
1511 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1514 if (outCurrentMeasureDownBeat) {
1516 /* beat for the start of the bar.
1518 2|1|0 -> 1 + divisions_per_bar
1519 3|1|0 -> 1 + (2 * divisions_per_bar)
1523 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1530 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1531 Boolean* outTransportStateChanged,
1532 Float64* outCurrentSampleInTimeLine,
1533 Boolean* outIsCycling,
1534 Float64* outCycleStartBeat,
1535 Float64* outCycleEndBeat)
1540 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1542 rolling = _session.transport_rolling();
1543 speed = _session.transport_speed ();
1546 *outIsPlaying = _session.transport_rolling();
1549 if (outTransportStateChanged) {
1550 if (rolling != last_transport_rolling) {
1551 *outTransportStateChanged = true;
1552 } else if (speed != last_transport_speed) {
1553 *outTransportStateChanged = true;
1555 *outTransportStateChanged = false;
1559 if (outCurrentSampleInTimeLine) {
1560 /* this assumes that the AU can only call this host callback from render context,
1561 where input_offset is valid.
1563 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1567 Location* loc = _session.locations()->auto_loop_location();
1569 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1571 if (*outIsCycling) {
1573 if (outCycleStartBeat || outCycleEndBeat) {
1575 TempoMap& tmap (_session.tempo_map());
1577 /* more than 1 meter means that a simplistic computation (and interpretation) of
1578 a beat position will be incorrect. so refuse to offer the value.
1581 if (tmap.n_meters() > 1) {
1582 return kAudioUnitErr_CannotDoInCurrentContext;
1585 Timecode::BBT_Time bbt;
1587 if (outCycleStartBeat) {
1588 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1589 _session.tempo_map().bbt_time (loc->start(), bbt);
1592 beat = metric.meter().divisions_per_bar() * bbt.bars;
1594 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1596 *outCycleStartBeat = beat;
1599 if (outCycleEndBeat) {
1600 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1601 _session.tempo_map().bbt_time (loc->end(), bbt);
1604 beat = metric.meter().divisions_per_bar() * bbt.bars;
1606 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1608 *outCycleEndBeat = beat;
1614 last_transport_rolling = rolling;
1615 last_transport_speed = speed;
1620 set<Evoral::Parameter>
1621 AUPlugin::automatable() const
1623 set<Evoral::Parameter> automates;
1625 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1626 if (descriptors[i].automatable) {
1627 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1635 AUPlugin::describe_parameter (Evoral::Parameter param)
1637 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1638 return descriptors[param.id()].label;
1645 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1647 // NameValue stuff here
1651 AUPlugin::parameter_is_audio (uint32_t) const
1657 AUPlugin::parameter_is_control (uint32_t) const
1663 AUPlugin::parameter_is_input (uint32_t) const
1669 AUPlugin::parameter_is_output (uint32_t) const
1675 AUPlugin::add_state (XMLNode* root) const
1677 LocaleGuard lg (X_("POSIX"));
1679 #ifdef AU_STATE_SUPPORT
1681 CFPropertyListRef propertyList;
1683 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1684 if (unit->GetAUPreset (propertyList) != noErr) {
1688 // Convert the property list into XML data.
1690 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1693 error << _("Could not create XML version of property list") << endmsg;
1697 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1698 our state node. GACK!
1703 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1705 root->add_child_copy (*t.root());
1709 CFRelease (xmlData);
1710 CFRelease (propertyList);
1712 if (!seen_get_state_message) {
1713 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1716 seen_get_state_message = true;
1722 AUPlugin::set_state(const XMLNode& node, int version)
1724 #ifdef AU_STATE_SUPPORT
1726 CFPropertyListRef propertyList;
1727 LocaleGuard lg (X_("POSIX"));
1729 if (node.name() != state_node_name()) {
1730 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1734 if (node.children().empty()) {
1738 XMLNode* top = node.children().front();
1739 XMLNode* copy = new XMLNode (*top);
1744 const string& xml = t.write_buffer ();
1745 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1746 CFStringRef errorString;
1748 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1750 kCFPropertyListImmutable,
1753 CFRelease (xmlData);
1756 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1757 if (unit->SetAUPreset (propertyList) == noErr) {
1760 /* tell the world */
1762 AudioUnitParameter changedUnit;
1763 changedUnit.mAudioUnit = unit->AU();
1764 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1765 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1767 CFRelease (propertyList);
1770 Plugin::set_state (node, version);
1773 if (!seen_set_state_message) {
1774 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1778 return Plugin::set_state (node, version);
1783 AUPlugin::load_preset (PresetRecord r)
1785 Plugin::load_preset (r);
1787 #ifdef AU_STATE_SUPPORT
1789 CFPropertyListRef propertyList;
1791 UserPresetMap::iterator ux;
1792 FactoryPresetMap::iterator fx;
1794 /* look first in "user" presets */
1796 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1798 if ((propertyList = load_property_list (ux->second)) != 0) {
1799 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1800 if (unit->SetAUPreset (propertyList) == noErr) {
1803 /* tell the world */
1805 AudioUnitParameter changedUnit;
1806 changedUnit.mAudioUnit = unit->AU();
1807 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1808 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1810 CFRelease(propertyList);
1813 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1817 preset.presetNumber = fx->second;
1818 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1820 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1822 if (unit->SetPresentPreset (preset) == 0) {
1825 /* tell the world */
1827 AudioUnitParameter changedUnit;
1828 changedUnit.mAudioUnit = unit->AU();
1829 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1830 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1836 if (!seen_loading_message) {
1837 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1840 seen_loading_message = true;
1847 AUPlugin::do_remove_preset (std::string)
1852 AUPlugin::do_save_preset (string preset_name)
1854 #ifdef AU_STATE_SUPPORT
1855 CFPropertyListRef propertyList;
1856 vector<Glib::ustring> v;
1857 Glib::ustring user_preset_path;
1860 std::string m = maker();
1861 std::string n = name();
1863 strip_whitespace_edges (m);
1864 strip_whitespace_edges (n);
1866 v.push_back (Glib::get_home_dir());
1867 v.push_back ("Library");
1868 v.push_back ("Audio");
1869 v.push_back ("Presets");
1873 user_preset_path = Glib::build_filename (v);
1875 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1876 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1880 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1881 if (unit->GetAUPreset (propertyList) != noErr) {
1885 // add the actual preset name */
1887 v.push_back (preset_name + preset_suffix);
1891 user_preset_path = Glib::build_filename (v);
1893 set_preset_name_in_plist (propertyList, preset_name);
1895 if (save_property_list (propertyList, user_preset_path)) {
1896 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1900 CFRelease(propertyList);
1902 return string ("file:///") + user_preset_path;
1904 if (!seen_saving_message) {
1905 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1908 seen_saving_message = true;
1914 //-----------------------------------------------------------------------------
1915 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1917 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1919 CFNumberRef cfNumber;
1920 SInt32 numberValue = 0;
1921 Boolean dummySuccess;
1923 if (outSuccess == NULL)
1924 outSuccess = &dummySuccess;
1925 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1927 *outSuccess = FALSE;
1931 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1932 if (cfNumber == NULL)
1934 *outSuccess = FALSE;
1937 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1945 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1947 CFDictionaryRef auStateDictionary;
1948 ComponentDescription tempDesc = {0,0,0,0,0};
1949 SInt32 versionValue;
1952 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1955 // the property list for AU state data must be of the dictionary type
1956 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1957 return kAudioUnitErr_InvalidPropertyValue;
1960 auStateDictionary = (CFDictionaryRef)inAUStateData;
1962 // first check to make sure that the version of the AU state data is one that we know understand
1963 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1964 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1967 return kAudioUnitErr_InvalidPropertyValue;
1969 #define kCurrentSavedStateVersion 0
1970 if (versionValue != kCurrentSavedStateVersion) {
1971 return kAudioUnitErr_InvalidPropertyValue;
1974 // grab the ComponentDescription values from the AU state data
1975 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1976 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1977 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1978 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1979 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1980 return kAudioUnitErr_InvalidPropertyValue;
1982 *outComponentDescription = tempDesc;
1987 static bool au_preset_filter (const string& str, void* arg)
1989 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1993 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1997 /* check the preset file path name against this plugin
1998 ID. The idea is that all preset files for this plugin
1999 include "<manufacturer>/<plugin-name>" in their path.
2002 Plugin* p = (Plugin *) arg;
2003 string match = p->maker();
2007 ret = str.find (match) != string::npos;
2010 string m = p->maker ();
2011 string n = p->name ();
2012 strip_whitespace_edges (m);
2013 strip_whitespace_edges (n);
2018 ret = str.find (match) != string::npos;
2026 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2029 CFPropertyListRef plist;
2030 ComponentDescription presetDesc;
2033 plist = load_property_list (pathstr);
2039 // get the ComponentDescription from the AU preset file
2041 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2043 if (status == noErr) {
2044 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2046 /* try to get the preset name from the property list */
2048 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2050 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2054 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2057 char buf[PATH_MAX+1];
2059 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2074 AUPlugin::current_preset() const
2078 #ifdef AU_STATE_SUPPORT
2079 CFPropertyListRef propertyList;
2081 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2082 if (unit->GetAUPreset (propertyList) == noErr) {
2083 preset_name = get_preset_name_in_plist (propertyList);
2084 CFRelease(propertyList);
2091 AUPlugin::find_presets ()
2093 #ifdef AU_STATE_SUPPORT
2094 vector<string*>* preset_files;
2095 PathScanner scanner;
2097 user_preset_map.clear ();
2099 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2101 if (!preset_files) {
2105 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2107 string path = *(*x);
2110 /* make an initial guess at the preset name using the path */
2112 preset_name = Glib::path_get_basename (path);
2113 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2115 /* check that this preset file really matches this plugin
2116 and potentially get the "real" preset name from
2120 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2121 user_preset_map[preset_name] = path;
2127 delete preset_files;
2129 /* now fill the vector<string> with the names we have */
2131 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2132 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2135 /* add factory presets */
2137 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2139 string const uri = string_compose ("%1", _presets.size ());
2140 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2147 AUPlugin::has_editor () const
2149 // even if the plugin doesn't have its own editor, the AU API can be used
2150 // to create one that looks native.
2154 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2157 type = ARDOUR::AudioUnit;
2160 AUPluginInfo::~AUPluginInfo ()
2162 type = ARDOUR::AudioUnit;
2166 AUPluginInfo::load (Session& session)
2171 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2172 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2174 if (!comp->IsValid()) {
2175 error << ("AudioUnit: not a valid Component") << endmsg;
2177 plugin.reset (new AUPlugin (session.engine(), session, comp));
2180 AUPluginInfo *aup = new AUPluginInfo (*this);
2181 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2182 plugin->set_info (PluginInfoPtr (aup));
2183 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2187 catch (failed_constructor &err) {
2188 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2189 return PluginPtr ();
2194 AUPluginInfo::au_cache_path ()
2196 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2200 AUPluginInfo::discover ()
2204 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2205 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2208 PluginInfoList* plugs = new PluginInfoList;
2210 discover_fx (*plugs);
2211 discover_music (*plugs);
2212 discover_generators (*plugs);
2213 discover_instruments (*plugs);
2215 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2221 AUPluginInfo::discover_music (PluginInfoList& plugs)
2223 CAComponentDescription desc;
2224 desc.componentFlags = 0;
2225 desc.componentFlagsMask = 0;
2226 desc.componentSubType = 0;
2227 desc.componentManufacturer = 0;
2228 desc.componentType = kAudioUnitType_MusicEffect;
2230 discover_by_description (plugs, desc);
2234 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2236 CAComponentDescription desc;
2237 desc.componentFlags = 0;
2238 desc.componentFlagsMask = 0;
2239 desc.componentSubType = 0;
2240 desc.componentManufacturer = 0;
2241 desc.componentType = kAudioUnitType_Effect;
2243 discover_by_description (plugs, desc);
2247 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2249 CAComponentDescription desc;
2250 desc.componentFlags = 0;
2251 desc.componentFlagsMask = 0;
2252 desc.componentSubType = 0;
2253 desc.componentManufacturer = 0;
2254 desc.componentType = kAudioUnitType_Generator;
2256 discover_by_description (plugs, desc);
2260 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2262 CAComponentDescription desc;
2263 desc.componentFlags = 0;
2264 desc.componentFlagsMask = 0;
2265 desc.componentSubType = 0;
2266 desc.componentManufacturer = 0;
2267 desc.componentType = kAudioUnitType_MusicDevice;
2269 discover_by_description (plugs, desc);
2273 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2277 comp = FindNextComponent (NULL, &desc);
2279 while (comp != NULL) {
2280 CAComponentDescription temp;
2281 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2283 AUPluginInfoPtr info (new AUPluginInfo
2284 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2286 /* although apple designed the subtype field to be a "category" indicator,
2287 its really turned into a plugin ID field for a given manufacturer. Hence
2288 there are no categories for AudioUnits. However, to keep the plugins
2289 showing up under "categories", we'll use the "type" as a high level
2292 NOTE: no panners, format converters or i/o AU's for our purposes
2295 switch (info->descriptor->Type()) {
2296 case kAudioUnitType_Panner:
2297 case kAudioUnitType_OfflineEffect:
2298 case kAudioUnitType_FormatConverter:
2301 case kAudioUnitType_Output:
2302 info->category = _("AudioUnit Outputs");
2304 case kAudioUnitType_MusicDevice:
2305 info->category = _("AudioUnit Instruments");
2307 case kAudioUnitType_MusicEffect:
2308 info->category = _("AudioUnit MusicEffects");
2310 case kAudioUnitType_Effect:
2311 info->category = _("AudioUnit Effects");
2313 case kAudioUnitType_Mixer:
2314 info->category = _("AudioUnit Mixers");
2316 case kAudioUnitType_Generator:
2317 info->category = _("AudioUnit Generators");
2320 info->category = _("AudioUnit (Unknown)");
2324 AUPluginInfo::get_names (temp, info->name, info->creator);
2326 info->type = ARDOUR::AudioUnit;
2327 info->unique_id = stringify_descriptor (*info->descriptor);
2329 /* XXX not sure of the best way to handle plugin versioning yet
2332 CAComponent cacomp (*info->descriptor);
2334 if (cacomp.GetResourceVersion (info->version) != noErr) {
2338 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2340 /* here we have to map apple's wildcard system to a simple pair
2341 of values. in ::can_do() we use the whole system, but here
2342 we need a single pair of values. XXX probably means we should
2343 remove any use of these values.
2345 for now, if the plugin provides a wildcard, treat it as 1. we really
2346 don't care much, because whether we can handle an i/o configuration
2347 depends upon ::can_support_io_configuration(), not these counts.
2349 they exist because other parts of ardour try to present i/o configuration
2350 info to the user, which should perhaps be revisited.
2353 int32_t possible_in = info->cache.io_configs.front().first;
2354 int32_t possible_out = info->cache.io_configs.front().second;
2356 if (possible_in > 0) {
2357 info->n_inputs.set (DataType::AUDIO, possible_in);
2359 info->n_inputs.set (DataType::AUDIO, 1);
2362 if (possible_out > 0) {
2363 info->n_outputs.set (DataType::AUDIO, possible_out);
2365 info->n_outputs.set (DataType::AUDIO, 1);
2368 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2369 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2371 plugs.push_back (info);
2374 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2377 comp = FindNextComponent (comp, &desc);
2382 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2385 AUPluginCachedInfo& cinfo,
2386 const std::string& name)
2391 /* concatenate unique ID with version to provide a key for cached info lookup.
2392 this ensures we don't get stale information, or should if plugin developers
2393 follow Apple "guidelines".
2396 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2401 CachedInfoMap::iterator cim = cached_info.find (id);
2403 if (cim != cached_info.end()) {
2404 cinfo = cim->second;
2409 AUChannelInfo* channel_info;
2413 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2417 if (CAAudioUnit::Open (comp, unit) != noErr) {
2423 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2428 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2429 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2435 /* no explicit info available, so default to 1in/1out */
2437 /* XXX this is wrong. we should be indicating wildcard values */
2439 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2443 /* store each configuration */
2445 for (uint32_t n = 0; n < cnt; ++n) {
2446 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2447 channel_info[n].outChannels));
2450 free (channel_info);
2453 add_cached_info (id, cinfo);
2454 save_cached_info ();
2460 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2462 cached_info[id] = cinfo;
2465 #define AU_CACHE_VERSION "2.0"
2468 AUPluginInfo::save_cached_info ()
2472 node = new XMLNode (X_("AudioUnitPluginCache"));
2473 node->add_property( "version", AU_CACHE_VERSION );
2475 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2476 XMLNode* parent = new XMLNode (X_("plugin"));
2477 parent->add_property ("id", i->first);
2478 node->add_child_nocopy (*parent);
2480 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2482 XMLNode* child = new XMLNode (X_("io"));
2485 snprintf (buf, sizeof (buf), "%d", j->first);
2486 child->add_property (X_("in"), buf);
2487 snprintf (buf, sizeof (buf), "%d", j->second);
2488 child->add_property (X_("out"), buf);
2489 parent->add_child_nocopy (*child);
2494 Glib::ustring path = au_cache_path ();
2497 tree.set_root (node);
2499 if (!tree.write (path)) {
2500 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2501 unlink (path.c_str());
2506 AUPluginInfo::load_cached_info ()
2508 Glib::ustring path = au_cache_path ();
2511 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2515 if ( !tree.read (path) ) {
2516 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2520 const XMLNode* root (tree.root());
2522 if (root->name() != X_("AudioUnitPluginCache")) {
2526 //initial version has incorrectly stored i/o info, and/or garbage chars.
2527 const XMLProperty* version = root->property(X_("version"));
2528 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2529 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2533 cached_info.clear ();
2535 const XMLNodeList children = root->children();
2537 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2539 const XMLNode* child = *iter;
2541 if (child->name() == X_("plugin")) {
2543 const XMLNode* gchild;
2544 const XMLNodeList gchildren = child->children();
2545 const XMLProperty* prop = child->property (X_("id"));
2551 string id = prop->value();
2555 string::size_type slash = id.find_last_of ('/');
2557 if (slash == string::npos) {
2561 version = id.substr (slash);
2562 id = id.substr (0, slash);
2563 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2565 if (fixed.empty()) {
2566 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2573 AUPluginCachedInfo cinfo;
2575 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2579 if (gchild->name() == X_("io")) {
2583 const XMLProperty* iprop;
2584 const XMLProperty* oprop;
2586 if (((iprop = gchild->property (X_("in"))) != 0) &&
2587 ((oprop = gchild->property (X_("out"))) != 0)) {
2588 in = atoi (iprop->value());
2589 out = atoi (oprop->value());
2591 cinfo.io_configs.push_back (pair<int,int> (in, out));
2596 if (cinfo.io_configs.size()) {
2597 add_cached_info (id, cinfo);
2606 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2608 CFStringRef itemName = NULL;
2610 // Marc Poirier-style item name
2611 CAComponent auComponent (comp_desc);
2612 if (auComponent.IsValid()) {
2613 CAComponentDescription dummydesc;
2614 Handle nameHandle = NewHandle(sizeof(void*));
2615 if (nameHandle != NULL) {
2616 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2618 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2619 if (nameString != NULL) {
2620 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2623 DisposeHandle(nameHandle);
2627 // if Marc-style fails, do the original way
2628 if (itemName == NULL) {
2629 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2630 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2631 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2633 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2634 compTypeString, compManufacturerString, compSubTypeString);
2636 if (compTypeString != NULL)
2637 CFRelease(compTypeString);
2638 if (compSubTypeString != NULL)
2639 CFRelease(compSubTypeString);
2640 if (compManufacturerString != NULL)
2641 CFRelease(compManufacturerString);
2644 string str = CFStringRefToStdString(itemName);
2645 string::size_type colon = str.find (':');
2648 name = str.substr (colon+1);
2649 maker = str.substr (0, colon);
2650 strip_whitespace_edges (maker);
2651 strip_whitespace_edges (name);
2655 strip_whitespace_edges (name);
2660 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2664 /* note: OSType is a compiler-implemenation-defined value,
2665 historically a 32 bit integer created with a multi-character
2666 constant such as 'abcd'. It is, fundamentally, an abomination.
2671 s << desc.SubType();
2679 AUPluginInfo::needs_midi_input ()
2681 return is_effect_with_midi_input () || is_instrument ();
2685 AUPluginInfo::is_effect () const
2687 return is_effect_without_midi_input() || is_effect_with_midi_input();
2691 AUPluginInfo::is_effect_without_midi_input () const
2693 return descriptor->IsAUFX();
2697 AUPluginInfo::is_effect_with_midi_input () const
2699 return descriptor->IsAUFM();
2703 AUPluginInfo::is_instrument () const
2705 return descriptor->IsMusicDevice();
2709 AUPlugin::set_info (PluginInfoPtr info)
2711 Plugin::set_info (info);
2713 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2714 _has_midi_input = pinfo->needs_midi_input ();
2715 _has_midi_output = false;
2719 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2722 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2724 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2726 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2728 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2732 _parameter_listener_arg = arg;
2738 AUPlugin::listen_to_parameter (uint32_t param_id)
2740 AudioUnitEvent event;
2742 if (!_parameter_listener || param_id >= descriptors.size()) {
2746 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2747 event.mArgument.mParameter.mAudioUnit = unit->AU();
2748 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2749 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2750 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2752 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2760 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2762 AudioUnitEvent event;
2764 if (!_parameter_listener || param_id >= descriptors.size()) {
2768 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2769 event.mArgument.mParameter.mAudioUnit = unit->AU();
2770 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2771 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2772 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2774 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2782 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2784 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2788 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2790 ParameterMap::iterator i = parameter_map.find (event->mArgument.mParameter.mParameterID);
2792 if (i != parameter_map.end()) {
2793 ParameterChanged (i->second, new_value);