abort if configuration fails
[ardour.git] / libs / ardour / audio_unit.cc
index 1a24977399e504d8c4a1ca8522b0c7f723d49f7f..bcc8c2c31044e70db8a2a16dc794303ad7855139 100644 (file)
 */
 
 #include <sstream>
+#include <fstream>
 #include <errno.h>
 #include <string.h>
 #include <math.h>
 #include <ctype.h>
 
+#include "pbd/gstdio_compat.h"
 #include "pbd/transmitter.h"
 #include "pbd/xml++.h"
 #include "pbd/convert.h"
 #include "pbd/whitespace.h"
-#include "pbd/pathscanner.h"
+#include "pbd/file_utils.h"
 #include "pbd/locale_guard.h"
 
 #include <glibmm/threads.h>
 #include <glibmm/fileutils.h>
 #include <glibmm/miscutils.h>
-#include <glib/gstdio.h>
 
 #include "ardour/ardour.h"
 #include "ardour/audioengine.h"
@@ -49,8 +50,8 @@
 #include "ardour/tempo.h"
 #include "ardour/utils.h"
 
-#include "appleutility/CAAudioUnit.h"
-#include "appleutility/CAAUParameter.h"
+#include "CAAudioUnit.h"
+#include "CAAUParameter.h"
 
 #include <CoreFoundation/CoreFoundation.h>
 #include <CoreServices/CoreServices.h>
 #include <Carbon/Carbon.h>
 #endif
 
+#ifdef COREAUDIO105
+#define ArdourComponent Component
+#define ArdourDescription ComponentDescription
+#define ArdourFindNext FindNextComponent
+#else
+#define ArdourComponent AudioComponent
+#define ArdourDescription AudioComponentDescription
+#define ArdourFindNext AudioComponentFindNext
+#endif
+
 #include "i18n.h"
 
 using namespace std;
@@ -71,6 +82,81 @@ AUPluginInfo::CachedInfoMap AUPluginInfo::cached_info;
 static string preset_search_path = "/Library/Audio/Presets:/Network/Library/Audio/Presets";
 static string preset_suffix = ".aupreset";
 static bool preset_search_path_initialized = false;
