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 if (_has_midi_input) {
1310 for (uint32_t i = 0; i < bufs.count().n_midi(); ++i) {
1312 /* one MIDI port/buffer only */
1314 MidiBuffer& m = bufs.get_midi (i);
1316 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1317 Evoral::MIDIEvent<framepos_t> ev (*i);
1319 if (ev.is_channel_event()) {
1320 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n",
1322 unit->MIDIEvent (ev.type() << 8 | ev.channel(),
1328 /* XXX need to handle sysex and other message types */
1333 ts.mSampleTime = frames_processed;
1334 ts.mFlags = kAudioTimeStampSampleTimeValid;
1336 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1339 frames_processed += nframes;
1341 uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
1344 for (i = 0; i < limit; ++i) {
1345 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1346 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1347 // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
1348 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1352 /* now silence any buffers that were passed in but the that the plugin
1353 did not fill/touch/use.
1356 for (;i < maxbuf; ++i) {
1357 Sample* buffer_address= bufs.get_audio (i).data (offset);
1358 memset (buffer_address, 0, nframes * sizeof (Sample));
1364 cerr << name() << " render status " << err << endl;
1369 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1370 Float64* outCurrentTempo)
1372 TempoMap& tmap (_session.tempo_map());
1374 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1376 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1377 (and interpretation) of a beat position will be incorrect. So refuse to
1381 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1382 return kAudioUnitErr_CannotDoInCurrentContext;
1385 Timecode::BBT_Time bbt;
1386 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1387 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1389 if (outCurrentBeat) {
1391 beat = metric.meter().beats_per_bar() * bbt.bars;
1393 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1394 *outCurrentBeat = beat;
1397 if (outCurrentTempo) {
1398 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1406 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1407 Float32* outTimeSig_Numerator,
1408 UInt32* outTimeSig_Denominator,
1409 Float64* outCurrentMeasureDownBeat)
1411 TempoMap& tmap (_session.tempo_map());
1413 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1415 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1416 (and interpretation) of a beat position will be incorrect. So refuse to
1420 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1421 return kAudioUnitErr_CannotDoInCurrentContext;
1424 Timecode::BBT_Time bbt;
1425 TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
1426 tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
1428 if (outDeltaSampleOffsetToNextBeat) {
1429 if (bbt.ticks == 0) {
1431 *outDeltaSampleOffsetToNextBeat = 0;
1433 *outDeltaSampleOffsetToNextBeat = (UInt32)
1434 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1435 metric.tempo().frames_per_beat(_session.frame_rate(), metric.meter())); // frames per beat
1439 if (outTimeSig_Numerator) {
1440 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
1442 if (outTimeSig_Denominator) {
1443 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1446 if (outCurrentMeasureDownBeat) {
1448 /* beat for the start of the bar.
1450 2|1|0 -> 1 + beats_per_bar
1451 3|1|0 -> 1 + (2 * beats_per_bar)
1455 *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
1462 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1463 Boolean* outTransportStateChanged,
1464 Float64* outCurrentSampleInTimeLine,
1465 Boolean* outIsCycling,
1466 Float64* outCycleStartBeat,
1467 Float64* outCycleEndBeat)
1472 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1474 rolling = _session.transport_rolling();
1475 speed = _session.transport_speed ();
1478 *outIsPlaying = _session.transport_rolling();
1481 if (outTransportStateChanged) {
1482 if (rolling != last_transport_rolling) {
1483 *outTransportStateChanged = true;
1484 } else if (speed != last_transport_speed) {
1485 *outTransportStateChanged = true;
1487 *outTransportStateChanged = false;
1491 if (outCurrentSampleInTimeLine) {
1492 /* this assumes that the AU can only call this host callback from render context,
1493 where current_offset is valid.
1495 *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
1499 Location* loc = _session.locations()->auto_loop_location();
1501 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1503 if (*outIsCycling) {
1505 if (outCycleStartBeat || outCycleEndBeat) {
1507 TempoMap& tmap (_session.tempo_map());
1509 /* more than 1 meter means that a simplistic computation (and interpretation) of
1510 a beat position will be incorrect. so refuse to offer the value.
1513 if (tmap.n_meters() > 1) {
1514 return kAudioUnitErr_CannotDoInCurrentContext;
1517 Timecode::BBT_Time bbt;
1519 if (outCycleStartBeat) {
1520 TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
1521 _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
1524 beat = metric.meter().beats_per_bar() * bbt.bars;
1526 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1528 *outCycleStartBeat = beat;
1531 if (outCycleEndBeat) {
1532 TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
1533 _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
1536 beat = metric.meter().beats_per_bar() * bbt.bars;
1538 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1540 *outCycleEndBeat = beat;
1546 last_transport_rolling = rolling;
1547 last_transport_speed = speed;
1552 set<Evoral::Parameter>
1553 AUPlugin::automatable() const
1555 set<Evoral::Parameter> automates;
1557 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1558 if (descriptors[i].automatable) {
1559 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1567 AUPlugin::describe_parameter (Evoral::Parameter param)
1569 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1570 return descriptors[param.id()].label;
1577 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1579 // NameValue stuff here
1583 AUPlugin::parameter_is_audio (uint32_t) const
1589 AUPlugin::parameter_is_control (uint32_t) const
1595 AUPlugin::parameter_is_input (uint32_t) const
1601 AUPlugin::parameter_is_output (uint32_t) const
1607 AUPlugin::add_state (XMLNode* root) const
1609 LocaleGuard lg (X_("POSIX"));
1611 #ifdef AU_STATE_SUPPORT
1613 CFPropertyListRef propertyList;
1615 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1616 if (unit->GetAUPreset (propertyList) != noErr) {
1620 // Convert the property list into XML data.
1622 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1625 error << _("Could not create XML version of property list") << endmsg;
1629 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1630 our state node. GACK!
1635 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1637 root->add_child_copy (*t.root());
1641 CFRelease (xmlData);
1642 CFRelease (propertyList);
1644 if (!seen_get_state_message) {
1645 info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1648 seen_get_state_message = true;
1654 AUPlugin::set_state(const XMLNode& node, int version)
1656 #ifdef AU_STATE_SUPPORT
1658 CFPropertyListRef propertyList;
1659 LocaleGuard lg (X_("POSIX"));
1661 if (node.name() != state_node_name()) {
1662 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1666 if (node.children().empty()) {
1670 XMLNode* top = node.children().front();
1671 XMLNode* copy = new XMLNode (*top);
1676 const string& xml = t.write_buffer ();
1677 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1678 CFStringRef errorString;
1680 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1682 kCFPropertyListImmutable,
1685 CFRelease (xmlData);
1688 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1689 if (unit->SetAUPreset (propertyList) == noErr) {
1692 /* tell the world */
1694 AudioUnitParameter changedUnit;
1695 changedUnit.mAudioUnit = unit->AU();
1696 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1697 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1699 CFRelease (propertyList);
1702 Plugin::set_state (node, version);
1705 if (!seen_set_state_message) {
1706 info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
1710 return Plugin::set_state (node, version);
1715 AUPlugin::load_preset (PresetRecord r)
1717 Plugin::load_preset (r);
1719 #ifdef AU_STATE_SUPPORT
1721 CFPropertyListRef propertyList;
1723 UserPresetMap::iterator ux;
1724 FactoryPresetMap::iterator fx;
1726 /* look first in "user" presets */
1728 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1730 if ((propertyList = load_property_list (ux->second)) != 0) {
1731 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1732 if (unit->SetAUPreset (propertyList) == noErr) {
1735 /* tell the world */
1737 AudioUnitParameter changedUnit;
1738 changedUnit.mAudioUnit = unit->AU();
1739 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1740 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1742 CFRelease(propertyList);
1745 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1749 preset.presetNumber = fx->second;
1750 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1752 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1754 if (unit->SetPresentPreset (preset) == 0) {
1757 /* tell the world */
1759 AudioUnitParameter changedUnit;
1760 changedUnit.mAudioUnit = unit->AU();
1761 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1762 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1768 if (!seen_loading_message) {
1769 info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1772 seen_loading_message = true;
1779 AUPlugin::do_remove_preset (std::string)
1784 AUPlugin::do_save_preset (string preset_name)
1786 #ifdef AU_STATE_SUPPORT
1787 CFPropertyListRef propertyList;
1788 vector<Glib::ustring> v;
1789 Glib::ustring user_preset_path;
1792 std::string m = maker();
1793 std::string n = name();
1795 strip_whitespace_edges (m);
1796 strip_whitespace_edges (n);
1798 v.push_back (Glib::get_home_dir());
1799 v.push_back ("Library");
1800 v.push_back ("Audio");
1801 v.push_back ("Presets");
1805 user_preset_path = Glib::build_filename (v);
1807 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1808 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1812 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1813 if (unit->GetAUPreset (propertyList) != noErr) {
1817 // add the actual preset name */
1819 v.push_back (preset_name + preset_suffix);
1823 user_preset_path = Glib::build_filename (v);
1825 set_preset_name_in_plist (propertyList, preset_name);
1827 if (save_property_list (propertyList, user_preset_path)) {
1828 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1832 CFRelease(propertyList);
1834 return string ("file:///") + user_preset_path;
1836 if (!seen_saving_message) {
1837 info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
1840 seen_saving_message = true;
1846 //-----------------------------------------------------------------------------
1847 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1849 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1851 CFNumberRef cfNumber;
1852 SInt32 numberValue = 0;
1853 Boolean dummySuccess;
1855 if (outSuccess == NULL)
1856 outSuccess = &dummySuccess;
1857 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
1859 *outSuccess = FALSE;
1863 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
1864 if (cfNumber == NULL)
1866 *outSuccess = FALSE;
1869 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
1877 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
1879 CFDictionaryRef auStateDictionary;
1880 ComponentDescription tempDesc = {0,0,0,0,0};
1881 SInt32 versionValue;
1884 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
1887 // the property list for AU state data must be of the dictionary type
1888 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
1889 return kAudioUnitErr_InvalidPropertyValue;
1892 auStateDictionary = (CFDictionaryRef)inAUStateData;
1894 // first check to make sure that the version of the AU state data is one that we know understand
1895 // XXX should I really do this? later versions would probably still hold these ID keys, right?
1896 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
1899 return kAudioUnitErr_InvalidPropertyValue;
1901 #define kCurrentSavedStateVersion 0
1902 if (versionValue != kCurrentSavedStateVersion) {
1903 return kAudioUnitErr_InvalidPropertyValue;
1906 // grab the ComponentDescription values from the AU state data
1907 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
1908 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
1909 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
1910 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
1911 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
1912 return kAudioUnitErr_InvalidPropertyValue;
1914 *outComponentDescription = tempDesc;
1919 static bool au_preset_filter (const string& str, void* arg)
1921 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
1925 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
1929 /* check the preset file path name against this plugin
1930 ID. The idea is that all preset files for this plugin
1931 include "<manufacturer>/<plugin-name>" in their path.
1934 Plugin* p = (Plugin *) arg;
1935 string match = p->maker();
1939 ret = str.find (match) != string::npos;
1942 string m = p->maker ();
1943 string n = p->name ();
1944 strip_whitespace_edges (m);
1945 strip_whitespace_edges (n);
1950 ret = str.find (match) != string::npos;
1958 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
1961 CFPropertyListRef plist;
1962 ComponentDescription presetDesc;
1965 plist = load_property_list (pathstr);
1971 // get the ComponentDescription from the AU preset file
1973 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
1975 if (status == noErr) {
1976 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
1978 /* try to get the preset name from the property list */
1980 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
1982 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
1986 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
1989 char buf[PATH_MAX+1];
1991 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2006 AUPlugin::current_preset() const
2010 #ifdef AU_STATE_SUPPORT
2011 CFPropertyListRef propertyList;
2013 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2014 if (unit->GetAUPreset (propertyList) == noErr) {
2015 preset_name = get_preset_name_in_plist (propertyList);
2016 CFRelease(propertyList);
2023 AUPlugin::find_presets ()
2025 #ifdef AU_STATE_SUPPORT
2026 vector<string*>* preset_files;
2027 PathScanner scanner;
2029 user_preset_map.clear ();
2031 preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
2033 if (!preset_files) {
2037 for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
2039 string path = *(*x);
2042 /* make an initial guess at the preset name using the path */
2044 preset_name = Glib::path_get_basename (path);
2045 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2047 /* check that this preset file really matches this plugin
2048 and potentially get the "real" preset name from
2052 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2053 user_preset_map[preset_name] = path;
2059 delete preset_files;
2061 /* now fill the vector<string> with the names we have */
2063 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2064 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2067 /* add factory presets */
2069 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2071 string const uri = string_compose ("%1", _presets.size ());
2072 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first)));
2079 AUPlugin::has_editor () const
2081 // even if the plugin doesn't have its own editor, the AU API can be used
2082 // to create one that looks native.
2086 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2089 type = ARDOUR::AudioUnit;
2092 AUPluginInfo::~AUPluginInfo ()
2094 type = ARDOUR::AudioUnit;
2098 AUPluginInfo::load (Session& session)
2103 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2104 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2106 if (!comp->IsValid()) {
2107 error << ("AudioUnit: not a valid Component") << endmsg;
2109 plugin.reset (new AUPlugin (session.engine(), session, comp));
2112 AUPluginInfo *aup = new AUPluginInfo (*this);
2113 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2114 plugin->set_info (PluginInfoPtr (aup));
2115 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2119 catch (failed_constructor &err) {
2120 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2121 return PluginPtr ();
2126 AUPluginInfo::au_cache_path ()
2128 return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
2132 AUPluginInfo::discover ()
2136 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2137 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2140 PluginInfoList* plugs = new PluginInfoList;
2142 discover_fx (*plugs);
2143 discover_music (*plugs);
2144 discover_generators (*plugs);
2145 discover_instruments (*plugs);
2147 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2153 AUPluginInfo::discover_music (PluginInfoList& plugs)
2155 CAComponentDescription desc;
2156 desc.componentFlags = 0;
2157 desc.componentFlagsMask = 0;
2158 desc.componentSubType = 0;
2159 desc.componentManufacturer = 0;
2160 desc.componentType = kAudioUnitType_MusicEffect;
2162 discover_by_description (plugs, desc);
2166 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2168 CAComponentDescription desc;
2169 desc.componentFlags = 0;
2170 desc.componentFlagsMask = 0;
2171 desc.componentSubType = 0;
2172 desc.componentManufacturer = 0;
2173 desc.componentType = kAudioUnitType_Effect;
2175 discover_by_description (plugs, desc);
2179 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2181 CAComponentDescription desc;
2182 desc.componentFlags = 0;
2183 desc.componentFlagsMask = 0;
2184 desc.componentSubType = 0;
2185 desc.componentManufacturer = 0;
2186 desc.componentType = kAudioUnitType_Generator;
2188 discover_by_description (plugs, desc);
2192 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2194 CAComponentDescription desc;
2195 desc.componentFlags = 0;
2196 desc.componentFlagsMask = 0;
2197 desc.componentSubType = 0;
2198 desc.componentManufacturer = 0;
2199 desc.componentType = kAudioUnitType_MusicDevice;
2201 discover_by_description (plugs, desc);
2205 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2209 comp = FindNextComponent (NULL, &desc);
2211 while (comp != NULL) {
2212 CAComponentDescription temp;
2213 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2215 AUPluginInfoPtr info (new AUPluginInfo
2216 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2218 /* although apple designed the subtype field to be a "category" indicator,
2219 its really turned into a plugin ID field for a given manufacturer. Hence
2220 there are no categories for AudioUnits. However, to keep the plugins
2221 showing up under "categories", we'll use the "type" as a high level
2224 NOTE: no panners, format converters or i/o AU's for our purposes
2227 switch (info->descriptor->Type()) {
2228 case kAudioUnitType_Panner:
2229 case kAudioUnitType_OfflineEffect:
2230 case kAudioUnitType_FormatConverter:
2233 case kAudioUnitType_Output:
2234 info->category = _("AudioUnit Outputs");
2236 case kAudioUnitType_MusicDevice:
2237 info->category = _("AudioUnit Instruments");
2239 case kAudioUnitType_MusicEffect:
2240 info->category = _("AudioUnit MusicEffects");
2242 case kAudioUnitType_Effect:
2243 info->category = _("AudioUnit Effects");
2245 case kAudioUnitType_Mixer:
2246 info->category = _("AudioUnit Mixers");
2248 case kAudioUnitType_Generator:
2249 info->category = _("AudioUnit Generators");
2252 info->category = _("AudioUnit (Unknown)");
2256 AUPluginInfo::get_names (temp, info->name, info->creator);
2258 info->type = ARDOUR::AudioUnit;
2259 info->unique_id = stringify_descriptor (*info->descriptor);
2261 /* XXX not sure of the best way to handle plugin versioning yet
2264 CAComponent cacomp (*info->descriptor);
2266 if (cacomp.GetResourceVersion (info->version) != noErr) {
2270 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2272 /* here we have to map apple's wildcard system to a simple pair
2273 of values. in ::can_do() we use the whole system, but here
2274 we need a single pair of values. XXX probably means we should
2275 remove any use of these values.
2278 info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
2279 info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
2281 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2282 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2284 plugs.push_back (info);
2287 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2290 comp = FindNextComponent (comp, &desc);
2295 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2298 AUPluginCachedInfo& cinfo,
2299 const std::string& name)
2304 /* concatenate unique ID with version to provide a key for cached info lookup.
2305 this ensures we don't get stale information, or should if plugin developers
2306 follow Apple "guidelines".
2309 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2314 CachedInfoMap::iterator cim = cached_info.find (id);
2316 if (cim != cached_info.end()) {
2317 cinfo = cim->second;
2322 AUChannelInfo* channel_info;
2326 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2330 if (CAAudioUnit::Open (comp, unit) != noErr) {
2336 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2341 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2342 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2348 /* no explicit info available, so default to 1in/1out */
2350 cinfo.io_configs.push_back (pair<int,int> (1, 1));
2354 /* store each configuration */
2356 for (uint32_t n = 0; n < cnt; ++n) {
2357 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2358 channel_info[n].outChannels));
2361 free (channel_info);
2364 add_cached_info (id, cinfo);
2365 save_cached_info ();
2371 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2373 cached_info[id] = cinfo;
2376 #define AU_CACHE_VERSION "2.0"
2379 AUPluginInfo::save_cached_info ()
2383 node = new XMLNode (X_("AudioUnitPluginCache"));
2384 node->add_property( "version", AU_CACHE_VERSION );
2386 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2387 XMLNode* parent = new XMLNode (X_("plugin"));
2388 parent->add_property ("id", i->first);
2389 node->add_child_nocopy (*parent);
2391 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2393 XMLNode* child = new XMLNode (X_("io"));
2396 snprintf (buf, sizeof (buf), "%d", j->first);
2397 child->add_property (X_("in"), buf);
2398 snprintf (buf, sizeof (buf), "%d", j->second);
2399 child->add_property (X_("out"), buf);
2400 parent->add_child_nocopy (*child);
2405 Glib::ustring path = au_cache_path ();
2408 tree.set_root (node);
2410 if (!tree.write (path)) {
2411 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2412 unlink (path.c_str());
2417 AUPluginInfo::load_cached_info ()
2419 Glib::ustring path = au_cache_path ();
2422 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2426 if ( !tree.read (path) ) {
2427 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2431 const XMLNode* root (tree.root());
2433 if (root->name() != X_("AudioUnitPluginCache")) {
2437 //initial version has incorrectly stored i/o info, and/or garbage chars.
2438 const XMLProperty* version = root->property(X_("version"));
2439 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2440 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2444 cached_info.clear ();
2446 const XMLNodeList children = root->children();
2448 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2450 const XMLNode* child = *iter;
2452 if (child->name() == X_("plugin")) {
2454 const XMLNode* gchild;
2455 const XMLNodeList gchildren = child->children();
2456 const XMLProperty* prop = child->property (X_("id"));
2462 string id = prop->value();
2466 string::size_type slash = id.find_last_of ('/');
2468 if (slash == string::npos) {
2472 version = id.substr (slash);
2473 id = id.substr (0, slash);
2474 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2476 if (fixed.empty()) {
2477 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2484 AUPluginCachedInfo cinfo;
2486 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2490 if (gchild->name() == X_("io")) {
2494 const XMLProperty* iprop;
2495 const XMLProperty* oprop;
2497 if (((iprop = gchild->property (X_("in"))) != 0) &&
2498 ((oprop = gchild->property (X_("out"))) != 0)) {
2499 in = atoi (iprop->value());
2500 out = atoi (oprop->value());
2502 cinfo.io_configs.push_back (pair<int,int> (in, out));
2507 if (cinfo.io_configs.size()) {
2508 add_cached_info (id, cinfo);
2517 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2519 CFStringRef itemName = NULL;
2521 // Marc Poirier-style item name
2522 CAComponent auComponent (comp_desc);
2523 if (auComponent.IsValid()) {
2524 CAComponentDescription dummydesc;
2525 Handle nameHandle = NewHandle(sizeof(void*));
2526 if (nameHandle != NULL) {
2527 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2529 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2530 if (nameString != NULL) {
2531 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2534 DisposeHandle(nameHandle);
2538 // if Marc-style fails, do the original way
2539 if (itemName == NULL) {
2540 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2541 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2542 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2544 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2545 compTypeString, compManufacturerString, compSubTypeString);
2547 if (compTypeString != NULL)
2548 CFRelease(compTypeString);
2549 if (compSubTypeString != NULL)
2550 CFRelease(compSubTypeString);
2551 if (compManufacturerString != NULL)
2552 CFRelease(compManufacturerString);
2555 string str = CFStringRefToStdString(itemName);
2556 string::size_type colon = str.find (':');
2559 name = str.substr (colon+1);
2560 maker = str.substr (0, colon);
2561 strip_whitespace_edges (maker);
2562 strip_whitespace_edges (name);
2566 strip_whitespace_edges (name);
2571 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2575 /* note: OSType is a compiler-implemenation-defined value,
2576 historically a 32 bit integer created with a multi-character
2577 constant such as 'abcd'. It is, fundamentally, an abomination.
2582 s << desc.SubType();
2590 AUPluginInfo::needs_midi_input ()
2592 return is_effect_with_midi_input () || is_instrument ();
2596 AUPluginInfo::is_effect () const
2598 return is_effect_without_midi_input() || is_effect_with_midi_input();
2602 AUPluginInfo::is_effect_without_midi_input () const
2604 return descriptor->IsAUFX();
2608 AUPluginInfo::is_effect_with_midi_input () const
2610 return descriptor->IsAUFM();
2614 AUPluginInfo::is_instrument () const
2616 return descriptor->IsMusicDevice();
2620 AUPlugin::set_info (PluginInfoPtr info)
2622 Plugin::set_info (info);
2624 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2626 _has_midi_input = pinfo->needs_midi_input ();
2627 _has_midi_output = false;