set fader and plugin parameter automation curve default values - what else needs...
[ardour.git] / libs / ardour / audio_unit.cc
index 5440156ebb46ba4ef18e17519caf62824575796f..e02a00c28e9fc7be493e26221239632dead8b85f 100644 (file)
@@ -43,6 +43,7 @@
 #include "ardour/filesystem_paths.h"
 #include "ardour/io.h"
 #include "ardour/audio_unit.h"
+#include "ardour/route.h"
 #include "ardour/session.h"
 #include "ardour/tempo.h"
 #include "ardour/utils.h"
@@ -54,6 +55,9 @@
 #include <CoreServices/CoreServices.h>
 #include <AudioUnit/AudioUnit.h>
 #include <AudioToolbox/AudioUnitUtilities.h>
+#ifdef WITH_CARBON
+#include <Carbon/Carbon.h>
+#endif
 
 #include "i18n.h"
 
@@ -345,10 +349,12 @@ AUPlugin::AUPlugin (AudioEngine& engine, Session& session, boost::shared_ptr<CAC
        , _current_block_size (0)
        , _requires_fixed_size_buffers (false)
        , buffers (0)
-       , current_maxbuf (0)
-       , current_offset (0)
-       , current_buffers (0)
+       , input_maxbuf (0)
+       , input_offset (0)
+       , input_buffers (0)
        , frames_processed (0)
+       , _parameter_listener (0)
+       , _parameter_listener_arg (0)
        , last_transport_rolling (false)
        , last_transport_speed (0.0)
 {
@@ -373,10 +379,12 @@ AUPlugin::AUPlugin (const AUPlugin& other)
        , _last_nframes (0)
        , _requires_fixed_size_buffers (false)
        , buffers (0)
-       , current_maxbuf (0)
-       , current_offset (0)
-       , current_buffers (0)
+       , input_maxbuf (0)
+       , input_offset (0)
+       , input_buffers (0)
        , frames_processed (0)
+       , _parameter_listener (0)
+       , _parameter_listener_arg (0)
 
 {
        init ();
@@ -384,6 +392,11 @@ AUPlugin::AUPlugin (const AUPlugin& other)
 
 AUPlugin::~AUPlugin ()
 {
+       if (_parameter_listener) {
+               AUListenerDispose (_parameter_listener);
+               _parameter_listener = 0;
+       }
+       
        if (unit) {
                DEBUG_TRACE (DEBUG::AudioUnits, "about to call uninitialize in plugin destructor\n");
                unit->Uninitialize ();
@@ -398,12 +411,19 @@ void
 AUPlugin::discover_factory_presets ()
 {
        CFArrayRef presets;
-       UInt32 dataSize = sizeof (presets);
+       UInt32 dataSize;
+       Boolean isWritable;
        OSStatus err;
 
-       DEBUG_TRACE (DEBUG::AudioUnits, "get property FactoryPresets in global scope\n");
+       if ((err = unit->GetPropertyInfo (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &dataSize, &isWritable)) != 0) {
+               DEBUG_TRACE (DEBUG::AudioUnits, "no factory presets for AU\n");
+               return;
+       }
+
+       assert (dataSize == sizeof (presets));
+
        if ((err = unit->GetProperty (kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, (void*) &presets, &dataSize)) != 0) {
-               cerr << "cannot get factory preset info: " << err << endl;
+               error << string_compose (_("cannot get factory preset info: errcode %1"), err) << endmsg;
                return;
        }
 
@@ -456,15 +476,18 @@ AUPlugin::init ()
        unit->GetElementCount (kAudioUnitScope_Output, output_elements);
 
        if (input_elements > 0) {
+               /* 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) {
-                       cerr << "cannot install render callback (err = " << err << ')' << endl;
+                                             0, (void*) &renderCallbackInfo, sizeof(renderCallbackInfo))) != 0) {
+                       error << string_compose (_("cannot install render callback (err = %1)"), err) << endmsg;
                        throw failed_constructor();
                }
        }
@@ -491,6 +514,7 @@ AUPlugin::init ()
                throw failed_constructor();
        }
 
+       create_parameter_listener (AUPlugin::_parameter_change_listener, this, 0.05);
        discover_parameters ();
        discover_factory_presets ();
 
@@ -606,6 +630,10 @@ AUPlugin::discover_parameters ()
                        d.max_unbound = 0; // upper is bound
 
                        descriptors.push_back (d);
+
+                       uint32_t last_param = descriptors.size() - 1;
+                       parameter_map.insert (pair<uint32_t,uint32_t> (d.id, last_param));
+                       listen_to_parameter (last_param);
                }
        }
 }
@@ -656,7 +684,6 @@ AUPlugin::maybe_fix_broken_au_id (const std::string& id)
 
                                /* too close to the end for \xNN parsing: treat as literal characters */
 
-                               cerr << "Parse " << cstr << " as a literal \\" << endl;
                                nascent[in] = *cstr;
                                ++cstr;
                                ++in;
@@ -675,7 +702,6 @@ AUPlugin::maybe_fix_broken_au_id (const std::string& id)
                                } else {
 
                                        /* treat as literal characters */
-                                       cerr << "Parse " << cstr << " as a literal \\" << endl;
                                        nascent[in] = *cstr;
                                        ++cstr;
                                        ++in;
@@ -784,7 +810,7 @@ AUPlugin::get_parameter (uint32_t which) const
        float val = 0.0;
        if (which < descriptors.size()) {
                const AUParameterDescriptor& d (descriptors[which]);
-               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
+               // DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("get value of parameter %1 in scope %2 element %3\n", d.id, d.scope, d.element));
                unit->GetParameter(d.id, d.scope, d.element, val);
        }
        return val;
@@ -862,7 +888,7 @@ AUPlugin::set_block_size (pframes_t nframes)
        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("set MaximumFramesPerSlice in global scope to %1\n", numFrames));
        if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
                                      0, &numFrames, sizeof (numFrames))) != noErr) {
-               cerr << "cannot set max frames (err = " << err << ')' << endl;
+               error << string_compose (_("AU: cannot set max frames (err = %1)"), err) << endmsg;
                return -1;
        }
 
@@ -977,12 +1003,11 @@ AUPlugin::output_streams() const
 bool
 AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) const
 {
-       // XXX as of May 13th 2008, AU plugin support returns a count of either 1 or -1. We never
-       // attempt to multiply-instantiate plugins to meet io configurations.
+       // Note: We never attempt to multiply-instantiate plugins to meet io configurations.
 
        int32_t audio_in = in.n_audio();
        int32_t audio_out;
-       int32_t plugcnt = -1;
+       bool found = false;
        AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
 
        /* lets check MIDI first */
@@ -995,27 +1020,37 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
 
        vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
 
-       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 has %2 IO configurations\n", name(), io_configs.size()));
+       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 configuration
-       //but AU plugins can have multiple I/O configurations
-       //in most cases (since we don't allow special routing like sidechains in A2, we want to preserve the number of streams
-       //so first lets see if there's a configuration that keeps out==in
+       //Ardour expects the plugin to tell it the output
+       //configuration but AU plugins can have multiple I/O
+       //configurations in most cases. so first lets see
+       //if there's a configuration that keeps out==in
 
        audio_out = audio_in;
 
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
+
                int32_t possible_in = i->first;
                int32_t possible_out = i->second;
 
-               if (possible_in == audio_in && possible_out == audio_out) {
-                       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
+               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", 
+                                                                       possible_in, possible_out,
+                                                                       in, out));
+
+                       out.set (DataType::MIDI, 0);
+                       out.set (DataType::AUDIO, audio_out);
+
                        return 1;
                }
        }
 
        /* now allow potentially "imprecise" matches */