+FILE * AUPluginInfo::_crashlog_fd = NULL;
+bool AUPluginInfo::_scan_only = true;
+
+
+static void au_blacklist (std::string id)
+{
+       string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
+       FILE * blacklist_fd = NULL;
+       if (! (blacklist_fd = fopen(fn.c_str(), "a"))) {
+               PBD::error << "Cannot append to AU blacklist for '"<< id <<"'\n";
+               return;
+       }
+       assert(id.find("\n") == string::npos);
+       fprintf(blacklist_fd, "%s\n", id.c_str());
+       ::fclose(blacklist_fd);
+}
+
+static void au_unblacklist (std::string id)
+{
+       string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
+       if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
+               PBD::warning << "Expected Blacklist file does not exist.\n";
+               return;
+       }
+
+       std::string bl;
+       {
+               std::ifstream ifs(fn.c_str());
+               bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+       }
+
+       ::g_unlink (fn.c_str());
+
+       assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
+       assert(id.find("\n") == string::npos);
+
+       id += "\n"; // add separator
+       const size_t rpl = bl.find(id);
+       if (rpl != string::npos) {
+               bl.replace(rpl, id.size(), "");
+       }
+       if (bl.empty()) {
+               return;
+       }
+
+       FILE * blacklist_fd = NULL;
+       if (! (blacklist_fd = fopen(fn.c_str(), "w"))) {
+               PBD::error << "Cannot open AU blacklist.\n";
+               return;
+       }
+       fprintf(blacklist_fd, "%s", bl.c_str());
+       ::fclose(blacklist_fd);
+}
+
+static bool is_blacklisted (std::string id)
+{
+       string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_blacklist.txt");
+       if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
+               return false;
+       }
+       std::string bl;
+       std::ifstream ifs(fn.c_str());
+       bl.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+
+       assert(id.find("\n") == string::npos);
+
+       id += "\n"; // add separator
+       const size_t rpl = bl.find(id);
+       if (rpl != string::npos) {
+               return true;
+       }
+       return false;
+}
+
+
 
 static OSStatus
 _render_callback(void *userData,
@@ -263,8 +349,8 @@ get_preset_name_in_plist (CFPropertyListRef plist)
 //--------------------------------------------------------------------------
 // general implementation for ComponentDescriptionsMatch() and ComponentDescriptionsMatch_Loosely()
 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
-Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType);
-Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2, Boolean inIgnoreType)
+Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType);
+Boolean ComponentDescriptionsMatch_General(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2, Boolean inIgnoreType)
 {
        if ( (inComponentDescription1 == NULL) || (inComponentDescription2 == NULL) )
                return FALSE;
@@ -286,17 +372,21 @@ Boolean ComponentDescriptionsMatch_General(const ComponentDescription * inCompon
 //--------------------------------------------------------------------------
 // general implementation for ComponentAndDescriptionMatch() and ComponentAndDescriptionMatch_Loosely()
 // if inIgnoreType is true, then the type code is ignored in the ComponentDescriptions
-Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType);
-Boolean ComponentAndDescriptionMatch_General(Component inComponent, const ComponentDescription * inComponentDescription, Boolean inIgnoreType)
+Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType);
+Boolean ComponentAndDescriptionMatch_General(ArdourComponent inComponent, const ArdourDescription * inComponentDescription, Boolean inIgnoreType)
 {
        OSErr status;
-       ComponentDescription desc;
+       ArdourDescription desc;
 
        if ( (inComponent == NULL) || (inComponentDescription == NULL) )
                return FALSE;
 
        // get the ComponentDescription of the input Component
+#ifdef COREAUDIO105
        status = GetComponentInfo(inComponent, &desc, NULL, NULL, NULL);
+#else
+       status = AudioComponentGetDescription (inComponent, &desc);
+#endif
        if (status != noErr)
                return FALSE;
 
@@ -308,28 +398,28 @@ Boolean ComponentAndDescriptionMatch_General(Component inComponent, const Compon
 // determine if 2 ComponentDescriptions are basically equal
 // (by that, I mean that the important identifying values are compared,
 // but not the ComponentDescription flags)
-Boolean ComponentDescriptionsMatch(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
+Boolean ComponentDescriptionsMatch(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
 {
        return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, FALSE);
 }
 
 //--------------------------------------------------------------------------
 // determine if 2 ComponentDescriptions have matching sub-type and manufacturer codes
-Boolean ComponentDescriptionsMatch_Loose(const ComponentDescription * inComponentDescription1, const ComponentDescription * inComponentDescription2)
+Boolean ComponentDescriptionsMatch_Loose(const ArdourDescription * inComponentDescription1, const ArdourDescription * inComponentDescription2)
 {
        return ComponentDescriptionsMatch_General(inComponentDescription1, inComponentDescription2, TRUE);
 }
 
 //--------------------------------------------------------------------------
 // determine if a ComponentDescription basically matches that of a particular Component
-Boolean ComponentAndDescriptionMatch(Component inComponent, const ComponentDescription * inComponentDescription)
+Boolean ComponentAndDescriptionMatch(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
 {
        return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, FALSE);
 }
 
 //--------------------------------------------------------------------------
 // determine if a ComponentDescription matches only the sub-type and manufacturer codes of a particular Component
-Boolean ComponentAndDescriptionMatch_Loosely(Component inComponent, const ComponentDescription * inComponentDescription)
+Boolean ComponentAndDescriptionMatch_Loosely(ArdourComponent inComponent, const ArdourDescription * inComponentDescription)
 {
        return ComponentAndDescriptionMatch_General(inComponent, inComponentDescription, TRUE);
 }
@@ -347,6 +437,7 @@ AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAC
        , input_offset (0)
        , input_buffers (0)
        , frames_processed (0)
+       , audio_input_cnt (0)
        , _parameter_listener (0)
        , _parameter_listener_arg (0)
        , last_transport_rolling (false)
@@ -358,6 +449,7 @@ AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAC
                p += preset_search_path;
                preset_search_path = p;
                preset_search_path_initialized = true;
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
        }
 
        init ();
@@ -382,6 +474,9 @@ AUPlugin::AUPlugin (const AUPlugin& other)
 
 {
        init ();
+       for (size_t i = 0; i < descriptors.size(); ++i) {
+               set_parameter (i, other.get_parameter (i));
+       }
 }
 
 AUPlugin::~AUPlugin ()
@@ -390,7 +485,7 @@ AUPlugin::~AUPlugin ()
                AUListenerDispose (_parameter_listener);
                _parameter_listener = 0;
        }
-       
+
        if (unit) {
                DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
                unit->Uninitialize ();
@@ -432,6 +527,7 @@ AUPlugin::discover_factory_presets ()
 
                string name = CFStringRefToStdString (preset->presetName);
                factory_preset_map[name] = preset->presetNumber;
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Factory Preset: %1 > %2\n", name, preset->presetNumber));
        }
 
        CFRelease (presets);
@@ -441,6 +537,7 @@ void
 AUPlugin::init ()
 {
        OSErr err;
+       CFStringRef itemName;
 
        /* these keep track of *configured* channel set up,
           not potential set ups.
@@ -448,6 +545,24 @@ AUPlugin::init ()
 
        input_channels = -1;
        output_channels = -1;
+       {
+               CAComponentDescription temp;
+#ifdef COREAUDIO105
+               GetComponentInfo (comp.get()->Comp(), &temp, NULL, NULL, NULL);
+#else
+               AudioComponentGetDescription (comp.get()->Comp(), &temp);
+#endif
+               CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
+               CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
+               CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
+               itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
+                               compTypeString, compManufacturerString, compSubTypeString);
+               if (compTypeString != NULL) CFRelease(compTypeString);
+               if (compSubTypeString != NULL) CFRelease(compSubTypeString);
+               if (compManufacturerString != NULL) CFRelease(compManufacturerString);
+       }
+
+       au_blacklist(CFStringRefToStdString(itemName));
 
        try {
                DEBUG_TRACE (DEBUG::AudioUnits, "opening AudioUnit\n");
@@ -470,14 +585,14 @@ AUPlugin::init ()
        unit->GetElementCount (kAudioUnitScope_Output, output_elements);
 
        if (input_elements > 0) {
-               /* setup render callback: the plugin calls this to get input data 
+               /* setup render callback: the plugin calls this to get input data
                 */
-               
+
                AURenderCallbackStruct renderCallbackInfo;
-               
+
                renderCallbackInfo.inputProc = _render_callback;
                renderCallbackInfo.inputProcRefCon = this;
-               
+
                DEBUG_TRACE (DEBUG::AudioUnits, "set render callback in input scope\n");
                if ((err = unit->SetProperty (kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
                                              0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
@@ -513,6 +628,9 @@ AUPlugin::init ()
        discover_factory_presets ();
 
        // Plugin::setup_controls ();
+
+       au_unblacklist(CFStringRefToStdString(itemName));
+       if (itemName != NULL) CFRelease(itemName);
 }
 
 void
@@ -530,7 +648,7 @@ AUPlugin::discover_parameters ()
 
        for (uint32_t i = 0; i < sizeof (scopes) / sizeof (scopes[0]); ++i) {
 
-               AUParamInfo param_info (unit->AU(), false, false, scopes[i]);
+               AUParamInfo param_info (unit->AU(), false, /* include read only */ true, scopes[i]);
 
                for (uint32_t i = 0; i < param_info.NumParams(); ++i) {
 
@@ -541,9 +659,9 @@ AUPlugin::discover_parameters ()
                        const CAAUParameter* param = param_info.GetParamInfo (d.id);
                        const AudioUnitParameterInfo& info (param->ParamInfo());
 
-                       const int len = CFStringGetLength (param->GetName());;
+                       const int len = CFStringGetLength (param->GetName());
                        char local_buffer[len*2];
-                       Boolean good = CFStringGetCString(param->GetName(),local_buffer,len*2,kCFStringEncodingMacRoman);
+                       Boolean good = CFStringGetCString (param->GetName(), local_buffer ,len*2 , kCFStringEncodingUTF8);
                        if (!good) {
                                d.label = "???";
                        } else {
@@ -604,24 +722,33 @@ AUPlugin::discover_parameters ()
 
                        d.lower = info.minValue;
                        d.upper = info.maxValue;
-                       d.default_value = info.defaultValue;
+                       d.normal = info.defaultValue;
 
                        d.integer_step = (info.unit == kAudioUnitParameterUnit_Indexed);
                        d.toggled = (info.unit == kAudioUnitParameterUnit_Boolean) ||
                                (d.integer_step && ((d.upper - d.lower) == 1.0));
                        d.sr_dependent = (info.unit == kAudioUnitParameterUnit_SampleFrames);
-                       d.automatable = !d.toggled &&
+                       d.automatable = /* !d.toggled && -- ardour can automate toggles, can AU ? */
                                !(info.flags & kAudioUnitParameterFlag_NonRealTime) &&
                                (info.flags & kAudioUnitParameterFlag_IsWritable);
 
                        d.logarithmic = (info.flags & kAudioUnitParameterFlag_DisplayLogarithmic);
-                       d.unit = info.unit;
+                       d.au_unit = info.unit;
+                       switch (info.unit) {
+                       case kAudioUnitParameterUnit_Decibels:
+                               d.unit = ParameterDescriptor::DB;
+                               break;
+                       case kAudioUnitParameterUnit_MIDINoteNumber:
+                               d.unit = ParameterDescriptor::MIDI_NOTE;
+                               break;
+                       case kAudioUnitParameterUnit_Hertz:
+                               d.unit = ParameterDescriptor::HZ;
+                               break;
+                       }
 
-                       d.step = 1.0;
-                       d.smallstep = 0.1;
-                       d.largestep = 10.0;
                        d.min_unbound = 0; // lower is bound
                        d.max_unbound = 0; // upper is bound
+                       d.update_steps();
 
                        descriptors.push_back (d);
 
@@ -733,7 +860,7 @@ AUPlugin::maybe_fix_broken_au_id (const std::string& id)
 
        return s.str();
 
-  err:
+err:
        return string();
 }
 
@@ -759,7 +886,7 @@ float
 AUPlugin::default_value (uint32_t port)
 {
        if (port < descriptors.size()) {
-               return descriptors[port].default_value;
+               return descriptors[port].normal;
        }
 
        return 0;
@@ -797,7 +924,8 @@ AUPlugin::set_parameter (uint32_t which, float val)
        theEvent.mArgument.mParameter.mElement = d.element;
 
        DEBUG_TRACE (DEBUG::AudioUnits, "notify about parameter change\n");
-       AUEventListenerNotify (NULL, NULL, &theEvent);
+        /* Note the 1st argument, which means "Don't notify us about a change we made ourselves" */
+        AUEventListenerNotify (_parameter_listener, NULL, &theEvent);
 
        Plugin::set_parameter (which, val);
 }
@@ -904,15 +1032,18 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
 {
        AudioStreamBasicDescription streamFormat;
        bool was_initialized = initialized;
-       int32_t audio_in = in.n_audio();
        int32_t audio_out = out.n_audio();
+       if (audio_input_cnt > 0) {
+               in.set (DataType::AUDIO, audio_input_cnt);
+       }
+       int32_t audio_in = in.n_audio();
 
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("configure %1 for %2 in %3 out\n", name(), in, out));
 
        if (initialized) {
                //if we are already running with the requested i/o config, bail out here
                if ( (audio_in==input_channels) && (audio_out==output_channels) ) {
-                       return 0;
+                       return true;
                } else {
                        deactivate ();
                }
@@ -940,17 +1071,17 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
        streamFormat.mChannelsPerFrame = audio_in;
 
        if (set_input_format (streamFormat) != 0) {
-               return -1;
+               return false;
        }
 
        streamFormat.mChannelsPerFrame = audio_out;
 
        if (set_output_format (streamFormat) != 0) {
-               return -1;
+               return false;
        }
 
        /* reset plugin info to show currently configured state */
-       
+
        _info->n_inputs = in;
        _info->n_outputs = out;
 
@@ -958,7 +1089,7 @@ AUPlugin::configure_io (ChanCount in, ChanCount out)
                activate ();
        }
 
-       return 0;
+       return true;
 }
 
 ChanCount
@@ -966,11 +1097,11 @@ AUPlugin::input_streams() const
 {
        ChanCount c;
 
-       c.set (DataType::AUDIO, 1);
-       c.set (DataType::MIDI, 0);
 
        if (input_channels < 0) {
-               warning << string_compose (_("AUPlugin: %1 input_streams() called without any format set!"), name()) << endmsg;
+               // force PluginIoReConfigure -- see also commit msg e38eb06
+               c.set (DataType::AUDIO, 0);
+               c.set (DataType::MIDI, 0);
        } else {
                c.set (DataType::AUDIO, input_channels);
                c.set (DataType::MIDI, _has_midi_input ? 1 : 0);
@@ -985,11 +1116,10 @@ AUPlugin::output_streams() const
 {
        ChanCount c;
 
-       c.set (DataType::AUDIO, 1);
-       c.set (DataType::MIDI, 0);
-
        if (output_channels < 0) {
-               warning << string_compose (_("AUPlugin: %1 output_streams() called without any format set!"), name()) << endmsg;
+               // force PluginIoReConfigure - see also commit msg e38eb06
+               c.set (DataType::AUDIO, 0);
+               c.set (DataType::MIDI, 0);
        } else {
                c.set (DataType::AUDIO, output_channels);
                c.set (DataType::MIDI, _has_midi_output ? 1 : 0);
@@ -1018,7 +1148,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
 
        vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
 
-       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n", 
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations, looking for %3 in, %4 out\n",
                                                        name(), io_configs.size(), in, out));
 
        //Ardour expects the plugin to tell it the output
@@ -1026,7 +1156,37 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
        //configurations in most cases. so first lets see
        //if there's a configuration that keeps out==in
 
-       audio_out = audio_in;
+       if (in.n_midi() > 0 && audio_in == 0) {
+               audio_out = 2; // prefer stereo version if available.
+       } else {
+               audio_out = audio_in;
+       }
+
+       /* kAudioUnitProperty_SupportedNumChannels
+        * https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html#//apple_ref/doc/uid/TP40003278-CH12-SW20
+        *
+        * - both fields are -1
+        *   e.g. inChannels = -1 outChannels = -1
+        *    This is the default case. Any number of input and output channels, as long as the numbers match
+        *
+        * - one field is -1, the other field is positive
+        *   e.g. inChannels = -1 outChannels = 2
+        *    Any number of input channels, exactly two output channels
+        *
+        * - one field is -1, the other field is -2
+        *   e.g. inChannels = -1 outChannels = -2
+        *    Any number of input channels, any number of output channels
+        *
+        * - both fields have non-negative values
+        *   e.g. inChannels = 2 outChannels = 6
+        *    Exactly two input channels, exactly six output channels
+        *   e.g. inChannels = 0 outChannels = 2
+        *    No input channels, exactly two output channels (such as for an instrument unit with stereo output)
+        *
+        * - both fields have negative values, neither of which is â€“1 or â€“2
+        *   e.g. inChannels = -4 outChannels = -8
+        *    Up to four input channels and up to eight output channels
+        */
 
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
 
@@ -1034,7 +1194,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
                int32_t possible_out = i->second;
 
                if ((possible_in == audio_in) && (possible_out == audio_out)) {
-                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n", 
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: %1 in %2 out to match in %3 out %4\n",
                                                                        possible_in, possible_out,
                                                                        in, out));
 
@@ -1072,27 +1232,18 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
                                audio_out = 2;
                                found = true;
                        } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (0,-2) but might. 
-                                  any configuration possible, provide stereo output 
+                               /* plugins shouldn't really use (0,-2) but might.
+                                  any configuration possible, provide stereo output
                                */
                                audio_out = 2;
                                found = true;
                        } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs. 
-
-                                   Since Ardour can handle any configuration,
-                                   we have to somehow pick a number. 
-
-                                   We'll use the number of inputs
-                                   to the master bus, or 2 if there
-                                   is no master bus.
-                                */
-                                boost::shared_ptr<Route> master = _session.master_out();
-                                if (master) {
-                                        audio_out = master->input()->n_ports().n_audio();
-                                } else {
-                                        audio_out = 2;
-                                }
+                               /* explicitly variable number of outputs.
+                                *
+                                * We really need to ask the user in this case.
+                                * stereo will be correct in 99.9% of all cases.
+                                */
+                               audio_out = 2;
                                found = true;
                        } else {
                                /* exact number of outputs */
@@ -1131,7 +1282,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
                                audio_out = audio_in;
                                found = true;
                        } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (-2,-2) but might. 
+                               /* plugins shouldn't really use (-2,-2) but might.
                                   interpret as (-1,-1).
                                */
                                audio_out = audio_in;
@@ -1161,27 +1312,18 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
                                audio_out = 2;
                                found = true;
                        } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (<-2,-2) but might. 
-                                  interpret as (<-2,-1): any configuration possible, provide stereo output 
+                               /* plugins shouldn't really use (<-2,-2) but might.
+                                  interpret as (<-2,-1): any configuration possible, provide stereo output
                                */
                                audio_out = 2;
                                found = true;
                        } else if (possible_out < -2) {
-                               /* explicitly variable number of outputs. 
-
-                                   Since Ardour can handle any configuration,
-                                   we have to somehow pick a number. 
-
-                                   We'll use the number of inputs
-                                   to the master bus, or 2 if there
-                                   is no master bus.
-                                */
-                                boost::shared_ptr<Route> master = _session.master_out();
-                                if (master) {
-                                        audio_out = master->input()->n_ports().n_audio();
-                                } else {
-                                        audio_out = 2;
-                                }
+                               /* explicitly variable number of outputs.
+                                *
+                                * We really need to ask the user in this case.
+                                * stereo will be correct in 99.9% of all cases.
+                                */
+                               audio_out = 2;
                                found = true;
                        } else {
                                /* exact number of outputs */
@@ -1199,8 +1341,8 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
                                audio_out = 2;
                                found = true;
                        } else if (possible_out == -2) {
-                               /* plugins shouldn't really use (>0,-2) but might. 
-                                  interpret as (>0,-1): 
+                               /* plugins shouldn't really use (>0,-2) but might.
+                                  interpret as (>0,-1):
                                   any output configuration possible, provide stereo output
                                */
                                audio_out = 2;
@@ -1217,21 +1359,25 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out)
                }
 
                if (found) {
+                       if (possible_in < -2 && audio_in == 0) {
+                               // input-port count cannot be zero, use as many ports
+                               // as outputs, but at most abs(possible_in)
+                               audio_input_cnt = max (1, min (audio_out, -possible_in));
+                       }
                        break;
                }
 
        }
 
        if (found) {
+               out.set (DataType::MIDI, 0); /// XXX
+               out.set (DataType::AUDIO, audio_out);
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
        } else {
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tFAIL: no io configs match %1\n", in));
                return false;
        }
 
