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.
28 #include "pbd/transmitter.h"
29 #include "pbd/xml++.h"
30 #include "pbd/convert.h"
31 #include "pbd/whitespace.h"
32 #include "pbd/file_utils.h"
33 #include "pbd/locale_guard.h"
35 #include <glibmm/threads.h>
36 #include <glibmm/fileutils.h>
37 #include <glibmm/miscutils.h>
38 #include <glib/gstdio.h>
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/debug.h"
44 #include "ardour/midi_buffer.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/audio_unit.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
53 #include "appleutility/CAAudioUnit.h"
54 #include "appleutility/CAAUParameter.h"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
61 #include <Carbon/Carbon.h>
68 using namespace ARDOUR;
70 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
72 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
73 static string preset_suffix = ".aupreset";
74 static bool preset_search_path_initialized = false;
75 FILE * AUPluginInfo::_crashlog_fd = NULL;
78 _render_callback(void *userData,
79 AudioUnitRenderActionFlags *ioActionFlags,
80 const AudioTimeStamp *inTimeStamp,
82 UInt32 inNumberFrames,
83 AudioBufferList* ioData)
86 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
92 _get_beat_and_tempo_callback (void* userData,
93 Float64* outCurrentBeat,
94 Float64* outCurrentTempo)
97 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
104 _get_musical_time_location_callback (void * userData,
105 UInt32 * outDeltaSampleOffsetToNextBeat,
106 Float32 * outTimeSig_Numerator,
107 UInt32 * outTimeSig_Denominator,
108 Float64 * outCurrentMeasureDownBeat)
111 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
112 outTimeSig_Numerator,
113 outTimeSig_Denominator,
114 outCurrentMeasureDownBeat);
120 _get_transport_state_callback (void* userData,
121 Boolean* outIsPlaying,
122 Boolean* outTransportStateChanged,
123 Float64* outCurrentSampleInTimeLine,
124 Boolean* outIsCycling,
125 Float64* outCycleStartBeat,
126 Float64* outCycleEndBeat)
129 return ((AUPlugin*)userData)->get_transport_state_callback (
130 outIsPlaying, outTransportStateChanged,
131 outCurrentSampleInTimeLine, outIsCycling,
132 outCycleStartBeat, outCycleEndBeat);
139 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
145 // Convert the property list into XML data.
147 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
150 error << _("Could not create XML version of property list") << endmsg;
154 // Write the XML data to the file.
156 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
158 if (errno == EEXIST) {
159 error << string_compose (_("Preset file %1 exists; not overwriting"),
162 error << string_compose (_("Cannot open preset file %1 (%2)"),
163 path, strerror (errno)) << endmsg;
169 size_t cnt = CFDataGetLength (xmlData);
171 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
182 static CFPropertyListRef
183 load_property_list (Glib::ustring path)
186 CFPropertyListRef propertyList = 0;
188 CFStringRef errorString;
190 // Read the XML file.
192 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
197 off_t len = lseek (fd, 0, SEEK_END);
198 char* buf = new char[len];
199 lseek (fd, 0, SEEK_SET);
201 if (read (fd, buf, len) != len) {
209 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
211 // Reconstitute the dictionary using the XML data.
213 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
215 kCFPropertyListImmutable,
224 //-----------------------------------------------------------------------------
226 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
231 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
233 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
234 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
240 //-----------------------------------------------------------------------------
242 get_preset_name_in_plist (CFPropertyListRef plist)
250 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
251 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
253 CFStringRef str = (CFStringRef) p;
254 int len = CFStringGetLength(str);
256 char local_buffer[len];
257 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
265 //--------------------------------------------------------------------------
266 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
267 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
268 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
269 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
271 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
274 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
275 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
277 // only sub-type and manufacturer IDs need to be equal
280 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
281 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
288 //--------------------------------------------------------------------------
289 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
290 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
291 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
292 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
295 ComponentDescription desc;
297 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
300 // get the ComponentDescription of the input Component
301 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
305 // check if the Component's ComponentDescription matches the input ComponentDescription
306 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
309 //--------------------------------------------------------------------------
310 // determine if 2 ComponentDescriptions are basically equal
311 // (by that, I mean that the important identifying values are compared,
312 // but not the ComponentDescription flags)
313 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
315 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
318 //--------------------------------------------------------------------------
319 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
320 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
322 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
325 //--------------------------------------------------------------------------
326 // determine if a ComponentDescription basically matches that of a particular Component
327 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
329 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
332 //--------------------------------------------------------------------------
333 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
334 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
336 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
340 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
341 : Plugin (engine, session)
343 , unit (new CAAudioUnit)
344 , initialized (false)
345 , _current_block_size (0)
346 , _requires_fixed_size_buffers (false)
351 , frames_processed (0)
352 , _parameter_listener (0)
353 , _parameter_listener_arg (0)
354 , last_transport_rolling (false)
355 , last_transport_speed (0.0)
357 if (!preset_search_path_initialized) {
358 Glib::ustring p = Glib::get_home_dir();
359 p += "/Library/Audio/Presets:";
360 p += preset_search_path;
361 preset_search_path = p;
362 preset_search_path_initialized = true;
369 AUPlugin::AUPlugin (const AUPlugin& other)
371 , comp (other.get_comp())
372 , unit (new CAAudioUnit)
373 , initialized (false)
374 , _current_block_size (0)
376 , _requires_fixed_size_buffers (false)
381 , frames_processed (0)
382 , _parameter_listener (0)
383 , _parameter_listener_arg (0)
389 AUPlugin::~AUPlugin ()
391 if (_parameter_listener) {
392 AUListenerDispose (_parameter_listener);
393 _parameter_listener = 0;
397 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
398 unit->Uninitialize ();
407 AUPlugin::discover_factory_presets ()
414 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
415 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
419 assert (dataSize == sizeof (presets));
421 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
422 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
430 CFIndex cnt = CFArrayGetCount (presets);
432 for (CFIndex i = 0; i < cnt; ++i) {
433 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
435 string name = CFStringRefToStdString (preset->presetName);
436 factory_preset_map[name] = preset->presetNumber;
447 /* these keep track of *configured* channel set up,
448 not potential set ups.
452 output_channels = -1;
455 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
456 err = CAAudioUnit::Open (*(comp.get()), *unit);
458 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
459 throw failed_constructor();
463 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
464 throw failed_constructor ();
467 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
468 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
469 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
470 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
471 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
472 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
474 if (input_elements > 0) {
475 /* setup render callback: the plugin calls this to get input data
478 AURenderCallbackStruct renderCallbackInfo;
480 renderCallbackInfo.inputProc = _render_callback;
481 renderCallbackInfo.inputProcRefCon = this;
483 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
484 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
485 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
486 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
487 throw failed_constructor();
491 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
493 HostCallbackInfo info;
494 memset (&info, 0, sizeof (HostCallbackInfo));
495 info.hostUserData = this;
496 info.beatAndTempoProc = _get_beat_and_tempo_callback;
497 info.musicalTimeLocationProc = _get_musical_time_location_callback;
498 info.transportStateProc = _get_transport_state_callback;
500 //ignore result of this - don't care if the property isn't supported
501 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
502 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
503 kAudioUnitScope_Global,
506 sizeof (HostCallbackInfo));
508 if (set_block_size (_session.get_block_size())) {
509 error << _("AUPlugin: cannot set processing block size") << endmsg;
510 throw failed_constructor();
513 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
514 discover_parameters ();
515 discover_factory_presets ();
517 // Plugin::setup_controls ();
521 AUPlugin::discover_parameters ()
523 /* discover writable parameters */
525 AudioUnitScope scopes[] = {
526 kAudioUnitScope_Global,
527 kAudioUnitScope_Output,
528 kAudioUnitScope_Input
531 descriptors.clear ();
533 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
535 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
537 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
539 AUParameterDescriptor d;
541 d.id = param_info.ParamID (i);
543 const CAAUParameter* param = param_info.GetParamInfo (d.id);
544 const AudioUnitParameterInfo& info (param->ParamInfo());
546 const int len = CFStringGetLength (param->GetName());;
547 char local_buffer[len*2];
548 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
552 d.label = local_buffer;
555 d.scope = param_info.GetScope ();
556 d.element = param_info.GetElement ();
558 /* info.units to consider */
560 kAudioUnitParameterUnit_Generic = 0
561 kAudioUnitParameterUnit_Indexed = 1
562 kAudioUnitParameterUnit_Boolean = 2
563 kAudioUnitParameterUnit_Percent = 3
564 kAudioUnitParameterUnit_Seconds = 4
565 kAudioUnitParameterUnit_SampleFrames = 5
566 kAudioUnitParameterUnit_Phase = 6
567 kAudioUnitParameterUnit_Rate = 7
568 kAudioUnitParameterUnit_Hertz = 8
569 kAudioUnitParameterUnit_Cents = 9
570 kAudioUnitParameterUnit_RelativeSemiTones = 10
571 kAudioUnitParameterUnit_MIDINoteNumber = 11
572 kAudioUnitParameterUnit_MIDIController = 12
573 kAudioUnitParameterUnit_Decibels = 13
574 kAudioUnitParameterUnit_LinearGain = 14
575 kAudioUnitParameterUnit_Degrees = 15
576 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
577 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
578 kAudioUnitParameterUnit_Pan = 18
579 kAudioUnitParameterUnit_Meters = 19
580 kAudioUnitParameterUnit_AbsoluteCents = 20
581 kAudioUnitParameterUnit_Octaves = 21
582 kAudioUnitParameterUnit_BPM = 22
583 kAudioUnitParameterUnit_Beats = 23
584 kAudioUnitParameterUnit_Milliseconds = 24
585 kAudioUnitParameterUnit_Ratio = 25
588 /* info.flags to consider */
592 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
593 kAudioUnitParameterFlag_HasClump = (1L << 20)
594 kAudioUnitParameterFlag_HasName = (1L << 21)
595 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
596 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
597 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
598 kAudioUnitParameterFlag_CanRamp = (1L << 25)
599 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
600 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
601 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
602 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
603 kAudioUnitParameterFlag_IsReadable = (1L << 30)
604 kAudioUnitParameterFlag_IsWritable = (1L << 31)
607 d.lower = info.minValue;
608 d.upper = info.maxValue;
609 d.normal = info.defaultValue;
611 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
612 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
613 (d.integer_step && ((d.upper - d.lower) == 1.0));
614 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
615 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
616 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
617 (info.flags & kAudioUnitParameterFlag_IsWritable);
619 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
620 d.au_unit = info.unit;
622 case kAudioUnitParameterUnit_Decibels:
623 d.unit = ParameterDescriptor::DB;
625 case kAudioUnitParameterUnit_MIDINoteNumber:
626 d.unit = ParameterDescriptor::MIDI_NOTE;
628 case kAudioUnitParameterUnit_Hertz:
629 d.unit = ParameterDescriptor::HZ;
633 d.min_unbound = 0; // lower is bound
634 d.max_unbound = 0; // upper is bound
637 descriptors.push_back (d);
639 uint32_t last_param = descriptors.size() - 1;
640 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
641 listen_to_parameter (last_param);
648 four_ints_to_four_byte_literal (unsigned char n[4])
650 /* this is actually implementation dependent. sigh. this is what gcc
651 and quite a few others do.
653 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
657 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
659 if (isdigit (id[0])) {
663 /* ID format is xxxx-xxxx-xxxx
664 where x maybe \xNN or a printable character.
666 Split at the '-' and and process each part into an integer.
667 Then put it back together.
671 unsigned char nascent[4];
672 const char* cstr = id.c_str();
673 const char* estr = cstr + id.size();
684 while (*cstr && next_int < 4) {
688 if (estr - cstr < 3) {
690 /* too close to the end for \xNN parsing: treat as literal characters */
698 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
702 memcpy (short_buf, &cstr[2], 2);
703 nascent[in] = strtol (short_buf, NULL, 16);
709 /* treat as literal characters */
723 if (in && (in % 4 == 0)) {
724 /* nascent is ready */
725 n[next_int] = four_ints_to_four_byte_literal (nascent);
729 /* swallow space-hyphen-space */
743 s << n[0] << '-' << n[1] << '-' << n[2];
752 AUPlugin::unique_id () const
754 return AUPluginInfo::stringify_descriptor (comp->Desc());
758 AUPlugin::label () const
760 return _info->name.c_str();
764 AUPlugin::parameter_count () const
766 return descriptors.size();
770 AUPlugin::default_value (uint32_t port)
772 if (port < descriptors.size()) {
773 return descriptors[port].normal;
780 AUPlugin::signal_latency () const
782 return unit->Latency() * _session.frame_rate();
786 AUPlugin::set_parameter (uint32_t which, float val)
788 if (which >= descriptors.size()) {
792 if (get_parameter(which) == val) {
796 const AUParameterDescriptor& d (descriptors[which]);
797 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
798 unit->SetParameter (d.id, d.scope, d.element, val);
800 /* tell the world what we did */
802 AudioUnitEvent theEvent;
804 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
805 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
806 theEvent.mArgument.mParameter.mParameterID = d.id;
807 theEvent.mArgument.mParameter.mScope = d.scope;
808 theEvent.mArgument.mParameter.mElement = d.element;
810 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
811 AUEventListenerNotify (NULL, NULL, &theEvent);
813 Plugin::set_parameter (which, val);
817 AUPlugin::get_parameter (uint32_t which) const
820 if (which < descriptors.size()) {
821 const AUParameterDescriptor& d (descriptors[which]);
822 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
823 unit->GetParameter(d.id, d.scope, d.element, val);
829 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
831 if (which < descriptors.size()) {
832 pd = descriptors[which];
839 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
841 if (which < descriptors.size()) {
850 AUPlugin::activate ()
854 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
855 if ((err = unit->Initialize()) != noErr) {
856 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
858 frames_processed = 0;
865 AUPlugin::deactivate ()
867 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
868 unit->Uninitialize ();
875 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
876 unit->GlobalReset ();
880 AUPlugin::requires_fixed_size_buffers() const
882 return _requires_fixed_size_buffers;
887 AUPlugin::set_block_size (pframes_t nframes)
889 bool was_initialized = initialized;
890 UInt32 numFrames = nframes;
897 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
898 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
899 0, &numFrames, sizeof (numFrames))) != noErr) {
900 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
904 if (was_initialized) {
908 _current_block_size = nframes;
914 AUPlugin::configure_io (ChanCount in, ChanCount out)
916 AudioStreamBasicDescription streamFormat;
917 bool was_initialized = initialized;
918 int32_t audio_in = in.n_audio();
919 int32_t audio_out = out.n_audio();
921 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
924 //if we are already running with the requested i/o config, bail out here
925 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
932 streamFormat.mSampleRate = _session.frame_rate();
933 streamFormat.mFormatID = kAudioFormatLinearPCM;
934 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
936 #ifdef __LITTLE_ENDIAN__
939 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
942 streamFormat.mBitsPerChannel = 32;
943 streamFormat.mFramesPerPacket = 1;
945 /* apple says that for non-interleaved data, these
946 values always refer to a single channel.
948 streamFormat.mBytesPerPacket = 4;
949 streamFormat.mBytesPerFrame = 4;
951 streamFormat.mChannelsPerFrame = audio_in;
953 if (set_input_format (streamFormat) != 0) {
957 streamFormat.mChannelsPerFrame = audio_out;
959 if (set_output_format (streamFormat) != 0) {
963 /* reset plugin info to show currently configured state */
965 _info->n_inputs = in;
966 _info->n_outputs = out;
968 if (was_initialized) {
976 AUPlugin::input_streams() const
981 if (input_channels < 0) {
982 // force PluginIoReConfigure -- see also commit msg e38eb06
983 c.set (DataType::AUDIO, 0);
984 c.set (DataType::MIDI, 0);
986 c.set (DataType::AUDIO, input_channels);
987 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
995 AUPlugin::output_streams() const
999 if (output_channels < 0) {
1000 // force PluginIoReConfigure - see also commit msg e38eb06
1001 c.set (DataType::AUDIO, 0);
1002 c.set (DataType::MIDI, 0);
1004 c.set (DataType::AUDIO, output_channels);
1005 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1012 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1014 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1016 int32_t audio_in = in.n_audio();
1019 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1021 /* lets check MIDI first */
1023 if (in.n_midi() > 0) {
1024 if (!_has_midi_input) {
1029 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1031 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1032 name(), io_configs.size(), in, out));
1034 //Ardour expects the plugin to tell it the output
1035 //configuration but AU plugins can have multiple I/O
1036 //configurations in most cases. so first lets see
1037 //if there's a configuration that keeps out==in
1039 if (in.n_midi() > 0 && audio_in == 0) {
1040 audio_out = 2; // prefer stereo version if available.
1042 audio_out = audio_in;
1045 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1047 int32_t possible_in = i->first;
1048 int32_t possible_out = i->second;
1050 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1051 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1052 possible_in, possible_out,
1055 out.set (DataType::MIDI, 0);
1056 out.set (DataType::AUDIO, audio_out);
1062 /* now allow potentially "imprecise" matches */
1066 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1068 int32_t possible_in = i->first;
1069 int32_t possible_out = i->second;
1071 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1073 if (possible_out == 0) {
1074 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1075 /* XXX surely this is just a send? (e.g. AUNetSend) */
1079 if (possible_in == 0) {
1081 /* instrument plugin, always legal but throws away inputs ...
1084 if (possible_out == -1) {
1085 /* any configuration possible, provide stereo output */
1088 } else if (possible_out == -2) {
1089 /* plugins shouldn't really use (0,-2) but might.
1090 any configuration possible, provide stereo output
1094 } else if (possible_out < -2) {
1095 /* explicitly variable number of outputs.
1097 Since Ardour can handle any configuration,
1098 we have to somehow pick a number.
1100 We'll use the number of inputs
1101 to the master bus, or 2 if there
1104 boost::shared_ptr<Route> master = _session.master_out();
1106 audio_out = master->input()->n_ports().n_audio();
1112 /* exact number of outputs */
1113 audio_out = possible_out;
1118 if (possible_in == -1) {
1120 /* wildcard for input */
1122 if (possible_out == -1) {
1123 /* out much match in */
1124 audio_out = audio_in;
1126 } else if (possible_out == -2) {
1127 /* any configuration possible, pick matching */
1128 audio_out = audio_in;
1130 } else if (possible_out < -2) {
1131 /* explicitly variable number of outputs, pick maximum */
1132 audio_out = -possible_out;
1135 /* exact number of outputs */
1136 audio_out = possible_out;
1141 if (possible_in == -2) {
1143 if (possible_out == -1) {
1144 /* any configuration possible, pick matching */
1145 audio_out = audio_in;
1147 } else if (possible_out == -2) {
1148 /* plugins shouldn't really use (-2,-2) but might.
1149 interpret as (-1,-1).
1151 audio_out = audio_in;
1153 } else if (possible_out < -2) {
1154 /* explicitly variable number of outputs, pick maximum */
1155 audio_out = -possible_out;
1158 /* exact number of outputs */
1159 audio_out = possible_out;
1164 if (possible_in < -2) {
1166 /* explicit variable number of inputs */
1168 if (audio_in > -possible_in) {
1169 /* request is too large */
1173 if (possible_out == -1) {
1174 /* any output configuration possible, provide stereo out */
1177 } else if (possible_out == -2) {
1178 /* plugins shouldn't really use (<-2,-2) but might.
1179 interpret as (<-2,-1): any configuration possible, provide stereo output
1183 } else if (possible_out < -2) {
1184 /* explicitly variable number of outputs.
1186 Since Ardour can handle any configuration,
1187 we have to somehow pick a number.
1189 We'll use the number of inputs
1190 to the master bus, or 2 if there
1193 boost::shared_ptr<Route> master = _session.master_out();
1195 audio_out = master->input()->n_ports().n_audio();
1201 /* exact number of outputs */
1202 audio_out = possible_out;
1207 if (possible_in && (possible_in == audio_in)) {
1209 /* exact number of inputs ... must match obviously */
1211 if (possible_out == -1) {
1212 /* any output configuration possible, provide stereo output */
1215 } else if (possible_out == -2) {
1216 /* plugins shouldn't really use (>0,-2) but might.
1217 interpret as (>0,-1):
1218 any output configuration possible, provide stereo output
1222 } else if (possible_out < -2) {
1223 /* explicitly variable number of outputs, pick maximum */
1224 audio_out = -possible_out;
1227 /* exact number of outputs */
1228 audio_out = possible_out;
1240 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1242 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1246 out.set (DataType::MIDI, 0);
1247 out.set (DataType::AUDIO, audio_out);
1253 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1255 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1259 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1261 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1270 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1271 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1277 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1281 for (uint32_t i = 0; i < cnt; ++i) {
1282 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1283 (scope == kAudioUnitScope_Input ? "input" : "output"),
1285 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1286 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1287 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1292 if (scope == kAudioUnitScope_Input) {
1293 input_channels = fmt.mChannelsPerFrame;
1295 output_channels = fmt.mChannelsPerFrame;
1302 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1303 const AudioTimeStamp*,
1305 UInt32 inNumberFrames,
1306 AudioBufferList* ioData)
1308 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1310 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1311 // name(), inNumberFrames, ioData->mNumberBuffers));
1313 if (input_maxbuf == 0) {
1314 error << _("AUPlugin: render callback called illegally!") << endmsg;
1315 return kAudioUnitErr_CannotDoInCurrentContext;
1317 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1319 for (uint32_t i = 0; i < limit; ++i) {
1320 ioData->mBuffers[i].mNumberChannels = 1;
1321 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1323 /* we don't use the channel mapping because audiounits are
1324 never replicated. one plugin instance uses all channels/buffers
1325 passed to PluginInsert::connect_and_run()
1328 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1331 cb_offset += inNumberFrames;
1337 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1339 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1341 AudioUnitRenderActionFlags flags = 0;
1345 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1346 unit->GlobalReset();
1347 _last_nframes = nframes;
1350 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1351 name(), input_channels, output_channels, _has_midi_input,
1352 bufs.count(), bufs.available()));
1354 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1355 has the capacity to handle our outputs.
1358 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1360 input_buffers = &bufs;
1361 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1362 input_offset = offset;
1365 buffers->mNumberBuffers = output_channels;
1367 for (int32_t i = 0; i < output_channels; ++i) {
1368 buffers->mBuffers[i].mNumberChannels = 1;
1369 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1370 /* setting this to 0 indicates to the AU that it can provide buffers here
1371 if necessary. if it can process in-place, it will use the buffers provided
1372 as input by ::render_callback() above.
1374 a non-null values tells the plugin to render into the buffer pointed
1377 buffers->mBuffers[i].mData = 0;
1380 if (_has_midi_input) {
1382 uint32_t nmidi = bufs.count().n_midi();
1384 for (uint32_t i = 0; i < nmidi; ++i) {
1386 /* one MIDI port/buffer only */
1388 MidiBuffer& m = bufs.get_midi (i);
1390 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1391 Evoral::MIDIEvent<framepos_t> ev (*i);
1393 if (ev.is_channel_event()) {
1394 const uint8_t* b = ev.buffer();
1395 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1396 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1399 /* XXX need to handle sysex and other message types */
1404 /* does this really mean anything ?
1407 ts.mSampleTime = frames_processed;
1408 ts.mFlags = kAudioTimeStampSampleTimeValid;
1410 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1411 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1413 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1416 frames_processed += nframes;
1418 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1419 name(), buffers->mNumberBuffers, output_channels));
1421 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1424 for (i = 0; i < limit; ++i) {
1425 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1426 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1427 /* plugin provided its own buffer for output so copy it back to where we want it
1429 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1433 /* now silence any buffers that were passed in but the that the plugin
1434 did not fill/touch/use.
1437 for (;i < output_channels; ++i) {
1438 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1444 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1449 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1450 Float64* outCurrentTempo)
1452 TempoMap& tmap (_session.tempo_map());
1454 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1456 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1457 (and interpretation) of a beat position will be incorrect. So refuse to
1461 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1462 return kAudioUnitErr_CannotDoInCurrentContext;
1465 Timecode::BBT_Time bbt;
1466 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1467 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1469 if (outCurrentBeat) {
1471 beat = metric.meter().divisions_per_bar() * bbt.bars;
1473 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1474 *outCurrentBeat = beat;
1477 if (outCurrentTempo) {
1478 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1486 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1487 Float32* outTimeSig_Numerator,
1488 UInt32* outTimeSig_Denominator,
1489 Float64* outCurrentMeasureDownBeat)
1491 TempoMap& tmap (_session.tempo_map());
1493 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1495 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1496 (and interpretation) of a beat position will be incorrect. So refuse to
1500 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1501 return kAudioUnitErr_CannotDoInCurrentContext;
1504 Timecode::BBT_Time bbt;
1505 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1506 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1508 if (outDeltaSampleOffsetToNextBeat) {
1509 if (bbt.ticks == 0) {
1511 *outDeltaSampleOffsetToNextBeat = 0;
1513 *outDeltaSampleOffsetToNextBeat = (UInt32)
1514 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1515 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1519 if (outTimeSig_Numerator) {
1520 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1522 if (outTimeSig_Denominator) {
1523 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1526 if (outCurrentMeasureDownBeat) {
1528 /* beat for the start of the bar.
1530 2|1|0 -> 1 + divisions_per_bar
1531 3|1|0 -> 1 + (2 * divisions_per_bar)
1535 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1542 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1543 Boolean* outTransportStateChanged,
1544 Float64* outCurrentSampleInTimeLine,
1545 Boolean* outIsCycling,
1546 Float64* outCycleStartBeat,
1547 Float64* outCycleEndBeat)
1552 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1554 rolling = _session.transport_rolling();
1555 speed = _session.transport_speed ();
1558 *outIsPlaying = _session.transport_rolling();
1561 if (outTransportStateChanged) {
1562 if (rolling != last_transport_rolling) {
1563 *outTransportStateChanged = true;
1564 } else if (speed != last_transport_speed) {
1565 *outTransportStateChanged = true;
1567 *outTransportStateChanged = false;
1571 if (outCurrentSampleInTimeLine) {
1572 /* this assumes that the AU can only call this host callback from render context,
1573 where input_offset is valid.
1575 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1579 Location* loc = _session.locations()->auto_loop_location();
1581 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1583 if (*outIsCycling) {
1585 if (outCycleStartBeat || outCycleEndBeat) {
1587 TempoMap& tmap (_session.tempo_map());
1589 /* more than 1 meter means that a simplistic computation (and interpretation) of
1590 a beat position will be incorrect. so refuse to offer the value.
1593 if (tmap.n_meters() > 1) {
1594 return kAudioUnitErr_CannotDoInCurrentContext;
1597 Timecode::BBT_Time bbt;
1599 if (outCycleStartBeat) {
1600 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1601 _session.tempo_map().bbt_time (loc->start(), bbt);
1604 beat = metric.meter().divisions_per_bar() * bbt.bars;
1606 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1608 *outCycleStartBeat = beat;
1611 if (outCycleEndBeat) {
1612 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1613 _session.tempo_map().bbt_time (loc->end(), bbt);
1616 beat = metric.meter().divisions_per_bar() * bbt.bars;
1618 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1620 *outCycleEndBeat = beat;
1626 last_transport_rolling = rolling;
1627 last_transport_speed = speed;
1632 set<Evoral::Parameter>
1633 AUPlugin::automatable() const
1635 set<Evoral::Parameter> automates;
1637 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1638 if (descriptors[i].automatable) {
1639 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1647 AUPlugin::describe_parameter (Evoral::Parameter param)
1649 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1650 return descriptors[param.id()].label;
1657 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1659 // NameValue stuff here
1663 AUPlugin::parameter_is_audio (uint32_t) const
1669 AUPlugin::parameter_is_control (uint32_t param) const
1671 assert(param < descriptors.size());
1672 if (descriptors[param].automatable) {
1673 /* corrently ardour expects all controls to be automatable
1674 * IOW ardour GUI elements mandate an Evoral::Parameter
1675 * for all input+control ports.
1683 AUPlugin::parameter_is_input (uint32_t param) const
1685 /* AU params that are both readable and writeable,
1686 * are listed in kAudioUnitScope_Global
1688 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1692 AUPlugin::parameter_is_output (uint32_t param) const
1694 assert(param < descriptors.size());
1695 // TODO check if ardour properly handles ports
1696 // that report is_input + is_output == true
1697 // -> add || descriptors[param].scope == kAudioUnitScope_Global
1698 return (descriptors[param].scope == kAudioUnitScope_Output);
1702 AUPlugin::add_state (XMLNode* root) const
1704 LocaleGuard lg (X_("C"));
1706 CFPropertyListRef propertyList;
1708 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1709 if (unit->GetAUPreset (propertyList) != noErr) {
1713 // Convert the property list into XML data.
1715 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1718 error << _("Could not create XML version of property list") << endmsg;
1722 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1723 our state node. GACK!
1728 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1730 root->add_child_copy (*t.root());
1734 CFRelease (xmlData);
1735 CFRelease (propertyList);
1739 AUPlugin::set_state(const XMLNode& node, int version)
1742 CFPropertyListRef propertyList;
1743 LocaleGuard lg (X_("C"));
1745 if (node.name() != state_node_name()) {
1746 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1750 #ifndef NO_PLUGIN_STATE
1751 if (node.children().empty()) {
1755 XMLNode* top = node.children().front();
1756 XMLNode* copy = new XMLNode (*top);
1761 const string& xml = t.write_buffer ();
1762 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1763 CFStringRef errorString;
1765 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1767 kCFPropertyListImmutable,
1770 CFRelease (xmlData);
1773 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1774 if (unit->SetAUPreset (propertyList) == noErr) {
1777 /* tell the world */
1779 AudioUnitParameter changedUnit;
1780 changedUnit.mAudioUnit = unit->AU();
1781 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1782 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1784 CFRelease (propertyList);
1788 Plugin::set_state (node, version);
1793 AUPlugin::load_preset (PresetRecord r)
1795 Plugin::load_preset (r);
1798 CFPropertyListRef propertyList;
1800 UserPresetMap::iterator ux;
1801 FactoryPresetMap::iterator fx;
1803 /* look first in "user" presets */
1805 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1807 if ((propertyList = load_property_list (ux->second)) != 0) {
1808 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1809 if (unit->SetAUPreset (propertyList) == noErr) {
1812 /* tell the world */
1814 AudioUnitParameter changedUnit;
1815 changedUnit.mAudioUnit = unit->AU();
1816 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1817 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1819 CFRelease(propertyList);
1822 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1826 preset.presetNumber = fx->second;
1827 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1829 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1831 if (unit->SetPresentPreset (preset) == 0) {
1834 /* tell the world */
1836 AudioUnitParameter changedUnit;
1837 changedUnit.mAudioUnit = unit->AU();
1838 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1839 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1847 AUPlugin::do_remove_preset (std::string)
1852 AUPlugin::do_save_preset (string preset_name)
1854 CFPropertyListRef propertyList;
1855 vector<Glib::ustring> v;
1856 Glib::ustring user_preset_path;
1858 std::string m = maker();
1859 std::string n = name();
1861 strip_whitespace_edges (m);
1862 strip_whitespace_edges (n);
1864 v.push_back (Glib::get_home_dir());
1865 v.push_back ("Library");
1866 v.push_back ("Audio");
1867 v.push_back ("Presets");
1871 user_preset_path = Glib::build_filename (v);
1873 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1874 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1878 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1879 if (unit->GetAUPreset (propertyList) != noErr) {
1883 // add the actual preset name */
1885 v.push_back (preset_name + preset_suffix);
1889 user_preset_path = Glib::build_filename (v);
1891 set_preset_name_in_plist (propertyList, preset_name);
1893 if (save_property_list (propertyList, user_preset_path)) {
1894 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1898 CFRelease(propertyList);
1900 return string ("file:///") + user_preset_path;
1903 //-----------------------------------------------------------------------------
1904 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1906 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1908 CFNumberRef cfNumber;
1909 SInt32 numberValue = 0;
1910 Boolean dummySuccess;
1912 if (outSuccess == NULL)
1913 outSuccess = &dummySuccess;
1914 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1916 *outSuccess = FALSE;
1920 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1921 if (cfNumber == NULL)
1923 *outSuccess = FALSE;
1926 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1934 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1936 CFDictionaryRef auStateDictionary;
1937 ComponentDescription tempDesc = {0,0,0,0,0};
1938 SInt32 versionValue;
1941 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1944 // the property list for AU state data must be of the dictionary type
1945 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1946 return kAudioUnitErr_InvalidPropertyValue;
1949 auStateDictionary = (CFDictionaryRef)inAUStateData;
1951 // first check to make sure that the version of the AU state data is one that we know understand
1952 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1953 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1956 return kAudioUnitErr_InvalidPropertyValue;
1958 #define kCurrentSavedStateVersion 0
1959 if (versionValue != kCurrentSavedStateVersion) {
1960 return kAudioUnitErr_InvalidPropertyValue;
1963 // grab the ComponentDescription values from the AU state data
1964 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1965 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1966 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1967 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1968 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1969 return kAudioUnitErr_InvalidPropertyValue;
1971 *outComponentDescription = tempDesc;
1976 static bool au_preset_filter (const string& str, void* arg)
1978 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1982 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1986 /* check the preset file path name against this plugin
1987 ID. The idea is that all preset files for this plugin
1988 include "<manufacturer>/<plugin-name>" in their path.
1991 Plugin* p = (Plugin *) arg;
1992 string match = p->maker();
1996 ret = str.find (match) != string::npos;
1999 string m = p->maker ();
2000 string n = p->name ();
2001 strip_whitespace_edges (m);
2002 strip_whitespace_edges (n);
2007 ret = str.find (match) != string::npos;
2015 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2018 CFPropertyListRef plist;
2019 ComponentDescription presetDesc;
2022 plist = load_property_list (pathstr);
2028 // get the ComponentDescription from the AU preset file
2030 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2032 if (status == noErr) {
2033 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2035 /* try to get the preset name from the property list */
2037 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2039 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2043 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2046 char buf[PATH_MAX+1];
2048 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2063 AUPlugin::current_preset() const
2067 CFPropertyListRef propertyList;
2069 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2070 if (unit->GetAUPreset (propertyList) == noErr) {
2071 preset_name = get_preset_name_in_plist (propertyList);
2072 CFRelease(propertyList);
2079 AUPlugin::find_presets ()
2081 vector<string> preset_files;
2083 user_preset_map.clear ();
2085 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2087 if (preset_files.empty()) {
2091 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2096 /* make an initial guess at the preset name using the path */
2098 preset_name = Glib::path_get_basename (path);
2099 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2101 /* check that this preset file really matches this plugin
2102 and potentially get the "real" preset name from
2106 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2107 user_preset_map[preset_name] = path;
2112 /* now fill the vector<string> with the names we have */
2114 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2115 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2118 /* add factory presets */
2120 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2122 string const uri = string_compose ("%1", _presets.size ());
2123 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2128 AUPlugin::has_editor () const
2130 // even if the plugin doesn't have its own editor, the AU API can be used
2131 // to create one that looks native.
2135 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2138 type = ARDOUR::AudioUnit;
2141 AUPluginInfo::~AUPluginInfo ()
2143 type = ARDOUR::AudioUnit;
2147 AUPluginInfo::load (Session& session)
2152 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2153 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2155 if (!comp->IsValid()) {
2156 error << ("AudioUnit: not a valid Component") << endmsg;
2158 plugin.reset (new AUPlugin (session.engine(), session, comp));
2161 AUPluginInfo *aup = new AUPluginInfo (*this);
2162 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2163 plugin->set_info (PluginInfoPtr (aup));
2164 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2168 catch (failed_constructor &err) {
2169 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2170 return PluginPtr ();
2175 AUPluginInfo::au_cache_path ()
2177 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2181 AUPluginInfo::discover ()
2185 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2186 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2188 // create crash log file
2189 au_start_crashlog ();
2191 PluginInfoList* plugs = new PluginInfoList;
2193 discover_fx (*plugs);
2194 discover_music (*plugs);
2195 discover_generators (*plugs);
2196 discover_instruments (*plugs);
2198 // all fine if we get here
2199 au_remove_crashlog ();
2201 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2207 AUPluginInfo::discover_music (PluginInfoList& plugs)
2209 CAComponentDescription desc;
2210 desc.componentFlags = 0;
2211 desc.componentFlagsMask = 0;
2212 desc.componentSubType = 0;
2213 desc.componentManufacturer = 0;
2214 desc.componentType = kAudioUnitType_MusicEffect;
2216 discover_by_description (plugs, desc);
2220 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2222 CAComponentDescription desc;
2223 desc.componentFlags = 0;
2224 desc.componentFlagsMask = 0;
2225 desc.componentSubType = 0;
2226 desc.componentManufacturer = 0;
2227 desc.componentType = kAudioUnitType_Effect;
2229 discover_by_description (plugs, desc);
2233 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2235 CAComponentDescription desc;
2236 desc.componentFlags = 0;
2237 desc.componentFlagsMask = 0;
2238 desc.componentSubType = 0;
2239 desc.componentManufacturer = 0;
2240 desc.componentType = kAudioUnitType_Generator;
2242 discover_by_description (plugs, desc);
2246 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2248 CAComponentDescription desc;
2249 desc.componentFlags = 0;
2250 desc.componentFlagsMask = 0;
2251 desc.componentSubType = 0;
2252 desc.componentManufacturer = 0;
2253 desc.componentType = kAudioUnitType_MusicDevice;
2255 discover_by_description (plugs, desc);
2260 AUPluginInfo::au_get_crashlog (std::string &msg)
2262 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2263 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2266 std::ifstream ifs(fn.c_str());
2267 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2268 au_remove_crashlog ();
2273 AUPluginInfo::au_start_crashlog ()
2275 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2276 assert(!_crashlog_fd);
2277 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2278 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2279 PBD::error << "Cannot create AU error-log\n";
2284 AUPluginInfo::au_remove_crashlog ()
2287 ::fclose(_crashlog_fd);
2288 _crashlog_fd = NULL;
2290 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2291 ::g_unlink(fn.c_str());
2292 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2297 AUPluginInfo::au_crashlog (std::string msg)
2299 assert(_crashlog_fd);
2300 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2301 ::fflush(_crashlog_fd);
2305 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2308 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2310 comp = FindNextComponent (NULL, &desc);
2312 while (comp != NULL) {
2313 CAComponentDescription temp;
2314 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2317 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2318 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2319 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2320 CFStringRef itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2321 compTypeString, compManufacturerString, compSubTypeString);
2322 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2323 if (compTypeString != NULL)
2324 CFRelease(compTypeString);
2325 if (compSubTypeString != NULL)
2326 CFRelease(compSubTypeString);
2327 if (compManufacturerString != NULL)
2328 CFRelease(compManufacturerString);
2331 AUPluginInfoPtr info (new AUPluginInfo
2332 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2334 /* although apple designed the subtype field to be a "category" indicator,
2335 its really turned into a plugin ID field for a given manufacturer. Hence
2336 there are no categories for AudioUnits. However, to keep the plugins
2337 showing up under "categories", we'll use the "type" as a high level
2340 NOTE: no panners, format converters or i/o AU's for our purposes
2343 switch (info->descriptor->Type()) {
2344 case kAudioUnitType_Panner:
2345 case kAudioUnitType_OfflineEffect:
2346 case kAudioUnitType_FormatConverter:
2349 case kAudioUnitType_Output:
2350 info->category = _("AudioUnit Outputs");
2352 case kAudioUnitType_MusicDevice:
2353 info->category = _("AudioUnit Instruments");
2355 case kAudioUnitType_MusicEffect:
2356 info->category = _("AudioUnit MusicEffects");
2358 case kAudioUnitType_Effect:
2359 info->category = _("AudioUnit Effects");
2361 case kAudioUnitType_Mixer:
2362 info->category = _("AudioUnit Mixers");
2364 case kAudioUnitType_Generator:
2365 info->category = _("AudioUnit Generators");
2368 info->category = _("AudioUnit (Unknown)");
2372 AUPluginInfo::get_names (temp, info->name, info->creator);
2373 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2374 au_crashlog(string_compose("Plugin: %1", info->name));
2376 info->type = ARDOUR::AudioUnit;
2377 info->unique_id = stringify_descriptor (*info->descriptor);
2379 /* XXX not sure of the best way to handle plugin versioning yet
2382 CAComponent cacomp (*info->descriptor);
2384 if (cacomp.GetResourceVersion (info->version) != noErr) {
2388 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2390 /* here we have to map apple's wildcard system to a simple pair
2391 of values. in ::can_do() we use the whole system, but here
2392 we need a single pair of values. XXX probably means we should
2393 remove any use of these values.
2395 for now, if the plugin provides a wildcard, treat it as 1. we really
2396 don't care much, because whether we can handle an i/o configuration
2397 depends upon ::can_support_io_configuration(), not these counts.
2399 they exist because other parts of ardour try to present i/o configuration
2400 info to the user, which should perhaps be revisited.
2403 int32_t possible_in = info->cache.io_configs.front().first;
2404 int32_t possible_out = info->cache.io_configs.front().second;
2406 if (possible_in > 0) {
2407 info->n_inputs.set (DataType::AUDIO, possible_in);
2409 info->n_inputs.set (DataType::AUDIO, 1);
2412 if (possible_out > 0) {
2413 info->n_outputs.set (DataType::AUDIO, possible_out);
2415 info->n_outputs.set (DataType::AUDIO, 1);
2418 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2419 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2421 plugs.push_back (info);
2424 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2427 au_crashlog("Success.");
2428 comp = FindNextComponent (comp, &desc);
2430 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2434 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2437 AUPluginCachedInfo& cinfo,
2438 const std::string& name)
2443 /* concatenate unique ID with version to provide a key for cached info lookup.
2444 this ensures we don't get stale information, or should if plugin developers
2445 follow Apple "guidelines".
2448 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2453 CachedInfoMap::iterator cim = cached_info.find (id);
2455 if (cim != cached_info.end()) {
2456 cinfo = cim->second;
2461 AUChannelInfo* channel_info;
2465 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2469 if (CAAudioUnit::Open (comp, unit) != noErr) {
2475 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2480 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2481 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2487 /* no explicit info available, so default to 1in/1out */
2489 /* XXX this is wrong. we should be indicating wildcard values */
2491 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2495 /* store each configuration */
2497 for (uint32_t n = 0; n < cnt; ++n) {
2498 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2499 channel_info[n].outChannels));
2502 free (channel_info);
2505 add_cached_info (id, cinfo);
2506 save_cached_info ();
2512 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2514 cached_info[id] = cinfo;
2517 #define AU_CACHE_VERSION "2.0"
2520 AUPluginInfo::save_cached_info ()
2524 node = new XMLNode (X_("AudioUnitPluginCache"));
2525 node->add_property( "version", AU_CACHE_VERSION );
2527 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2528 XMLNode* parent = new XMLNode (X_("plugin"));
2529 parent->add_property ("id", i->first);
2530 node->add_child_nocopy (*parent);
2532 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2534 XMLNode* child = new XMLNode (X_("io"));
2537 snprintf (buf, sizeof (buf), "%d", j->first);
2538 child->add_property (X_("in"), buf);
2539 snprintf (buf, sizeof (buf), "%d", j->second);
2540 child->add_property (X_("out"), buf);
2541 parent->add_child_nocopy (*child);
2546 Glib::ustring path = au_cache_path ();
2549 tree.set_root (node);
2551 if (!tree.write (path)) {
2552 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2553 g_unlink (path.c_str());
2558 AUPluginInfo::load_cached_info ()
2560 Glib::ustring path = au_cache_path ();
2563 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2567 if ( !tree.read (path) ) {
2568 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2572 const XMLNode* root (tree.root());
2574 if (root->name() != X_("AudioUnitPluginCache")) {
2578 //initial version has incorrectly stored i/o info, and/or garbage chars.
2579 const XMLProperty* version = root->property(X_("version"));
2580 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2581 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2585 cached_info.clear ();
2587 const XMLNodeList children = root->children();
2589 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2591 const XMLNode* child = *iter;
2593 if (child->name() == X_("plugin")) {
2595 const XMLNode* gchild;
2596 const XMLNodeList gchildren = child->children();
2597 const XMLProperty* prop = child->property (X_("id"));
2603 string id = prop->value();
2607 string::size_type slash = id.find_last_of ('/');
2609 if (slash == string::npos) {
2613 version = id.substr (slash);
2614 id = id.substr (0, slash);
2615 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2617 if (fixed.empty()) {
2618 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2625 AUPluginCachedInfo cinfo;
2627 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2631 if (gchild->name() == X_("io")) {
2635 const XMLProperty* iprop;
2636 const XMLProperty* oprop;
2638 if (((iprop = gchild->property (X_("in"))) != 0) &&
2639 ((oprop = gchild->property (X_("out"))) != 0)) {
2640 in = atoi (iprop->value());
2641 out = atoi (oprop->value());
2643 cinfo.io_configs.push_back (pair<int,int> (in, out));
2648 if (cinfo.io_configs.size()) {
2649 add_cached_info (id, cinfo);
2658 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2660 CFStringRef itemName = NULL;
2662 // Marc Poirier-style item name
2663 CAComponent auComponent (comp_desc);
2664 if (auComponent.IsValid()) {
2665 CAComponentDescription dummydesc;
2666 Handle nameHandle = NewHandle(sizeof(void*));
2667 if (nameHandle != NULL) {
2668 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2670 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2671 if (nameString != NULL) {
2672 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2675 DisposeHandle(nameHandle);
2679 // if Marc-style fails, do the original way
2680 if (itemName == NULL) {
2681 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2682 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2683 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2685 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2686 compTypeString, compManufacturerString, compSubTypeString);
2688 if (compTypeString != NULL)
2689 CFRelease(compTypeString);
2690 if (compSubTypeString != NULL)
2691 CFRelease(compSubTypeString);
2692 if (compManufacturerString != NULL)
2693 CFRelease(compManufacturerString);
2696 string str = CFStringRefToStdString(itemName);
2697 string::size_type colon = str.find (':');
2700 name = str.substr (colon+1);
2701 maker = str.substr (0, colon);
2702 strip_whitespace_edges (maker);
2703 strip_whitespace_edges (name);
2707 strip_whitespace_edges (name);
2712 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2716 /* note: OSType is a compiler-implemenation-defined value,
2717 historically a 32 bit integer created with a multi-character
2718 constant such as 'abcd'. It is, fundamentally, an abomination.
2723 s << desc.SubType();
2731 AUPluginInfo::needs_midi_input ()
2733 return is_effect_with_midi_input () || is_instrument ();
2737 AUPluginInfo::is_effect () const
2739 return is_effect_without_midi_input() || is_effect_with_midi_input();
2743 AUPluginInfo::is_effect_without_midi_input () const
2745 return descriptor->IsAUFX();
2749 AUPluginInfo::is_effect_with_midi_input () const
2751 return descriptor->IsAUFM();
2755 AUPluginInfo::is_instrument () const
2757 return descriptor->IsMusicDevice();
2761 AUPlugin::set_info (PluginInfoPtr info)
2763 Plugin::set_info (info);
2765 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2766 _has_midi_input = pinfo->needs_midi_input ();
2767 _has_midi_output = false;
2771 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2774 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2776 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2778 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2780 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2784 _parameter_listener_arg = arg;
2790 AUPlugin::listen_to_parameter (uint32_t param_id)
2792 AudioUnitEvent event;
2794 if (!_parameter_listener || param_id >= descriptors.size()) {
2798 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2799 event.mArgument.mParameter.mAudioUnit = unit->AU();
2800 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2801 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2802 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2804 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2808 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2809 event.mArgument.mParameter.mAudioUnit = unit->AU();
2810 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2811 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2812 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2814 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2818 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2819 event.mArgument.mParameter.mAudioUnit = unit->AU();
2820 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2821 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2822 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2824 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2832 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2834 AudioUnitEvent event;
2836 if (!_parameter_listener || param_id >= descriptors.size()) {
2840 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2841 event.mArgument.mParameter.mAudioUnit = unit->AU();
2842 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2843 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2844 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2846 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2850 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2851 event.mArgument.mParameter.mAudioUnit = unit->AU();
2852 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2853 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2854 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2856 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2860 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2861 event.mArgument.mParameter.mAudioUnit = unit->AU();
2862 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2863 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2864 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2866 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2874 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2876 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2880 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2882 ParameterMap::iterator i;
2884 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
2888 switch (event->mEventType) {
2889 case kAudioUnitEvent_BeginParameterChangeGesture:
2890 StartTouch (i->second);
2892 case kAudioUnitEvent_EndParameterChangeGesture:
2893 EndTouch (i->second);
2895 case kAudioUnitEvent_ParameterValueChange:
2896 ParameterChanged (i->second, new_value);