+
        audio_out = -1;
+
        for (vector<pair<int,int> >::iterator i = io_configs.begin(); i != io_configs.end(); ++i) {
 
                int32_t possible_in = i->first;
@@ -1025,6 +1060,7 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
 
                if (possible_out == 0) {
                        warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
+                       /* XXX surely this is just a send? (e.g. AUNetSend) */
                        continue;
                }
 
@@ -1034,21 +1070,36 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                        */
 
                        if (possible_out == -1) {
-                               /* out much match in (UNLIKELY!!) */
-                               audio_out = audio_in;
-                               plugcnt = 1;
+                               /* any configuration possible, provide stereo output */
+                               audio_out = 2;
+                               found = true;
                        } else if (possible_out == -2) {
-                               /* any configuration possible, pick matching */
-                               audio_out = audio_in;
-                               plugcnt = 1;
+                               /* 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) {
-                               /* explicit variable number of outputs, pick maximum */
-                               audio_out = -possible_out;
-                               plugcnt = 1;
+                               /* 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;
+                                }
+                               found = true;
                        } else {
                                /* exact number of outputs */
                                audio_out = possible_out;
-                               plugcnt = 1;
+                               found = true;
                        }
                }
 
@@ -1059,19 +1110,19 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                        if (possible_out == -1) {
                                /* out much match in */
                                audio_out = audio_in;
-                               plugcnt = 1;
+                               found = true;
                        } else if (possible_out == -2) {
                                /* any configuration possible, pick matching */
                                audio_out = audio_in;
-                               plugcnt = 1;
+                               found = true;
                        } else if (possible_out < -2) {
-                               /* explicit variable number of outputs, pick maximum */
+                               /* explicitly variable number of outputs, pick maximum */
                                audio_out = -possible_out;
-                               plugcnt = 1;
+                               found = true;
                        } else {
                                /* exact number of outputs */
                                audio_out = possible_out;
-                               plugcnt = 1;
+                               found = true;
                        }
                }
 