-       out.set (DataType::MIDI, 0);
-       out.set (DataType::AUDIO, audio_out);
-
        return true;
 }
 
@@ -1294,7 +1440,7 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags*,
        /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
 
        // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
-        // name(), inNumberFrames, ioData->mNumberBuffers));
+       // name(), inNumberFrames, ioData->mNumberBuffers));
 
        if (input_maxbuf == 0) {
                error << _("AUPlugin: render callback called illegally!") << endmsg;
@@ -1307,9 +1453,9 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                ioData->mBuffers[i].mDataByteSize = sizeof (Sample) * inNumberFrames;
 
                /* we don't use the channel mapping because audiounits are
-                  never replicated. one plugin instance uses all channels/buffers
-                  passed to PluginInsert::connect_and_run()
-               */
+                * never replicated. one plugin instance uses all channels/buffers
+                * passed to PluginInsert::connect_and_run()
+                */
 
                ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
        }
@@ -1334,12 +1480,12 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
        }
 
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 in %2 out %3 MIDI %4 bufs %5 (available %6)\n",
-                                                       name(), input_channels, output_channels, _has_midi_input,
-                                                       bufs.count(), bufs.available()));
+                               name(), input_channels, output_channels, _has_midi_input,
+                               bufs.count(), bufs.available()));
 
        /* the apparent number of buffers matches our input configuration, but we know that the bufferset
           has the capacity to handle our outputs.
-       */
+          */
 
        assert (bufs.available() >= ChanCount (DataType::AUDIO, output_channels));
 
