2 Copyright (C) 2006-2009 Paul Davis
3 Some portions Copyright (C) Sophia Poirier.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include "pbd/transmitter.h"
29 #include "pbd/xml++.h"
30 #include "pbd/convert.h"
31 #include "pbd/whitespace.h"
32 #include "pbd/file_utils.h"
33 #include "pbd/locale_guard.h"
35 #include <glibmm/threads.h>
36 #include <glibmm/fileutils.h>
37 #include <glibmm/miscutils.h>
38 #include <glib/gstdio.h>
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/debug.h"
44 #include "ardour/midi_buffer.h"
45 #include "ardour/filesystem_paths.h"
46 #include "ardour/io.h"
47 #include "ardour/audio_unit.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/utils.h"
53 #include "appleutility/CAAudioUnit.h"
54 #include "appleutility/CAAUParameter.h"
56 #include <CoreFoundation/CoreFoundation.h>
57 #include <CoreServices/CoreServices.h>
58 #include <AudioUnit/AudioUnit.h>
59 #include <AudioToolbox/AudioUnitUtilities.h>
61 #include <Carbon/Carbon.h>
68 using namespace ARDOUR;
70 AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
72 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
73 static string preset_suffix = ".aupreset";
74 static bool preset_search_path_initialized = false;
75 FILE * AUPluginInfo::_crashlog_fd = NULL;
78 static void au_blacklist (std::string id)
80 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
81 FILE * blacklist_fd = NULL;
82 if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
83 PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
86 assert(id.find("\n") == string::npos);
87 fprintf(blacklist_fd, "%s\n", id.c_str());
88 ::fclose(blacklist_fd);
91 static void au_unblacklist (std::string id)
93 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
94 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
95 PBD::warning << "Expected Blacklist file does not exist.\n";
100 std::ifstream ifs(fn.c_str());
101 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
102 ::g_unlink(fn.c_str());
104 assert(id.find("\n") == string::npos);
106 id += "\n"; // add separator
107 const size_t rpl = bl.find(id);
108 if (rpl != string::npos) {
109 bl.replace(rpl, id.size(), "");
115 FILE * blacklist_fd = NULL;
116 if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
117 PBD::error << "Cannot open AU blacklist.\n";
120 fprintf(blacklist_fd, "%s", bl.c_str());
121 ::fclose(blacklist_fd);
124 static bool is_blacklisted (std::string id)
126 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
127 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
131 std::ifstream ifs(fn.c_str());
132 bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
134 assert(id.find("\n") == string::npos);
136 id += "\n"; // add separator
137 const size_t rpl = bl.find(id);
138 if (rpl != string::npos) {
147 _render_callback(void *userData,
148 AudioUnitRenderActionFlags *ioActionFlags,
149 const AudioTimeStamp *inTimeStamp,
151 UInt32 inNumberFrames,
152 AudioBufferList* ioData)
155 return ((AUPlugin*)userData)->render_callback (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
161 _get_beat_and_tempo_callback (void* userData,
162 Float64* outCurrentBeat,
163 Float64* outCurrentTempo)
166 return ((AUPlugin*)userData)->get_beat_and_tempo_callback (outCurrentBeat, outCurrentTempo);
173 _get_musical_time_location_callback (void * userData,
174 UInt32 * outDeltaSampleOffsetToNextBeat,
175 Float32 * outTimeSig_Numerator,
176 UInt32 * outTimeSig_Denominator,
177 Float64 * outCurrentMeasureDownBeat)
180 return ((AUPlugin*)userData)->get_musical_time_location_callback (outDeltaSampleOffsetToNextBeat,
181 outTimeSig_Numerator,
182 outTimeSig_Denominator,
183 outCurrentMeasureDownBeat);
189 _get_transport_state_callback (void* userData,
190 Boolean* outIsPlaying,
191 Boolean* outTransportStateChanged,
192 Float64* outCurrentSampleInTimeLine,
193 Boolean* outIsCycling,
194 Float64* outCycleStartBeat,
195 Float64* outCycleEndBeat)
198 return ((AUPlugin*)userData)->get_transport_state_callback (
199 outIsPlaying, outTransportStateChanged,
200 outCurrentSampleInTimeLine, outIsCycling,
201 outCycleStartBeat, outCycleEndBeat);
208 save_property_list (CFPropertyListRef propertyList, Glib::ustring path)
214 // Convert the property list into XML data.
216 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
219 error << _("Could not create XML version of property list") << endmsg;
223 // Write the XML data to the file.
225 fd = open (path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0664);
227 if (errno == EEXIST) {
228 error << string_compose (_("Preset file %1 exists; not overwriting"),
231 error << string_compose (_("Cannot open preset file %1 (%2)"),
232 path, strerror (errno)) << endmsg;
238 size_t cnt = CFDataGetLength (xmlData);
240 if (write (fd, CFDataGetBytePtr (xmlData), cnt) != (ssize_t) cnt) {
251 static CFPropertyListRef
252 load_property_list (Glib::ustring path)
255 CFPropertyListRef propertyList = 0;
257 CFStringRef errorString;
259 // Read the XML file.
261 if ((fd = open (path.c_str(), O_RDONLY)) < 0) {
266 off_t len = lseek (fd, 0, SEEK_END);
267 char* buf = new char[len];
268 lseek (fd, 0, SEEK_SET);
270 if (read (fd, buf, len) != len) {
278 xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) buf, len, kCFAllocatorNull);
280 // Reconstitute the dictionary using the XML data.
282 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
284 kCFPropertyListImmutable,
293 //-----------------------------------------------------------------------------
295 set_preset_name_in_plist (CFPropertyListRef plist, string preset_name)
300 CFStringRef pn = CFStringCreateWithCString (kCFAllocatorDefault, preset_name.c_str(), kCFStringEncodingUTF8);
302 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
303 CFDictionarySetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey), pn);
309 //-----------------------------------------------------------------------------
311 get_preset_name_in_plist (CFPropertyListRef plist)
319 if (CFGetTypeID (plist) == CFDictionaryGetTypeID()) {
320 const void *p = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
322 CFStringRef str = (CFStringRef) p;
323 int len = CFStringGetLength(str);
325 char local_buffer[len];
326 if (CFStringGetCString (str, local_buffer, len, kCFStringEncodingUTF8)) {
334 //--------------------------------------------------------------------------
335 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
336 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
337 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
338 Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
340 if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
343 if ( (inComponentDescription1->componentSubType == inComponentDescription2->componentSubType)
344 && (inComponentDescription1->componentManufacturer == inComponentDescription2->componentManufacturer) )
346 // only sub-type and manufacturer IDs need to be equal
349 // type, sub-type, and manufacturer IDs all need to be equal in order to call this a match
350 else if (inComponentDescription1->componentType == inComponentDescription2->componentType)
357 //--------------------------------------------------------------------------
358 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
359 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
360 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
361 Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
364 ComponentDescription desc;
366 if ( (inComponent == NULL) || (inComponentDescription == NULL) )
369 // get the ComponentDescription of the input Component
370 status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
374 // check if the Component's ComponentDescription matches the input ComponentDescription
375 return ComponentDescriptionsMatch_General(&desc, inComponentDescription, inIgnoreType);
378 //--------------------------------------------------------------------------
379 // determine if 2 ComponentDescriptions are basically equal
380 // (by that, I mean that the important identifying values are compared,
381 // but not the ComponentDescription flags)
382 Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
384 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
387 //--------------------------------------------------------------------------
388 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
389 Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
391 return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
394 //--------------------------------------------------------------------------
395 // determine if a ComponentDescription basically matches that of a particular Component
396 Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
398 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
401 //--------------------------------------------------------------------------
402 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
403 Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
405 return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
409 AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAComponent> _comp)
410 : Plugin (engine, session)
412 , unit (new CAAudioUnit)
413 , initialized (false)
414 , _current_block_size (0)
415 , _requires_fixed_size_buffers (false)
420 , frames_processed (0)
421 , _parameter_listener (0)
422 , _parameter_listener_arg (0)
423 , last_transport_rolling (false)
424 , last_transport_speed (0.0)
426 if (!preset_search_path_initialized) {
427 Glib::ustring p = Glib::get_home_dir();
428 p += "/Library/Audio/Presets:";
429 p += preset_search_path;
430 preset_search_path = p;
431 preset_search_path_initialized = true;
438 AUPlugin::AUPlugin (const AUPlugin& other)
440 , comp (other.get_comp())
441 , unit (new CAAudioUnit)
442 , initialized (false)
443 , _current_block_size (0)
445 , _requires_fixed_size_buffers (false)
450 , frames_processed (0)
451 , _parameter_listener (0)
452 , _parameter_listener_arg (0)
458 AUPlugin::~AUPlugin ()
460 if (_parameter_listener) {
461 AUListenerDispose (_parameter_listener);
462 _parameter_listener = 0;
466 DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
467 unit->Uninitialize ();
476 AUPlugin::discover_factory_presets ()
483 if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
484 DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
488 assert (dataSize == sizeof (presets));
490 if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
491 error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
499 CFIndex cnt = CFArrayGetCount (presets);
501 for (CFIndex i = 0; i < cnt; ++i) {
502 AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
504 string name = CFStringRefToStdString (preset->presetName);
505 factory_preset_map[name] = preset->presetNumber;
515 CFStringRef itemName;
517 /* these keep track of *configured* channel set up,
518 not potential set ups.
522 output_channels = -1;
524 CAComponentDescription temp;
525 GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
526 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
527 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
528 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
529 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
530 compTypeString, compManufacturerString, compSubTypeString);
531 if (compTypeString != NULL) CFRelease(compTypeString);
532 if (compSubTypeString != NULL) CFRelease(compSubTypeString);
533 if (compManufacturerString != NULL) CFRelease(compManufacturerString);
536 au_blacklist(CFStringRefToStdString(itemName));
539 DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
540 err = CAAudioUnit::Open (*(comp.get()), *unit);
542 error << _("Exception thrown during AudioUnit plugin loading - plugin ignored") << endmsg;
543 throw failed_constructor();
547 error << _("AudioUnit: Could not convert CAComponent to CAAudioUnit") << endmsg;
548 throw failed_constructor ();
551 DEBUG_TRACE (DEBUG::AudioUnits, "count global elements\n");
552 unit->GetElementCount (kAudioUnitScope_Global, global_elements);
553 DEBUG_TRACE (DEBUG::AudioUnits, "count input elements\n");
554 unit->GetElementCount (kAudioUnitScope_Input, input_elements);
555 DEBUG_TRACE (DEBUG::AudioUnits, "count output elements\n");
556 unit->GetElementCount (kAudioUnitScope_Output, output_elements);
558 if (input_elements > 0) {
559 /* setup render callback: the plugin calls this to get input data
562 AURenderCallbackStruct renderCallbackInfo;
564 renderCallbackInfo.inputProc = _render_callback;
565 renderCallbackInfo.inputProcRefCon = this;
567 DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
568 if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
569 0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
570 error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
571 throw failed_constructor();
575 /* tell the plugin about tempo/meter/transport callbacks in case it wants them */
577 HostCallbackInfo info;
578 memset (&info, 0, sizeof (HostCallbackInfo));
579 info.hostUserData = this;
580 info.beatAndTempoProc = _get_beat_and_tempo_callback;
581 info.musicalTimeLocationProc = _get_musical_time_location_callback;
582 info.transportStateProc = _get_transport_state_callback;
584 //ignore result of this - don't care if the property isn't supported
585 DEBUG_TRACE (DEBUG::AudioUnits, "set host callbacks in global scope\n");
586 unit->SetProperty (kAudioUnitProperty_HostCallbacks,
587 kAudioUnitScope_Global,
590 sizeof (HostCallbackInfo));
592 if (set_block_size (_session.get_block_size())) {
593 error << _("AUPlugin: cannot set processing block size") << endmsg;
594 throw failed_constructor();
597 create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
598 discover_parameters ();
599 discover_factory_presets ();
601 // Plugin::setup_controls ();
603 au_blacklist(CFStringRefToStdString(itemName));
604 if (itemName != NULL) CFRelease(itemName);
608 AUPlugin::discover_parameters ()
610 /* discover writable parameters */
612 AudioUnitScope scopes[] = {
613 kAudioUnitScope_Global,
614 kAudioUnitScope_Output,
615 kAudioUnitScope_Input
618 descriptors.clear ();
620 for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
622 AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
624 for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
626 AUParameterDescriptor d;
628 d.id = param_info.ParamID (i);
630 const CAAUParameter* param = param_info.GetParamInfo (d.id);
631 const AudioUnitParameterInfo& info (param->ParamInfo());
633 const int len = CFStringGetLength (param->GetName());;
634 char local_buffer[len*2];
635 Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
639 d.label = local_buffer;
642 d.scope = param_info.GetScope ();
643 d.element = param_info.GetElement ();
645 /* info.units to consider */
647 kAudioUnitParameterUnit_Generic = 0
648 kAudioUnitParameterUnit_Indexed = 1
649 kAudioUnitParameterUnit_Boolean = 2
650 kAudioUnitParameterUnit_Percent = 3
651 kAudioUnitParameterUnit_Seconds = 4
652 kAudioUnitParameterUnit_SampleFrames = 5
653 kAudioUnitParameterUnit_Phase = 6
654 kAudioUnitParameterUnit_Rate = 7
655 kAudioUnitParameterUnit_Hertz = 8
656 kAudioUnitParameterUnit_Cents = 9
657 kAudioUnitParameterUnit_RelativeSemiTones = 10
658 kAudioUnitParameterUnit_MIDINoteNumber = 11
659 kAudioUnitParameterUnit_MIDIController = 12
660 kAudioUnitParameterUnit_Decibels = 13
661 kAudioUnitParameterUnit_LinearGain = 14
662 kAudioUnitParameterUnit_Degrees = 15
663 kAudioUnitParameterUnit_EqualPowerCrossfade = 16
664 kAudioUnitParameterUnit_MixerFaderCurve1 = 17
665 kAudioUnitParameterUnit_Pan = 18
666 kAudioUnitParameterUnit_Meters = 19
667 kAudioUnitParameterUnit_AbsoluteCents = 20
668 kAudioUnitParameterUnit_Octaves = 21
669 kAudioUnitParameterUnit_BPM = 22
670 kAudioUnitParameterUnit_Beats = 23
671 kAudioUnitParameterUnit_Milliseconds = 24
672 kAudioUnitParameterUnit_Ratio = 25
675 /* info.flags to consider */
679 kAudioUnitParameterFlag_CFNameRelease = (1L << 4)
680 kAudioUnitParameterFlag_HasClump = (1L << 20)
681 kAudioUnitParameterFlag_HasName = (1L << 21)
682 kAudioUnitParameterFlag_DisplayLogarithmic = (1L << 22)
683 kAudioUnitParameterFlag_IsHighResolution = (1L << 23)
684 kAudioUnitParameterFlag_NonRealTime = (1L << 24)
685 kAudioUnitParameterFlag_CanRamp = (1L << 25)
686 kAudioUnitParameterFlag_ExpertMode = (1L << 26)
687 kAudioUnitParameterFlag_HasCFNameString = (1L << 27)
688 kAudioUnitParameterFlag_IsGlobalMeta = (1L << 28)
689 kAudioUnitParameterFlag_IsElementMeta = (1L << 29)
690 kAudioUnitParameterFlag_IsReadable = (1L << 30)
691 kAudioUnitParameterFlag_IsWritable = (1L << 31)
694 d.lower = info.minValue;
695 d.upper = info.maxValue;
696 d.normal = info.defaultValue;
698 d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
699 d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
700 (d.integer_step && ((d.upper - d.lower) == 1.0));
701 d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
702 d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
703 !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
704 (info.flags & kAudioUnitParameterFlag_IsWritable);
706 d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
707 d.au_unit = info.unit;
709 case kAudioUnitParameterUnit_Decibels:
710 d.unit = ParameterDescriptor::DB;
712 case kAudioUnitParameterUnit_MIDINoteNumber:
713 d.unit = ParameterDescriptor::MIDI_NOTE;
715 case kAudioUnitParameterUnit_Hertz:
716 d.unit = ParameterDescriptor::HZ;
720 d.min_unbound = 0; // lower is bound
721 d.max_unbound = 0; // upper is bound
724 descriptors.push_back (d);
726 uint32_t last_param = descriptors.size() - 1;
727 parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
728 listen_to_parameter (last_param);
735 four_ints_to_four_byte_literal (unsigned char n[4])
737 /* this is actually implementation dependent. sigh. this is what gcc
738 and quite a few others do.
740 return ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + n[3]);
744 AUPlugin::maybe_fix_broken_au_id (const std::string& id)
746 if (isdigit (id[0])) {
750 /* ID format is xxxx-xxxx-xxxx
751 where x maybe \xNN or a printable character.
753 Split at the '-' and and process each part into an integer.
754 Then put it back together.
758 unsigned char nascent[4];
759 const char* cstr = id.c_str();
760 const char* estr = cstr + id.size();
771 while (*cstr && next_int < 4) {
775 if (estr - cstr < 3) {
777 /* too close to the end for \xNN parsing: treat as literal characters */
785 if (cstr[1] == 'x' && isxdigit (cstr[2]) && isxdigit (cstr[3])) {
789 memcpy (short_buf, &cstr[2], 2);
790 nascent[in] = strtol (short_buf, NULL, 16);
796 /* treat as literal characters */
810 if (in && (in % 4 == 0)) {
811 /* nascent is ready */
812 n[next_int] = four_ints_to_four_byte_literal (nascent);
816 /* swallow space-hyphen-space */
830 s << n[0] << '-' << n[1] << '-' << n[2];
839 AUPlugin::unique_id () const
841 return AUPluginInfo::stringify_descriptor (comp->Desc());
845 AUPlugin::label () const
847 return _info->name.c_str();
851 AUPlugin::parameter_count () const
853 return descriptors.size();
857 AUPlugin::default_value (uint32_t port)
859 if (port < descriptors.size()) {
860 return descriptors[port].normal;
867 AUPlugin::signal_latency () const
869 return unit->Latency() * _session.frame_rate();
873 AUPlugin::set_parameter (uint32_t which, float val)
875 if (which >= descriptors.size()) {
879 if (get_parameter(which) == val) {
883 const AUParameterDescriptor& d (descriptors[which]);
884 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set parameter %1 in scope %2 element %3 to %4\n", d.id, d.scope, d.element, val));
885 unit->SetParameter (d.id, d.scope, d.element, val);
887 /* tell the world what we did */
889 AudioUnitEvent theEvent;
891 theEvent.mEventType = kAudioUnitEvent_ParameterValueChange;
892 theEvent.mArgument.mParameter.mAudioUnit = unit->AU();
893 theEvent.mArgument.mParameter.mParameterID = d.id;
894 theEvent.mArgument.mParameter.mScope = d.scope;
895 theEvent.mArgument.mParameter.mElement = d.element;
897 DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
898 AUEventListenerNotify (NULL, NULL, &theEvent);
900 Plugin::set_parameter (which, val);
904 AUPlugin::get_parameter (uint32_t which) const
907 if (which < descriptors.size()) {
908 const AUParameterDescriptor& d (descriptors[which]);
909 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
910 unit->GetParameter(d.id, d.scope, d.element, val);
916 AUPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& pd) const
918 if (which < descriptors.size()) {
919 pd = descriptors[which];
926 AUPlugin::nth_parameter (uint32_t which, bool& ok) const
928 if (which < descriptors.size()) {
937 AUPlugin::activate ()
941 DEBUG_TRACE (DEBUG::AudioUnits, "call Initialize in activate()\n");
942 if ((err = unit->Initialize()) != noErr) {
943 error << string_compose (_("AUPlugin: %1 cannot initialize plugin (err = %2)"), name(), err) << endmsg;
945 frames_processed = 0;
952 AUPlugin::deactivate ()
954 DEBUG_TRACE (DEBUG::AudioUnits, "call Uninitialize in deactivate()\n");
955 unit->Uninitialize ();
962 DEBUG_TRACE (DEBUG::AudioUnits, "call Reset in flush()\n");
963 unit->GlobalReset ();
967 AUPlugin::requires_fixed_size_buffers() const
969 return _requires_fixed_size_buffers;
974 AUPlugin::set_block_size (pframes_t nframes)
976 bool was_initialized = initialized;
977 UInt32 numFrames = nframes;
984 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
985 if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
986 0, &numFrames, sizeof (numFrames))) != noErr) {
987 error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
991 if (was_initialized) {
995 _current_block_size = nframes;
1001 AUPlugin::configure_io (ChanCount in, ChanCount out)
1003 AudioStreamBasicDescription streamFormat;
1004 bool was_initialized = initialized;
1005 int32_t audio_in = in.n_audio();
1006 int32_t audio_out = out.n_audio();
1008 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
1011 //if we are already running with the requested i/o config, bail out here
1012 if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
1019 streamFormat.mSampleRate = _session.frame_rate();
1020 streamFormat.mFormatID = kAudioFormatLinearPCM;
1021 streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
1023 #ifdef __LITTLE_ENDIAN__
1026 streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
1029 streamFormat.mBitsPerChannel = 32;
1030 streamFormat.mFramesPerPacket = 1;
1032 /* apple says that for non-interleaved data, these
1033 values always refer to a single channel.
1035 streamFormat.mBytesPerPacket = 4;
1036 streamFormat.mBytesPerFrame = 4;
1038 streamFormat.mChannelsPerFrame = audio_in;
1040 if (set_input_format (streamFormat) != 0) {
1044 streamFormat.mChannelsPerFrame = audio_out;
1046 if (set_output_format (streamFormat) != 0) {
1050 /* reset plugin info to show currently configured state */
1052 _info->n_inputs = in;
1053 _info->n_outputs = out;
1055 if (was_initialized) {
1063 AUPlugin::input_streams() const
1068 if (input_channels < 0) {
1069 // force PluginIoReConfigure -- see also commit msg e38eb06
1070 c.set (DataType::AUDIO, 0);
1071 c.set (DataType::MIDI, 0);
1073 c.set (DataType::AUDIO, input_channels);
1074 c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
1082 AUPlugin::output_streams() const
1086 if (output_channels < 0) {
1087 // force PluginIoReConfigure - see also commit msg e38eb06
1088 c.set (DataType::AUDIO, 0);
1089 c.set (DataType::MIDI, 0);
1091 c.set (DataType::AUDIO, output_channels);
1092 c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
1099 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1101 // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
1103 int32_t audio_in = in.n_audio();
1106 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
1108 /* lets check MIDI first */
1110 if (in.n_midi() > 0) {
1111 if (!_has_midi_input) {
1116 vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
1118 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
1119 name(), io_configs.size(), in, out));
1121 //Ardour expects the plugin to tell it the output
1122 //configuration but AU plugins can have multiple I/O
1123 //configurations in most cases. so first lets see
1124 //if there's a configuration that keeps out==in
1126 if (in.n_midi() > 0 && audio_in == 0) {
1127 audio_out = 2; // prefer stereo version if available.
1129 audio_out = audio_in;
1132 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1134 int32_t possible_in = i->first;
1135 int32_t possible_out = i->second;
1137 if ((possible_in == audio_in) && (possible_out == audio_out)) {
1138 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
1139 possible_in, possible_out,
1142 out.set (DataType::MIDI, 0);
1143 out.set (DataType::AUDIO, audio_out);
1149 /* now allow potentially "imprecise" matches */
1153 for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
1155 int32_t possible_in = i->first;
1156 int32_t possible_out = i->second;
1158 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tpossible in %1 possible out %2\n", possible_in, possible_out));
1160 if (possible_out == 0) {
1161 warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
1162 /* XXX surely this is just a send? (e.g. AUNetSend) */
1166 if (possible_in == 0) {
1168 /* instrument plugin, always legal but throws away inputs ...
1171 if (possible_out == -1) {
1172 /* any configuration possible, provide stereo output */
1175 } else if (possible_out == -2) {
1176 /* plugins shouldn't really use (0,-2) but might.
1177 any configuration possible, provide stereo output
1181 } else if (possible_out < -2) {
1182 /* explicitly variable number of outputs.
1184 Since Ardour can handle any configuration,
1185 we have to somehow pick a number.
1187 We'll use the number of inputs
1188 to the master bus, or 2 if there
1191 boost::shared_ptr<Route> master = _session.master_out();
1193 audio_out = master->input()->n_ports().n_audio();
1199 /* exact number of outputs */
1200 audio_out = possible_out;
1205 if (possible_in == -1) {
1207 /* wildcard for input */
1209 if (possible_out == -1) {
1210 /* out much match in */
1211 audio_out = audio_in;
1213 } else if (possible_out == -2) {
1214 /* any configuration possible, pick matching */
1215 audio_out = audio_in;
1217 } else if (possible_out < -2) {
1218 /* explicitly variable number of outputs, pick maximum */
1219 audio_out = -possible_out;
1222 /* exact number of outputs */
1223 audio_out = possible_out;
1228 if (possible_in == -2) {
1230 if (possible_out == -1) {
1231 /* any configuration possible, pick matching */
1232 audio_out = audio_in;
1234 } else if (possible_out == -2) {
1235 /* plugins shouldn't really use (-2,-2) but might.
1236 interpret as (-1,-1).
1238 audio_out = audio_in;
1240 } else if (possible_out < -2) {
1241 /* explicitly variable number of outputs, pick maximum */
1242 audio_out = -possible_out;
1245 /* exact number of outputs */
1246 audio_out = possible_out;
1251 if (possible_in < -2) {
1253 /* explicit variable number of inputs */
1255 if (audio_in > -possible_in) {
1256 /* request is too large */
1260 if (possible_out == -1) {
1261 /* any output configuration possible, provide stereo out */
1264 } else if (possible_out == -2) {
1265 /* plugins shouldn't really use (<-2,-2) but might.
1266 interpret as (<-2,-1): any configuration possible, provide stereo output
1270 } else if (possible_out < -2) {
1271 /* explicitly variable number of outputs.
1273 Since Ardour can handle any configuration,
1274 we have to somehow pick a number.
1276 We'll use the number of inputs
1277 to the master bus, or 2 if there
1280 boost::shared_ptr<Route> master = _session.master_out();
1282 audio_out = master->input()->n_ports().n_audio();
1288 /* exact number of outputs */
1289 audio_out = possible_out;
1294 if (possible_in && (possible_in == audio_in)) {
1296 /* exact number of inputs ... must match obviously */
1298 if (possible_out == -1) {
1299 /* any output configuration possible, provide stereo output */
1302 } else if (possible_out == -2) {
1303 /* plugins shouldn't really use (>0,-2) but might.
1304 interpret as (>0,-1):
1305 any output configuration possible, provide stereo output
1309 } else if (possible_out < -2) {
1310 /* explicitly variable number of outputs, pick maximum */
1311 audio_out = -possible_out;
1314 /* exact number of outputs */
1315 audio_out = possible_out;
1327 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
1329 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
1333 out.set (DataType::MIDI, 0);
1334 out.set (DataType::AUDIO, audio_out);
1340 AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
1342 return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
1346 AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
1348 if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
1357 buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
1358 fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
1364 AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
1368 for (uint32_t i = 0; i < cnt; ++i) {
1369 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set stream format for %1, scope = %2 element %3\n",
1370 (scope == kAudioUnitScope_Input ? "input" : "output"),
1372 if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
1373 error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
1374 (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
1379 if (scope == kAudioUnitScope_Input) {
1380 input_channels = fmt.mChannelsPerFrame;
1382 output_channels = fmt.mChannelsPerFrame;
1389 AUPlugin::render_callback(AudioUnitRenderActionFlags*,
1390 const AudioTimeStamp*,
1392 UInt32 inNumberFrames,
1393 AudioBufferList* ioData)
1395 /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
1397 // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
1398 // name(), inNumberFrames, ioData->mNumberBuffers));
1400 if (input_maxbuf == 0) {
1401 error << _("AUPlugin: render callback called illegally!") << endmsg;
1402 return kAudioUnitErr_CannotDoInCurrentContext;
1404 uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
1406 for (uint32_t i = 0; i < limit; ++i) {
1407 ioData->mBuffers[i].mNumberChannels = 1;
1408 ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
1410 /* we don't use the channel mapping because audiounits are
1411 never replicated. one plugin instance uses all channels/buffers
1412 passed to PluginInsert::connect_and_run()
1415 ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
1418 cb_offset += inNumberFrames;
1424 AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
1426 Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
1428 AudioUnitRenderActionFlags flags = 0;
1432 if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
1433 unit->GlobalReset();
1434 _last_nframes = nframes;
1437 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
1438 name(), input_channels, output_channels, _has_midi_input,
1439 bufs.count(), bufs.available()));
1441 /* the apparent number of buffers matches our input configuration, but we know that the bufferset
1442 has the capacity to handle our outputs.
1445 assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
1447 input_buffers = &bufs;
1448 input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
1449 input_offset = offset;
1452 buffers->mNumberBuffers = output_channels;
1454 for (int32_t i = 0; i < output_channels; ++i) {
1455 buffers->mBuffers[i].mNumberChannels = 1;
1456 buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
1457 /* setting this to 0 indicates to the AU that it can provide buffers here
1458 if necessary. if it can process in-place, it will use the buffers provided
1459 as input by ::render_callback() above.
1461 a non-null values tells the plugin to render into the buffer pointed
1464 buffers->mBuffers[i].mData = 0;
1467 if (_has_midi_input) {
1469 uint32_t nmidi = bufs.count().n_midi();
1471 for (uint32_t i = 0; i < nmidi; ++i) {
1473 /* one MIDI port/buffer only */
1475 MidiBuffer& m = bufs.get_midi (i);
1477 for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
1478 Evoral::MIDIEvent<framepos_t> ev (*i);
1480 if (ev.is_channel_event()) {
1481 const uint8_t* b = ev.buffer();
1482 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
1483 unit->MIDIEvent (b[0], b[1], b[2], ev.time());
1486 /* XXX need to handle sysex and other message types */
1491 /* does this really mean anything ?
1494 ts.mSampleTime = frames_processed;
1495 ts.mFlags = kAudioTimeStampSampleTimeValid;
1497 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
1498 name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
1500 if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
1503 frames_processed += nframes;
1505 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
1506 name(), buffers->mNumberBuffers, output_channels));
1508 int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
1511 for (i = 0; i < limit; ++i) {
1512 Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
1513 if (expected_buffer_address != buffers->mBuffers[i].mData) {
1514 /* plugin provided its own buffer for output so copy it back to where we want it
1516 memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
1520 /* now silence any buffers that were passed in but the that the plugin
1521 did not fill/touch/use.
1524 for (;i < output_channels; ++i) {
1525 memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
1531 error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
1536 AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
1537 Float64* outCurrentTempo)
1539 TempoMap& tmap (_session.tempo_map());
1541 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour beat&tempo callback\n");
1543 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1544 (and interpretation) of a beat position will be incorrect. So refuse to
1548 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1549 return kAudioUnitErr_CannotDoInCurrentContext;
1552 Timecode::BBT_Time bbt;
1553 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1554 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1556 if (outCurrentBeat) {
1558 beat = metric.meter().divisions_per_bar() * bbt.bars;
1560 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1561 *outCurrentBeat = beat;
1564 if (outCurrentTempo) {
1565 *outCurrentTempo = floor (metric.tempo().beats_per_minute());
1573 AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
1574 Float32* outTimeSig_Numerator,
1575 UInt32* outTimeSig_Denominator,
1576 Float64* outCurrentMeasureDownBeat)
1578 TempoMap& tmap (_session.tempo_map());
1580 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour music time location callback\n");
1582 /* more than 1 meter or more than 1 tempo means that a simplistic computation
1583 (and interpretation) of a beat position will be incorrect. So refuse to
1587 if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
1588 return kAudioUnitErr_CannotDoInCurrentContext;
1591 Timecode::BBT_Time bbt;
1592 TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
1593 tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
1595 if (outDeltaSampleOffsetToNextBeat) {
1596 if (bbt.ticks == 0) {
1598 *outDeltaSampleOffsetToNextBeat = 0;
1600 *outDeltaSampleOffsetToNextBeat = (UInt32)
1601 floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
1602 metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
1606 if (outTimeSig_Numerator) {
1607 *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
1609 if (outTimeSig_Denominator) {
1610 *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
1613 if (outCurrentMeasureDownBeat) {
1615 /* beat for the start of the bar.
1617 2|1|0 -> 1 + divisions_per_bar
1618 3|1|0 -> 1 + (2 * divisions_per_bar)
1622 *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
1629 AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
1630 Boolean* outTransportStateChanged,
1631 Float64* outCurrentSampleInTimeLine,
1632 Boolean* outIsCycling,
1633 Float64* outCycleStartBeat,
1634 Float64* outCycleEndBeat)
1639 DEBUG_TRACE (DEBUG::AudioUnits, "AU calls ardour transport state callback\n");
1641 rolling = _session.transport_rolling();
1642 speed = _session.transport_speed ();
1645 *outIsPlaying = _session.transport_rolling();
1648 if (outTransportStateChanged) {
1649 if (rolling != last_transport_rolling) {
1650 *outTransportStateChanged = true;
1651 } else if (speed != last_transport_speed) {
1652 *outTransportStateChanged = true;
1654 *outTransportStateChanged = false;
1658 if (outCurrentSampleInTimeLine) {
1659 /* this assumes that the AU can only call this host callback from render context,
1660 where input_offset is valid.
1662 *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
1666 Location* loc = _session.locations()->auto_loop_location();
1668 *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
1670 if (*outIsCycling) {
1672 if (outCycleStartBeat || outCycleEndBeat) {
1674 TempoMap& tmap (_session.tempo_map());
1676 /* more than 1 meter means that a simplistic computation (and interpretation) of
1677 a beat position will be incorrect. so refuse to offer the value.
1680 if (tmap.n_meters() > 1) {
1681 return kAudioUnitErr_CannotDoInCurrentContext;
1684 Timecode::BBT_Time bbt;
1686 if (outCycleStartBeat) {
1687 TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
1688 _session.tempo_map().bbt_time (loc->start(), bbt);
1691 beat = metric.meter().divisions_per_bar() * bbt.bars;
1693 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1695 *outCycleStartBeat = beat;
1698 if (outCycleEndBeat) {
1699 TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
1700 _session.tempo_map().bbt_time (loc->end(), bbt);
1703 beat = metric.meter().divisions_per_bar() * bbt.bars;
1705 beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
1707 *outCycleEndBeat = beat;
1713 last_transport_rolling = rolling;
1714 last_transport_speed = speed;
1719 set<Evoral::Parameter>
1720 AUPlugin::automatable() const
1722 set<Evoral::Parameter> automates;
1724 for (uint32_t i = 0; i < descriptors.size(); ++i) {
1725 if (descriptors[i].automatable) {
1726 automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
1734 AUPlugin::describe_parameter (Evoral::Parameter param)
1736 if (param.type() == PluginAutomation && param.id() < parameter_count()) {
1737 return descriptors[param.id()].label;
1744 AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
1746 // NameValue stuff here
1750 AUPlugin::parameter_is_audio (uint32_t) const
1756 AUPlugin::parameter_is_control (uint32_t param) const
1758 assert(param < descriptors.size());
1759 if (descriptors[param].automatable) {
1760 /* corrently ardour expects all controls to be automatable
1761 * IOW ardour GUI elements mandate an Evoral::Parameter
1762 * for all input+control ports.
1770 AUPlugin::parameter_is_input (uint32_t param) const
1772 /* AU params that are both readable and writeable,
1773 * are listed in kAudioUnitScope_Global
1775 return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
1779 AUPlugin::parameter_is_output (uint32_t param) const
1781 assert(param < descriptors.size());
1782 // TODO check if ardour properly handles ports
1783 // that report is_input + is_output == true
1784 // -> add || descriptors[param].scope == kAudioUnitScope_Global
1785 return (descriptors[param].scope == kAudioUnitScope_Output);
1789 AUPlugin::add_state (XMLNode* root) const
1791 LocaleGuard lg (X_("C"));
1793 CFPropertyListRef propertyList;
1795 DEBUG_TRACE (DEBUG::AudioUnits, "get preset state\n");
1796 if (unit->GetAUPreset (propertyList) != noErr) {
1800 // Convert the property list into XML data.
1802 xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
1805 error << _("Could not create XML version of property list") << endmsg;
1809 /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
1810 our state node. GACK!
1815 if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
1817 root->add_child_copy (*t.root());
1821 CFRelease (xmlData);
1822 CFRelease (propertyList);
1826 AUPlugin::set_state(const XMLNode& node, int version)
1829 CFPropertyListRef propertyList;
1830 LocaleGuard lg (X_("C"));
1832 if (node.name() != state_node_name()) {
1833 error << _("Bad node sent to AUPlugin::set_state") << endmsg;
1837 #ifndef NO_PLUGIN_STATE
1838 if (node.children().empty()) {
1842 XMLNode* top = node.children().front();
1843 XMLNode* copy = new XMLNode (*top);
1848 const string& xml = t.write_buffer ();
1849 CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
1850 CFStringRef errorString;
1852 propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
1854 kCFPropertyListImmutable,
1857 CFRelease (xmlData);
1860 DEBUG_TRACE (DEBUG::AudioUnits, "set preset\n");
1861 if (unit->SetAUPreset (propertyList) == noErr) {
1864 /* tell the world */
1866 AudioUnitParameter changedUnit;
1867 changedUnit.mAudioUnit = unit->AU();
1868 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1869 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1871 CFRelease (propertyList);
1875 Plugin::set_state (node, version);
1880 AUPlugin::load_preset (PresetRecord r)
1882 Plugin::load_preset (r);
1885 CFPropertyListRef propertyList;
1887 UserPresetMap::iterator ux;
1888 FactoryPresetMap::iterator fx;
1890 /* look first in "user" presets */
1892 if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
1894 if ((propertyList = load_property_list (ux->second)) != 0) {
1895 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from user presets\n");
1896 if (unit->SetAUPreset (propertyList) == noErr) {
1899 /* tell the world */
1901 AudioUnitParameter changedUnit;
1902 changedUnit.mAudioUnit = unit->AU();
1903 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1904 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1906 CFRelease(propertyList);
1909 } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
1913 preset.presetNumber = fx->second;
1914 preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
1916 DEBUG_TRACE (DEBUG::AudioUnits, "set preset from factory presets\n");
1918 if (unit->SetPresentPreset (preset) == 0) {
1921 /* tell the world */
1923 AudioUnitParameter changedUnit;
1924 changedUnit.mAudioUnit = unit->AU();
1925 changedUnit.mParameterID = kAUParameterListener_AnyParameter;
1926 AUParameterListenerNotify (NULL, NULL, &changedUnit);
1934 AUPlugin::do_remove_preset (std::string)
1939 AUPlugin::do_save_preset (string preset_name)
1941 CFPropertyListRef propertyList;
1942 vector<Glib::ustring> v;
1943 Glib::ustring user_preset_path;
1945 std::string m = maker();
1946 std::string n = name();
1948 strip_whitespace_edges (m);
1949 strip_whitespace_edges (n);
1951 v.push_back (Glib::get_home_dir());
1952 v.push_back ("Library");
1953 v.push_back ("Audio");
1954 v.push_back ("Presets");
1958 user_preset_path = Glib::build_filename (v);
1960 if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
1961 error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
1965 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset\n");
1966 if (unit->GetAUPreset (propertyList) != noErr) {
1970 // add the actual preset name */
1972 v.push_back (preset_name + preset_suffix);
1976 user_preset_path = Glib::build_filename (v);
1978 set_preset_name_in_plist (propertyList, preset_name);
1980 if (save_property_list (propertyList, user_preset_path)) {
1981 error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
1985 CFRelease(propertyList);
1987 user_preset_map[preset_name] = user_preset_path;;
1989 return string ("file:///") + user_preset_path;
1992 //-----------------------------------------------------------------------------
1993 // this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
1995 GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
1997 CFNumberRef cfNumber;
1998 SInt32 numberValue = 0;
1999 Boolean dummySuccess;
2001 if (outSuccess == NULL)
2002 outSuccess = &dummySuccess;
2003 if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
2005 *outSuccess = FALSE;
2009 cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
2010 if (cfNumber == NULL)
2012 *outSuccess = FALSE;
2015 *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
2023 GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
2025 CFDictionaryRef auStateDictionary;
2026 ComponentDescription tempDesc = {0,0,0,0,0};
2027 SInt32 versionValue;
2030 if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
2033 // the property list for AU state data must be of the dictionary type
2034 if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
2035 return kAudioUnitErr_InvalidPropertyValue;
2038 auStateDictionary = (CFDictionaryRef)inAUStateData;
2040 // first check to make sure that the version of the AU state data is one that we know understand
2041 // XXX should I really do this? later versions would probably still hold these ID keys, right?
2042 versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
2045 return kAudioUnitErr_InvalidPropertyValue;
2047 #define kCurrentSavedStateVersion 0
2048 if (versionValue != kCurrentSavedStateVersion) {
2049 return kAudioUnitErr_InvalidPropertyValue;
2052 // grab the ComponentDescription values from the AU state data
2053 tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
2054 tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
2055 tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
2056 // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
2057 if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
2058 return kAudioUnitErr_InvalidPropertyValue;
2060 *outComponentDescription = tempDesc;
2065 static bool au_preset_filter (const string& str, void* arg)
2067 /* Not a dotfile, has a prefix before a period, suffix is aupreset */
2071 ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
2075 /* check the preset file path name against this plugin
2076 ID. The idea is that all preset files for this plugin
2077 include "<manufacturer>/<plugin-name>" in their path.
2080 Plugin* p = (Plugin *) arg;
2081 string match = p->maker();
2085 ret = str.find (match) != string::npos;
2088 string m = p->maker ();
2089 string n = p->name ();
2090 strip_whitespace_edges (m);
2091 strip_whitespace_edges (n);
2096 ret = str.find (match) != string::npos;
2104 check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
2107 CFPropertyListRef plist;
2108 ComponentDescription presetDesc;
2111 plist = load_property_list (pathstr);
2117 // get the ComponentDescription from the AU preset file
2119 status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
2121 if (status == noErr) {
2122 if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
2124 /* try to get the preset name from the property list */
2126 if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
2128 const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
2132 const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
2135 char buf[PATH_MAX+1];
2137 if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
2152 AUPlugin::current_preset() const
2156 CFPropertyListRef propertyList;
2158 DEBUG_TRACE (DEBUG::AudioUnits, "get current preset for current_preset()\n");
2159 if (unit->GetAUPreset (propertyList) == noErr) {
2160 preset_name = get_preset_name_in_plist (propertyList);
2161 CFRelease(propertyList);
2168 AUPlugin::find_presets ()
2170 vector<string> preset_files;
2172 user_preset_map.clear ();
2174 find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, this, true, true, true);
2176 if (preset_files.empty()) {
2180 for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
2185 /* make an initial guess at the preset name using the path */
2187 preset_name = Glib::path_get_basename (path);
2188 preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
2190 /* check that this preset file really matches this plugin
2191 and potentially get the "real" preset name from
2195 if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
2196 user_preset_map[preset_name] = path;
2201 /* now fill the vector<string> with the names we have */
2203 for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
2204 _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
2207 /* add factory presets */
2209 for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
2211 string const uri = string_compose ("%1", _presets.size ());
2212 _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
2217 AUPlugin::has_editor () const
2219 // even if the plugin doesn't have its own editor, the AU API can be used
2220 // to create one that looks native.
2224 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
2227 type = ARDOUR::AudioUnit;
2230 AUPluginInfo::~AUPluginInfo ()
2232 type = ARDOUR::AudioUnit;
2236 AUPluginInfo::load (Session& session)
2241 DEBUG_TRACE (DEBUG::AudioUnits, "load AU as a component\n");
2242 boost::shared_ptr<CAComponent> comp (new CAComponent(*descriptor));
2244 if (!comp->IsValid()) {
2245 error << ("AudioUnit: not a valid Component") << endmsg;
2247 plugin.reset (new AUPlugin (session.engine(), session, comp));
2250 AUPluginInfo *aup = new AUPluginInfo (*this);
2251 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("plugin info for %1 = %2\n", this, aup));
2252 plugin->set_info (PluginInfoPtr (aup));
2253 boost::dynamic_pointer_cast<AUPlugin> (plugin)->set_fixed_size_buffers (aup->creator == "Universal Audio");
2257 catch (failed_constructor &err) {
2258 DEBUG_TRACE (DEBUG::AudioUnits, "failed to load component/plugin\n");
2259 return PluginPtr ();
2264 AUPluginInfo::au_cache_path ()
2266 return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
2270 AUPluginInfo::discover ()
2274 if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
2275 ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
2277 // create crash log file
2278 au_start_crashlog ();
2280 PluginInfoList* plugs = new PluginInfoList;
2282 discover_fx (*plugs);
2283 discover_music (*plugs);
2284 discover_generators (*plugs);
2285 discover_instruments (*plugs);
2287 // all fine if we get here
2288 au_remove_crashlog ();
2290 DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
2296 AUPluginInfo::discover_music (PluginInfoList& plugs)
2298 CAComponentDescription desc;
2299 desc.componentFlags = 0;
2300 desc.componentFlagsMask = 0;
2301 desc.componentSubType = 0;
2302 desc.componentManufacturer = 0;
2303 desc.componentType = kAudioUnitType_MusicEffect;
2305 discover_by_description (plugs, desc);
2309 AUPluginInfo::discover_fx (PluginInfoList& plugs)
2311 CAComponentDescription desc;
2312 desc.componentFlags = 0;
2313 desc.componentFlagsMask = 0;
2314 desc.componentSubType = 0;
2315 desc.componentManufacturer = 0;
2316 desc.componentType = kAudioUnitType_Effect;
2318 discover_by_description (plugs, desc);
2322 AUPluginInfo::discover_generators (PluginInfoList& plugs)
2324 CAComponentDescription desc;
2325 desc.componentFlags = 0;
2326 desc.componentFlagsMask = 0;
2327 desc.componentSubType = 0;
2328 desc.componentManufacturer = 0;
2329 desc.componentType = kAudioUnitType_Generator;
2331 discover_by_description (plugs, desc);
2335 AUPluginInfo::discover_instruments (PluginInfoList& plugs)
2337 CAComponentDescription desc;
2338 desc.componentFlags = 0;
2339 desc.componentFlagsMask = 0;
2340 desc.componentSubType = 0;
2341 desc.componentManufacturer = 0;
2342 desc.componentType = kAudioUnitType_MusicDevice;
2344 discover_by_description (plugs, desc);
2349 AUPluginInfo::au_get_crashlog (std::string &msg)
2351 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2352 if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
2355 std::ifstream ifs(fn.c_str());
2356 msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
2357 au_remove_crashlog ();
2362 AUPluginInfo::au_start_crashlog ()
2364 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2365 assert(!_crashlog_fd);
2366 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
2367 if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
2368 PBD::error << "Cannot create AU error-log\n";
2373 AUPluginInfo::au_remove_crashlog ()
2376 ::fclose(_crashlog_fd);
2377 _crashlog_fd = NULL;
2379 string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
2380 ::g_unlink(fn.c_str());
2381 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
2386 AUPluginInfo::au_crashlog (std::string msg)
2388 assert(_crashlog_fd);
2389 fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
2390 ::fflush(_crashlog_fd);
2394 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
2397 au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
2399 comp = FindNextComponent (NULL, &desc);
2401 while (comp != NULL) {
2402 CAComponentDescription temp;
2403 GetComponentInfo (comp, &temp, NULL, NULL, NULL);
2404 CFStringRef itemName = NULL;
2407 if (itemName != NULL) CFRelease(itemName);
2408 CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
2409 CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
2410 CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
2411 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2412 compTypeString, compManufacturerString, compSubTypeString);
2413 au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
2414 if (compTypeString != NULL)
2415 CFRelease(compTypeString);
2416 if (compSubTypeString != NULL)
2417 CFRelease(compSubTypeString);
2418 if (compManufacturerString != NULL)
2419 CFRelease(compManufacturerString);
2422 if (is_blacklisted(CFStringRefToStdString(itemName))) {
2423 info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
2424 comp = FindNextComponent (comp, &desc);
2428 AUPluginInfoPtr info (new AUPluginInfo
2429 (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
2431 /* although apple designed the subtype field to be a "category" indicator,
2432 its really turned into a plugin ID field for a given manufacturer. Hence
2433 there are no categories for AudioUnits. However, to keep the plugins
2434 showing up under "categories", we'll use the "type" as a high level
2437 NOTE: no panners, format converters or i/o AU's for our purposes
2440 switch (info->descriptor->Type()) {
2441 case kAudioUnitType_Panner:
2442 case kAudioUnitType_OfflineEffect:
2443 case kAudioUnitType_FormatConverter:
2444 comp = FindNextComponent (comp, &desc);
2447 case kAudioUnitType_Output:
2448 info->category = _("AudioUnit Outputs");
2450 case kAudioUnitType_MusicDevice:
2451 info->category = _("AudioUnit Instruments");
2453 case kAudioUnitType_MusicEffect:
2454 info->category = _("AudioUnit MusicEffects");
2456 case kAudioUnitType_Effect:
2457 info->category = _("AudioUnit Effects");
2459 case kAudioUnitType_Mixer:
2460 info->category = _("AudioUnit Mixers");
2462 case kAudioUnitType_Generator:
2463 info->category = _("AudioUnit Generators");
2466 info->category = _("AudioUnit (Unknown)");
2470 au_blacklist(CFStringRefToStdString(itemName));
2471 AUPluginInfo::get_names (temp, info->name, info->creator);
2472 ARDOUR::PluginScanMessage(_("AU"), info->name, false);
2473 au_crashlog(string_compose("Plugin: %1", info->name));
2475 info->type = ARDOUR::AudioUnit;
2476 info->unique_id = stringify_descriptor (*info->descriptor);
2478 /* XXX not sure of the best way to handle plugin versioning yet
2481 CAComponent cacomp (*info->descriptor);
2483 if (cacomp.GetResourceVersion (info->version) != noErr) {
2487 if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
2489 /* here we have to map apple's wildcard system to a simple pair
2490 of values. in ::can_do() we use the whole system, but here
2491 we need a single pair of values. XXX probably means we should
2492 remove any use of these values.
2494 for now, if the plugin provides a wildcard, treat it as 1. we really
2495 don't care much, because whether we can handle an i/o configuration
2496 depends upon ::can_support_io_configuration(), not these counts.
2498 they exist because other parts of ardour try to present i/o configuration
2499 info to the user, which should perhaps be revisited.
2502 int32_t possible_in = info->cache.io_configs.front().first;
2503 int32_t possible_out = info->cache.io_configs.front().second;
2505 if (possible_in > 0) {
2506 info->n_inputs.set (DataType::AUDIO, possible_in);
2508 info->n_inputs.set (DataType::AUDIO, 1);
2511 if (possible_out > 0) {
2512 info->n_outputs.set (DataType::AUDIO, possible_out);
2514 info->n_outputs.set (DataType::AUDIO, 1);
2517 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
2518 info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
2520 plugs.push_back (info);
2523 error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
2526 au_unblacklist(CFStringRefToStdString(itemName));
2527 au_crashlog("Success.");
2528 comp = FindNextComponent (comp, &desc);
2529 if (itemName != NULL) CFRelease(itemName); itemName = NULL;
2531 au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
2535 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
2538 AUPluginCachedInfo& cinfo,
2539 const std::string& name)
2544 /* concatenate unique ID with version to provide a key for cached info lookup.
2545 this ensures we don't get stale information, or should if plugin developers
2546 follow Apple "guidelines".
2549 snprintf (buf, sizeof (buf), "%u", (uint32_t) version);
2554 CachedInfoMap::iterator cim = cached_info.find (id);
2556 if (cim != cached_info.end()) {
2557 cinfo = cim->second;
2562 AUChannelInfo* channel_info;
2566 ARDOUR::BootMessage (string_compose (_("Checking AudioUnit: %1"), name));
2570 if (CAAudioUnit::Open (comp, unit) != noErr) {
2576 warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
2581 DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
2582 if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
2588 /* no explicit info available, so default to 1in/1out */
2590 /* XXX this is wrong. we should be indicating wildcard values */
2592 cinfo.io_configs.push_back (pair<int,int> (-1, -1));
2596 /* store each configuration */
2598 for (uint32_t n = 0; n < cnt; ++n) {
2599 cinfo.io_configs.push_back (pair<int,int> (channel_info[n].inChannels,
2600 channel_info[n].outChannels));
2603 free (channel_info);
2606 add_cached_info (id, cinfo);
2607 save_cached_info ();
2613 AUPluginInfo::add_cached_info (const std::string& id, AUPluginCachedInfo& cinfo)
2615 cached_info[id] = cinfo;
2618 #define AU_CACHE_VERSION "2.0"
2621 AUPluginInfo::save_cached_info ()
2625 node = new XMLNode (X_("AudioUnitPluginCache"));
2626 node->add_property( "version", AU_CACHE_VERSION );
2628 for (map<string,AUPluginCachedInfo>::iterator i = cached_info.begin(); i != cached_info.end(); ++i) {
2629 XMLNode* parent = new XMLNode (X_("plugin"));
2630 parent->add_property ("id", i->first);
2631 node->add_child_nocopy (*parent);
2633 for (vector<pair<int, int> >::iterator j = i->second.io_configs.begin(); j != i->second.io_configs.end(); ++j) {
2635 XMLNode* child = new XMLNode (X_("io"));
2638 snprintf (buf, sizeof (buf), "%d", j->first);
2639 child->add_property (X_("in"), buf);
2640 snprintf (buf, sizeof (buf), "%d", j->second);
2641 child->add_property (X_("out"), buf);
2642 parent->add_child_nocopy (*child);
2647 Glib::ustring path = au_cache_path ();
2650 tree.set_root (node);
2652 if (!tree.write (path)) {
2653 error << string_compose (_("could not save AU cache to %1"), path) << endmsg;
2654 g_unlink (path.c_str());
2659 AUPluginInfo::load_cached_info ()
2661 Glib::ustring path = au_cache_path ();
2664 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
2668 if ( !tree.read (path) ) {
2669 error << "au_cache is not a valid XML file. AU plugins will be re-scanned" << endmsg;
2673 const XMLNode* root (tree.root());
2675 if (root->name() != X_("AudioUnitPluginCache")) {
2679 //initial version has incorrectly stored i/o info, and/or garbage chars.
2680 const XMLProperty* version = root->property(X_("version"));
2681 if (! ((version != NULL) && (version->value() == X_(AU_CACHE_VERSION)))) {
2682 error << "au_cache is not correct version. AU plugins will be re-scanned" << endmsg;
2686 cached_info.clear ();
2688 const XMLNodeList children = root->children();
2690 for (XMLNodeConstIterator iter = children.begin(); iter != children.end(); ++iter) {
2692 const XMLNode* child = *iter;
2694 if (child->name() == X_("plugin")) {
2696 const XMLNode* gchild;
2697 const XMLNodeList gchildren = child->children();
2698 const XMLProperty* prop = child->property (X_("id"));
2704 string id = prop->value();
2708 string::size_type slash = id.find_last_of ('/');
2710 if (slash == string::npos) {
2714 version = id.substr (slash);
2715 id = id.substr (0, slash);
2716 fixed = AUPlugin::maybe_fix_broken_au_id (id);
2718 if (fixed.empty()) {
2719 error << string_compose (_("Your AudioUnit configuration cache contains an AU plugin whose ID cannot be understood - ignored (%1)"), id) << endmsg;
2726 AUPluginCachedInfo cinfo;
2728 for (XMLNodeConstIterator giter = gchildren.begin(); giter != gchildren.end(); giter++) {
2732 if (gchild->name() == X_("io")) {
2736 const XMLProperty* iprop;
2737 const XMLProperty* oprop;
2739 if (((iprop = gchild->property (X_("in"))) != 0) &&
2740 ((oprop = gchild->property (X_("out"))) != 0)) {
2741 in = atoi (iprop->value());
2742 out = atoi (oprop->value());
2744 cinfo.io_configs.push_back (pair<int,int> (in, out));
2749 if (cinfo.io_configs.size()) {
2750 add_cached_info (id, cinfo);
2759 AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
2761 CFStringRef itemName = NULL;
2763 // Marc Poirier-style item name
2764 CAComponent auComponent (comp_desc);
2765 if (auComponent.IsValid()) {
2766 CAComponentDescription dummydesc;
2767 Handle nameHandle = NewHandle(sizeof(void*));
2768 if (nameHandle != NULL) {
2769 OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
2771 ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
2772 if (nameString != NULL) {
2773 itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
2776 DisposeHandle(nameHandle);
2780 // if Marc-style fails, do the original way
2781 if (itemName == NULL) {
2782 CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
2783 CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
2784 CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
2786 itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
2787 compTypeString, compManufacturerString, compSubTypeString);
2789 if (compTypeString != NULL)
2790 CFRelease(compTypeString);
2791 if (compSubTypeString != NULL)
2792 CFRelease(compSubTypeString);
2793 if (compManufacturerString != NULL)
2794 CFRelease(compManufacturerString);
2797 string str = CFStringRefToStdString(itemName);
2798 string::size_type colon = str.find (':');
2801 name = str.substr (colon+1);
2802 maker = str.substr (0, colon);
2803 strip_whitespace_edges (maker);
2804 strip_whitespace_edges (name);
2808 strip_whitespace_edges (name);
2813 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
2817 /* note: OSType is a compiler-implemenation-defined value,
2818 historically a 32 bit integer created with a multi-character
2819 constant such as 'abcd'. It is, fundamentally, an abomination.
2824 s << desc.SubType();
2832 AUPluginInfo::needs_midi_input ()
2834 return is_effect_with_midi_input () || is_instrument ();
2838 AUPluginInfo::is_effect () const
2840 return is_effect_without_midi_input() || is_effect_with_midi_input();
2844 AUPluginInfo::is_effect_without_midi_input () const
2846 return descriptor->IsAUFX();
2850 AUPluginInfo::is_effect_with_midi_input () const
2852 return descriptor->IsAUFM();
2856 AUPluginInfo::is_instrument () const
2858 return descriptor->IsMusicDevice();
2862 AUPlugin::set_info (PluginInfoPtr info)
2864 Plugin::set_info (info);
2866 AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
2867 _has_midi_input = pinfo->needs_midi_input ();
2868 _has_midi_output = false;
2872 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
2875 CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
2877 CFRunLoopRef run_loop = CFRunLoopGetCurrent();
2879 CFStringRef loop_mode = kCFRunLoopDefaultMode;
2881 if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
2885 _parameter_listener_arg = arg;
2891 AUPlugin::listen_to_parameter (uint32_t param_id)
2893 AudioUnitEvent event;
2895 if (!_parameter_listener || param_id >= descriptors.size()) {
2899 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2900 event.mArgument.mParameter.mAudioUnit = unit->AU();
2901 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2902 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2903 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2905 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2909 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2910 event.mArgument.mParameter.mAudioUnit = unit->AU();
2911 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2912 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2913 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2915 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2919 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2920 event.mArgument.mParameter.mAudioUnit = unit->AU();
2921 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2922 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2923 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2925 if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2933 AUPlugin::end_listen_to_parameter (uint32_t param_id)
2935 AudioUnitEvent event;
2937 if (!_parameter_listener || param_id >= descriptors.size()) {
2941 event.mEventType = kAudioUnitEvent_ParameterValueChange;
2942 event.mArgument.mParameter.mAudioUnit = unit->AU();
2943 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2944 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2945 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2947 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2951 event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
2952 event.mArgument.mParameter.mAudioUnit = unit->AU();
2953 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2954 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2955 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2957 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2961 event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
2962 event.mArgument.mParameter.mAudioUnit = unit->AU();
2963 event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
2964 event.mArgument.mParameter.mScope = descriptors[param_id].scope;
2965 event.mArgument.mParameter.mElement = descriptors[param_id].element;
2967 if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
2975 AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
2977 ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
2981 AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
2983 ParameterMap::iterator i;
2985 if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
2989 switch (event->mEventType) {
2990 case kAudioUnitEvent_BeginParameterChangeGesture:
2991 StartTouch (i->second);
2993 case kAudioUnitEvent_EndParameterChangeGesture:
2994 EndTouch (i->second);
2996 case kAudioUnitEvent_ParameterValueChange:
2997 ParameterChanged (i->second, new_value);