@@ -1080,19 +1131,21 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
                        if (possible_out == -1) {
                                /* any configuration possible, pick matching */
                                audio_out = audio_in;
-                               plugcnt = 1;
+                               found = true;
                        } else if (possible_out == -2) {
-                               error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
-                                     << endmsg;
-                               plugcnt = -1;
+                               /* plugins shouldn't really use (-2,-2) but might. 
+                                  interpret as (-1,-1).
+                               */
+                               audio_out = audio_in;
+                               found = true;
                        } else if (possible_out < -2) {
-                               /* explicit variable number of outputs, pick maximum */
+                               /* explicitly variable number of outputs, pick maximum */
                                audio_out = -possible_out;
-                               plugcnt = 1;
+                               found = true;
                        } else {
                                /* exact number of outputs */
                                audio_out = possible_out;
-                               plugcnt = 1;
+                               found = true;
                        }
                }
 
@@ -1102,67 +1155,86 @@ AUPlugin::can_support_io_configuration (const ChanCount& in, ChanCount& out) con
 
                        if (audio_in > -possible_in) {
                                /* request is too large */
-                               plugcnt = -1;
                        }
 
+
                        if (possible_out == -1) {
-                               /* out must match in */
-                               audio_out = audio_in;
-                               plugcnt = 1;
+                               /* any output configuration possible, provide stereo out */
+                               audio_out = 2;
+                               found = true;
                        } else if (possible_out == -2) {
-                               error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
-                                     << endmsg;
-                               plugcnt = -1;
+                               /* 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) {
-                               /* explicit variable number of outputs, pick maximum */
-                               audio_out = -possible_out;
-                               plugcnt = 1;
+                               /* 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;
+                                }
+                               found = true;
                        } else {
                                /* exact number of outputs */
                                audio_out = possible_out;
-                               plugcnt = 1;
+                               found = true;
                        }
                }
 
-               if (possible_in == audio_in) {
+               if (possible_in && (possible_in == audio_in)) {
 
                        /* exact number of inputs ... must match obviously */
 
                        if (possible_out == -1) {
-                               /* out must match in */
-                               audio_out = audio_in;
-                               plugcnt = 1;
+                               /* any output configuration possible, provide stereo output */
+                               audio_out = 2;
+                               found = true;
                        } else if (possible_out == -2) {
-                               /* any output configuration, pick matching */
-                               audio_out = audio_in;
-                               plugcnt = -1;
+                               /* plugins shouldn't really use (>0,-2) but might. 
+                                  interpret as (>0,-1): 
+                                  any output configuration possible, provide stereo output
+                               */
+                               audio_out = 2;
+                               found = true;
                        } else if (possible_out < -2) {
-                               /* explicit variable number of outputs, pick maximum */
+                               /* explicitly variable number of outputs, pick maximum */
                                audio_out = -possible_out;
-                               plugcnt = 1;
+                               found = true;
                        } else {
                                /* exact number of outputs */
                                audio_out = possible_out;
-                               plugcnt = 1;
+                               found = true;
                        }
                }
 
-               if (plugcnt == 1) {
+               if (found) {
                        break;
                }
 
        }
 
-       if (plugcnt > 0) {
-               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2 plugcnt %3\n", in, out, plugcnt));
+       if (found) {
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\tCHOSEN: in %1 out %2\n", in, out));
        } else {
-               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("\FAIL: no io configs match %1\n", in));
+               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 plugcnt;
+       return true;
 }
 
 int
@@ -1221,44 +1293,16 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                          UInt32       inNumberFrames,
                          AudioBufferList*       ioData)
 {
-       if (_has_midi_input) {
-               assert (current_buffers->count().n_midi() > 0);
-
-               /* deliver the first (and assumed only) MIDI buffer's data
-                  to the plugin
-               */
-
-               MidiBuffer& mb (current_buffers->get_midi(0));
-
-               for (MidiBuffer::iterator i = mb.begin(); i != mb.end(); ++i) {
-                       Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *i;
-                       switch (ev.type()) {
-                       case MIDI_CMD_NOTE_ON:
-                       case MIDI_CMD_NOTE_OFF:
-                       case MIDI_CMD_CONTROL:
-                       case MIDI_CMD_BENDER:
-                       case MIDI_CMD_PGM_CHANGE:
-                       case MIDI_CMD_CHANNEL_PRESSURE:
-                       {
-                               const uint8_t* b = ev.buffer();
-                               unit->MIDIEvent (b[0], b[1], b[2], ev.time());
-                               break;
-                       }
-
-                       default:
-                               /* plugins do not get other stuff by default */
-                               break;
-                       };
-               }
-       }
-
        /* not much to do with audio - the data is already in the buffers given to us in connect_and_run() */
 
-       if (current_maxbuf == 0) {
+       DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1: render callback, frames %2 bufs %3\n",
+                                                       name(), inNumberFrames, ioData->mNumberBuffers));
+
+       if (input_maxbuf == 0) {
                error << _("AUPlugin: render callback called illegally!") << endmsg;
                return kAudioUnitErr_CannotDoInCurrentContext;
        }