@@ -1354,12 +1500,12 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                buffers->mBuffers[i].mNumberChannels = 1;
                buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
                /* setting this to 0 indicates to the AU that it can provide buffers here
-                  if necessary. if it can process in-place, it will use the buffers provided
-                  as input by ::render_callback() above. 
-                   
-                   a non-null values tells the plugin to render into the buffer pointed
-                   at by the value.
-               */
+                * if necessary. if it can process in-place, it will use the buffers provided
+                * as input by ::render_callback() above.
+                *
+                * a non-null values tells the plugin to render into the buffer pointed
+                * at by the value.
+                */
                buffers->mBuffers[i].mData = 0;
        }
 
@@ -1368,14 +1514,14 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                uint32_t nmidi = bufs.count().n_midi();
 
                for (uint32_t i = 0; i < nmidi; ++i) {
-                       
+
                        /* one MIDI port/buffer only */
-                       
+
                        MidiBuffer& m = bufs.get_midi (i);
-                       
+
                        for (MidiBuffer::iterator i = m.begin(); i != m.end(); ++i) {
                                Evoral::MIDIEvent<framepos_t> ev (*i);
-                               
+
                                if (ev.is_channel_event()) {
                                        const uint8_t* b = ev.buffer();
                                        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: MIDI event %2\n", name(), ev));
@@ -1387,14 +1533,14 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                }
        }
 
-       /* does this really mean anything ? 
-        */
+       /* does this really mean anything ?
+       */
 
        ts.mSampleTime = frames_processed;
        ts.mFlags = kAudioTimeStampSampleTimeValid;
 
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 render flags=%2 time=%3 nframes=%4 buffers=%5\n",
-                                                        name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
+                               name(), flags, frames_processed, nframes, buffers->mNumberBuffers));
 
        if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
 
@@ -1402,7 +1548,7 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                frames_processed += nframes;
 
                DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
