2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "pbd/transmitter.h"
28 #include "pbd/xml++.h"
29 #include "pbd/convert.h"
30 #include "pbd/whitespace.h"
31 #include "pbd/pathscanner.h"
32 #include "pbd/locale_guard.h"
34 #include <glibmm/thread.h>
35 #include <glibmm/fileutils.h>
36 #include <glibmm/miscutils.h>
38 #include "ardour/ardour.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/debug.h"
42 #include "ardour/midi_buffer.h"
43 #include "ardour/filesystem_paths.h"
44 #include "ardour/io.h"
45 #include "ardour/audio_unit.h"
46 #include "ardour/session.h"
47 #include "ardour/tempo.h"
48 #include "ardour/utils.h"
50 #include "appleutility/CAAudioUnit.h"
51 #include "appleutility/CAAUParameter.h"
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreServices/CoreServices.h>
55 #include <AudioUnit/AudioUnit.h>
56 #include <AudioToolbox/AudioUnitUtilities.h>
62 using namespace ARDOUR;
64 #ifndef AU_STATE_SUPPORT
65 static bool seen_get_state_message = false;
66 static bool seen_set_state_message = false;
67 static bool seen_loading_message = false;
68 static bool seen_saving_message = false;
71 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
73 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
74 static string preset_suffix = ".aupreset";
75 static bool preset_search_path_initialized = false;
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)
350 , current_buffers (0)
351 , frames_processed (0)
352 , last_transport_rolling (false)
353 , last_transport_speed (0.0)
355 if (!preset_search_path_initialized) {
356 Glib::ustring p = Glib::get_home_dir();
357 p += "/Library/Audio/Presets:";
358 p += preset_search_path;
359 preset_search_path = p;
360 preset_search_path_initialized = true;
367 AUPlugin::AUPlugin (const AUPlugin& other)
369 , comp (other.get_comp())
370 , unit (new CAAudioUnit)
371 , initialized (false)
372 , _current_block_size (0)
374 , _requires_fixed_size_buffers (false)
378 , current_buffers (0)
379 , frames_processed (0)
385 AUPlugin::~AUPlugin ()
388 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
389 unit->Uninitialize ();
398 AUPlugin::discover_factory_presets ()
401 UInt32 dataSize = sizeof (presets);
404 DEBUG_TRACE (DEBUG::AudioUnits, "get property FactoryPresets in global scope\n");
405 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
406 cerr << "cannot get factory preset info: " << err << endl;
414 CFIndex cnt = CFArrayGetCount (presets);
416 for (CFIndex i = 0; i < cnt; ++i) {
417 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
419 string name = CFStringRefToStdString (preset->presetName);
420 factory_preset_map[name] = preset->presetNumber;
431 /* these keep track of *configured* channel set up,
432 not potential set ups.
436 output_channels = -1;
439 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
440 err = CAAudioUnit::Open (*(comp.get()), *unit);
442 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
443 throw failed_constructor();
447 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
448 throw failed_constructor ();
451 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
452 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
453 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
454 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
455 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
456 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
458 if (input_elements > 0) {
459 AURenderCallbackStruct renderCallbackInfo;
461 renderCallbackInfo.inputProc = _render_callback;
462 renderCallbackInfo.inputProcRefCon = this;
464 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
465 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
466 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
467 cerr << "cannot install render callback (err = " << err << ')' << endl;
468 throw failed_constructor();
472 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
474 HostCallbackInfo info;
475 memset (&info, 0, sizeof (HostCallbackInfo));
476 info.hostUserData = this;
477 info.beatAndTempoProc = _get_beat_and_tempo_callback;
478 info.musicalTimeLocationProc = _get_musical_time_location_callback;
479 info.transportStateProc = _get_transport_state_callback;
481 //ignore result of this - don't care if the property isn't supported
482 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
483 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
484 kAudioUnitScope_Global,
487 sizeof (HostCallbackInfo));
489 if (set_block_size (_session.get_block_size())) {
490 error << _("AUPlugin: cannot set processing block size") << endmsg;
491 throw failed_constructor();
494 discover_parameters ();
495 discover_factory_presets ();
497 // Plugin::setup_controls ();
501 AUPlugin::discover_parameters ()
503 /* discover writable parameters */
505 AudioUnitScope scopes[] = {
506 kAudioUnitScope_Global,
507 kAudioUnitScope_Output,
508 kAudioUnitScope_Input
511 descriptors.clear ();
513 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
515 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
517 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
519 AUParameterDescriptor d;
521 d.id = param_info.ParamID (i);
523 const CAAUParameter* param = param_info.GetParamInfo (d.id);
524 const AudioUnitParameterInfo& info (param->ParamInfo());
526 const int len = CFStringGetLength (param->GetName());;
527 char local_buffer[len*2];
528 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
532 d.label = local_buffer;
535 d.scope = param_info.GetScope ();
536 d.element = param_info.GetElement ();
538 /* info.units to consider */
540 kAudioUnitParameterUnit_Generic = 0
541 kAudioUnitParameterUnit_Indexed = 1
542 kAudioUnitParameterUnit_Boolean = 2
543 kAudioUnitParameterUnit_Percent = 3
544 kAudioUnitParameterUnit_Seconds = 4
545 kAudioUnitParameterUnit_SampleFrames = 5
546 kAudioUnitParameterUnit_Phase = 6
547 kAudioUnitParameterUnit_Rate = 7
548 kAudioUnitParameterUnit_Hertz = 8
549 kAudioUnitParameterUnit_Cents = 9
550 kAudioUnitParameterUnit_RelativeSemiTones = 10
551 kAudioUnitParameterUnit_MIDINoteNumber = 11
552 kAudioUnitParameterUnit_MIDIController = 12
553 kAudioUnitParameterUnit_Decibels = 13
554 kAudioUnitParameterUnit_LinearGain = 14
555 kAudioUnitParameterUnit_Degrees = 15
556 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
557 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
558 kAudioUnitParameterUnit_Pan = 18
559 kAudioUnitParameterUnit_Meters = 19
560 kAudioUnitParameterUnit_AbsoluteCents = 20
561 kAudioUnitParameterUnit_Octaves = 21
562 kAudioUnitParameterUnit_BPM = 22
563 kAudioUnitParameterUnit_Beats = 23
564 kAudioUnitParameterUnit_Milliseconds = 24
565 kAudioUnitParameterUnit_Ratio = 25
568 /* info.flags to consider */
572 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
573 kAudioUnitParameterFlag_HasClump = (1L << 20)
574 kAudioUnitParameterFlag_HasName = (1L << 21)
575 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
576 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
577 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
578 kAudioUnitParameterFlag_CanRamp = (1L << 25)
579 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
580 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
581 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
582 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
583 kAudioUnitParameterFlag_IsReadable = (1L << 30)
584 kAudioUnitParameterFlag_IsWritable = (1L << 31)
587 d.lower = info.minValue;
588 d.upper = info.maxValue;
589 d.default_value = info.defaultValue;
591 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
592 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
593 (d.integer_step && ((d.upper - d.lower) == 1.0));
594 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
595 d.automatable = !d.toggled &&
596 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
597 (info.flags & kAudioUnitParameterFlag_IsWritable);
599 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
605 d.min_unbound = 0; // lower is bound
606 d.max_unbound = 0; // upper is bound
608 descriptors.push_back (d);
615 four_ints_to_four_byte_literal (unsigned char n[4])
617 /* this is actually implementation dependent. sigh. this is what gcc
618 and quite a few others do.
620 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
624 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
626 if (isdigit (id[0])) {
630 /* ID format is xxxx-xxxx-xxxx
631 where x maybe \xNN or a printable character.
633 Split at the '-' and and process each part into an integer.
634 Then put it back together.
638 unsigned char nascent[4];
639 const char* cstr = id.c_str();
640 const char* estr = cstr + id.size();
651 while (*cstr && next_int < 4) {
655 if (estr - cstr < 3) {
657 /* too close to the end for \xNN parsing: treat as literal characters */
659 cerr << "Parse " << cstr << " as a literal \\" << endl;
666 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
670 memcpy (short_buf, &cstr[2], 2);
671 nascent[in] = strtol (short_buf, NULL, 16);
677 /* treat as literal characters */
678 cerr << "Parse " << cstr << " as a literal \\" << endl;
692 if (in && (in % 4 == 0)) {
693 /* nascent is ready */
694 n[next_int] = four_ints_to_four_byte_literal (nascent);
698 /* swallow space-hyphen-space */
712 s << n[0] << '-' << n[1] << '-' << n[2];
721 AUPlugin::unique_id () const
723 return AUPluginInfo::stringify_descriptor (comp->Desc());
727 AUPlugin::label () const
729 return _info->name.c_str();
733 AUPlugin::parameter_count () const
735 return descriptors.size();
739 AUPlugin::default_value (uint32_t port)
741 if (port < descriptors.size()) {
742 return descriptors[port].default_value;
749 AUPlugin::signal_latency () const
751 return unit->Latency() * _session.frame_rate();
755 AUPlugin::set_parameter (uint32_t which, float val)
757 if (which >= descriptors.size()) {
761 const AUParameterDescriptor& d (descriptors[which]);
762 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
763 unit->SetParameter (d.id, d.scope, d.element, val);
765 /* tell the world what we did */
767 AudioUnitEvent theEvent;
769 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
770 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
771 theEvent.mArgument.mParameter.mParameterID = d.id;
772 theEvent.mArgument.mParameter.mScope = d.scope;
773 theEvent.mArgument.mParameter.mElement = d.element;
775 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
776 AUEventListenerNotify (NULL, NULL, &theEvent);
778 Plugin::set_parameter (which, val);
782 AUPlugin::get_parameter (uint32_t which) const
785 if (which < descriptors.size()) {
786 const AUParameterDescriptor& d (descriptors[which]);
787 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
788 unit->GetParameter(d.id, d.scope, d.element, val);
794 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
796 if (which < descriptors.size()) {
797 pd = descriptors[which];
804 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
806 if (which < descriptors.size()) {
815 AUPlugin::activate ()
819 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
820 if ((err = unit->Initialize()) != noErr) {
821 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
823 frames_processed = 0;
830 AUPlugin::deactivate ()
832 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
833 unit->Uninitialize ();
840 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
841 unit->GlobalReset ();
845 AUPlugin::requires_fixed_size_buffers() const
847 return _requires_fixed_size_buffers;
852 AUPlugin::set_block_size (pframes_t nframes)
854 bool was_initialized = initialized;
855 UInt32 numFrames = nframes;
862 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
863 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
864 0, &numFrames, sizeof (numFrames))) != noErr) {
865 cerr << "cannot set max frames (err = " << err << ')' << endl;
869 if (was_initialized) {
873 _current_block_size = nframes;
879 AUPlugin::configure_io (ChanCount in, ChanCount out)
881 AudioStreamBasicDescription streamFormat;
882 bool was_initialized = initialized;
883 int32_t audio_in = in.n_audio();
884 int32_t audio_out = out.n_audio();
886 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
889 //if we are already running with the requested i/o config, bail out here
890 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
897 streamFormat.mSampleRate = _session.frame_rate();
898 streamFormat.mFormatID = kAudioFormatLinearPCM;
899 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
901 #ifdef __LITTLE_ENDIAN__
904 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
907 streamFormat.mBitsPerChannel = 32;
908 streamFormat.mFramesPerPacket = 1;
910 /* apple says that for non-interleaved data, these
911 values always refer to a single channel.
913 streamFormat.mBytesPerPacket = 4;
914 streamFormat.mBytesPerFrame = 4;
916 streamFormat.mChannelsPerFrame = audio_in;
918 if (set_input_format (streamFormat) != 0) {
922 streamFormat.mChannelsPerFrame = audio_out;
924 if (set_output_format (streamFormat) != 0) {
928 /* reset plugin info to show currently configured state */
930 _info->n_inputs = in;
931 _info->n_outputs = out;
933 if (was_initialized) {
941 AUPlugin::input_streams() const
945 c.set (DataType::AUDIO, 1);
946 c.set (DataType::MIDI, 0);
948 if (input_channels < 0) {
949 warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
951 c.set (DataType::AUDIO, input_channels);
952 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
960 AUPlugin::output_streams() const
964 c.set (DataType::AUDIO, 1);
965 c.set (DataType::MIDI, 0);
967 if (output_channels < 0) {
968 warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
970 c.set (DataType::AUDIO, output_channels);
971 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
978 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
980 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
981 // attempt to multiply-instantiate plugins to meet io configurations.
983 int32_t audio_in = in.n_audio();
985 int32_t plugcnt = -1;
986 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
988 /* lets check MIDI first */
990 if (in.n_midi() > 0) {
991 if (!_has_midi_input) {
996 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
998 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations\n", name(), io_configs.size()));
1000 //Ardour expects the plugin to tell it the output configuration
1001 //but AU plugins can have multiple I/O configurations
1002 //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
1003 //so first lets see if there's a configuration that keeps out==in
1005 audio_out = audio_in;
1007 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1008 int32_t possible_in = i->first;
1009 int32_t possible_out = i->second;
1011 if (possible_in == audio_in && possible_out == audio_out) {
1012 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1017 /* now allow potentially "imprecise" matches */
1019 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1021 int32_t possible_in = i->first;
1022 int32_t possible_out = i->second;
1024 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1026 if (possible_out == 0) {
1027 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1031 if (possible_in == 0) {
1033 /* instrument plugin, always legal but throws away inputs ...
1036 if (possible_out == -1) {
1037 /* out much match in (UNLIKELY!!) */
1038 audio_out = audio_in;
1040 } else if (possible_out == -2) {
1041 /* any configuration possible, pick matching */
1042 audio_out = audio_in;
1044 } else if (possible_out < -2) {
1045 /* explicit variable number of outputs, pick maximum */
1046 audio_out = -possible_out;
1049 /* exact number of outputs */
1050 audio_out = possible_out;
1055 if (possible_in == -1) {
1057 /* wildcard for input */
1059 if (possible_out == -1) {
1060 /* out much match in */
1061 audio_out = audio_in;
1063 } else if (possible_out == -2) {
1064 /* any configuration possible, pick matching */
1065 audio_out = audio_in;
1067 } else if (possible_out < -2) {
1068 /* explicit variable number of outputs, pick maximum */
1069 audio_out = -possible_out;
1072 /* exact number of outputs */
1073 audio_out = possible_out;
1078 if (possible_in == -2) {
1080 if (possible_out == -1) {
1081 /* any configuration possible, pick matching */
1082 audio_out = audio_in;
1084 } else if (possible_out == -2) {
1085 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1088 } else if (possible_out < -2) {
1089 /* explicit variable number of outputs, pick maximum */
1090 audio_out = -possible_out;
1093 /* exact number of outputs */
1094 audio_out = possible_out;
1099 if (possible_in < -2) {
1101 /* explicit variable number of inputs */
1103 if (audio_in > -possible_in) {
1104 /* request is too large */
1108 if (possible_out == -1) {
1109 /* out must match in */
1110 audio_out = audio_in;
1112 } else if (possible_out == -2) {
1113 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1116 } else if (possible_out < -2) {
1117 /* explicit variable number of outputs, pick maximum */
1118 audio_out = -possible_out;
1121 /* exact number of outputs */
1122 audio_out = possible_out;
1127 if (possible_in == audio_in) {
1129 /* exact number of inputs ... must match obviously */
1131 if (possible_out == -1) {
1132 /* out must match in */
1133 audio_out = audio_in;
1135 } else if (possible_out == -2) {
1136 /* any output configuration, pick matching */
1137 audio_out = audio_in;
1139 } else if (possible_out < -2) {
1140 /* explicit variable number of outputs, pick maximum */
1141 audio_out = -possible_out;
1144 /* exact number of outputs */
1145 audio_out = possible_out;
1157 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2 plugcnt %3\n", in, out, plugcnt));
1159 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\FAIL: no io configs match %1\n", in));
1162 out.set (DataType::MIDI, 0);
1163 out.set (DataType::AUDIO, audio_out);
1169 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1171 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1175 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1177 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1186 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1187 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1193 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1197 for (uint32_t i = 0; i < cnt; ++i) {
1198 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1199 (scope == kAudioUnitScope_Input ? "input" : "output"),
1201 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1202 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1203 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1208 if (scope == kAudioUnitScope_Input) {
1209 input_channels = fmt.mChannelsPerFrame;
1211 output_channels = fmt.mChannelsPerFrame;
1218 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1219 const AudioTimeStamp*,
1221 UInt32 inNumberFrames,
1222 AudioBufferList* ioData)
1224 if (_has_midi_input) {
1225 assert (current_buffers->count().n_midi() > 0);
1227 /* deliver the first (and assumed only) MIDI buffer's data
1231 MidiBuffer& mb (current_buffers->get_midi(0));
1233 for (MidiBuffer::iterator i = mb.begin(); i != mb.end(); ++i) {
1234 Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *i;
1235 switch (ev.type()) {
1236 case MIDI_CMD_NOTE_ON:
1237 case MIDI_CMD_NOTE_OFF:
1238 case MIDI_CMD_CONTROL:
1239 case MIDI_CMD_BENDER:
1240 case MIDI_CMD_PGM_CHANGE:
1241 case MIDI_CMD_CHANNEL_PRESSURE:
1243 const uint8_t* b = ev.buffer();
1244 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1249 /* plugins do not get other stuff by default */
1255 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1257 if (current_maxbuf == 0) {
1258 error << _("AUPlugin: render callback called illegally!") << endmsg;
1259 return kAudioUnitErr_CannotDoInCurrentContext;
1261 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
1263 for (uint32_t i = 0; i < limit; ++i) {
1264 ioData->mBuffers[i].mNumberChannels = 1;
1265 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1267 /* we don't use the channel mapping because audiounits are
1268 never replicated. one plugin instance uses all channels/buffers
1269 passed to PluginInsert::connect_and_run()
1272 ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
1275 cb_offset += inNumberFrames;
1281 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1283 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1285 AudioUnitRenderActionFlags flags = 0;
1288 uint32_t maxbuf = bufs.count().n_audio();
1290 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1291 unit->GlobalReset();
1292 _last_nframes = nframes;
1295 current_buffers = &bufs;
1296 current_maxbuf = maxbuf;
1297 current_offset = offset;
1300 buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
1302 for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
1303 buffers->mBuffers[i].mNumberChannels = 1;
1304 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1305 buffers->mBuffers[i].mData = 0;
1308 ts.mSampleTime = frames_processed;
1309 ts.mFlags = kAudioTimeStampSampleTimeValid;
1311 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1314 frames_processed += nframes;
1316 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1319 for (i = 0; i < limit; ++i) {
1320 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1321 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1322 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1323 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1327 /* now silence any buffers that were passed in but the that the plugin
1328 did not fill/touch/use.
1331 for (;i < maxbuf; ++i) {
1332 Sample* buffer_address= bufs.get_audio (i).data (offset);
1333 memset (buffer_address, 0, nframes * sizeof (Sample));
1339 cerr << name() << " render status " << err << endl;
1344 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1345 Float64* outCurrentTempo)
1347 TempoMap& tmap (_session.tempo_map());
1349 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1351 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1352 (and interpretation) of a beat position will be incorrect. So refuse to
1356 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1357 return kAudioUnitErr_CannotDoInCurrentContext;
1360 Timecode::BBT_Time bbt;
1361 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1362 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1364 if (outCurrentBeat) {
1366 beat = metric.meter().beats_per_bar() * bbt.bars;
1368 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1369 *outCurrentBeat = beat;
1372 if (outCurrentTempo) {
1373 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1381 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1382 Float32* outTimeSig_Numerator,
1383 UInt32* outTimeSig_Denominator,
1384 Float64* outCurrentMeasureDownBeat)
1386 TempoMap& tmap (_session.tempo_map());
1388 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1390 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1391 (and interpretation) of a beat position will be incorrect. So refuse to
1395 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1396 return kAudioUnitErr_CannotDoInCurrentContext;
1399 Timecode::BBT_Time bbt;
1400 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1401 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1403 if (outDeltaSampleOffsetToNextBeat) {
1404 if (bbt.ticks == 0) {
1406 *outDeltaSampleOffsetToNextBeat = 0;
1408 *outDeltaSampleOffsetToNextBeat = (UInt32)
1409 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1410 metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1414 if (outTimeSig_Numerator) {
1415 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1417 if (outTimeSig_Denominator) {
1418 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1421 if (outCurrentMeasureDownBeat) {
1423 /* beat for the start of the bar.
1425 2|1|0 -> 1 + beats_per_bar
1426 3|1|0 -> 1 + (2 * beats_per_bar)
1430 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1437 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1438 Boolean* outTransportStateChanged,
1439 Float64* outCurrentSampleInTimeLine,
1440 Boolean* outIsCycling,
1441 Float64* outCycleStartBeat,
1442 Float64* outCycleEndBeat)
1447 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1449 rolling = _session.transport_rolling();
1450 speed = _session.transport_speed ();
1453 *outIsPlaying = _session.transport_rolling();
1456 if (outTransportStateChanged) {
1457 if (rolling != last_transport_rolling) {
1458 *outTransportStateChanged = true;
1459 } else if (speed != last_transport_speed) {
1460 *outTransportStateChanged = true;
1462 *outTransportStateChanged = false;
1466 if (outCurrentSampleInTimeLine) {
1467 /* this assumes that the AU can only call this host callback from render context,
1468 where current_offset is valid.
1470 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1474 Location* loc = _session.locations()->auto_loop_location();
1476 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1478 if (*outIsCycling) {
1480 if (outCycleStartBeat || outCycleEndBeat) {
1482 TempoMap& tmap (_session.tempo_map());
1484 /* more than 1 meter means that a simplistic computation (and interpretation) of
1485 a beat position will be incorrect. so refuse to offer the value.
1488 if (tmap.n_meters() > 1) {
1489 return kAudioUnitErr_CannotDoInCurrentContext;
1492 Timecode::BBT_Time bbt;
1494 if (outCycleStartBeat) {
1495 TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
1496 _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1499 beat = metric.meter().beats_per_bar() * bbt.bars;
1501 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1503 *outCycleStartBeat = beat;
1506 if (outCycleEndBeat) {
1507 TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
1508 _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1511 beat = metric.meter().beats_per_bar() * bbt.bars;
1513 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1515 *outCycleEndBeat = beat;
1521 last_transport_rolling = rolling;
1522 last_transport_speed = speed;
1527 set<Evoral::Parameter>
1528 AUPlugin::automatable() const
1530 set<Evoral::Parameter> automates;
1532 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1533 if (descriptors[i].automatable) {
1534 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1542 AUPlugin::describe_parameter (Evoral::Parameter param)
1544 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1545 return descriptors[param.id()].label;
1552 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1554 // NameValue stuff here
1558 AUPlugin::parameter_is_audio (uint32_t) const
1564 AUPlugin::parameter_is_control (uint32_t) const
1570 AUPlugin::parameter_is_input (uint32_t) const
1576 AUPlugin::parameter_is_output (uint32_t) const
1582 AUPlugin::add_state (XMLNode* root) const
1584 LocaleGuard lg (X_("POSIX"));
1586 #ifdef AU_STATE_SUPPORT
1588 CFPropertyListRef propertyList;
1590 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1591 if (unit->GetAUPreset (propertyList) != noErr) {
1595 // Convert the property list into XML data.
1597 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1600 error << _("Could not create XML version of property list") << endmsg;
1604 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1605 our state node. GACK!
1610 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1612 root->add_child_copy (*t.root());
1616 CFRelease (xmlData);
1617 CFRelease (propertyList);
1619 if (!seen_get_state_message) {
1620 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1623 seen_get_state_message = true;
1629 AUPlugin::set_state(const XMLNode& node, int version)
1631 #ifdef AU_STATE_SUPPORT
1633 CFPropertyListRef propertyList;
1634 LocaleGuard lg (X_("POSIX"));
1636 if (node.name() != state_node_name()) {
1637 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1641 if (node.children().empty()) {
1645 XMLNode* top = node.children().front();
1646 XMLNode* copy = new XMLNode (*top);
1651 const string& xml = t.write_buffer ();
1652 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1653 CFStringRef errorString;
1655 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1657 kCFPropertyListImmutable,
1660 CFRelease (xmlData);
1663 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1664 if (unit->SetAUPreset (propertyList) == noErr) {
1667 /* tell the world */
1669 AudioUnitParameter changedUnit;
1670 changedUnit.mAudioUnit = unit->AU();
1671 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1672 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1674 CFRelease (propertyList);
1677 Plugin::set_state (node, version);
1680 if (!seen_set_state_message) {
1681 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1685 return Plugin::set_state (node, version);
1690 AUPlugin::load_preset (PresetRecord r)
1692 Plugin::load_preset (r);
1694 #ifdef AU_STATE_SUPPORT
1696 CFPropertyListRef propertyList;
1698 UserPresetMap::iterator ux;
1699 FactoryPresetMap::iterator fx;
1701 /* look first in "user" presets */
1703 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1705 if ((propertyList = load_property_list (ux->second)) != 0) {
1706 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1707 if (unit->SetAUPreset (propertyList) == noErr) {
1710 /* tell the world */
1712 AudioUnitParameter changedUnit;
1713 changedUnit.mAudioUnit = unit->AU();
1714 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1715 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1717 CFRelease(propertyList);
1720 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1724 preset.presetNumber = fx->second;
1725 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1727 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1729 if (unit->SetPresentPreset (preset) == 0) {
1732 /* tell the world */
1734 AudioUnitParameter changedUnit;
1735 changedUnit.mAudioUnit = unit->AU();
1736 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1737 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1743 if (!seen_loading_message) {
1744 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1747 seen_loading_message = true;
1754 AUPlugin::do_remove_preset (std::string)
1759 AUPlugin::do_save_preset (string preset_name)
1761 #ifdef AU_STATE_SUPPORT
1762 CFPropertyListRef propertyList;
1763 vector<Glib::ustring> v;
1764 Glib::ustring user_preset_path;
1767 std::string m = maker();
1768 std::string n = name();
1770 strip_whitespace_edges (m);
1771 strip_whitespace_edges (n);
1773 v.push_back (Glib::get_home_dir());
1774 v.push_back ("Library");
1775 v.push_back ("Audio");
1776 v.push_back ("Presets");
1780 user_preset_path = Glib::build_filename (v);
1782 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1783 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1787 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1788 if (unit->GetAUPreset (propertyList) != noErr) {
1792 // add the actual preset name */
1794 v.push_back (preset_name + preset_suffix);
1798 user_preset_path = Glib::build_filename (v);
1800 set_preset_name_in_plist (propertyList, preset_name);
1802 if (save_property_list (propertyList, user_preset_path)) {
1803 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1807 CFRelease(propertyList);
1809 return string ("file:///") + user_preset_path;
1811 if (!seen_saving_message) {
1812 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1815 seen_saving_message = true;
1821 //-----------------------------------------------------------------------------
1822 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1824 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1826 CFNumberRef cfNumber;
1827 SInt32 numberValue = 0;
1828 Boolean dummySuccess;
1830 if (outSuccess == NULL)
1831 outSuccess = &dummySuccess;
1832 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1834 *outSuccess = FALSE;
1838 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1839 if (cfNumber == NULL)
1841 *outSuccess = FALSE;
1844 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1852 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1854 CFDictionaryRef auStateDictionary;
1855 ComponentDescription tempDesc = {0,0,0,0,0};
1856 SInt32 versionValue;
1859 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1862 // the property list for AU state data must be of the dictionary type
1863 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1864 return kAudioUnitErr_InvalidPropertyValue;
1867 auStateDictionary = (CFDictionaryRef)inAUStateData;
1869 // first check to make sure that the version of the AU state data is one that we know understand
1870 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1871 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1874 return kAudioUnitErr_InvalidPropertyValue;
1876 #define kCurrentSavedStateVersion 0
1877 if (versionValue != kCurrentSavedStateVersion) {
1878 return kAudioUnitErr_InvalidPropertyValue;
1881 // grab the ComponentDescription values from the AU state data
1882 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1883 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1884 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1885 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1886 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1887 return kAudioUnitErr_InvalidPropertyValue;
1889 *outComponentDescription = tempDesc;
1894 static bool au_preset_filter (const string& str, void* arg)
1896 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1900 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1904 /* check the preset file path name against this plugin
1905 ID. The idea is that all preset files for this plugin
1906 include "<manufacturer>/<plugin-name>" in their path.
1909 Plugin* p = (Plugin *) arg;
1910 string match = p->maker();
1914 ret = str.find (match) != string::npos;
1917 string m = p->maker ();
1918 string n = p->name ();
1919 strip_whitespace_edges (m);
1920 strip_whitespace_edges (n);
1925 ret = str.find (match) != string::npos;
1933 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1936 CFPropertyListRef plist;
1937 ComponentDescription presetDesc;
1940 plist = load_property_list (pathstr);
1946 // get the ComponentDescription from the AU preset file
1948 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1950 if (status == noErr) {
1951 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1953 /* try to get the preset name from the property list */
1955 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1957 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1961 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1964 char buf[PATH_MAX+1];
1966 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1981 AUPlugin::current_preset() const
1985 #ifdef AU_STATE_SUPPORT
1986 CFPropertyListRef propertyList;
1988 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
1989 if (unit->GetAUPreset (propertyList) == noErr) {
1990 preset_name = get_preset_name_in_plist (propertyList);
1991 CFRelease(propertyList);
1998 AUPlugin::find_presets ()
2000 #ifdef AU_STATE_SUPPORT
2001 vector<string*>* preset_files;
2002 PathScanner scanner;
2004 user_preset_map.clear ();
2006 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2008 if (!preset_files) {
2012 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2014 string path = *(*x);
2017 /* make an initial guess at the preset name using the path */
2019 preset_name = Glib::path_get_basename (path);
2020 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2022 /* check that this preset file really matches this plugin
2023 and potentially get the "real" preset name from
2027 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2028 user_preset_map[preset_name] = path;
2034 delete preset_files;
2036 /* now fill the vector<string> with the names we have */
2038 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2039 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2042 /* add factory presets */
2044 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2046 string const uri = string_compose ("%1", _presets.size ());
2047 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first)));
2054 AUPlugin::has_editor () const
2056 // even if the plugin doesn't have its own editor, the AU API can be used
2057 // to create one that looks native.
2061 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2064 type = ARDOUR::AudioUnit;
2067 AUPluginInfo::~AUPluginInfo ()
2069 type = ARDOUR::AudioUnit;
2073 AUPluginInfo::load (Session& session)
2078 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2079 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2081 if (!comp->IsValid()) {
2082 error << ("AudioUnit: not a valid Component") << endmsg;
2084 plugin.reset (new AUPlugin (session.engine(), session, comp));
2087 AUPluginInfo *aup = new AUPluginInfo (*this);
2088 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2089 plugin->set_info (PluginInfoPtr (aup));
2090 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2094 catch (failed_constructor &err) {
2095 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2096 return PluginPtr ();
2101 AUPluginInfo::au_cache_path ()
2103 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2107 AUPluginInfo::discover ()
2111 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2112 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2115 PluginInfoList* plugs = new PluginInfoList;
2117 discover_fx (*plugs);
2118 discover_music (*plugs);
2119 discover_generators (*plugs);
2120 discover_instruments (*plugs);
2122 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2128 AUPluginInfo::discover_music (PluginInfoList& plugs)
2130 CAComponentDescription desc;
2131 desc.componentFlags = 0;
2132 desc.componentFlagsMask = 0;
2133 desc.componentSubType = 0;
2134 desc.componentManufacturer = 0;
2135 desc.componentType = kAudioUnitType_MusicEffect;
2137 discover_by_description (plugs, desc);
2141 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2143 CAComponentDescription desc;
2144 desc.componentFlags = 0;
2145 desc.componentFlagsMask = 0;
2146 desc.componentSubType = 0;
2147 desc.componentManufacturer = 0;
2148 desc.componentType = kAudioUnitType_Effect;
2150 discover_by_description (plugs, desc);
2154 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2156 CAComponentDescription desc;
2157 desc.componentFlags = 0;
2158 desc.componentFlagsMask = 0;
2159 desc.componentSubType = 0;
2160 desc.componentManufacturer = 0;
2161 desc.componentType = kAudioUnitType_Generator;
2163 discover_by_description (plugs, desc);
2167 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2169 CAComponentDescription desc;
2170 desc.componentFlags = 0;
2171 desc.componentFlagsMask = 0;
2172 desc.componentSubType = 0;
2173 desc.componentManufacturer = 0;
2174 desc.componentType = kAudioUnitType_MusicDevice;
2176 discover_by_description (plugs, desc);
2180 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2184 comp = FindNextComponent (NULL, &desc);
2186 while (comp != NULL) {
2187 CAComponentDescription temp;
2188 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2190 AUPluginInfoPtr info (new AUPluginInfo
2191 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2193 /* although apple designed the subtype field to be a "category" indicator,
2194 its really turned into a plugin ID field for a given manufacturer. Hence
2195 there are no categories for AudioUnits. However, to keep the plugins
2196 showing up under "categories", we'll use the "type" as a high level
2199 NOTE: no panners, format converters or i/o AU's for our purposes
2202 switch (info->descriptor->Type()) {
2203 case kAudioUnitType_Panner:
2204 case kAudioUnitType_OfflineEffect:
2205 case kAudioUnitType_FormatConverter:
2208 case kAudioUnitType_Output:
2209 info->category = _("AudioUnit Outputs");
2211 case kAudioUnitType_MusicDevice:
2212 info->category = _("AudioUnit Instruments");
2214 case kAudioUnitType_MusicEffect:
2215 info->category = _("AudioUnit MusicEffects");
2217 case kAudioUnitType_Effect:
2218 info->category = _("AudioUnit Effects");
2220 case kAudioUnitType_Mixer:
2221 info->category = _("AudioUnit Mixers");
2223 case kAudioUnitType_Generator:
2224 info->category = _("AudioUnit Generators");
2227 info->category = _("AudioUnit (Unknown)");
2231 AUPluginInfo::get_names (temp, info->name, info->creator);
2233 info->type = ARDOUR::AudioUnit;
2234 info->unique_id = stringify_descriptor (*info->descriptor);
2236 /* XXX not sure of the best way to handle plugin versioning yet
2239 CAComponent cacomp (*info->descriptor);
2241 if (cacomp.GetResourceVersion (info->version) != noErr) {
2245 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2247 /* here we have to map apple's wildcard system to a simple pair
2248 of values. in ::can_do() we use the whole system, but here
2249 we need a single pair of values. XXX probably means we should
2250 remove any use of these values.
2253 info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
2254 info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
2256 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2257 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2259 plugs.push_back (info);
2262 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2265 comp = FindNextComponent (comp, &desc);
2270 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2273 AUPluginCachedInfo& cinfo,
2274 const std::string& name)
2279 /* concatenate unique ID with version to provide a key for cached info lookup.
2280 this ensures we don't get stale information, or should if plugin developers
2281 follow Apple "guidelines".
2284 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2289 CachedInfoMap::iterator cim = cached_info.find (id);
2291 if (cim != cached_info.end()) {
2292 cinfo = cim->second;
2297 AUChannelInfo* channel_info;
2301 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2305 if (CAAudioUnit::Open (comp, unit) != noErr) {
2311 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2316 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2317 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2323 /* no explicit info available, so default to 1in/1out */
2325 cinfo.io_configs.push_back (pair<int,int> (1, 1));
2329 /* store each configuration */
2331 for (uint32_t n = 0; n < cnt; ++n) {
2332 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2333 channel_info[n].outChannels));
2336 free (channel_info);
2339 add_cached_info (id, cinfo);
2340 save_cached_info ();
2346 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2348 cached_info[id] = cinfo;
2351 #define AU_CACHE_VERSION "2.0"
2354 AUPluginInfo::save_cached_info ()
2358 node = new XMLNode (X_("AudioUnitPluginCache"));
2359 node->add_property( "version", AU_CACHE_VERSION );
2361 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2362 XMLNode* parent = new XMLNode (X_("plugin"));
2363 parent->add_property ("id", i->first);
2364 node->add_child_nocopy (*parent);
2366 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2368 XMLNode* child = new XMLNode (X_("io"));
2371 snprintf (buf, sizeof (buf), "%d", j->first);
2372 child->add_property (X_("in"), buf);
2373 snprintf (buf, sizeof (buf), "%d", j->second);
2374 child->add_property (X_("out"), buf);
2375 parent->add_child_nocopy (*child);
2380 Glib::ustring path = au_cache_path ();
2383 tree.set_root (node);
2385 if (!tree.write (path)) {
2386 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2387 unlink (path.c_str());
2392 AUPluginInfo::load_cached_info ()
2394 Glib::ustring path = au_cache_path ();
2397 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2401 if ( !tree.read (path) ) {
2402 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2406 const XMLNode* root (tree.root());
2408 if (root->name() != X_("AudioUnitPluginCache")) {
2412 //initial version has incorrectly stored i/o info, and/or garbage chars.
2413 const XMLProperty* version = root->property(X_("version"));
2414 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2415 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2419 cached_info.clear ();
2421 const XMLNodeList children = root->children();
2423 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2425 const XMLNode* child = *iter;
2427 if (child->name() == X_("plugin")) {
2429 const XMLNode* gchild;
2430 const XMLNodeList gchildren = child->children();
2431 const XMLProperty* prop = child->property (X_("id"));
2437 string id = prop->value();
2441 string::size_type slash = id.find_last_of ('/');
2443 if (slash == string::npos) {
2447 version = id.substr (slash);
2448 id = id.substr (0, slash);
2449 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2451 if (fixed.empty()) {
2452 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2459 AUPluginCachedInfo cinfo;
2461 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2465 if (gchild->name() == X_("io")) {
2469 const XMLProperty* iprop;
2470 const XMLProperty* oprop;
2472 if (((iprop = gchild->property (X_("in"))) != 0) &&
2473 ((oprop = gchild->property (X_("out"))) != 0)) {
2474 in = atoi (iprop->value());
2475 out = atoi (oprop->value());
2477 cinfo.io_configs.push_back (pair<int,int> (in, out));
2482 if (cinfo.io_configs.size()) {
2483 add_cached_info (id, cinfo);
2492 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2494 CFStringRef itemName = NULL;
2496 // Marc Poirier-style item name
2497 CAComponent auComponent (comp_desc);
2498 if (auComponent.IsValid()) {
2499 CAComponentDescription dummydesc;
2500 Handle nameHandle = NewHandle(sizeof(void*));
2501 if (nameHandle != NULL) {
2502 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2504 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2505 if (nameString != NULL) {
2506 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2509 DisposeHandle(nameHandle);
2513 // if Marc-style fails, do the original way
2514 if (itemName == NULL) {
2515 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2516 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2517 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2519 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2520 compTypeString, compManufacturerString, compSubTypeString);
2522 if (compTypeString != NULL)
2523 CFRelease(compTypeString);
2524 if (compSubTypeString != NULL)
2525 CFRelease(compSubTypeString);
2526 if (compManufacturerString != NULL)
2527 CFRelease(compManufacturerString);
2530 string str = CFStringRefToStdString(itemName);
2531 string::size_type colon = str.find (':');
2534 name = str.substr (colon+1);
2535 maker = str.substr (0, colon);
2536 strip_whitespace_edges (maker);
2537 strip_whitespace_edges (name);
2541 strip_whitespace_edges (name);
2546 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2550 /* note: OSType is a compiler-implemenation-defined value,
2551 historically a 32 bit integer created with a multi-character
2552 constant such as 'abcd'. It is, fundamentally, an abomination.
2557 s << desc.SubType();
2565 AUPluginInfo::needs_midi_input ()
2567 return is_effect_with_midi_input () || is_instrument ();
2571 AUPluginInfo::is_effect () const
2573 return is_effect_without_midi_input() || is_effect_with_midi_input();
2577 AUPluginInfo::is_effect_without_midi_input () const
2579 return descriptor->IsAUFX();
2583 AUPluginInfo::is_effect_with_midi_input () const
2585 return descriptor->IsAUFM();
2589 AUPluginInfo::is_instrument () const
2591 return descriptor->IsMusicDevice();
2595 AUPlugin::set_info (PluginInfoPtr info)
2597 Plugin::set_info (info);
2599 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2601 _has_midi_input = pinfo->needs_midi_input ();
2602 _has_midi_output = false;