-       uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
+       uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, input_maxbuf);
 
        for (uint32_t i = 0; i < limit; ++i) {
                ioData->mBuffers[i].mNumberChannels = 1;
@@ -1269,7 +1313,7 @@ AUPlugin::render_callback(AudioUnitRenderActionFlags*,
                   passed to PluginInsert::connect_and_run()
                */
 
-               ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
+               ioData->mBuffers[i].mData = input_buffers->get_audio (i).data (cb_offset + input_offset);
        }
 
        cb_offset += inNumberFrames;
@@ -1285,41 +1329,91 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
        AudioUnitRenderActionFlags flags = 0;
        AudioTimeStamp ts;
        OSErr err;
-       uint32_t maxbuf = bufs.count().n_audio();
 
        if (requires_fixed_size_buffers() && (nframes != _last_nframes)) {
                unit->GlobalReset();
                _last_nframes = nframes;
        }
 
-       current_buffers = &bufs;
-       current_maxbuf = maxbuf;
-       current_offset = offset;
+       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()));
+
+       /* 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));
+
+       input_buffers = &bufs;
+       input_maxbuf = bufs.count().n_audio(); // number of input audio buffers
+       input_offset = offset;
        cb_offset = 0;
 
-       buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
+       buffers->mNumberBuffers = output_channels;
 
-       for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
+       for (int32_t i = 0; i < output_channels; ++i) {
                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.
+               */
                buffers->mBuffers[i].mData = 0;
        }
 
+       if (_has_midi_input) {
+
+               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));
+                                       unit->MIDIEvent (b[0], b[1], b[2], ev.time());
+                               }
+
+                               /* XXX need to handle sysex and other message types */
+                       }
+               }
+       }
+
+       /* 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));
+
        if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
 
-               current_maxbuf = 0;
+               input_maxbuf = 0;
                frames_processed += nframes;
 
-               uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
-               uint32_t i;
+               DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("%1 rendered %2 buffers of %3\n",
+                                                               name(), buffers->mNumberBuffers, output_channels));
+
+               int32_t limit = min ((int32_t) buffers->mNumberBuffers, output_channels);
+               int32_t i;
 
                for (i = 0; i < limit; ++i) {
                        Sample* expected_buffer_address= bufs.get_audio (i).data (offset);
                        if (expected_buffer_address != buffers->mBuffers[i].mData) {
-                               // cerr << "chn " << i << " rendered into " << bufs[i]+offset << endl;
+                               /* 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));
                        }
                }
@@ -1328,15 +1422,14 @@ AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_
                   did not fill/touch/use.
                */
 
-               for (;i < maxbuf; ++i) {
-                       Sample* buffer_address= bufs.get_audio (i).data (offset);
-                       memset (buffer_address, 0, nframes * sizeof (Sample));
+               for (;i < output_channels; ++i) {
+                       memset (bufs.get_audio (i).data (offset), 0, nframes * sizeof (Sample));
                }
 
                return 0;
        }
 
-       cerr << name() << " render status " << err << endl;
+       error << string_compose (_("AU: render error for %1, status = %2"), name(), err) << endmsg;
        return -1;
 }
 