-                                                               name(), buffers->mNumberBuffers, output_channels));
+                                       name(), buffers->mNumberBuffers, output_channels));
 
                int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
                int32_t i;
@@ -1411,14 +1557,14 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                        Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
                        if (expected_buffer_address != buffers->mBuffers[i].mData) {
                                /* plugin provided its own buffer for output so copy it back to where we want it
-                                */
+                               */
                                memcpy (expected_buffer_address, buffers->mBuffers[i].mData, nframes * sizeof (Sample));
                        }
                }
 
                /* now silence any buffers that were passed in but the that the plugin
-                  did not fill/touch/use.
-               */
+                * did not fill/touch/use.
+                */
 
                for (;i < output_channels; ++i) {
                        memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
@@ -1496,7 +1642,7 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
                        /* on the beat */
                        *outDeltaSampleOffsetToNextBeat = 0;
                } else {
-                       *outDeltaSampleOffsetToNextBeat = (UInt32) 
+                       *outDeltaSampleOffsetToNextBeat = (UInt32)
                                floor (((Timecode::BBT_Time::ticks_per_beat - bbt.ticks)/Timecode::BBT_Time::ticks_per_beat) * // fraction of a beat to next beat
                                       metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
                }
@@ -1652,27 +1798,42 @@ AUPlugin::parameter_is_audio (uint32_t) const
 }
 
 bool
-AUPlugin::parameter_is_control (uint32_t) const
+AUPlugin::parameter_is_control (uint32_t param) const
 {
-       return true;
+       assert(param < descriptors.size());
+       if (descriptors[param].automatable) {
+               /* corrently ardour expects all controls to be automatable
+                * IOW ardour GUI elements mandate an Evoral::Parameter
+                * for all input+control ports.
+                */
+               return true;
+       }
+       return false;
 }
 
 bool
-AUPlugin::parameter_is_input (uint32_t) const
+AUPlugin::parameter_is_input (uint32_t param) const
 {
-       return false;
+       /* AU params that are both readable and writeable,
+        * are listed in kAudioUnitScope_Global
+        */
+       return (descriptors[param].scope == kAudioUnitScope_Input || descriptors[param].scope == kAudioUnitScope_Global);
 }
 
 bool
-AUPlugin::parameter_is_output (uint32_t) const
+AUPlugin::parameter_is_output (uint32_t param) const
 {
-       return false;
+       assert(param < descriptors.size());
+       // TODO check if ardour properly handles ports
+       // that report is_input + is_output == true
+       // -> add || descriptors[param].scope == kAudioUnitScope_Global
+       return (descriptors[param].scope == kAudioUnitScope_Output);
 }
 
 void
 AUPlugin::add_state (XMLNode* root) const
 {
-       LocaleGuard lg (X_("POSIX"));
+       LocaleGuard lg (X_("C"));
        CFDataRef xmlData;
        CFPropertyListRef propertyList;
 
@@ -1711,7 +1872,7 @@ AUPlugin::set_state(const XMLNode& node, int version)
 {
        int ret = -1;
        CFPropertyListRef propertyList;
-       LocaleGuard lg (X_("POSIX"));
+       LocaleGuard lg (X_("C"));
 
        if (node.name() != state_node_name()) {
                error << _("Bad node sent to AUPlugin::set_state") << endmsg;
@@ -1815,7 +1976,7 @@ AUPlugin::load_preset (PresetRecord r)
 }
 
 void
-AUPlugin::do_remove_preset (std::string) 
+AUPlugin::do_remove_preset (std::string)
 {
 }
 
@@ -1868,6 +2029,10 @@ AUPlugin::do_save_preset (string preset_name)
 
        CFRelease(propertyList);
 
+       user_preset_map[preset_name] = user_preset_path;;
+
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Saving Preset to %1\n", user_preset_path));
+
        return string ("file:///") + user_preset_path;
 }
 
@@ -1902,10 +2067,10 @@ GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDict
 }
 
 static OSStatus
-GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
+GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ArdourDescription * outComponentDescription)
 {
        CFDictionaryRef auStateDictionary;
-       ComponentDescription tempDesc = {0,0,0,0,0};
+       ArdourDescription tempDesc = {0,0,0,0,0};
        SInt32 versionValue;
        Boolean gotValue;
 
@@ -1959,16 +2124,16 @@ static bool au_preset_filter (const string& str, void* arg)
                   include "<manufacturer>/<plugin-name>" in their path.
                */
 
-               Plugin* p = (Plugin *) arg;
-               string match = p->maker();
+               AUPluginInfo* p = (AUPluginInfo *) arg;
+               string match = p->creator;
                match += '/';
-               match += p->name();
+               match += p->name;
 
                ret = str.find (match) != string::npos;
 
                if (ret == false) {
-                       string m = p->maker ();
-                       string n = p->name ();
+                       string m = p->creator;
+                       string n = p->name;
                        strip_whitespace_edges (m);
                        strip_whitespace_edges (n);
                        match = m;
@@ -1982,12 +2147,12 @@ static bool au_preset_filter (const string& str, void* arg)
        return ret;
 }
 
-bool
-check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
+static bool
+check_and_get_preset_name (ArdourComponent component, const string& pathstr, string& preset_name)
 {
        OSStatus status;
        CFPropertyListRef plist;
-       ComponentDescription presetDesc;
+       ArdourDescription presetDesc;
        bool ret = false;
 
        plist = load_property_list (pathstr);
@@ -2030,6 +2195,73 @@ check_and_get_preset_name (Component component, const string& pathstr, string& p
        return true;
 }
 
+
+static void
+#ifdef COREAUDIO105
+get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
+#else
+get_names (ArdourComponent& comp, std::string& name, std::string& maker)
+#endif
+{
+       CFStringRef itemName = NULL;
+       // Marc Poirier-style item name
+#ifdef COREAUDIO105
+       CAComponent auComponent (comp_desc);
+       if (auComponent.IsValid()) {
+               CAComponentDescription dummydesc;
+               Handle nameHandle = NewHandle(sizeof(void*));
+               if (nameHandle != NULL) {
+                       OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
+                       if (err == noErr) {
+                               ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
+                               if (nameString != NULL) {
+                                       itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
+                               }
+                       }
+                       DisposeHandle(nameHandle);
+               }
+       }
+#else
+       assert (comp);
+       AudioComponentCopyName (comp, &itemName);
+#endif
+
+       // if Marc-style fails, do the original way
+       if (itemName == NULL) {
+#ifndef COREAUDIO105
+               CAComponentDescription comp_desc;
+               AudioComponentGetDescription (comp, &comp_desc);
+#endif
+               CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
+               CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
+               CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
+
+               itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
+                               compTypeString, compManufacturerString, compSubTypeString);
+
+               if (compTypeString != NULL)
+                       CFRelease(compTypeString);
+               if (compSubTypeString != NULL)
+                       CFRelease(compSubTypeString);
+               if (compManufacturerString != NULL)
+                       CFRelease(compManufacturerString);
+       }
+
+       string str = CFStringRefToStdString(itemName);
+       string::size_type colon = str.find (':');
+
+       if (colon) {
+               name = str.substr (colon+1);
+               maker = str.substr (0, colon);
+               strip_whitespace_edges (maker);
+               strip_whitespace_edges (name);
+       } else {
+               name = str;
+               maker = "unknown";
+               strip_whitespace_edges (name);
+       }
+}
+
 std::string
 AUPlugin::current_preset() const
 {
@@ -2049,20 +2281,22 @@ AUPlugin::current_preset() const
 void
 AUPlugin::find_presets ()
 {
-       vector<string*>* preset_files;
-       PathScanner scanner;
+       vector<string> preset_files;
 
        user_preset_map.clear ();
 
-       preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
+       PluginInfoPtr nfo = get_info();
+       find_files_matching_filter (preset_files, preset_search_path, au_preset_filter,
+                       boost::dynamic_pointer_cast<AUPluginInfo> (nfo).get(),
+                       true, true, true);
 
-       if (!preset_files) {
-               return;
+       if (preset_files.empty()) {
+               DEBUG_TRACE (DEBUG::AudioUnits, "AU No Preset Files found for given plugin.\n");
        }
 
-       for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
+       for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
 
-               string path = *(*x);
+               string path = *x;
                string preset_name;
 
                /* make an initial guess at the preset name using the path */
@@ -2077,17 +2311,18 @@ AUPlugin::find_presets ()
 
                if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
                        user_preset_map[preset_name] = path;
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset File: %1 > %2\n", preset_name, path));
+               } else {
+                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU INVALID Preset: %1 > %2\n", preset_name, path));
                }
 
-               delete *x;
        }
 
-       delete preset_files;
-
        /* now fill the vector<string> with the names we have */
 
        for (UserPresetMap::iterator i = user_preset_map.begin(); i != user_preset_map.end(); ++i) {
                _presets.insert (make_pair (i->second, Plugin::PresetRecord (i->second, i->first)));
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding User Preset: %1 > %2\n", i->first, i->second));
        }
 
        /* add factory presets */
@@ -2095,7 +2330,8 @@ AUPlugin::find_presets ()
        for (FactoryPresetMap::iterator i = factory_preset_map.begin(); i != factory_preset_map.end(); ++i) {
                /* XXX: dubious */
                string const uri = string_compose ("%1", _presets.size ());
-               _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
+               _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, false)));
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Adding Factory Preset: %1 > %2\n", i->first, i->second));
        }
 }
 
@@ -2109,6 +2345,7 @@ AUPlugin::has_editor () const
 
 AUPluginInfo::AUPluginInfo (boost::shared_ptr<CAComponentDescription> d)
        : descriptor (d)
+       , version (0)
 {
        type = ARDOUR::AudioUnit;
 }
@@ -2146,20 +2383,111 @@ AUPluginInfo::load (Session& session)
        }
 }
 
+std::vector<Plugin::PresetRecord>
+AUPluginInfo::get_presets (bool user_only) const
+{
+       std::vector<Plugin::PresetRecord> p;
+       boost::shared_ptr<CAComponent> comp;
+#ifndef NO_PLUGIN_STATE
+       try {
+               comp = boost::shared_ptr<CAComponent>(new CAComponent(*descriptor));
+               if (!comp->IsValid()) {
+                       throw failed_constructor();
+               }
+       } catch (failed_constructor& err) {
+               return p;
+       }
+
+       // user presets
+
+       if (!preset_search_path_initialized) {
+               Glib::ustring p = Glib::get_home_dir();
+               p += "/Library/Audio/Presets:";
+               p += preset_search_path;
+               preset_search_path = p;
+               preset_search_path_initialized = true;
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose("AU Preset Path: %1\n", preset_search_path));
+       }
+
+       vector<string> preset_files;
+       find_files_matching_filter (preset_files, preset_search_path, au_preset_filter, const_cast<AUPluginInfo*>(this), true, true, true);
+
+       for (vector<string>::iterator x = preset_files.begin(); x != preset_files.end(); ++x) {
+               string path = *x;
+               string preset_name;
+               preset_name = Glib::path_get_basename (path);
+               preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
+               if (check_and_get_preset_name (comp.get()->Comp(), path, preset_name)) {
+                       p.push_back (Plugin::PresetRecord (path, preset_name));
+               }
+       }
+
+       if (user_only) {
+               return p;
+       }
+
+       // factory presets
+
+       CFArrayRef presets;
+       UInt32 dataSize;
+       Boolean isWritable;
+
+       boost::shared_ptr<CAAudioUnit> unit (new CAAudioUnit);
+       if (noErr != CAAudioUnit::Open (*(comp.get()), *unit)) {
+               return p;
+       }
+       if (noErr != unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) {
+               unit->Uninitialize ();
+               return p;
+       }
+       if (noErr != unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) {
+               unit->Uninitialize ();
+               return p;
+       }
+       if (!presets) {
+               unit->Uninitialize ();
+               return p;
+       }
+
+       CFIndex cnt = CFArrayGetCount (presets);
+       for (CFIndex i = 0; i < cnt; ++i) {
+               AUPreset* preset = (AUPreset*) CFArrayGetValueAtIndex (presets, i);
+               string const uri = string_compose ("%1", i);
+               string name = CFStringRefToStdString (preset->presetName);
+               p.push_back (Plugin::PresetRecord (uri, name, false));
+       }
+       CFRelease (presets);
+       unit->Uninitialize ();
+
+#endif // NO_PLUGIN_STATE
+       return p;
+}
+
 Glib::ustring
 AUPluginInfo::au_cache_path ()
 {
-       return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
+       return Glib::build_filename (ARDOUR::user_cache_directory(), "au_cache");
 }
 
 PluginInfoList*
