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 #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 if (get_parameter(which) == val) {
791 const AUParameterDescriptor& d (descriptors[which]);
792 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
793 unit->SetParameter (d.id, d.scope, d.element, val);
795 /* tell the world what we did */
797 AudioUnitEvent theEvent;
799 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
800 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
801 theEvent.mArgument.mParameter.mParameterID = d.id;
802 theEvent.mArgument.mParameter.mScope = d.scope;
803 theEvent.mArgument.mParameter.mElement = d.element;
805 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
806 AUEventListenerNotify (NULL, NULL, &theEvent);
808 Plugin::set_parameter (which, val);
812 AUPlugin::get_parameter (uint32_t which) const
815 if (which < descriptors.size()) {
816 const AUParameterDescriptor& d (descriptors[which]);
817 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
818 unit->GetParameter(d.id, d.scope, d.element, val);
824 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
826 if (which < descriptors.size()) {
827 pd = descriptors[which];
834 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
836 if (which < descriptors.size()) {
845 AUPlugin::activate ()
849 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
850 if ((err = unit->Initialize()) != noErr) {
851 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
853 frames_processed = 0;
860 AUPlugin::deactivate ()
862 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
863 unit->Uninitialize ();
870 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
871 unit->GlobalReset ();
875 AUPlugin::requires_fixed_size_buffers() const
877 return _requires_fixed_size_buffers;
882 AUPlugin::set_block_size (pframes_t nframes)
884 bool was_initialized = initialized;
885 UInt32 numFrames = nframes;
892 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
893 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
894 0, &numFrames, sizeof (numFrames))) != noErr) {
895 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
899 if (was_initialized) {
903 _current_block_size = nframes;
909 AUPlugin::configure_io (ChanCount in, ChanCount out)
911 AudioStreamBasicDescription streamFormat;
912 bool was_initialized = initialized;
913 int32_t audio_in = in.n_audio();
914 int32_t audio_out = out.n_audio();
916 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
919 //if we are already running with the requested i/o config, bail out here
920 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
927 streamFormat.mSampleRate = _session.frame_rate();
928 streamFormat.mFormatID = kAudioFormatLinearPCM;
929 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
931 #ifdef __LITTLE_ENDIAN__
934 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
937 streamFormat.mBitsPerChannel = 32;
938 streamFormat.mFramesPerPacket = 1;
940 /* apple says that for non-interleaved data, these
941 values always refer to a single channel.
943 streamFormat.mBytesPerPacket = 4;
944 streamFormat.mBytesPerFrame = 4;
946 streamFormat.mChannelsPerFrame = audio_in;
948 if (set_input_format (streamFormat) != 0) {
952 streamFormat.mChannelsPerFrame = audio_out;
954 if (set_output_format (streamFormat) != 0) {
958 /* reset plugin info to show currently configured state */
960 _info->n_inputs = in;
961 _info->n_outputs = out;
963 if (was_initialized) {
971 AUPlugin::input_streams() const
975 c.set (DataType::AUDIO, 1);
976 c.set (DataType::MIDI, 0);
978 if (input_channels < 0) {
979 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
981 c.set (DataType::AUDIO, input_channels);
982 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
990 AUPlugin::output_streams() const
994 c.set (DataType::AUDIO, 1);
995 c.set (DataType::MIDI, 0);
997 if (output_channels < 0) {
998 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
1000 c.set (DataType::AUDIO, output_channels);
1001 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1008 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
1010 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1012 int32_t audio_in = in.n_audio();
1015 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1017 /* lets check MIDI first */
1019 if (in.n_midi() > 0) {
1020 if (!_has_midi_input) {
1025 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1027 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1028 name(), io_configs.size(), in, out));
1030 //Ardour expects the plugin to tell it the output
1031 //configuration but AU plugins can have multiple I/O
1032 //configurations in most cases. so first lets see
1033 //if there's a configuration that keeps out==in
1035 audio_out = audio_in;
1037 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1039 int32_t possible_in = i->first;
1040 int32_t possible_out = i->second;
1042 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1043 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1044 possible_in, possible_out,
1047 out.set (DataType::MIDI, 0);
1048 out.set (DataType::AUDIO, audio_out);
1054 /* now allow potentially "imprecise" matches */
1058 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1060 int32_t possible_in = i->first;
1061 int32_t possible_out = i->second;
1063 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1065 if (possible_out == 0) {
1066 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1067 /* XXX surely this is just a send? (e.g. AUNetSend) */
1071 if (possible_in == 0) {
1073 /* instrument plugin, always legal but throws away inputs ...
1076 if (possible_out == -1) {
1077 /* any configuration possible, provide stereo output */
1080 } else if (possible_out == -2) {
1081 /* plugins shouldn't really use (0,-2) but might.
1082 any configuration possible, provide stereo output
1086 } else if (possible_out < -2) {
1087 /* explicitly variable number of outputs.
1089 Since Ardour can handle any configuration,
1090 we have to somehow pick a number.
1092 We'll use the number of inputs
1093 to the master bus, or 2 if there
1096 boost::shared_ptr<Route> master = _session.master_out();
1098 audio_out = master->input()->n_ports().n_audio();
1104 /* exact number of outputs */
1105 audio_out = possible_out;
1110 if (possible_in == -1) {
1112 /* wildcard for input */
1114 if (possible_out == -1) {
1115 /* out much match in */
1116 audio_out = audio_in;
1118 } else if (possible_out == -2) {
1119 /* any configuration possible, pick matching */
1120 audio_out = audio_in;
1122 } else if (possible_out < -2) {
1123 /* explicitly variable number of outputs, pick maximum */
1124 audio_out = -possible_out;
1127 /* exact number of outputs */
1128 audio_out = possible_out;
1133 if (possible_in == -2) {
1135 if (possible_out == -1) {
1136 /* any configuration possible, pick matching */
1137 audio_out = audio_in;
1139 } else if (possible_out == -2) {
1140 /* plugins shouldn't really use (-2,-2) but might.
1141 interpret as (-1,-1).
1143 audio_out = audio_in;
1145 } else if (possible_out < -2) {
1146 /* explicitly variable number of outputs, pick maximum */
1147 audio_out = -possible_out;
1150 /* exact number of outputs */
1151 audio_out = possible_out;
1156 if (possible_in < -2) {
1158 /* explicit variable number of inputs */
1160 if (audio_in > -possible_in) {
1161 /* request is too large */
1165 if (possible_out == -1) {
1166 /* any output configuration possible, provide stereo out */
1169 } else if (possible_out == -2) {
1170 /* plugins shouldn't really use (<-2,-2) but might.
1171 interpret as (<-2,-1): any configuration possible, provide stereo output
1175 } else if (possible_out < -2) {
1176 /* explicitly variable number of outputs.
1178 Since Ardour can handle any configuration,
1179 we have to somehow pick a number.
1181 We'll use the number of inputs
1182 to the master bus, or 2 if there
1185 boost::shared_ptr<Route> master = _session.master_out();
1187 audio_out = master->input()->n_ports().n_audio();
1193 /* exact number of outputs */
1194 audio_out = possible_out;
1199 if (possible_in && (possible_in == audio_in)) {
1201 /* exact number of inputs ... must match obviously */
1203 if (possible_out == -1) {
1204 /* any output configuration possible, provide stereo output */
1207 } else if (possible_out == -2) {
1208 /* plugins shouldn't really use (>0,-2) but might.
1209 interpret as (>0,-1):
1210 any output configuration possible, provide stereo output
1214 } else if (possible_out < -2) {
1215 /* explicitly variable number of outputs, pick maximum */
1216 audio_out = -possible_out;
1219 /* exact number of outputs */
1220 audio_out = possible_out;
1232 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1234 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1238 out.set (DataType::MIDI, 0);
1239 out.set (DataType::AUDIO, audio_out);
1245 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1247 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1251 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1253 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1262 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1263 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1269 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1273 for (uint32_t i = 0; i < cnt; ++i) {
1274 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1275 (scope == kAudioUnitScope_Input ? "input" : "output"),
1277 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1278 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1279 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1284 if (scope == kAudioUnitScope_Input) {
1285 input_channels = fmt.mChannelsPerFrame;
1287 output_channels = fmt.mChannelsPerFrame;
1294 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1295 const AudioTimeStamp*,
1297 UInt32 inNumberFrames,
1298 AudioBufferList* ioData)
1300 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1302 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1303 name(), inNumberFrames, ioData->mNumberBuffers));
1305 if (input_maxbuf == 0) {
1306 error << _("AUPlugin: render callback called illegally!") << endmsg;
1307 return kAudioUnitErr_CannotDoInCurrentContext;
1309 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1311 for (uint32_t i = 0; i < limit; ++i) {
1312 ioData->mBuffers[i].mNumberChannels = 1;
1313 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1315 /* we don't use the channel mapping because audiounits are
1316 never replicated. one plugin instance uses all channels/buffers
1317 passed to PluginInsert::connect_and_run()
1320 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1323 cb_offset += inNumberFrames;
1329 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1331 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1333 AudioUnitRenderActionFlags flags = 0;
1337 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1338 unit->GlobalReset();
1339 _last_nframes = nframes;
1342 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1343 name(), input_channels, output_channels, _has_midi_input,
1344 bufs.count(), bufs.available()));
1346 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1347 has the capacity to handle our outputs.
1350 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1352 input_buffers = &bufs;
1353 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1354 input_offset = offset;
1357 buffers->mNumberBuffers = output_channels;
1359 for (int32_t i = 0; i < output_channels; ++i) {
1360 buffers->mBuffers[i].mNumberChannels = 1;
1361 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1362 /* setting this to 0 indicates to the AU that it can provide buffers here
1363 if necessary. if it can process in-place, it will use the buffers provided
1364 as input by ::render_callback() above.
1366 a non-null values tells the plugin to render into the buffer pointed
1369 buffers->mBuffers[i].mData = 0;
1372 if (_has_midi_input) {
1374 uint32_t nmidi = bufs.count().n_midi();
1376 for (uint32_t i = 0; i < nmidi; ++i) {
1378 /* one MIDI port/buffer only */
1380 MidiBuffer& m = bufs.get_midi (i);
1382 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1383 Evoral::MIDIEvent<framepos_t> ev (*i);
1385 if (ev.is_channel_event()) {
1386 const uint8_t* b = ev.buffer();
1387 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1388 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1391 /* XXX need to handle sysex and other message types */
1396 /* does this really mean anything ?
1399 ts.mSampleTime = frames_processed;
1400 ts.mFlags = kAudioTimeStampSampleTimeValid;
1402 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1403 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1405 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1408 frames_processed += nframes;
1410 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1411 name(), buffers->mNumberBuffers, output_channels));
1413 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1416 for (i = 0; i < limit; ++i) {
1417 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1418 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1419 /* plugin provided its own buffer for output so copy it back to where we want it
1421 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1425 /* now silence any buffers that were passed in but the that the plugin
1426 did not fill/touch/use.
1429 for (;i < output_channels; ++i) {
1430 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1436 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1441 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1442 Float64* outCurrentTempo)
1444 TempoMap& tmap (_session.tempo_map());
1446 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1448 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1449 (and interpretation) of a beat position will be incorrect. So refuse to
1453 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1454 return kAudioUnitErr_CannotDoInCurrentContext;
1457 Timecode::BBT_Time bbt;
1458 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1459 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1461 if (outCurrentBeat) {
1463 beat = metric.meter().divisions_per_bar() * bbt.bars;
1465 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1466 *outCurrentBeat = beat;
1469 if (outCurrentTempo) {
1470 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1478 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1479 Float32* outTimeSig_Numerator,
1480 UInt32* outTimeSig_Denominator,
1481 Float64* outCurrentMeasureDownBeat)
1483 TempoMap& tmap (_session.tempo_map());
1485 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1487 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1488 (and interpretation) of a beat position will be incorrect. So refuse to
1492 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1493 return kAudioUnitErr_CannotDoInCurrentContext;
1496 Timecode::BBT_Time bbt;
1497 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1498 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1500 if (outDeltaSampleOffsetToNextBeat) {
1501 if (bbt.ticks == 0) {
1503 *outDeltaSampleOffsetToNextBeat = 0;
1505 *outDeltaSampleOffsetToNextBeat = (UInt32)
1506 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1507 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1511 if (outTimeSig_Numerator) {
1512 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1514 if (outTimeSig_Denominator) {
1515 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1518 if (outCurrentMeasureDownBeat) {
1520 /* beat for the start of the bar.
1522 2|1|0 -> 1 + divisions_per_bar
1523 3|1|0 -> 1 + (2 * divisions_per_bar)
1527 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1534 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1535 Boolean* outTransportStateChanged,
1536 Float64* outCurrentSampleInTimeLine,
1537 Boolean* outIsCycling,
1538 Float64* outCycleStartBeat,
1539 Float64* outCycleEndBeat)
1544 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1546 rolling = _session.transport_rolling();
1547 speed = _session.transport_speed ();
1550 *outIsPlaying = _session.transport_rolling();
1553 if (outTransportStateChanged) {
1554 if (rolling != last_transport_rolling) {
1555 *outTransportStateChanged = true;
1556 } else if (speed != last_transport_speed) {
1557 *outTransportStateChanged = true;
1559 *outTransportStateChanged = false;
1563 if (outCurrentSampleInTimeLine) {
1564 /* this assumes that the AU can only call this host callback from render context,
1565 where input_offset is valid.
1567 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1571 Location* loc = _session.locations()->auto_loop_location();
1573 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1575 if (*outIsCycling) {
1577 if (outCycleStartBeat || outCycleEndBeat) {
1579 TempoMap& tmap (_session.tempo_map());
1581 /* more than 1 meter means that a simplistic computation (and interpretation) of
1582 a beat position will be incorrect. so refuse to offer the value.
1585 if (tmap.n_meters() > 1) {
1586 return kAudioUnitErr_CannotDoInCurrentContext;
1589 Timecode::BBT_Time bbt;
1591 if (outCycleStartBeat) {
1592 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1593 _session.tempo_map().bbt_time (loc->start(), bbt);
1596 beat = metric.meter().divisions_per_bar() * bbt.bars;
1598 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1600 *outCycleStartBeat = beat;
1603 if (outCycleEndBeat) {
1604 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1605 _session.tempo_map().bbt_time (loc->end(), bbt);
1608 beat = metric.meter().divisions_per_bar() * bbt.bars;
1610 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1612 *outCycleEndBeat = beat;
1618 last_transport_rolling = rolling;
1619 last_transport_speed = speed;
1624 set<Evoral::Parameter>
1625 AUPlugin::automatable() const
1627 set<Evoral::Parameter> automates;
1629 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1630 if (descriptors[i].automatable) {
1631 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1639 AUPlugin::describe_parameter (Evoral::Parameter param)
1641 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1642 return descriptors[param.id()].label;
1649 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1651 // NameValue stuff here
1655 AUPlugin::parameter_is_audio (uint32_t) const
1661 AUPlugin::parameter_is_control (uint32_t) const
1667 AUPlugin::parameter_is_input (uint32_t) const
1673 AUPlugin::parameter_is_output (uint32_t) const
1679 AUPlugin::add_state (XMLNode* root) const
1681 LocaleGuard lg (X_("POSIX"));
1683 #ifdef AU_STATE_SUPPORT
1685 CFPropertyListRef propertyList;
1687 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1688 if (unit->GetAUPreset (propertyList) != noErr) {
1692 // Convert the property list into XML data.
1694 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1697 error << _("Could not create XML version of property list") << endmsg;
1701 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1702 our state node. GACK!
1707 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1709 root->add_child_copy (*t.root());
1713 CFRelease (xmlData);
1714 CFRelease (propertyList);
1716 if (!seen_get_state_message) {
1717 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1720 seen_get_state_message = true;
1726 AUPlugin::set_state(const XMLNode& node, int version)
1728 #ifdef AU_STATE_SUPPORT
1730 CFPropertyListRef propertyList;
1731 LocaleGuard lg (X_("POSIX"));
1733 if (node.name() != state_node_name()) {
1734 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1738 if (node.children().empty()) {
1742 XMLNode* top = node.children().front();
1743 XMLNode* copy = new XMLNode (*top);
1748 const string& xml = t.write_buffer ();
1749 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1750 CFStringRef errorString;
1752 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1754 kCFPropertyListImmutable,
1757 CFRelease (xmlData);
1760 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1761 if (unit->SetAUPreset (propertyList) == noErr) {
1764 /* tell the world */
1766 AudioUnitParameter changedUnit;
1767 changedUnit.mAudioUnit = unit->AU();
1768 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1769 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1771 CFRelease (propertyList);
1774 Plugin::set_state (node, version);
1777 if (!seen_set_state_message) {
1778 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1782 return Plugin::set_state (node, version);
1787 AUPlugin::load_preset (PresetRecord r)
1789 Plugin::load_preset (r);
1791 #ifdef AU_STATE_SUPPORT
1793 CFPropertyListRef propertyList;
1795 UserPresetMap::iterator ux;
1796 FactoryPresetMap::iterator fx;
1798 /* look first in "user" presets */
1800 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1802 if ((propertyList = load_property_list (ux->second)) != 0) {
1803 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1804 if (unit->SetAUPreset (propertyList) == noErr) {
1807 /* tell the world */
1809 AudioUnitParameter changedUnit;
1810 changedUnit.mAudioUnit = unit->AU();
1811 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1812 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1814 CFRelease(propertyList);
1817 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1821 preset.presetNumber = fx->second;
1822 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1824 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1826 if (unit->SetPresentPreset (preset) == 0) {
1829 /* tell the world */
1831 AudioUnitParameter changedUnit;
1832 changedUnit.mAudioUnit = unit->AU();
1833 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1834 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1840 if (!seen_loading_message) {
1841 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1844 seen_loading_message = true;
1851 AUPlugin::do_remove_preset (std::string)
1856 AUPlugin::do_save_preset (string preset_name)
1858 #ifdef AU_STATE_SUPPORT
1859 CFPropertyListRef propertyList;
1860 vector<Glib::ustring> v;
1861 Glib::ustring user_preset_path;
1864 std::string m = maker();
1865 std::string n = name();
1867 strip_whitespace_edges (m);
1868 strip_whitespace_edges (n);
1870 v.push_back (Glib::get_home_dir());
1871 v.push_back ("Library");
1872 v.push_back ("Audio");
1873 v.push_back ("Presets");
1877 user_preset_path = Glib::build_filename (v);
1879 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1880 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1884 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1885 if (unit->GetAUPreset (propertyList) != noErr) {
1889 // add the actual preset name */
1891 v.push_back (preset_name + preset_suffix);
1895 user_preset_path = Glib::build_filename (v);
1897 set_preset_name_in_plist (propertyList, preset_name);
1899 if (save_property_list (propertyList, user_preset_path)) {
1900 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1904 CFRelease(propertyList);
1906 return string ("file:///") + user_preset_path;
1908 if (!seen_saving_message) {
1909 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1912 seen_saving_message = true;
1918 //-----------------------------------------------------------------------------
1919 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1921 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1923 CFNumberRef cfNumber;
1924 SInt32 numberValue = 0;
1925 Boolean dummySuccess;
1927 if (outSuccess == NULL)
1928 outSuccess = &dummySuccess;
1929 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1931 *outSuccess = FALSE;
1935 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1936 if (cfNumber == NULL)
1938 *outSuccess = FALSE;
1941 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1949 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1951 CFDictionaryRef auStateDictionary;
1952 ComponentDescription tempDesc = {0,0,0,0,0};
1953 SInt32 versionValue;
1956 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1959 // the property list for AU state data must be of the dictionary type
1960 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1961 return kAudioUnitErr_InvalidPropertyValue;
1964 auStateDictionary = (CFDictionaryRef)inAUStateData;
1966 // first check to make sure that the version of the AU state data is one that we know understand
1967 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1968 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1971 return kAudioUnitErr_InvalidPropertyValue;
1973 #define kCurrentSavedStateVersion 0
1974 if (versionValue != kCurrentSavedStateVersion) {
1975 return kAudioUnitErr_InvalidPropertyValue;
1978 // grab the ComponentDescription values from the AU state data
1979 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1980 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1981 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1982 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1983 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1984 return kAudioUnitErr_InvalidPropertyValue;
1986 *outComponentDescription = tempDesc;
1991 static bool au_preset_filter (const string& str, void* arg)
1993 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1997 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2001 /* check the preset file path name against this plugin
2002 ID. The idea is that all preset files for this plugin
2003 include "<manufacturer>/<plugin-name>" in their path.
2006 Plugin* p = (Plugin *) arg;
2007 string match = p->maker();
2011 ret = str.find (match) != string::npos;
2014 string m = p->maker ();
2015 string n = p->name ();
2016 strip_whitespace_edges (m);
2017 strip_whitespace_edges (n);
2022 ret = str.find (match) != string::npos;
2030 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2033 CFPropertyListRef plist;
2034 ComponentDescription presetDesc;
2037 plist = load_property_list (pathstr);
2043 // get the ComponentDescription from the AU preset file
2045 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2047 if (status == noErr) {
2048 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2050 /* try to get the preset name from the property list */
2052 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2054 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2058 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2061 char buf[PATH_MAX+1];
2063 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2078 AUPlugin::current_preset() const
2082 #ifdef AU_STATE_SUPPORT
2083 CFPropertyListRef propertyList;
2085 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2086 if (unit->GetAUPreset (propertyList) == noErr) {
2087 preset_name = get_preset_name_in_plist (propertyList);
2088 CFRelease(propertyList);
2095 AUPlugin::find_presets ()
2097 #ifdef AU_STATE_SUPPORT
2098 vector<string*>* preset_files;
2099 PathScanner scanner;
2101 user_preset_map.clear ();
2103 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2105 if (!preset_files) {
2109 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2111 string path = *(*x);
2114 /* make an initial guess at the preset name using the path */
2116 preset_name = Glib::path_get_basename (path);
2117 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2119 /* check that this preset file really matches this plugin
2120 and potentially get the "real" preset name from
2124 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2125 user_preset_map[preset_name] = path;
2131 delete preset_files;
2133 /* now fill the vector<string> with the names we have */
2135 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2136 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2139 /* add factory presets */
2141 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2143 string const uri = string_compose ("%1", _presets.size ());
2144 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2151 AUPlugin::has_editor () const
2153 // even if the plugin doesn't have its own editor, the AU API can be used
2154 // to create one that looks native.
2158 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2161 type = ARDOUR::AudioUnit;
2164 AUPluginInfo::~AUPluginInfo ()
2166 type = ARDOUR::AudioUnit;
2170 AUPluginInfo::load (Session& session)
2175 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2176 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2178 if (!comp->IsValid()) {
2179 error << ("AudioUnit: not a valid Component") << endmsg;
2181 plugin.reset (new AUPlugin (session.engine(), session, comp));
2184 AUPluginInfo *aup = new AUPluginInfo (*this);
2185 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2186 plugin->set_info (PluginInfoPtr (aup));
2187 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2191 catch (failed_constructor &err) {
2192 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2193 return PluginPtr ();
2198 AUPluginInfo::au_cache_path ()
2200 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2204 AUPluginInfo::discover ()
2208 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2209 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2212 PluginInfoList* plugs = new PluginInfoList;
2214 discover_fx (*plugs);
2215 discover_music (*plugs);
2216 discover_generators (*plugs);
2217 discover_instruments (*plugs);
2219 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2225 AUPluginInfo::discover_music (PluginInfoList& plugs)
2227 CAComponentDescription desc;
2228 desc.componentFlags = 0;
2229 desc.componentFlagsMask = 0;
2230 desc.componentSubType = 0;
2231 desc.componentManufacturer = 0;
2232 desc.componentType = kAudioUnitType_MusicEffect;
2234 discover_by_description (plugs, desc);
2238 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2240 CAComponentDescription desc;
2241 desc.componentFlags = 0;
2242 desc.componentFlagsMask = 0;
2243 desc.componentSubType = 0;
2244 desc.componentManufacturer = 0;
2245 desc.componentType = kAudioUnitType_Effect;
2247 discover_by_description (plugs, desc);
2251 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2253 CAComponentDescription desc;
2254 desc.componentFlags = 0;
2255 desc.componentFlagsMask = 0;
2256 desc.componentSubType = 0;
2257 desc.componentManufacturer = 0;
2258 desc.componentType = kAudioUnitType_Generator;
2260 discover_by_description (plugs, desc);
2264 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2266 CAComponentDescription desc;
2267 desc.componentFlags = 0;
2268 desc.componentFlagsMask = 0;
2269 desc.componentSubType = 0;
2270 desc.componentManufacturer = 0;
2271 desc.componentType = kAudioUnitType_MusicDevice;
2273 discover_by_description (plugs, desc);
2277 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2281 comp = FindNextComponent (NULL, &desc);
2283 while (comp != NULL) {
2284 CAComponentDescription temp;
2285 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2287 AUPluginInfoPtr info (new AUPluginInfo
2288 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2290 /* although apple designed the subtype field to be a "category" indicator,
2291 its really turned into a plugin ID field for a given manufacturer. Hence
2292 there are no categories for AudioUnits. However, to keep the plugins
2293 showing up under "categories", we'll use the "type" as a high level
2296 NOTE: no panners, format converters or i/o AU's for our purposes
2299 switch (info->descriptor->Type()) {
2300 case kAudioUnitType_Panner:
2301 case kAudioUnitType_OfflineEffect:
2302 case kAudioUnitType_FormatConverter:
2305 case kAudioUnitType_Output:
2306 info->category = _("AudioUnit Outputs");
2308 case kAudioUnitType_MusicDevice:
2309 info->category = _("AudioUnit Instruments");
2311 case kAudioUnitType_MusicEffect:
2312 info->category = _("AudioUnit MusicEffects");
2314 case kAudioUnitType_Effect:
2315 info->category = _("AudioUnit Effects");
2317 case kAudioUnitType_Mixer:
2318 info->category = _("AudioUnit Mixers");
2320 case kAudioUnitType_Generator:
2321 info->category = _("AudioUnit Generators");
2324 info->category = _("AudioUnit (Unknown)");
2328 AUPluginInfo::get_names (temp, info->name, info->creator);
2330 info->type = ARDOUR::AudioUnit;
2331 info->unique_id = stringify_descriptor (*info->descriptor);
2333 /* XXX not sure of the best way to handle plugin versioning yet
2336 CAComponent cacomp (*info->descriptor);
2338 if (cacomp.GetResourceVersion (info->version) != noErr) {
2342 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2344 /* here we have to map apple's wildcard system to a simple pair
2345 of values. in ::can_do() we use the whole system, but here
2346 we need a single pair of values. XXX probably means we should
2347 remove any use of these values.
2349 for now, if the plugin provides a wildcard, treat it as 1. we really
2350 don't care much, because whether we can handle an i/o configuration
2351 depends upon ::can_support_io_configuration(), not these counts.
2353 they exist because other parts of ardour try to present i/o configuration
2354 info to the user, which should perhaps be revisited.
2357 int32_t possible_in = info->cache.io_configs.front().first;
2358 int32_t possible_out = info->cache.io_configs.front().second;
2360 if (possible_in > 0) {
2361 info->n_inputs.set (DataType::AUDIO, possible_in);
2363 info->n_inputs.set (DataType::AUDIO, 1);
2366 if (possible_out > 0) {
2367 info->n_outputs.set (DataType::AUDIO, possible_out);
2369 info->n_outputs.set (DataType::AUDIO, 1);
2372 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2373 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2375 plugs.push_back (info);
2378 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2381 comp = FindNextComponent (comp, &desc);
2386 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2389 AUPluginCachedInfo& cinfo,
2390 const std::string& name)
2395 /* concatenate unique ID with version to provide a key for cached info lookup.
2396 this ensures we don't get stale information, or should if plugin developers
2397 follow Apple "guidelines".
2400 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2405 CachedInfoMap::iterator cim = cached_info.find (id);
2407 if (cim != cached_info.end()) {
2408 cinfo = cim->second;
2413 AUChannelInfo* channel_info;
2417 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2421 if (CAAudioUnit::Open (comp, unit) != noErr) {
2427 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2432 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2433 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2439 /* no explicit info available, so default to 1in/1out */
2441 /* XXX this is wrong. we should be indicating wildcard values */
2443 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2447 /* store each configuration */
2449 for (uint32_t n = 0; n < cnt; ++n) {
2450 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2451 channel_info[n].outChannels));
2454 free (channel_info);
2457 add_cached_info (id, cinfo);
2458 save_cached_info ();
2464 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2466 cached_info[id] = cinfo;
2469 #define AU_CACHE_VERSION "2.0"
2472 AUPluginInfo::save_cached_info ()
2476 node = new XMLNode (X_("AudioUnitPluginCache"));
2477 node->add_property( "version", AU_CACHE_VERSION );
2479 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2480 XMLNode* parent = new XMLNode (X_("plugin"));
2481 parent->add_property ("id", i->first);
2482 node->add_child_nocopy (*parent);
2484 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2486 XMLNode* child = new XMLNode (X_("io"));
2489 snprintf (buf, sizeof (buf), "%d", j->first);
2490 child->add_property (X_("in"), buf);
2491 snprintf (buf, sizeof (buf), "%d", j->second);
2492 child->add_property (X_("out"), buf);
2493 parent->add_child_nocopy (*child);
2498 Glib::ustring path = au_cache_path ();
2501 tree.set_root (node);
2503 if (!tree.write (path)) {
2504 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2505 unlink (path.c_str());
2510 AUPluginInfo::load_cached_info ()
2512 Glib::ustring path = au_cache_path ();
2515 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2519 if ( !tree.read (path) ) {
2520 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2524 const XMLNode* root (tree.root());
2526 if (root->name() != X_("AudioUnitPluginCache")) {
2530 //initial version has incorrectly stored i/o info, and/or garbage chars.
2531 const XMLProperty* version = root->property(X_("version"));
2532 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2533 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2537 cached_info.clear ();
2539 const XMLNodeList children = root->children();
2541 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2543 const XMLNode* child = *iter;
2545 if (child->name() == X_("plugin")) {
2547 const XMLNode* gchild;
2548 const XMLNodeList gchildren = child->children();
2549 const XMLProperty* prop = child->property (X_("id"));
2555 string id = prop->value();
2559 string::size_type slash = id.find_last_of ('/');
2561 if (slash == string::npos) {
2565 version = id.substr (slash);
2566 id = id.substr (0, slash);
2567 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2569 if (fixed.empty()) {
2570 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2577 AUPluginCachedInfo cinfo;
2579 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2583 if (gchild->name() == X_("io")) {
2587 const XMLProperty* iprop;
2588 const XMLProperty* oprop;
2590 if (((iprop = gchild->property (X_("in"))) != 0) &&
2591 ((oprop = gchild->property (X_("out"))) != 0)) {
2592 in = atoi (iprop->value());
2593 out = atoi (oprop->value());
2595 cinfo.io_configs.push_back (pair<int,int> (in, out));
2600 if (cinfo.io_configs.size()) {
2601 add_cached_info (id, cinfo);
2610 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2612 CFStringRef itemName = NULL;
2614 // Marc Poirier-style item name
2615 CAComponent auComponent (comp_desc);
2616 if (auComponent.IsValid()) {
2617 CAComponentDescription dummydesc;
2618 Handle nameHandle = NewHandle(sizeof(void*));
2619 if (nameHandle != NULL) {
2620 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2622 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2623 if (nameString != NULL) {
2624 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2627 DisposeHandle(nameHandle);
2631 // if Marc-style fails, do the original way
2632 if (itemName == NULL) {
2633 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2634 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2635 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2637 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2638 compTypeString, compManufacturerString, compSubTypeString);
2640 if (compTypeString != NULL)
2641 CFRelease(compTypeString);
2642 if (compSubTypeString != NULL)
2643 CFRelease(compSubTypeString);
2644 if (compManufacturerString != NULL)
2645 CFRelease(compManufacturerString);
2648 string str = CFStringRefToStdString(itemName);
2649 string::size_type colon = str.find (':');
2652 name = str.substr (colon+1);
2653 maker = str.substr (0, colon);
2654 strip_whitespace_edges (maker);
2655 strip_whitespace_edges (name);
2659 strip_whitespace_edges (name);
2664 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2668 /* note: OSType is a compiler-implemenation-defined value,
2669 historically a 32 bit integer created with a multi-character
2670 constant such as 'abcd'. It is, fundamentally, an abomination.
2675 s << desc.SubType();
2683 AUPluginInfo::needs_midi_input ()
2685 return is_effect_with_midi_input () || is_instrument ();
2689 AUPluginInfo::is_effect () const
2691 return is_effect_without_midi_input() || is_effect_with_midi_input();
2695 AUPluginInfo::is_effect_without_midi_input () const
2697 return descriptor->IsAUFX();
2701 AUPluginInfo::is_effect_with_midi_input () const
2703 return descriptor->IsAUFM();
2707 AUPluginInfo::is_instrument () const
2709 return descriptor->IsMusicDevice();
2713 AUPlugin::set_info (PluginInfoPtr info)
2715 Plugin::set_info (info);
2717 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2718 _has_midi_input = pinfo->needs_midi_input ();
2719 _has_midi_output = false;
2723 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2726 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2728 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2730 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2732 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2736 _parameter_listener_arg = arg;
2742 AUPlugin::listen_to_parameter (uint32_t param_id)
2744 AudioUnitEvent event;
2746 if (!_parameter_listener || param_id >= descriptors.size()) {
2750 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2751 event.mArgument.mParameter.mAudioUnit = unit->AU();
2752 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2753 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2754 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2756 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2760 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2761 event.mArgument.mParameter.mAudioUnit = unit->AU();
2762 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2763 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2764 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2766 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2770 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2771 event.mArgument.mParameter.mAudioUnit = unit->AU();
2772 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2773 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2774 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2776 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2784 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2786 AudioUnitEvent event;
2788 if (!_parameter_listener || param_id >= descriptors.size()) {
2792 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2793 event.mArgument.mParameter.mAudioUnit = unit->AU();
2794 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2795 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2796 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2798 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2802 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2803 event.mArgument.mParameter.mAudioUnit = unit->AU();
2804 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2805 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2806 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2808 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2812 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2813 event.mArgument.mParameter.mAudioUnit = unit->AU();
2814 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2815 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2816 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2818 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2826 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2828 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2832 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2834 ParameterMap::iterator i;
2836 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
2840 switch (event->mEventType) {
2841 case kAudioUnitEvent_BeginParameterChangeGesture:
2842 StartTouch (i->second);
2844 case kAudioUnitEvent_EndParameterChangeGesture:
2845 EndTouch (i->second);
2847 case kAudioUnitEvent_ParameterValueChange:
2848 ParameterChanged (i->second, new_value);