@@ -1358,12 +1451,12 @@ AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
        }
 
        Timecode::BBT_Time bbt;
-       TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
-       tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
+       TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
+       tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
 
        if (outCurrentBeat) {
                float beat;
-               beat = metric.meter().beats_per_bar() * bbt.bars;
+               beat = metric.meter().divisions_per_bar() * bbt.bars;
                beat += bbt.beats;
                beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
                *outCurrentBeat = beat;
@@ -1397,8 +1490,8 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
        }
 
        Timecode::BBT_Time bbt;
-       TempoMetric metric = tmap.metric_at (_session.transport_frame() + current_offset);
-       tmap.bbt_time_with_metric (_session.transport_frame() + current_offset, bbt, metric);
+       TempoMetric metric = tmap.metric_at (_session.transport_frame() + input_offset);
+       tmap.bbt_time (_session.transport_frame() + input_offset, bbt);
 
        if (outDeltaSampleOffsetToNextBeat) {
                if (bbt.ticks == 0) {
@@ -1407,12 +1500,12 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
                } else {
                        *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(), metric.meter())); // frames per beat
+                                      metric.tempo().frames_per_beat (_session.frame_rate())); // frames per beat
                }
        }
 
        if (outTimeSig_Numerator) {
-               *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
+               *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().divisions_per_bar());
        }
        if (outTimeSig_Denominator) {
                *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
@@ -1422,12 +1515,12 @@ AUPlugin::get_musical_time_location_callback (UInt32*   outDeltaSampleOffsetToNe
 
                /* beat for the start of the bar.
                   1|1|0 -> 1
-                  2|1|0 -> 1 + beats_per_bar
-                  3|1|0 -> 1 + (2 * beats_per_bar)
+                  2|1|0 -> 1 + divisions_per_bar
+                  3|1|0 -> 1 + (2 * divisions_per_bar)
                   etc.
                */
 
-               *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
+               *outCurrentMeasureDownBeat = 1 + metric.meter().divisions_per_bar() * (bbt.bars - 1);
        }
 
        return noErr;
@@ -1465,9 +1558,9 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
 
        if (outCurrentSampleInTimeLine) {
                /* this assumes that the AU can only call this host callback from render context,
-                  where current_offset is valid.
+                  where input_offset is valid.
                */
-               *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
+               *outCurrentSampleInTimeLine = _session.transport_frame() + input_offset;
        }
 
        if (outIsCycling) {
@@ -1492,11 +1585,11 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
                                Timecode::BBT_Time bbt;
 
                                if (outCycleStartBeat) {
-                                       TempoMetric metric = tmap.metric_at (loc->start() + current_offset);
-                                       _session.tempo_map().bbt_time_with_metric (loc->start(), bbt, metric);
+                                       TempoMetric metric = tmap.metric_at (loc->start() + input_offset);
+                                       _session.tempo_map().bbt_time (loc->start(), bbt);
 
                                        float beat;
-                                       beat = metric.meter().beats_per_bar() * bbt.bars;
+                                       beat = metric.meter().divisions_per_bar() * bbt.bars;
                                        beat += bbt.beats;
                                        beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
 
@@ -1504,11 +1597,11 @@ AUPlugin::get_transport_state_callback (Boolean*  outIsPlaying,
                                }
 
                                if (outCycleEndBeat) {
-                                       TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
-                                       _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
+                                       TempoMetric metric = tmap.metric_at (loc->end() + input_offset);
+                                       _session.tempo_map().bbt_time (loc->end(), bbt);
 
                                        float beat;
-                                       beat = metric.meter().beats_per_bar() * bbt.bars;
+                                       beat = metric.meter().divisions_per_bar() * bbt.bars;
                                        beat += bbt.beats;
                                        beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
 
@@ -2044,7 +2137,7 @@ 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)));
+               _presets.insert (make_pair (uri, Plugin::PresetRecord (uri, i->first, i->second)));
        }
 
 #endif
@@ -2100,7 +2193,7 @@ AUPluginInfo::load (Session& session)
 Glib::ustring
 AUPluginInfo::au_cache_path ()
 {
-       return Glib::build_filename (ARDOUR::user_config_directory().to_string(), "au_cache");
+       return Glib::build_filename (ARDOUR::user_config_directory(), "au_cache");
 }
 
 PluginInfoList*