-AUPluginInfo::discover ()
+AUPluginInfo::discover (bool scan_only)
 {
        XMLTree tree;
 
+       /* AU require a CAComponentDescription pointer provided by the OS.
+        * Ardour only caches port and i/o config. It can't just 'scan' without
+        * 'discovering' (like we do for VST).
+        *
+        * "Scan Only" means
+        * "Iterate over all plugins. skip the ones where there's no io-cache".
+        */
+       _scan_only = scan_only;
+
        if (!Glib::file_test (au_cache_path(), Glib::FILE_TEST_EXISTS)) {
                ARDOUR::BootMessage (_("Discovering AudioUnit plugins (could take some time ...)"));
        }
+       // create crash log file
+       au_start_crashlog ();
 
        PluginInfoList* plugs = new PluginInfoList;
 
@@ -2168,6 +2496,9 @@ AUPluginInfo::discover ()
        discover_generators (*plugs);
        discover_instruments (*plugs);
 
+       // all fine if we get here
+       au_remove_crashlog ();
+
        DEBUG_TRACE (DEBUG::PluginManager, string_compose ("AU: discovered %1 plugins\n", plugs->size()));
 
        return plugs;
@@ -2225,16 +2556,94 @@ AUPluginInfo::discover_instruments (PluginInfoList& plugs)
        discover_by_description (plugs, desc);
 }
 
+
+bool
+AUPluginInfo::au_get_crashlog (std::string &msg)
+{
+       string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
+       if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
+               return false;
+       }
+       std::ifstream ifs(fn.c_str());
+       msg.assign ((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+       au_remove_crashlog ();
+       return true;
+}
+
+void
+AUPluginInfo::au_start_crashlog ()
+{
+       string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
+       assert(!_crashlog_fd);
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Creating AU Log: %1\n", fn));
+       if (!(_crashlog_fd = fopen(fn.c_str(), "w"))) {
+               PBD::error << "Cannot create AU error-log" << fn << "\n";
+               cerr << "Cannot create AU error-log" << fn << "\n";
+       }
+}
+
+void
+AUPluginInfo::au_remove_crashlog ()
+{
+       if (_crashlog_fd) {
+               ::fclose(_crashlog_fd);
+               _crashlog_fd = NULL;
+       }
+       string fn = Glib::build_filename (ARDOUR::user_cache_directory(), "au_crashlog.txt");
+       ::g_unlink(fn.c_str());
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Remove AU Log: %1\n", fn));
+}
+
+
+void
+AUPluginInfo::au_crashlog (std::string msg)
+{
+       if (!_crashlog_fd) {
+               fprintf(stderr, "AU: %s\n", msg.c_str());
+       } else {
+               fprintf(_crashlog_fd, "AU: %s\n", msg.c_str());
+               ::fflush(_crashlog_fd);
+       }
+}
+
 void
 AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescription& desc)
 {
-       Component comp = 0;
+       ArdourComponent comp = 0;
+       au_crashlog(string_compose("Start AU discovery for Type: %1", (int)desc.componentType));
 
-       comp = FindNextComponent (NULL, &desc);
+       comp = ArdourFindNext (NULL, &desc);
 
        while (comp != NULL) {
                CAComponentDescription temp;
+#ifdef COREAUDIO105
                GetComponentInfo (comp, &temp, NULL, NULL, NULL);
+#else
+               AudioComponentGetDescription (comp, &temp);
+#endif
+               CFStringRef itemName = NULL;
+
+               {
+                       if (itemName != NULL) CFRelease(itemName);
+                       CFStringRef compTypeString = UTCreateStringForOSType(temp.componentType);
+                       CFStringRef compSubTypeString = UTCreateStringForOSType(temp.componentSubType);
+                       CFStringRef compManufacturerString = UTCreateStringForOSType(temp.componentManufacturer);
+                       itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
+                                       compTypeString, compManufacturerString, compSubTypeString);
+                       au_crashlog(string_compose("Scanning ID: %1", CFStringRefToStdString(itemName)));
+                       if (compTypeString != NULL)
+                               CFRelease(compTypeString);
+                       if (compSubTypeString != NULL)
+                               CFRelease(compSubTypeString);
+                       if (compManufacturerString != NULL)
+                               CFRelease(compManufacturerString);
+               }
+
+               if (is_blacklisted(CFStringRefToStdString(itemName))) {
+                       info << string_compose (_("Skipped blacklisted AU plugin %1 "), CFStringRefToStdString(itemName)) << endmsg;
+                       comp = ArdourFindNext (comp, &desc);
+                       continue;
+               }
 
                AUPluginInfoPtr info (new AUPluginInfo
                                      (boost::shared_ptr<CAComponentDescription> (new CAComponentDescription(temp))));
@@ -2252,6 +2661,7 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                case kAudioUnitType_Panner:
                case kAudioUnitType_OfflineEffect:
                case kAudioUnitType_FormatConverter:
+                       comp = ArdourFindNext (comp, &desc);
                        continue;
 
                case kAudioUnitType_Output:
@@ -2277,7 +2687,14 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                        break;
                }
 
-               AUPluginInfo::get_names (temp, info->name, info->creator);
+               au_blacklist(CFStringRefToStdString(itemName));
+#ifdef COREAUDIO105
+               get_names (temp, info->name, info->creator);
+#else
+               get_names (comp, info->name, info->creator);
+#endif
+               ARDOUR::PluginScanMessage(_("AU"), info->name, false);
+               au_crashlog(string_compose("Plugin: %1", info->name));
 
                info->type = ARDOUR::AudioUnit;
                info->unique_id = stringify_descriptor (*info->descriptor);
@@ -2287,12 +2704,18 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
 
                CAComponent cacomp (*info->descriptor);
 
