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/filesystem_paths.h"
42 #include "ardour/io.h"
43 #include "ardour/audio_unit.h"
44 #include "ardour/session.h"
45 #include "ardour/tempo.h"
46 #include "ardour/utils.h"
48 #include "appleutility/CAAudioUnit.h"
49 #include "appleutility/CAAUParameter.h"
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreServices/CoreServices.h>
53 #include <AudioUnit/AudioUnit.h>
54 #include <AudioToolbox/AudioUnitUtilities.h>
60 using namespace ARDOUR;
62 //#define TRACE_AU_API
64 #define TRACE_API(fmt,...) fprintf (stderr, fmt, ## __VA_ARGS__)
66 #define TRACE_API(fmt,...)
69 #ifndef AU_STATE_SUPPORT
70 static bool seen_get_state_message = false;
71 static bool seen_set_state_message = false;
72 static bool seen_loading_message = false;
73 static bool seen_saving_message = false;
76 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
78 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
79 static string preset_suffix = ".aupreset";
80 static bool preset_search_path_initialized = false;
81 static bool debug_io_config = true;
84 _render_callback(void *userData,
85 AudioUnitRenderActionFlags *ioActionFlags,
86 const AudioTimeStamp *inTimeStamp,
88 UInt32 inNumberFrames,
89 AudioBufferList* ioData)
92 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
98 _get_beat_and_tempo_callback (void* userData,
99 Float64* outCurrentBeat,
100 Float64* outCurrentTempo)
103 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
110 _get_musical_time_location_callback (void * userData,
111 UInt32 * outDeltaSampleOffsetToNextBeat,
112 Float32 * outTimeSig_Numerator,
113 UInt32 * outTimeSig_Denominator,
114 Float64 * outCurrentMeasureDownBeat)
117 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
118 outTimeSig_Numerator,
119 outTimeSig_Denominator,
120 outCurrentMeasureDownBeat);
126 _get_transport_state_callback (void* userData,
127 Boolean* outIsPlaying,
128 Boolean* outTransportStateChanged,
129 Float64* outCurrentSampleInTimeLine,
130 Boolean* outIsCycling,
131 Float64* outCycleStartBeat,
132 Float64* outCycleEndBeat)
135 return ((AUPlugin*)userData)->get_transport_state_callback (outIsPlaying, outTransportStateChanged,
136 outCurrentSampleInTimeLine, outIsCycling,
137 outCycleStartBeat, outCycleEndBeat);
144 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
150 // Convert the property list into XML data.
152 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
155 error << _("Could not create XML version of property list") << endmsg;
159 // Write the XML data to the file.
161 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
163 if (errno == EEXIST) {
164 /* tell any UI's that this file already exists and ask them what to do */
165 bool overwrite = Plugin::PresetFileExists(); // EMIT SIGNAL
167 fd = open (path.c_str(), O_WRONLY, 0664);
173 error << string_compose (_("Cannot open preset file %1 (%2)"), path, strerror (errno)) << endmsg;
178 size_t cnt = CFDataGetLength (xmlData);
180 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
191 static CFPropertyListRef
192 load_property_list (Glib::ustring path)
195 CFPropertyListRef propertyList = 0;
197 CFStringRef errorString;
199 // Read the XML file.
201 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
206 off_t len = lseek (fd, 0, SEEK_END);
207 char* buf = new char[len];
208 lseek (fd, 0, SEEK_SET);
210 if (read (fd, buf, len) != len) {
218 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
220 // Reconstitute the dictionary using the XML data.
222 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
224 kCFPropertyListImmutable,
233 //-----------------------------------------------------------------------------
235 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
240 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
242 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
243 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
249 //-----------------------------------------------------------------------------
251 get_preset_name_in_plist (CFPropertyListRef plist)
259 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
260 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
262 CFStringRef str = (CFStringRef) p;
263 int len = CFStringGetLength(str);
265 char local_buffer[len];
266 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
274 //--------------------------------------------------------------------------
275 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
276 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
277 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
278 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
280 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
283 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
284 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
286 // only sub-type and manufacturer IDs need to be equal
289 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
290 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
297 //--------------------------------------------------------------------------
298 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
299 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
300 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
301 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
304 ComponentDescription desc;
306 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
309 // get the ComponentDescription of the input Component
310 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
314 // check if the Component's ComponentDescription matches the input ComponentDescription
315 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
318 //--------------------------------------------------------------------------
319 // determine if 2 ComponentDescriptions are basically equal
320 // (by that, I mean that the important identifying values are compared,
321 // but not the ComponentDescription flags)
322 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
324 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
327 //--------------------------------------------------------------------------
328 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
329 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
331 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
334 //--------------------------------------------------------------------------
335 // determine if a ComponentDescription basically matches that of a particular Component
336 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
338 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
341 //--------------------------------------------------------------------------
342 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
343 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
345 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
349 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
350 : Plugin (engine, session)
352 , unit (new CAAudioUnit)
353 , initialized (false)
354 , _current_block_size (0)
355 , _requires_fixed_size_buffers (false)
359 , current_buffers (0)
360 , frames_processed (0)
361 , last_transport_rolling (false)
362 , last_transport_speed (0.0)
364 if (!preset_search_path_initialized) {
365 Glib::ustring p = Glib::get_home_dir();
366 p += "/Library/Audio/Presets:";
367 p += preset_search_path;
368 preset_search_path = p;
369 preset_search_path_initialized = true;
375 AUPlugin::AUPlugin (const AUPlugin& other)
377 , comp (other.get_comp())
378 , unit (new CAAudioUnit)
379 , initialized (false)
380 , _current_block_size (0)
382 , _requires_fixed_size_buffers (false)
386 , current_buffers (0)
387 , frames_processed (0)
393 AUPlugin::~AUPlugin ()
396 TRACE_API ("about to call uninitialize in plugin destructor\n");
397 unit->Uninitialize ();
406 AUPlugin::discover_factory_presets ()
409 UInt32 dataSize = sizeof (presets);
412 TRACE_API ("get property FactoryPresets in global scope\n");
413 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
414 cerr << "cannot get factory preset info: " << err << endl;
422 CFIndex cnt = CFArrayGetCount (presets);
424 for (CFIndex i = 0; i < cnt; ++i) {
425 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
427 string name = CFStringRefToStdString (preset->presetName);
428 factory_preset_map[name] = preset->presetNumber;
440 TRACE_API ("opening AudioUnit\n");
441 err = CAAudioUnit::Open (*(comp.get()), *unit);
443 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
444 throw failed_constructor();
448 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
449 throw failed_constructor ();
452 TRACE_API ("count global elements\n");
453 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
454 TRACE_API ("count input elements\n");
455 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
456 TRACE_API ("count output elements\n");
457 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
459 if (input_elements > 0) {
460 AURenderCallbackStruct renderCallbackInfo;
462 renderCallbackInfo.inputProc = _render_callback;
463 renderCallbackInfo.inputProcRefCon = this;
465 TRACE_API ("set render callback in input scope\n");
466 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
467 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
468 cerr << "cannot install render callback (err = " << err << ')' << endl;
469 throw failed_constructor();
473 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
475 HostCallbackInfo info;
476 memset (&info, 0, sizeof (HostCallbackInfo));
477 info.hostUserData = this;
478 info.beatAndTempoProc = _get_beat_and_tempo_callback;
479 info.musicalTimeLocationProc = _get_musical_time_location_callback;
480 info.transportStateProc = _get_transport_state_callback;
482 //ignore result of this - don't care if the property isn't supported
483 TRACE_API ("set host callbacks in global scope\n");
484 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
485 kAudioUnitScope_Global,
488 sizeof (HostCallbackInfo));
490 /* these keep track of *configured* channel set up,
491 not potential set ups.
495 output_channels = -1;
497 if (set_block_size (_session.get_block_size())) {
498 error << _("AUPlugin: cannot set processing block size") << endmsg;
499 throw failed_constructor();
502 discover_parameters ();
503 discover_factory_presets ();
505 // Plugin::setup_controls ();
509 AUPlugin::discover_parameters ()
511 /* discover writable parameters */
513 AudioUnitScope scopes[] = {
514 kAudioUnitScope_Global,
515 kAudioUnitScope_Output,
516 kAudioUnitScope_Input
519 descriptors.clear ();
521 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
523 AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
525 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
527 AUParameterDescriptor d;
529 d.id = param_info.ParamID (i);
531 const CAAUParameter* param = param_info.GetParamInfo (d.id);
532 const AudioUnitParameterInfo& info (param->ParamInfo());
534 const int len = CFStringGetLength (param->GetName());;
535 char local_buffer[len*2];
536 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
540 d.label = local_buffer;
543 d.scope = param_info.GetScope ();
544 d.element = param_info.GetElement ();
546 /* info.units to consider */
548 kAudioUnitParameterUnit_Generic = 0
549 kAudioUnitParameterUnit_Indexed = 1
550 kAudioUnitParameterUnit_Boolean = 2
551 kAudioUnitParameterUnit_Percent = 3
552 kAudioUnitParameterUnit_Seconds = 4
553 kAudioUnitParameterUnit_SampleFrames = 5
554 kAudioUnitParameterUnit_Phase = 6
555 kAudioUnitParameterUnit_Rate = 7
556 kAudioUnitParameterUnit_Hertz = 8
557 kAudioUnitParameterUnit_Cents = 9
558 kAudioUnitParameterUnit_RelativeSemiTones = 10
559 kAudioUnitParameterUnit_MIDINoteNumber = 11
560 kAudioUnitParameterUnit_MIDIController = 12
561 kAudioUnitParameterUnit_Decibels = 13
562 kAudioUnitParameterUnit_LinearGain = 14
563 kAudioUnitParameterUnit_Degrees = 15
564 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
565 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
566 kAudioUnitParameterUnit_Pan = 18
567 kAudioUnitParameterUnit_Meters = 19
568 kAudioUnitParameterUnit_AbsoluteCents = 20
569 kAudioUnitParameterUnit_Octaves = 21
570 kAudioUnitParameterUnit_BPM = 22
571 kAudioUnitParameterUnit_Beats = 23
572 kAudioUnitParameterUnit_Milliseconds = 24
573 kAudioUnitParameterUnit_Ratio = 25
576 /* info.flags to consider */
580 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
581 kAudioUnitParameterFlag_HasClump = (1L << 20)
582 kAudioUnitParameterFlag_HasName = (1L << 21)
583 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
584 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
585 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
586 kAudioUnitParameterFlag_CanRamp = (1L << 25)
587 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
588 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
589 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
590 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
591 kAudioUnitParameterFlag_IsReadable = (1L << 30)
592 kAudioUnitParameterFlag_IsWritable = (1L << 31)
595 d.lower = info.minValue;
596 d.upper = info.maxValue;
597 d.default_value = info.defaultValue;
599 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
600 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
601 (d.integer_step && ((d.upper - d.lower) == 1.0));
602 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
603 d.automatable = !d.toggled &&
604 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
605 (info.flags & kAudioUnitParameterFlag_IsWritable);
607 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
613 d.min_unbound = 0; // lower is bound
614 d.max_unbound = 0; // upper is bound
616 descriptors.push_back (d);
623 four_ints_to_four_byte_literal (unsigned char n[4])
625 /* this is actually implementation dependent. sigh. this is what gcc
626 and quite a few others do.
628 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
632 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
634 if (isdigit (id[0])) {
638 /* ID format is xxxx-xxxx-xxxx
639 where x maybe \xNN or a printable character.
641 Split at the '-' and and process each part into an integer.
642 Then put it back together.
646 unsigned char nascent[4];
647 const char* cstr = id.c_str();
648 const char* estr = cstr + id.size();
659 while (*cstr && next_int < 4) {
663 if (estr - cstr < 3) {
665 /* too close to the end for \xNN parsing: treat as literal characters */
667 cerr << "Parse " << cstr << " as a literal \\" << endl;
674 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
678 memcpy (short_buf, &cstr[2], 2);
679 nascent[in] = strtol (short_buf, NULL, 16);
685 /* treat as literal characters */
686 cerr << "Parse " << cstr << " as a literal \\" << endl;
700 if (in && (in % 4 == 0)) {
701 /* nascent is ready */
702 n[next_int] = four_ints_to_four_byte_literal (nascent);
706 /* swallow space-hyphen-space */
720 s << n[0] << '-' << n[1] << '-' << n[2];
729 AUPlugin::unique_id () const
731 return AUPluginInfo::stringify_descriptor (comp->Desc());
735 AUPlugin::label () const
737 return _info->name.c_str();
741 AUPlugin::parameter_count () const
743 return descriptors.size();
747 AUPlugin::default_value (uint32_t port)
749 if (port < descriptors.size()) {
750 return descriptors[port].default_value;
757 AUPlugin::signal_latency () const
759 return unit->Latency() * _session.frame_rate();
763 AUPlugin::set_parameter (uint32_t which, float val)
765 if (which < descriptors.size()) {
766 const AUParameterDescriptor& d (descriptors[which]);
767 TRACE_API ("set parameter %d in scope %d element %d to %f\n", d.id, d.scope, d.element, val);
768 unit->SetParameter (d.id, d.scope, d.element, val);
770 /* tell the world what we did */
772 AudioUnitEvent theEvent;
774 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
775 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
776 theEvent.mArgument.mParameter.mParameterID = d.id;
777 theEvent.mArgument.mParameter.mScope = d.scope;
778 theEvent.mArgument.mParameter.mElement = d.element;
780 TRACE_API ("notify about parameter change\n");
781 AUEventListenerNotify (NULL, NULL, &theEvent);
786 AUPlugin::get_parameter (uint32_t which) const
789 if (which < descriptors.size()) {
790 const AUParameterDescriptor& d (descriptors[which]);
791 TRACE_API ("get value of parameter %d in scope %d element %d\n", d.id, d.scope, d.element);
792 unit->GetParameter(d.id, d.scope, d.element, val);
798 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
800 if (which < descriptors.size()) {
801 pd = descriptors[which];
808 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
810 if (which < descriptors.size()) {
819 AUPlugin::activate ()
823 TRACE_API ("call Initialize in activate()\n");
824 if ((err = unit->Initialize()) != noErr) {
825 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
827 frames_processed = 0;
834 AUPlugin::deactivate ()
836 TRACE_API ("call Uninitialize in deactivate()\n");
837 unit->Uninitialize ();
844 TRACE_API ("call Reset in flush()\n");
845 unit->GlobalReset ();
849 AUPlugin::requires_fixed_size_buffers() const
851 return _requires_fixed_size_buffers;
856 AUPlugin::set_block_size (nframes_t nframes)
858 bool was_initialized = initialized;
859 UInt32 numFrames = nframes;
866 TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
867 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
868 0, &numFrames, sizeof (numFrames))) != noErr) {
869 cerr << "cannot set max frames (err = " << err << ')' << endl;
873 if (was_initialized) {
877 _current_block_size = nframes;
883 AUPlugin::configure_io (ChanCount in, ChanCount out)
885 AudioStreamBasicDescription streamFormat;
886 bool was_initialized = initialized;
887 int32_t audio_in = in.n_audio();
888 int32_t audio_out = out.n_audio();
891 //if we are already running with the requested i/o config, bail out here
892 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
899 streamFormat.mSampleRate = _session.frame_rate();
900 streamFormat.mFormatID = kAudioFormatLinearPCM;
901 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
903 #ifdef __LITTLE_ENDIAN__
906 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
909 streamFormat.mBitsPerChannel = 32;
910 streamFormat.mFramesPerPacket = 1;
912 /* apple says that for non-interleaved data, these
913 values always refer to a single channel.
915 streamFormat.mBytesPerPacket = 4;
916 streamFormat.mBytesPerFrame = 4;
918 streamFormat.mChannelsPerFrame = audio_in;
920 if (set_input_format (streamFormat) != 0) {
924 streamFormat.mChannelsPerFrame = audio_out;
926 if (set_output_format (streamFormat) != 0) {
930 if (was_initialized) {
938 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
940 // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
941 // attempt to multiply-instantiate plugins to meet io configurations.
943 int32_t audio_in = in.n_audio();
945 int32_t plugcnt = -1;
946 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
948 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
950 if (debug_io_config) {
951 cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
954 //Ardour expects the plugin to tell it the output configuration
955 //but AU plugins can have multiple I/O configurations
956 //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
957 //so first lets see if there's a configuration that keeps out==in
959 audio_out = audio_in;
961 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
962 int32_t possible_in = i->first;
963 int32_t possible_out = i->second;
965 if (possible_in == audio_in && possible_out== audio_out) {
966 cerr << "\tCHOSEN: in " << in << " out " << out << endl;
971 /* now allow potentially "imprecise" matches */
973 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
975 int32_t possible_in = i->first;
976 int32_t possible_out = i->second;
978 if (debug_io_config) {
979 cerr << "\tin " << possible_in << " out " << possible_out << endl;
982 if (possible_out == 0) {
983 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
987 if (possible_in == 0) {
989 /* instrument plugin, always legal but throws away inputs ...
992 if (possible_out == -1) {
993 /* out much match in (UNLIKELY!!) */
994 audio_out = audio_in;
996 } else if (possible_out == -2) {
997 /* any configuration possible, pick matching */
998 audio_out = audio_in;
1000 } else if (possible_out < -2) {
1001 /* explicit variable number of outputs, pick maximum */
1002 audio_out = -possible_out;
1005 /* exact number of outputs */
1006 audio_out = possible_out;
1011 if (possible_in == -1) {
1013 /* wildcard for input */
1015 if (possible_out == -1) {
1016 /* out much match in */
1017 audio_out = audio_in;
1019 } else if (possible_out == -2) {
1020 /* any configuration possible, pick matching */
1021 audio_out = audio_in;
1023 } else if (possible_out < -2) {
1024 /* explicit variable number of outputs, pick maximum */
1025 audio_out = -possible_out;
1028 /* exact number of outputs */
1029 audio_out = possible_out;
1034 if (possible_in == -2) {
1036 if (possible_out == -1) {
1037 /* any configuration possible, pick matching */
1038 audio_out = audio_in;
1040 } else if (possible_out == -2) {
1041 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
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 < -2) {
1057 /* explicit variable number of inputs */
1059 if (audio_in > -possible_in) {
1060 /* request is too large */
1064 if (possible_out == -1) {
1065 /* out must match in */
1066 audio_out = audio_in;
1068 } else if (possible_out == -2) {
1069 error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
1072 } else if (possible_out < -2) {
1073 /* explicit variable number of outputs, pick maximum */
1074 audio_out = -possible_out;
1077 /* exact number of outputs */
1078 audio_out = possible_out;
1083 if (possible_in == audio_in) {
1085 /* exact number of inputs ... must match obviously */
1087 if (possible_out == -1) {
1088 /* out must match in */
1089 audio_out = audio_in;
1091 } else if (possible_out == -2) {
1092 /* any output configuration, pick matching */
1093 audio_out = audio_in;
1095 } else if (possible_out < -2) {
1096 /* explicit variable number of outputs, pick maximum */
1097 audio_out = -possible_out;
1100 /* exact number of outputs */
1101 audio_out = possible_out;
1112 if (debug_io_config) {
1114 cerr << "\tCHOSEN: in " << in << " out " << out << " plugcnt will be " << plugcnt << endl;
1116 cerr << "\tFAIL: no configs match requested in " << in << endl;
1120 out.set (DataType::MIDI, 0);
1121 out.set (DataType::AUDIO, audio_out);
1127 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1129 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1133 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1135 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1144 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1145 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1147 Glib::Mutex::Lock em (_session.engine().process_lock());
1148 IO::PortCountChanged (ChanCount(DataType::AUDIO, fmt.mChannelsPerFrame));
1154 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1158 for (uint32_t i = 0; i < cnt; ++i) {
1159 TRACE_API ("set stream format for %s, scope = %d element %d\n",
1160 (scope == kAudioUnitScope_Input ? "input" : "output"),
1162 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1163 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1164 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1169 if (scope == kAudioUnitScope_Input) {
1170 input_channels = fmt.mChannelsPerFrame;
1172 output_channels = fmt.mChannelsPerFrame;
1179 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1180 const AudioTimeStamp*,
1182 UInt32 inNumberFrames,
1183 AudioBufferList* ioData)
1185 /* not much to do - the data is already in the buffers given to us in connect_and_run() */
1187 if (current_maxbuf == 0) {
1188 error << _("AUPlugin: render callback called illegally!") << endmsg;
1189 return kAudioUnitErr_CannotDoInCurrentContext;
1191 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
1193 for (uint32_t i = 0; i < limit; ++i) {
1194 ioData->mBuffers[i].mNumberChannels = 1;
1195 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1197 /* we don't use the channel mapping because audiounits are
1198 never replicated. one plugin instance uses all channels/buffers
1199 passed to PluginInsert::connect_and_run()
1202 ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
1205 cb_offset += inNumberFrames;
1211 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping, ChanMapping, nframes_t nframes, nframes_t offset)
1213 AudioUnitRenderActionFlags flags = 0;
1216 uint32_t maxbuf = bufs.count().n_audio();
1218 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1219 unit->GlobalReset();
1220 _last_nframes = nframes;
1223 current_buffers = &bufs;
1224 current_maxbuf = maxbuf;
1225 current_offset = offset;
1228 buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
1230 for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
1231 buffers->mBuffers[i].mNumberChannels = 1;
1232 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1233 buffers->mBuffers[i].mData = 0;
1236 ts.mSampleTime = frames_processed;
1237 ts.mFlags = kAudioTimeStampSampleTimeValid;
1239 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1242 frames_processed += nframes;
1244 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1247 for (i = 0; i < limit; ++i) {
1248 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1249 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1250 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1251 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1255 /* now silence any buffers that were passed in but the that the plugin
1256 did not fill/touch/use.
1259 for (;i < maxbuf; ++i) {
1260 Sample* buffer_address= bufs.get_audio (i).data (offset);
1261 memset (buffer_address, 0, nframes * sizeof (Sample));
1267 cerr << name() << " render status " << err << endl;
1272 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1273 Float64* outCurrentTempo)
1275 TempoMap& tmap (_session.tempo_map());
1277 TRACE_API ("AU calls ardour beat&tempo callback\n");
1279 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1280 (and interpretation) of a beat position will be incorrect. So refuse to
1284 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1285 return kAudioUnitErr_CannotDoInCurrentContext;
1289 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1290 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1292 if (outCurrentBeat) {
1294 beat = metric.meter().beats_per_bar() * bbt.bars;
1296 beat += bbt.ticks / Meter::ticks_per_beat;
1297 *outCurrentBeat = beat;
1300 if (outCurrentTempo) {
1301 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1309 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1310 Float32* outTimeSig_Numerator,
1311 UInt32* outTimeSig_Denominator,
1312 Float64* outCurrentMeasureDownBeat)
1314 TempoMap& tmap (_session.tempo_map());
1316 TRACE_API ("AU calls ardour music time location callback\n");
1318 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1319 (and interpretation) of a beat position will be incorrect. So refuse to
1323 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1324 return kAudioUnitErr_CannotDoInCurrentContext;
1328 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1329 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1331 if (outDeltaSampleOffsetToNextBeat) {
1332 if (bbt.ticks == 0) {
1334 *outDeltaSampleOffsetToNextBeat = 0;
1336 *outDeltaSampleOffsetToNextBeat = (UInt32) floor (((Meter::ticks_per_beat - bbt.ticks)/Meter::ticks_per_beat) * // fraction of a beat to next beat
1337 metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1341 if (outTimeSig_Numerator) {
1342 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1344 if (outTimeSig_Denominator) {
1345 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1348 if (outCurrentMeasureDownBeat) {
1350 /* beat for the start of the bar.
1352 2|1|0 -> 1 + beats_per_bar
1353 3|1|0 -> 1 + (2 * beats_per_bar)
1357 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1364 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1365 Boolean* outTransportStateChanged,
1366 Float64* outCurrentSampleInTimeLine,
1367 Boolean* outIsCycling,
1368 Float64* outCycleStartBeat,
1369 Float64* outCycleEndBeat)
1374 TRACE_API ("AU calls ardour transport state callback\n");
1376 rolling = _session.transport_rolling();
1377 speed = _session.transport_speed ();
1380 *outIsPlaying = _session.transport_rolling();
1383 if (outTransportStateChanged) {
1384 if (rolling != last_transport_rolling) {
1385 *outTransportStateChanged = true;
1386 } else if (speed != last_transport_speed) {
1387 *outTransportStateChanged = true;
1389 *outTransportStateChanged = false;
1393 if (outCurrentSampleInTimeLine) {
1394 /* this assumes that the AU can only call this host callback from render context,
1395 where current_offset is valid.
1397 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1401 Location* loc = _session.locations()->auto_loop_location();
1403 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1405 if (*outIsCycling) {
1407 if (outCycleStartBeat || outCycleEndBeat) {
1409 TempoMap& tmap (_session.tempo_map());
1411 /* more than 1 meter means that a simplistic computation (and interpretation) of
1412 a beat position will be incorrect. so refuse to offer the value.
1415 if (tmap.n_meters() > 1) {
1416 return kAudioUnitErr_CannotDoInCurrentContext;
1421 if (outCycleStartBeat) {
1422 TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
1423 _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1426 beat = metric.meter().beats_per_bar() * bbt.bars;
1428 beat += bbt.ticks / Meter::ticks_per_beat;
1430 *outCycleStartBeat = beat;
1433 if (outCycleEndBeat) {
1434 TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
1435 _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1438 beat = metric.meter().beats_per_bar() * bbt.bars;
1440 beat += bbt.ticks / Meter::ticks_per_beat;
1442 *outCycleEndBeat = beat;
1448 last_transport_rolling = rolling;
1449 last_transport_speed = speed;
1454 set<Evoral::Parameter>
1455 AUPlugin::automatable() const
1457 set<Evoral::Parameter> automates;
1459 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1460 if (descriptors[i].automatable) {
1461 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1469 AUPlugin::describe_parameter (Evoral::Parameter param)
1471 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1472 return descriptors[param.id()].label;
1479 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1481 // NameValue stuff here
1485 AUPlugin::parameter_is_audio (uint32_t) const
1491 AUPlugin::parameter_is_control (uint32_t) const
1497 AUPlugin::parameter_is_input (uint32_t) const
1503 AUPlugin::parameter_is_output (uint32_t) const
1509 AUPlugin::get_state()
1511 LocaleGuard lg (X_("POSIX"));
1512 XMLNode *root = new XMLNode (state_node_name());
1514 #ifdef AU_STATE_SUPPORT
1516 CFPropertyListRef propertyList;
1518 TRACE_API ("get preset state\n");
1519 if (unit->GetAUPreset (propertyList) != noErr) {
1523 // Convert the property list into XML data.
1525 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1528 error << _("Could not create XML version of property list") << endmsg;
1532 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1533 our state node. GACK!
1538 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1540 root->add_child_copy (*t.root());
1544 CFRelease (xmlData);
1545 CFRelease (propertyList);
1547 if (!seen_get_state_message) {
1548 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1551 seen_get_state_message = true;
1559 AUPlugin::set_state(const XMLNode& node, int /* version*/)
1561 #ifdef AU_STATE_SUPPORT
1563 CFPropertyListRef propertyList;
1564 LocaleGuard lg (X_("POSIX"));
1566 if (node.name() != state_node_name()) {
1567 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1571 if (node.children().empty()) {
1575 XMLNode* top = node.children().front();
1576 XMLNode* copy = new XMLNode (*top);
1581 const string& xml = t.write_buffer ();
1582 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1583 CFStringRef errorString;
1585 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1587 kCFPropertyListImmutable,
1590 CFRelease (xmlData);
1593 TRACE_API ("set preset\n");
1594 if (unit->SetAUPreset (propertyList) == noErr) {
1597 /* tell the world */
1599 AudioUnitParameter changedUnit;
1600 changedUnit.mAudioUnit = unit->AU();
1601 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1602 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1604 CFRelease (propertyList);
1609 if (!seen_set_state_message) {
1610 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1619 AUPlugin::load_preset (const string& preset_label)
1621 #ifdef AU_STATE_SUPPORT
1623 CFPropertyListRef propertyList;
1625 UserPresetMap::iterator ux;
1626 FactoryPresetMap::iterator fx;
1628 /* look first in "user" presets */
1630 if ((ux = user_preset_map.find (preset_label)) != user_preset_map.end()) {
1632 if ((propertyList = load_property_list (ux->second)) != 0) {
1633 TRACE_API ("set preset from user presets\n");
1634 if (unit->SetAUPreset (propertyList) == noErr) {
1637 /* tell the world */
1639 AudioUnitParameter changedUnit;
1640 changedUnit.mAudioUnit = unit->AU();
1641 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1642 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1644 CFRelease(propertyList);
1647 } else if ((fx = factory_preset_map.find (preset_label)) != factory_preset_map.end()) {
1651 preset.presetNumber = fx->second;
1652 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1654 TRACE_API ("set preset from factory presets\n");
1656 if (unit->SetPresentPreset (preset) == 0) {
1659 /* tell the world */
1661 AudioUnitParameter changedUnit;
1662 changedUnit.mAudioUnit = unit->AU();
1663 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1664 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1670 if (!seen_loading_message) {
1671 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1674 seen_loading_message = true;
1681 AUPlugin::save_preset (string preset_name)
1683 #ifdef AU_STATE_SUPPORT
1684 CFPropertyListRef propertyList;
1685 vector<Glib::ustring> v;
1686 Glib::ustring user_preset_path;
1689 std::string m = maker();
1690 std::string n = name();
1692 strip_whitespace_edges (m);
1693 strip_whitespace_edges (n);
1695 v.push_back (Glib::get_home_dir());
1696 v.push_back ("Library");
1697 v.push_back ("Audio");
1698 v.push_back ("Presets");
1702 user_preset_path = Glib::build_filename (v);
1704 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1705 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1709 TRACE_API ("get current preset\n");
1710 if (unit->GetAUPreset (propertyList) != noErr) {
1714 // add the actual preset name */
1716 v.push_back (preset_name + preset_suffix);
1720 user_preset_path = Glib::build_filename (v);
1722 set_preset_name_in_plist (propertyList, preset_name);
1724 if (save_property_list (propertyList, user_preset_path)) {
1725 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1729 CFRelease(propertyList);
1733 if (!seen_saving_message) {
1734 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1737 seen_saving_message = true;
1743 //-----------------------------------------------------------------------------
1744 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1746 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1748 CFNumberRef cfNumber;
1749 SInt32 numberValue = 0;
1750 Boolean dummySuccess;
1752 if (outSuccess == NULL)
1753 outSuccess = &dummySuccess;
1754 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1756 *outSuccess = FALSE;
1760 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1761 if (cfNumber == NULL)
1763 *outSuccess = FALSE;
1766 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1774 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1776 CFDictionaryRef auStateDictionary;
1777 ComponentDescription tempDesc = {0,0,0,0,0};
1778 SInt32 versionValue;
1781 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1784 // the property list for AU state data must be of the dictionary type
1785 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1786 return kAudioUnitErr_InvalidPropertyValue;
1789 auStateDictionary = (CFDictionaryRef)inAUStateData;
1791 // first check to make sure that the version of the AU state data is one that we know understand
1792 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1793 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1796 return kAudioUnitErr_InvalidPropertyValue;
1798 #define kCurrentSavedStateVersion 0
1799 if (versionValue != kCurrentSavedStateVersion) {
1800 return kAudioUnitErr_InvalidPropertyValue;
1803 // grab the ComponentDescription values from the AU state data
1804 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1805 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1806 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1807 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1808 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1809 return kAudioUnitErr_InvalidPropertyValue;
1811 *outComponentDescription = tempDesc;
1816 static bool au_preset_filter (const string& str, void* arg)
1818 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1822 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1826 /* check the preset file path name against this plugin
1827 ID. The idea is that all preset files for this plugin
1828 include "<manufacturer>/<plugin-name>" in their path.
1831 Plugin* p = (Plugin *) arg;
1832 string match = p->maker();
1836 ret = str.find (match) != string::npos;
1839 string m = p->maker ();
1840 string n = p->name ();
1841 strip_whitespace_edges (m);
1842 strip_whitespace_edges (n);
1847 ret = str.find (match) != string::npos;
1855 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1858 CFPropertyListRef plist;
1859 ComponentDescription presetDesc;
1862 plist = load_property_list (pathstr);
1868 // get the ComponentDescription from the AU preset file
1870 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1872 if (status == noErr) {
1873 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1875 /* try to get the preset name from the property list */
1877 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1879 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1883 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1886 char buf[PATH_MAX+1];
1888 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
1903 AUPlugin::current_preset() const
1907 #ifdef AU_STATE_SUPPORT
1908 CFPropertyListRef propertyList;
1910 TRACE_API ("get current preset for current_preset()\n");
1911 if (unit->GetAUPreset (propertyList) == noErr) {
1912 preset_name = get_preset_name_in_plist (propertyList);
1913 CFRelease(propertyList);
1919 vector<Plugin::PresetRecord>
1920 AUPlugin::get_presets ()
1922 vector<Plugin::PresetRecord> presets;
1924 #ifdef AU_STATE_SUPPORT
1925 vector<string*>* preset_files;
1926 PathScanner scanner;
1928 user_preset_map.clear ();
1930 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
1932 if (!preset_files) {
1936 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
1938 string path = *(*x);
1941 /* make an initial guess at the preset name using the path */
1943 preset_name = Glib::path_get_basename (path);
1944 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
1946 /* check that this preset file really matches this plugin
1947 and potentially get the "real" preset name from
1951 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
1952 user_preset_map[preset_name] = path;
1958 delete preset_files;
1960 /* now fill the vector<string> with the names we have */
1962 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
1963 presets.push_back (Plugin::PresetRecord (i->second, i->first));
1966 /* add factory presets */
1968 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
1969 presets.push_back (Plugin::PresetRecord ("", i->first));
1978 AUPlugin::has_editor () const
1980 // even if the plugin doesn't have its own editor, the AU API can be used
1981 // to create one that looks native.
1985 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
1988 type = ARDOUR::AudioUnit;
1991 AUPluginInfo::~AUPluginInfo ()
1993 type = ARDOUR::AudioUnit;
1997 AUPluginInfo::load (Session& session)
2002 TRACE_API ("load AU as a component\n");
2003 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2005 if (!comp->IsValid()) {
2006 error << ("AudioUnit: not a valid Component") << endmsg;
2008 plugin.reset (new AUPlugin (session.engine(), session, comp));
2011 AUPluginInfo *aup = new AUPluginInfo (*this);
2012 plugin->set_info (PluginInfoPtr (aup));
2013 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2017 catch (failed_constructor &err) {
2018 return PluginPtr ();
2023 AUPluginInfo::au_cache_path ()
2025 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2029 AUPluginInfo::discover ()
2033 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2034 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2037 PluginInfoList* plugs = new PluginInfoList;
2039 discover_fx (*plugs);
2040 discover_music (*plugs);
2041 discover_generators (*plugs);
2047 AUPluginInfo::discover_music (PluginInfoList& plugs)
2049 CAComponentDescription desc;
2050 desc.componentFlags = 0;
2051 desc.componentFlagsMask = 0;
2052 desc.componentSubType = 0;
2053 desc.componentManufacturer = 0;
2054 desc.componentType = kAudioUnitType_MusicEffect;
2056 discover_by_description (plugs, desc);
2060 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2062 CAComponentDescription desc;
2063 desc.componentFlags = 0;
2064 desc.componentFlagsMask = 0;
2065 desc.componentSubType = 0;
2066 desc.componentManufacturer = 0;
2067 desc.componentType = kAudioUnitType_Effect;
2069 discover_by_description (plugs, desc);
2073 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2075 CAComponentDescription desc;
2076 desc.componentFlags = 0;
2077 desc.componentFlagsMask = 0;
2078 desc.componentSubType = 0;
2079 desc.componentManufacturer = 0;
2080 desc.componentType = kAudioUnitType_Generator;
2082 discover_by_description (plugs, desc);
2086 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2090 comp = FindNextComponent (NULL, &desc);
2092 while (comp != NULL) {
2093 CAComponentDescription temp;
2094 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2096 AUPluginInfoPtr info (new AUPluginInfo
2097 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2099 /* although apple designed the subtype field to be a "category" indicator,
2100 its really turned into a plugin ID field for a given manufacturer. Hence
2101 there are no categories for AudioUnits. However, to keep the plugins
2102 showing up under "categories", we'll use the "type" as a high level
2105 NOTE: no panners, format converters or i/o AU's for our purposes
2108 switch (info->descriptor->Type()) {
2109 case kAudioUnitType_Panner:
2110 case kAudioUnitType_OfflineEffect:
2111 case kAudioUnitType_FormatConverter:
2114 case kAudioUnitType_Output:
2115 info->category = _("AudioUnit Outputs");
2117 case kAudioUnitType_MusicDevice:
2118 info->category = _("AudioUnit Instruments");
2120 case kAudioUnitType_MusicEffect:
2121 info->category = _("AudioUnit MusicEffects");
2123 case kAudioUnitType_Effect:
2124 info->category = _("AudioUnit Effects");
2126 case kAudioUnitType_Mixer:
2127 info->category = _("AudioUnit Mixers");
2129 case kAudioUnitType_Generator:
2130 info->category = _("AudioUnit Generators");
2133 info->category = _("AudioUnit (Unknown)");
2137 AUPluginInfo::get_names (temp, info->name, info->creator);
2139 info->type = ARDOUR::AudioUnit;
2140 info->unique_id = stringify_descriptor (*info->descriptor);
2142 /* XXX not sure of the best way to handle plugin versioning yet
2145 CAComponent cacomp (*info->descriptor);
2147 if (cacomp.GetResourceVersion (info->version) != noErr) {
2151 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2153 /* here we have to map apple's wildcard system to a simple pair
2154 of values. in ::can_do() we use the whole system, but here
2155 we need a single pair of values. XXX probably means we should
2156 remove any use of these values.
2159 info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
2160 info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
2162 cerr << "detected AU: " << info->name.c_str() << " (" << info->cache.io_configs.size() << " i/o configurations) - " << info->unique_id << endl;
2164 plugs.push_back (info);
2167 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2170 comp = FindNextComponent (comp, &desc);
2175 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2178 AUPluginCachedInfo& cinfo,
2179 const std::string& name)
2184 /* concatenate unique ID with version to provide a key for cached info lookup.
2185 this ensures we don't get stale information, or should if plugin developers
2186 follow Apple "guidelines".
2189 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2194 CachedInfoMap::iterator cim = cached_info.find (id);
2196 if (cim != cached_info.end()) {
2197 cinfo = cim->second;
2202 AUChannelInfo* channel_info;
2206 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2210 if (CAAudioUnit::Open (comp, unit) != noErr) {
2216 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2217 cerr << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endl;
2222 TRACE_API ("get AU channel info\n");
2223 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2228 /* no explicit info available */
2230 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2234 /* store each configuration */
2236 for (uint32_t n = 0; n < cnt; ++n) {
2237 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2238 channel_info[n].outChannels));
2241 free (channel_info);
2244 add_cached_info (id, cinfo);
2245 save_cached_info ();
2251 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2253 cached_info[id] = cinfo;
2256 #define AU_CACHE_VERSION "2.0"
2259 AUPluginInfo::save_cached_info ()
2263 node = new XMLNode (X_("AudioUnitPluginCache"));
2264 node->add_property( "version", AU_CACHE_VERSION );
2266 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2267 XMLNode* parent = new XMLNode (X_("plugin"));
2268 parent->add_property ("id", i->first);
2269 node->add_child_nocopy (*parent);
2271 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2273 XMLNode* child = new XMLNode (X_("io"));
2276 snprintf (buf, sizeof (buf), "%d", j->first);
2277 child->add_property (X_("in"), buf);
2278 snprintf (buf, sizeof (buf), "%d", j->second);
2279 child->add_property (X_("out"), buf);
2280 parent->add_child_nocopy (*child);
2285 Glib::ustring path = au_cache_path ();
2288 tree.set_root (node);
2290 if (!tree.write (path)) {
2291 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2292 unlink (path.c_str());
2297 AUPluginInfo::load_cached_info ()
2299 Glib::ustring path = au_cache_path ();
2302 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2306 if ( !tree.read (path) ) {
2307 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2311 const XMLNode* root (tree.root());
2313 if (root->name() != X_("AudioUnitPluginCache")) {
2317 //initial version has incorrectly stored i/o info, and/or garbage chars.
2318 const XMLProperty* version = root->property(X_("version"));
2319 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2320 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2324 cached_info.clear ();
2326 const XMLNodeList children = root->children();
2328 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2330 const XMLNode* child = *iter;
2332 if (child->name() == X_("plugin")) {
2334 const XMLNode* gchild;
2335 const XMLNodeList gchildren = child->children();
2336 const XMLProperty* prop = child->property (X_("id"));
2342 string id = prop->value();
2346 string::size_type slash = id.find_last_of ('/');
2348 if (slash == string::npos) {
2352 version = id.substr (slash);
2353 id = id.substr (0, slash);
2354 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2356 if (fixed.empty()) {
2357 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2364 AUPluginCachedInfo cinfo;
2366 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2370 if (gchild->name() == X_("io")) {
2374 const XMLProperty* iprop;
2375 const XMLProperty* oprop;
2377 if (((iprop = gchild->property (X_("in"))) != 0) &&
2378 ((oprop = gchild->property (X_("out"))) != 0)) {
2379 in = atoi (iprop->value());
2380 out = atoi (oprop->value());
2382 cinfo.io_configs.push_back (pair<int,int> (in, out));
2387 if (cinfo.io_configs.size()) {
2388 add_cached_info (id, cinfo);
2397 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2399 CFStringRef itemName = NULL;
2401 // Marc Poirier-style item name
2402 CAComponent auComponent (comp_desc);
2403 if (auComponent.IsValid()) {
2404 CAComponentDescription dummydesc;
2405 Handle nameHandle = NewHandle(sizeof(void*));
2406 if (nameHandle != NULL) {
2407 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2409 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2410 if (nameString != NULL) {
2411 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2414 DisposeHandle(nameHandle);
2418 // if Marc-style fails, do the original way
2419 if (itemName == NULL) {
2420 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2421 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2422 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2424 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2425 compTypeString, compManufacturerString, compSubTypeString);
2427 if (compTypeString != NULL)
2428 CFRelease(compTypeString);
2429 if (compSubTypeString != NULL)
2430 CFRelease(compSubTypeString);
2431 if (compManufacturerString != NULL)
2432 CFRelease(compManufacturerString);
2435 string str = CFStringRefToStdString(itemName);
2436 string::size_type colon = str.find (':');
2439 name = str.substr (colon+1);
2440 maker = str.substr (0, colon);
2441 strip_whitespace_edges (maker);
2442 strip_whitespace_edges (name);
2446 strip_whitespace_edges (name);
2451 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2455 /* note: OSType is a compiler-implemenation-defined value,
2456 historically a 32 bit integer created with a multi-character
2457 constant such as 'abcd'. It is, fundamentally, an abomination.
2462 s << desc.SubType();