@@ -2248,10 +2341,29 @@ AUPluginInfo::discover_by_description (PluginInfoList& plugs, CAComponentDescrip
                           of values. in ::can_do() we use the whole system, but here
                           we need a single pair of values. XXX probably means we should
                           remove any use of these values.
+
+                          for now, if the plugin provides a wildcard, treat it as 1. we really
+                          don't care much, because whether we can handle an i/o configuration
+                          depends upon ::can_support_io_configuration(), not these counts.
+
+                          they exist because other parts of ardour try to present i/o configuration
+                          info to the user, which should perhaps be revisited.
                        */
 
-                       info->n_inputs.set (DataType::AUDIO, info->cache.io_configs.front().first);
-                       info->n_outputs.set (DataType::AUDIO, info->cache.io_configs.front().second);
+                       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 {
+                               info->n_inputs.set (DataType::AUDIO, 1);
+                       }
+
+                       if (possible_out > 0) {
+                               info->n_outputs.set (DataType::AUDIO, possible_out);
+                       } else {
+                               info->n_outputs.set (DataType::AUDIO, 1);
+                       }
 
                        DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("detected AU %1 with %2 i/o configurations - %3\n",
                                                                        info->name.c_str(), info->cache.io_configs.size(), info->unique_id));
@@ -2322,7 +2434,9 @@ AUPluginInfo::cached_io_configuration (const std::string& unique_id,
 
                /* no explicit info available, so default to 1in/1out */
 
-               cinfo.io_configs.push_back (pair<int,int> (1, 1));
+               /* XXX this is wrong. we should be indicating wildcard values */
+
+               cinfo.io_configs.push_back (pair<int,int> (-1, -1));
 
        } else {
 
@@ -2595,9 +2709,87 @@ 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;
 }
+
+int
+AUPlugin::create_parameter_listener (AUEventListenerProc cb, void* arg, float interval_secs)
+{
+#ifdef WITH_CARBON
+       CFRunLoopRef run_loop = (CFRunLoopRef) GetCFRunLoopFromEventLoop(GetCurrentEventLoop()); 
+#else
+       CFRunLoopRef run_loop = CFRunLoopGetCurrent();
+#endif
+       CFStringRef  loop_mode = kCFRunLoopDefaultMode;
+
+       if (AUEventListenerCreate (cb, arg, run_loop, loop_mode, interval_secs, interval_secs, &_parameter_listener) != noErr) {
+               return -1;
+       }
+
+       _parameter_listener_arg = arg;
+
+       return 0;
+}
+
+int
+AUPlugin::listen_to_parameter (uint32_t param_id)
+{
+       AudioUnitEvent      event;
+
+       if (!_parameter_listener || param_id >= descriptors.size()) {
+               return -2;
+       }
+
+       event.mEventType = kAudioUnitEvent_ParameterValueChange;
+       event.mArgument.mParameter.mAudioUnit = unit->AU();
+       event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
+       event.mArgument.mParameter.mScope = descriptors[param_id].scope;
+       event.mArgument.mParameter.mElement = descriptors[param_id].element;
+
+       if (AUEventListenerAddEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
+               return -1;
+       } 
+
+       return 0;
+}
+
+int
+AUPlugin::end_listen_to_parameter (uint32_t param_id)
+{
+       AudioUnitEvent      event;
+
+       if (!_parameter_listener || param_id >= descriptors.size()) {
+               return -2;
+       }
+
+       event.mEventType = kAudioUnitEvent_ParameterValueChange;
+       event.mArgument.mParameter.mAudioUnit = unit->AU();
+       event.mArgument.mParameter.mParameterID = descriptors[param_id].id;
+       event.mArgument.mParameter.mScope = descriptors[param_id].scope;
+       event.mArgument.mParameter.mElement = descriptors[param_id].element;
+
+       if (AUEventListenerRemoveEventType (_parameter_listener, _parameter_listener_arg, &event) != noErr) {
+               return -1;
+       } 
+
+       return 0;
+}
+
+void
+AUPlugin::_parameter_change_listener (void* arg, void* src, const AudioUnitEvent* event, UInt64 host_time, Float32 new_value)
+{
+       ((AUPlugin*) arg)->parameter_change_listener (arg, src, event, host_time, new_value);
+}
+
+void
+AUPlugin::parameter_change_listener (void* /*arg*/, void* /*src*/, const AudioUnitEvent* event, UInt64 /*host_time*/, Float32 new_value)
+{
+       ParameterMap::iterator i = parameter_map.find (event->mArgument.mParameter.mParameterID);
+
+       if (i != parameter_map.end()) {
+               ParameterChanged (i->second, new_value);
+       }
+}