-               if (cacomp.GetResourceVersion (info->version) != noErr) {
+#ifdef COREAUDIO105
+               if (cacomp.GetResourceVersion (info->version) != noErr)
+#else
+               if (cacomp.GetVersion (info->version) != noErr)
+#endif
+               {
                        info->version = 0;
                }
 
-               if (cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name)) {
+               const int rv = cached_io_configuration (info->unique_id, info->version, cacomp, info->cache, info->name);
 
+               if (rv == 0) {
                        /* here we have to map apple's wildcard system to a simple pair
                           of values. in ::can_do() we use the whole system, but here
                           we need a single pair of values. XXX probably means we should
@@ -2308,7 +2731,7 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
 
                        int32_t possible_in = info->cache.io_configs.front().first;
                        int32_t possible_out = info->cache.io_configs.front().second;
-                       
+
                        if (possible_in > 0) {
                                info->n_inputs.set (DataType::AUDIO, possible_in);
                        } else {
@@ -2326,15 +2749,20 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
 
                        plugs.push_back (info);
 
-               } else {
+               }
+               else if (rv == -1) {
                        error << string_compose (_("Cannot get I/O configuration info for AU %1"), info->name) << endmsg;
                }
 
-               comp = FindNextComponent (comp, &desc);
+               au_unblacklist(CFStringRefToStdString(itemName));
+               au_crashlog("Success.");
+               comp = ArdourFindNext (comp, &desc);
+               if (itemName != NULL) CFRelease(itemName); itemName = NULL;
        }
+       au_crashlog(string_compose("End AU discovery for Type: %1", (int)desc.componentType));
 }
 
-bool
+int
 AUPluginInfo::cached_io_configuration (const std::string& unique_id,
                                       UInt32 version,
                                       CAComponent& comp,
@@ -2358,7 +2786,12 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
 
        if (cim != cached_info.end()) {
                cinfo = cim->second;
-               return true;
+               return 0;
+       }
+
+       if (_scan_only) {
+               PBD::info << string_compose (_("Skipping AU %1 (not indexed. Discover new plugins to add)"), name) << endmsg;
+               return 1;
        }
 
        CAAudioUnit unit;
@@ -2371,19 +2804,19 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
        try {
 
                if (CAAudioUnit::Open (comp, unit) != noErr) {
-                       return false;
+                       return -1;
                }
 
        } catch (...) {
 
                warning << string_compose (_("Could not load AU plugin %1 - ignored"), name) << endmsg;
-               return false;
+               return -1;
 
        }
 
        DEBUG_TRACE (DEBUG::AudioUnits, "get AU channel info\n");
        if ((ret = unit.GetChannelInfo (&channel_info, cnt)) < 0) {
-               return false;
+               return -1;
        }
 
        if (ret > 0) {
@@ -2409,7 +2842,7 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
        add_cached_info (id, cinfo);
        save_cached_info ();
 
-       return true;
+       return 0;
 }
 
 void
@@ -2558,59 +2991,6 @@ AUPluginInfo::load_cached_info ()
        return 0;
 }
 
-void
-AUPluginInfo::get_names (CAComponentDescription& comp_desc, std::string& name, std::string& maker)
-{
-       CFStringRef itemName = NULL;
-
-       // Marc Poirier-style item name
-       CAComponent auComponent (comp_desc);
-       if (auComponent.IsValid()) {
-               CAComponentDescription dummydesc;
-               Handle nameHandle = NewHandle(sizeof(void*));
-               if (nameHandle != NULL) {
-                       OSErr err = GetComponentInfo(auComponent.Comp(), &dummydesc, nameHandle, NULL, NULL);
-                       if (err == noErr) {
-                               ConstStr255Param nameString = (ConstStr255Param) (*nameHandle);
-                               if (nameString != NULL) {
-                                       itemName = CFStringCreateWithPascalString(kCFAllocatorDefault, nameString, CFStringGetSystemEncoding());
-                               }
-                       }
-                       DisposeHandle(nameHandle);
-               }
-       }
-
-       // if Marc-style fails, do the original way
-       if (itemName == NULL) {
-               CFStringRef compTypeString = UTCreateStringForOSType(comp_desc.componentType);
-               CFStringRef compSubTypeString = UTCreateStringForOSType(comp_desc.componentSubType);
-               CFStringRef compManufacturerString = UTCreateStringForOSType(comp_desc.componentManufacturer);
-
-               itemName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ - %@ - %@"),
-                       compTypeString, compManufacturerString, compSubTypeString);
-
-               if (compTypeString != NULL)
-                       CFRelease(compTypeString);
-               if (compSubTypeString != NULL)
-                       CFRelease(compSubTypeString);
-               if (compManufacturerString != NULL)
-                       CFRelease(compManufacturerString);
-       }
-
-       string str = CFStringRefToStdString(itemName);
-       string::size_type colon = str.find (':');
-
-       if (colon) {
-               name = str.substr (colon+1);
-               maker = str.substr (0, colon);
-               strip_whitespace_edges (maker);
-               strip_whitespace_edges (name);
-       } else {
-               name = str;
-               maker = "unknown";
-               strip_whitespace_edges (name);
-       }
-}
 
 std::string
 AUPluginInfo::stringify_descriptor (const CAComponentDescription& desc)
@@ -2665,7 +3045,7 @@ void
 AUPlugin::set_info (PluginInfoPtr info)
 {
        Plugin::set_info (info);
-       
+
        AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
        _has_midi_input = pinfo->needs_midi_input ();
        _has_midi_output = false;
@@ -2675,7 +3055,7 @@ int
 AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
 {
 #ifdef WITH_CARBON
-       CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop()); 
+       CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop());
 #else
        CFRunLoopRef run_loop = CFRunLoopGetCurrent();
 #endif
@@ -2707,7 +3087,7 @@ AUPlugin::listen_to_parameter (uint32_t param_id)
 
        if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
                return -1;
-       } 
+       }
 
        event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
        event.mArgument.mParameter.mAudioUnit = unit->AU();
@@ -2717,7 +3097,7 @@ AUPlugin::listen_to_parameter (uint32_t param_id)
 
        if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
                return -1;
-       } 
+       }
 
        event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
        event.mArgument.mParameter.mAudioUnit = unit->AU();
@@ -2727,7 +3107,7 @@ AUPlugin::listen_to_parameter (uint32_t param_id)
 
        if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
                return -1;
-       } 
+       }
 
        return 0;
 }
@@ -2749,7 +3129,7 @@ AUPlugin::end_listen_to_parameter (uint32_t param_id)
 
        if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
                return -1;
-       } 
+       }
 
        event.mEventType = kAudioUnitEvent_BeginParameterChangeGesture;
        event.mArgument.mParameter.mAudioUnit = unit->AU();
@@ -2759,7 +3139,7 @@ AUPlugin::end_listen_to_parameter (uint32_t param_id)
 
        if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
                return -1;
-       } 
+       }
 
        event.mEventType = kAudioUnitEvent_EndParameterChangeGesture;
        event.mArgument.mParameter.mAudioUnit = unit->AU();
@@ -2769,7 +3149,7 @@ AUPlugin::end_listen_to_parameter (uint32_t param_id)
 
        if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
                return -1;
-       } 
+       }
 
        return 0;
 }
@@ -2781,14 +3161,14 @@ AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent
 }
 
 void
-AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
+AUPlugin::parameter_change_listener (void* /*arg*/, void* src, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
 {
         ParameterMap::iterator i;
 
         if ((i = parameter_map.find (event->mArgument.mParameter.mParameterID)) == parameter_map.end()) {
                 return;
         }
-        
+
         switch (event->mEventType) {
         case kAudioUnitEvent_BeginParameterChangeGesture:
                 StartTouch (i->second);
@@ -2797,7 +3177,10 @@ AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUn
                 EndTouch (i->second);
                 break;
         case kAudioUnitEvent_ParameterValueChange:
-                ParameterChanged (i->second, new_value);
+                /* whenever we change a parameter, we request that we are NOT notified of the change, so anytime we arrive here, it
+                   means that something else (i.e. the plugin GUI) made the change.
+                */
+                ParameterChangedExternally (i->second, new_value);
                 break;
         default:
                 break;