+ TRACE_API ("call Uninitialize in deactivate()\n");
+ unit->Uninitialize ();
+ initialized = false;
+}
+
+void
+AUPlugin::flush ()
+{
+ TRACE_API ("call Reset in flush()\n");
+ unit->GlobalReset ();
+}
+
+bool
+AUPlugin::requires_fixed_size_buffers() const
+{
+ return _requires_fixed_size_buffers;
+}
+
+
+int
+AUPlugin::set_block_size (pframes_t nframes)
+{
+ bool was_initialized = initialized;
+ UInt32 numFrames = nframes;
+ OSErr err;
+
+ if (initialized) {
+ deactivate ();
+ }
+
+ TRACE_API ("set MaximumFramesPerSlice in global scope to %u\n", numFrames);
+ if ((err = unit->SetProperty (kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global,
+ 0, &numFrames, sizeof (numFrames))) != noErr) {
+ cerr << "cannot set max frames (err = " << err << ')' << endl;
+ return -1;
+ }
+
+ if (was_initialized) {
+ activate ();
+ }
+
+ _current_block_size = nframes;
+
+ return 0;
+}
+
+bool
+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 (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;
+ } else {
+ deactivate ();
+ }
+ }
+
+ streamFormat.mSampleRate = _session.frame_rate();
+ streamFormat.mFormatID = kAudioFormatLinearPCM;
+ streamFormat.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked|kAudioFormatFlagIsNonInterleaved;
+
+#ifdef __LITTLE_ENDIAN__
+ /* relax */
+#else
+ streamFormat.mFormatFlags |= kAudioFormatFlagIsBigEndian;
+#endif
+
+ streamFormat.mBitsPerChannel = 32;
+ streamFormat.mFramesPerPacket = 1;
+
+ /* apple says that for non-interleaved data, these
+ values always refer to a single channel.
+ */
+ streamFormat.mBytesPerPacket = 4;
+ streamFormat.mBytesPerFrame = 4;
+
+ streamFormat.mChannelsPerFrame = audio_in;
+
+ if (set_input_format (streamFormat) != 0) {
+ return -1;
+ }
+
+ streamFormat.mChannelsPerFrame = audio_out;
+
+ if (set_output_format (streamFormat) != 0) {
+ return -1;
+ }
+
+ if (was_initialized) {
+ activate ();
+ }
+
+ return 0;
+}
+
+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.
+
+ int32_t audio_in = in.n_audio();
+ int32_t audio_out;
+ int32_t plugcnt = -1;
+ AUPluginInfoPtr pinfo = boost::dynamic_pointer_cast<AUPluginInfo>(get_info());
+
+ /* lets check MIDI first */
+
+ if (in.n_midi() > 0) {
+ if (!_has_midi_input) {
+ return false;
+ }
+ }
+
+ vector<pair<int,int> >& io_configs = pinfo->cache.io_configs;
+
+ if (debug_io_config) {
+ cerr << name() << " has " << io_configs.size() << " IO Configurations\n";
+ }
+
+ //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
+
+ 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) {
+ cerr << "\tCHOSEN: in " << in << " out " << out << endl;
+ 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;
+ int32_t possible_out = i->second;
+
+ if (debug_io_config) {
+ cerr << "\tin " << possible_in << " out " << possible_out << endl;
+ }
+
+ if (possible_out == 0) {
+ warning << string_compose (_("AU %1 has zero outputs - configuration ignored"), name()) << endmsg;
+ continue;
+ }
+
+ if (possible_in == 0) {
+
+ /* instrument plugin, always legal but throws away inputs ...
+ */
+
+ if (possible_out == -1) {
+ /* out much match in (UNLIKELY!!) */
+ audio_out = audio_in;
+ plugcnt = 1;
+ } else if (possible_out == -2) {
+ /* any configuration possible, pick matching */
+ audio_out = audio_in;
+ plugcnt = 1;
+ } else if (possible_out < -2) {
+ /* explicit variable number of outputs, pick maximum */
+ audio_out = -possible_out;
+ plugcnt = 1;
+ } else {
+ /* exact number of outputs */
+ audio_out = possible_out;
+ plugcnt = 1;
+ }
+ }
+
+ if (possible_in == -1) {
+
+ /* wildcard for input */
+
+ if (possible_out == -1) {
+ /* out much match in */
+ audio_out = audio_in;
+ plugcnt = 1;
+ } else if (possible_out == -2) {
+ /* any configuration possible, pick matching */
+ audio_out = audio_in;
+ plugcnt = 1;
+ } else if (possible_out < -2) {
+ /* explicit variable number of outputs, pick maximum */
+ audio_out = -possible_out;
+ plugcnt = 1;
+ } else {
+ /* exact number of outputs */
+ audio_out = possible_out;
+ plugcnt = 1;
+ }
+ }
+
+ if (possible_in == -2) {
+
+ if (possible_out == -1) {
+ /* any configuration possible, pick matching */
+ audio_out = audio_in;
+ plugcnt = 1;
+ } else if (possible_out == -2) {
+ error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
+ << endmsg;
+ plugcnt = -1;
+ } else if (possible_out < -2) {
+ /* explicit variable number of outputs, pick maximum */
+ audio_out = -possible_out;
+ plugcnt = 1;
+ } else {
+ /* exact number of outputs */
+ audio_out = possible_out;
+ plugcnt = 1;
+ }
+ }
+
+ if (possible_in < -2) {
+
+ /* explicit variable number of inputs */
+
+ 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;
+ } else if (possible_out == -2) {
+ error << string_compose (_("AU plugin %1 has illegal IO configuration (-2,-2)"), name())
+ << endmsg;
+ plugcnt = -1;
+ } else if (possible_out < -2) {
+ /* explicit variable number of outputs, pick maximum */
+ audio_out = -possible_out;
+ plugcnt = 1;
+ } else {
+ /* exact number of outputs */
+ audio_out = possible_out;
+ plugcnt = 1;
+ }
+ }
+
+ if (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;
+ } else if (possible_out == -2) {
+ /* any output configuration, pick matching */
+ audio_out = audio_in;
+ plugcnt = -1;
+ } else if (possible_out < -2) {
+ /* explicit variable number of outputs, pick maximum */
+ audio_out = -possible_out;
+ plugcnt = 1;
+ } else {
+ /* exact number of outputs */
+ audio_out = possible_out;
+ plugcnt = 1;
+ }
+ }
+
+ if (plugcnt == 1) {
+ break;
+ }
+
+ }
+
+ if (debug_io_config) {
+ if (plugcnt > 0) {
+ cerr << "\tCHOSEN: in " << in << " out " << out << " plugcnt will be " << plugcnt << endl;
+ } else {
+ cerr << "\tFAIL: no configs match requested in " << in << endl;
+ }
+ }
+
+ out.set (DataType::MIDI, 0);
+ out.set (DataType::AUDIO, audio_out);
+
+ return plugcnt;
+}
+
+int
+AUPlugin::set_input_format (AudioStreamBasicDescription& fmt)
+{
+ return set_stream_format (kAudioUnitScope_Input, input_elements, fmt);
+}
+
+int
+AUPlugin::set_output_format (AudioStreamBasicDescription& fmt)
+{
+ if (set_stream_format (kAudioUnitScope_Output, output_elements, fmt) != 0) {
+ return -1;
+ }
+
+ if (buffers) {
+ free (buffers);
+ buffers = 0;
+ }
+
+ buffers = (AudioBufferList *) malloc (offsetof(AudioBufferList, mBuffers) +
+ fmt.mChannelsPerFrame * sizeof(::AudioBuffer));
+
+ Glib::Mutex::Lock em (_session.engine().process_lock());
+ IO::PortCountChanged (ChanCount(DataType::AUDIO, fmt.mChannelsPerFrame));
+
+ return 0;
+}
+
+int
+AUPlugin::set_stream_format (int scope, uint32_t cnt, AudioStreamBasicDescription& fmt)
+{
+ OSErr result;
+
+ for (uint32_t i = 0; i < cnt; ++i) {
+ TRACE_API ("set stream format for %s, scope = %d element %d\n",
+ (scope == kAudioUnitScope_Input ? "input" : "output"),
+ scope, cnt);
+ if ((result = unit->SetFormat (scope, i, fmt)) != 0) {
+ error << string_compose (_("AUPlugin: could not set stream format for %1/%2 (err = %3)"),
+ (scope == kAudioUnitScope_Input ? "input" : "output"), i, result) << endmsg;
+ return -1;
+ }
+ }
+
+ if (scope == kAudioUnitScope_Input) {
+ input_channels = fmt.mChannelsPerFrame;
+ } else {
+ output_channels = fmt.mChannelsPerFrame;
+ }
+
+ return 0;
+}
+
+OSStatus
+AUPlugin::render_callback(AudioUnitRenderActionFlags*,
+ const AudioTimeStamp*,
+ UInt32,
+ 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) {
+ error << _("AUPlugin: render callback called illegally!") << endmsg;
+ return kAudioUnitErr_CannotDoInCurrentContext;
+ }
+ uint32_t limit = min ((uint32_t) ioData->mNumberBuffers, current_maxbuf);
+
+ for (uint32_t i = 0; i < limit; ++i) {
+ ioData->mBuffers[i].mNumberChannels = 1;
+ 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()
+ */
+
+ ioData->mBuffers[i].mData = current_buffers->get_audio (i).data (cb_offset + current_offset);
+ }
+
+ cb_offset += inNumberFrames;
+
+ return noErr;
+}
+
+int
+AUPlugin::connect_and_run (BufferSet& bufs, ChanMapping in_map, ChanMapping out_map, pframes_t nframes, framecnt_t offset)
+{
+ Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
+
+ 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;
+ cb_offset = 0;
+
+ buffers->mNumberBuffers = min ((uint32_t) output_channels, maxbuf);
+
+ for (uint32_t i = 0; i < buffers->mNumberBuffers; ++i) {
+ buffers->mBuffers[i].mNumberChannels = 1;
+ buffers->mBuffers[i].mDataByteSize = nframes * sizeof (Sample);
+ buffers->mBuffers[i].mData = 0;
+ }
+
+ ts.mSampleTime = frames_processed;
+ ts.mFlags = kAudioTimeStampSampleTimeValid;
+
+ if ((err = unit->Render (&flags, &ts, 0, nframes, buffers)) == noErr) {
+
+ current_maxbuf = 0;
+ frames_processed += nframes;
+
+ uint32_t limit = min ((uint32_t) buffers->mNumberBuffers, maxbuf);
+ uint32_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;
+ 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.
+ */
+
+ for (;i < maxbuf; ++i) {
+ Sample* buffer_address= bufs.get_audio (i).data (offset);
+ memset (buffer_address, 0, nframes * sizeof (Sample));
+ }
+
+ return 0;
+ }
+
+ cerr << name() << " render status " << err << endl;
+ return -1;
+}
+
+OSStatus
+AUPlugin::get_beat_and_tempo_callback (Float64* outCurrentBeat,
+ Float64* outCurrentTempo)
+{
+ TempoMap& tmap (_session.tempo_map());
+
+ TRACE_API ("AU calls ardour beat&tempo callback\n");
+
+ /* more than 1 meter or more than 1 tempo means that a simplistic computation
+ (and interpretation) of a beat position will be incorrect. So refuse to
+ offer the value.
+ */
+
+ if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
+ return kAudioUnitErr_CannotDoInCurrentContext;
+ }
+
+ 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);
+
+ if (outCurrentBeat) {
+ float beat;
+ beat = metric.meter().beats_per_bar() * bbt.bars;
+ beat += bbt.beats;
+ beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
+ *outCurrentBeat = beat;
+ }
+
+ if (outCurrentTempo) {
+ *outCurrentTempo = floor (metric.tempo().beats_per_minute());
+ }
+
+ return noErr;
+
+}
+
+OSStatus
+AUPlugin::get_musical_time_location_callback (UInt32* outDeltaSampleOffsetToNextBeat,
+ Float32* outTimeSig_Numerator,
+ UInt32* outTimeSig_Denominator,
+ Float64* outCurrentMeasureDownBeat)
+{
+ TempoMap& tmap (_session.tempo_map());
+
+ TRACE_API ("AU calls ardour music time location callback\n");
+
+ /* more than 1 meter or more than 1 tempo means that a simplistic computation
+ (and interpretation) of a beat position will be incorrect. So refuse to
+ offer the value.
+ */
+
+ if (tmap.n_tempos() > 1 || tmap.n_meters() > 1) {
+ return kAudioUnitErr_CannotDoInCurrentContext;
+ }
+
+ 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);
+
+ if (outDeltaSampleOffsetToNextBeat) {
+ if (bbt.ticks == 0) {
+ /* on the beat */
+ *outDeltaSampleOffsetToNextBeat = 0;
+ } 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
+ }
+ }
+
+ if (outTimeSig_Numerator) {
+ *outTimeSig_Numerator = (UInt32) lrintf (metric.meter().beats_per_bar());
+ }
+ if (outTimeSig_Denominator) {
+ *outTimeSig_Denominator = (UInt32) lrintf (metric.meter().note_divisor());
+ }
+
+ if (outCurrentMeasureDownBeat) {
+
+ /* 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)
+ etc.
+ */
+
+ *outCurrentMeasureDownBeat = 1 + metric.meter().beats_per_bar() * (bbt.bars - 1);
+ }
+
+ return noErr;
+}
+
+OSStatus
+AUPlugin::get_transport_state_callback (Boolean* outIsPlaying,
+ Boolean* outTransportStateChanged,
+ Float64* outCurrentSampleInTimeLine,
+ Boolean* outIsCycling,
+ Float64* outCycleStartBeat,
+ Float64* outCycleEndBeat)
+{
+ bool rolling;
+ float speed;
+
+ TRACE_API ("AU calls ardour transport state callback\n");
+
+ rolling = _session.transport_rolling();
+ speed = _session.transport_speed ();
+
+ if (outIsPlaying) {
+ *outIsPlaying = _session.transport_rolling();
+ }
+
+ if (outTransportStateChanged) {
+ if (rolling != last_transport_rolling) {
+ *outTransportStateChanged = true;
+ } else if (speed != last_transport_speed) {
+ *outTransportStateChanged = true;
+ } else {
+ *outTransportStateChanged = false;
+ }
+ }
+
+ if (outCurrentSampleInTimeLine) {
+ /* this assumes that the AU can only call this host callback from render context,
+ where current_offset is valid.
+ */
+ *outCurrentSampleInTimeLine = _session.transport_frame() + current_offset;
+ }
+
+ if (outIsCycling) {
+ Location* loc = _session.locations()->auto_loop_location();
+
+ *outIsCycling = (loc && _session.transport_rolling() && _session.get_play_loop());
+
+ if (*outIsCycling) {
+
+ if (outCycleStartBeat || outCycleEndBeat) {
+
+ TempoMap& tmap (_session.tempo_map());
+
+ /* more than 1 meter means that a simplistic computation (and interpretation) of
+ a beat position will be incorrect. so refuse to offer the value.
+ */
+
+ if (tmap.n_meters() > 1) {
+ return kAudioUnitErr_CannotDoInCurrentContext;
+ }
+
+ 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);
+
+ float beat;
+ beat = metric.meter().beats_per_bar() * bbt.bars;
+ beat += bbt.beats;
+ beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
+
+ *outCycleStartBeat = beat;
+ }
+
+ if (outCycleEndBeat) {
+ TempoMetric metric = tmap.metric_at (loc->end() + current_offset);
+ _session.tempo_map().bbt_time_with_metric (loc->end(), bbt, metric);
+
+ float beat;
+ beat = metric.meter().beats_per_bar() * bbt.bars;
+ beat += bbt.beats;
+ beat += bbt.ticks / Timecode::BBT_Time::ticks_per_beat;
+
+ *outCycleEndBeat = beat;
+ }
+ }
+ }
+ }
+
+ last_transport_rolling = rolling;
+ last_transport_speed = speed;
+
+ return noErr;
+}
+
+set<Evoral::Parameter>
+AUPlugin::automatable() const
+{
+ set<Evoral::Parameter> automates;
+
+ for (uint32_t i = 0; i < descriptors.size(); ++i) {
+ if (descriptors[i].automatable) {
+ automates.insert (automates.end(), Evoral::Parameter (PluginAutomation, 0, i));
+ }
+ }
+
+ return automates;
+}
+
+string
+AUPlugin::describe_parameter (Evoral::Parameter param)
+{
+ if (param.type() == PluginAutomation && param.id() < parameter_count()) {
+ return descriptors[param.id()].label;
+ } else {
+ return "??";
+ }
+}
+
+void
+AUPlugin::print_parameter (uint32_t /*param*/, char* /*buf*/, uint32_t /*len*/) const
+{
+ // NameValue stuff here
+}
+
+bool
+AUPlugin::parameter_is_audio (uint32_t) const
+{
+ return false;
+}
+
+bool
+AUPlugin::parameter_is_control (uint32_t) const
+{
+ return true;
+}
+
+bool
+AUPlugin::parameter_is_input (uint32_t) const
+{
+ return false;
+}
+
+bool
+AUPlugin::parameter_is_output (uint32_t) const
+{
+ return false;
+}
+
+void
+AUPlugin::add_state (XMLNode* root) const
+{
+ LocaleGuard lg (X_("POSIX"));
+
+#ifdef AU_STATE_SUPPORT
+ CFDataRef xmlData;
+ CFPropertyListRef propertyList;
+
+ TRACE_API ("get preset state\n");
+ if (unit->GetAUPreset (propertyList) != noErr) {
+ return;
+ }
+
+ // Convert the property list into XML data.
+
+ xmlData = CFPropertyListCreateXMLData( kCFAllocatorDefault, propertyList);
+
+ if (!xmlData) {
+ error << _("Could not create XML version of property list") << endmsg;
+ return;
+ }
+
+ /* re-parse XML bytes to create a libxml++ XMLTree that we can merge into
+ our state node. GACK!
+ */
+
+ XMLTree t;
+
+ if (t.read_buffer (string ((const char*) CFDataGetBytePtr (xmlData), CFDataGetLength (xmlData)))) {
+ if (t.root()) {
+ root->add_child_copy (*t.root());
+ }
+ }
+
+ CFRelease (xmlData);
+ CFRelease (propertyList);
+#else
+ if (!seen_get_state_message) {
+ info << string_compose (_("Saving AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
+ PROGRAM_NAME)
+ << endmsg;
+ seen_get_state_message = true;
+ }
+#endif
+}
+
+int
+AUPlugin::set_state(const XMLNode& node, int version)
+{
+#ifdef AU_STATE_SUPPORT
+ int ret = -1;
+ CFPropertyListRef propertyList;
+ LocaleGuard lg (X_("POSIX"));
+
+ if (node.name() != state_node_name()) {
+ error << _("Bad node sent to AUPlugin::set_state") << endmsg;
+ return -1;
+ }
+
+ if (node.children().empty()) {
+ return -1;
+ }
+
+ XMLNode* top = node.children().front();
+ XMLNode* copy = new XMLNode (*top);
+
+ XMLTree t;
+ t.set_root (copy);
+
+ const string& xml = t.write_buffer ();
+ CFDataRef xmlData = CFDataCreateWithBytesNoCopy (kCFAllocatorDefault, (UInt8*) xml.data(), xml.length(), kCFAllocatorNull);
+ CFStringRef errorString;
+
+ propertyList = CFPropertyListCreateFromXMLData( kCFAllocatorDefault,
+ xmlData,
+ kCFPropertyListImmutable,
+ &errorString);
+
+ CFRelease (xmlData);
+
+ if (propertyList) {
+ TRACE_API ("set preset\n");
+ if (unit->SetAUPreset (propertyList) == noErr) {
+ ret = 0;
+
+ /* tell the world */
+
+ AudioUnitParameter changedUnit;
+ changedUnit.mAudioUnit = unit->AU();
+ changedUnit.mParameterID = kAUParameterListener_AnyParameter;
+ AUParameterListenerNotify (NULL, NULL, &changedUnit);
+ }
+ CFRelease (propertyList);
+ }
+
+ Plugin::set_state (node, version);
+ return ret;
+#else
+ if (!seen_set_state_message) {
+ info << string_compose (_("Restoring AudioUnit settings is not supported in this build of %1. Consider paying for a newer version"),
+ PROGRAM_NAME)
+ << endmsg;
+ }
+ return Plugin::set_state (node, version);
+#endif
+}
+
+bool
+AUPlugin::load_preset (PresetRecord r)
+{
+ Plugin::load_preset (r);
+
+#ifdef AU_STATE_SUPPORT
+ bool ret = false;
+ CFPropertyListRef propertyList;
+ Glib::ustring path;
+ UserPresetMap::iterator ux;
+ FactoryPresetMap::iterator fx;
+
+ /* look first in "user" presets */
+
+ if ((ux = user_preset_map.find (r.label)) != user_preset_map.end()) {
+
+ if ((propertyList = load_property_list (ux->second)) != 0) {
+ TRACE_API ("set preset from user presets\n");
+ if (unit->SetAUPreset (propertyList) == noErr) {
+ ret = true;
+
+ /* tell the world */
+
+ AudioUnitParameter changedUnit;
+ changedUnit.mAudioUnit = unit->AU();
+ changedUnit.mParameterID = kAUParameterListener_AnyParameter;
+ AUParameterListenerNotify (NULL, NULL, &changedUnit);
+ }
+ CFRelease(propertyList);
+ }
+
+ } else if ((fx = factory_preset_map.find (r.label)) != factory_preset_map.end()) {
+
+ AUPreset preset;
+
+ preset.presetNumber = fx->second;
+ preset.presetName = CFStringCreateWithCString (kCFAllocatorDefault, fx->first.c_str(), kCFStringEncodingUTF8);
+
+ TRACE_API ("set preset from factory presets\n");
+
+ if (unit->SetPresentPreset (preset) == 0) {
+ ret = true;
+
+ /* tell the world */
+
+ AudioUnitParameter changedUnit;
+ changedUnit.mAudioUnit = unit->AU();
+ changedUnit.mParameterID = kAUParameterListener_AnyParameter;
+ AUParameterListenerNotify (NULL, NULL, &changedUnit);
+ }
+ }
+
+ return ret;
+#else
+ if (!seen_loading_message) {
+ info << string_compose (_("Loading AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
+ PROGRAM_NAME)
+ << endmsg;
+ seen_loading_message = true;
+ }
+ return true;
+#endif
+}
+
+void
+AUPlugin::do_remove_preset (std::string)
+{
+}
+
+string
+AUPlugin::do_save_preset (string preset_name)
+{
+#ifdef AU_STATE_SUPPORT
+ CFPropertyListRef propertyList;
+ vector<Glib::ustring> v;
+ Glib::ustring user_preset_path;
+ bool ret = true;
+
+ std::string m = maker();
+ std::string n = name();
+
+ strip_whitespace_edges (m);
+ strip_whitespace_edges (n);
+
+ v.push_back (Glib::get_home_dir());
+ v.push_back ("Library");
+ v.push_back ("Audio");
+ v.push_back ("Presets");
+ v.push_back (m);
+ v.push_back (n);
+
+ user_preset_path = Glib::build_filename (v);
+
+ if (g_mkdir_with_parents (user_preset_path.c_str(), 0775) < 0) {
+ error << string_compose (_("Cannot create user plugin presets folder (%1)"), user_preset_path) << endmsg;
+ return false;
+ }
+
+ TRACE_API ("get current preset\n");
+ if (unit->GetAUPreset (propertyList) != noErr) {
+ return false;
+ }
+
+ // add the actual preset name */
+
+ v.push_back (preset_name + preset_suffix);
+
+ // rebuild
+
+ user_preset_path = Glib::build_filename (v);
+
+ set_preset_name_in_plist (propertyList, preset_name);
+
+ if (save_property_list (propertyList, user_preset_path)) {
+ error << string_compose (_("Saving plugin state to %1 failed"), user_preset_path) << endmsg;
+ ret = false;
+ }
+
+ CFRelease(propertyList);
+
+ return string ("file:///") + user_preset_path;
+#else
+ if (!seen_saving_message) {
+ info << string_compose (_("Saving AudioUnit presets is not supported in this build of %1. Consider paying for a newer version"),
+ PROGRAM_NAME)
+ << endmsg;
+ seen_saving_message = true;
+ }
+ return string();
+#endif
+}
+
+//-----------------------------------------------------------------------------
+// this is just a little helper function used by GetAUComponentDescriptionFromPresetFile()
+static SInt32
+GetDictionarySInt32Value(CFDictionaryRef inAUStateDictionary, CFStringRef inDictionaryKey, Boolean * outSuccess)
+{
+ CFNumberRef cfNumber;
+ SInt32 numberValue = 0;
+ Boolean dummySuccess;
+
+ if (outSuccess == NULL)
+ outSuccess = &dummySuccess;
+ if ( (inAUStateDictionary == NULL) || (inDictionaryKey == NULL) )
+ {
+ *outSuccess = FALSE;
+ return 0;
+ }
+
+ cfNumber = (CFNumberRef) CFDictionaryGetValue(inAUStateDictionary, inDictionaryKey);
+ if (cfNumber == NULL)
+ {
+ *outSuccess = FALSE;
+ return 0;
+ }
+ *outSuccess = CFNumberGetValue(cfNumber, kCFNumberSInt32Type, &numberValue);
+ if (*outSuccess)
+ return numberValue;
+ else
+ return 0;
+}
+
+static OSStatus
+GetAUComponentDescriptionFromStateData(CFPropertyListRef inAUStateData, ComponentDescription * outComponentDescription)
+{
+ CFDictionaryRef auStateDictionary;
+ ComponentDescription tempDesc = {0,0,0,0,0};
+ SInt32 versionValue;
+ Boolean gotValue;
+
+ if ( (inAUStateData == NULL) || (outComponentDescription == NULL) )
+ return paramErr;
+
+ // the property list for AU state data must be of the dictionary type
+ if (CFGetTypeID(inAUStateData) != CFDictionaryGetTypeID()) {
+ return kAudioUnitErr_InvalidPropertyValue;
+ }
+
+ auStateDictionary = (CFDictionaryRef)inAUStateData;
+
+ // first check to make sure that the version of the AU state data is one that we know understand
+ // XXX should I really do this? later versions would probably still hold these ID keys, right?
+ versionValue = GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetVersionKey), &gotValue);
+
+ if (!gotValue) {
+ return kAudioUnitErr_InvalidPropertyValue;
+ }
+#define kCurrentSavedStateVersion 0
+ if (versionValue != kCurrentSavedStateVersion) {
+ return kAudioUnitErr_InvalidPropertyValue;
+ }
+
+ // grab the ComponentDescription values from the AU state data
+ tempDesc.componentType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetTypeKey), NULL);
+ tempDesc.componentSubType = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetSubtypeKey), NULL);
+ tempDesc.componentManufacturer = (OSType) GetDictionarySInt32Value(auStateDictionary, CFSTR(kAUPresetManufacturerKey), NULL);
+ // zero values are illegit for specific ComponentDescriptions, so zero for any value means that there was an error
+ if ( (tempDesc.componentType == 0) || (tempDesc.componentSubType == 0) || (tempDesc.componentManufacturer == 0) )
+ return kAudioUnitErr_InvalidPropertyValue;
+
+ *outComponentDescription = tempDesc;
+ return noErr;
+}
+
+
+static bool au_preset_filter (const string& str, void* arg)
+{
+ /* Not a dotfile, has a prefix before a period, suffix is aupreset */
+
+ bool ret;
+
+ ret = (str[0] != '.' && str.length() > 9 && str.find (preset_suffix) == (str.length() - preset_suffix.length()));
+
+ if (ret && arg) {
+
+ /* check the preset file path name against this plugin
+ ID. The idea is that all preset files for this plugin
+ include "<manufacturer>/<plugin-name>" in their path.
+ */
+
+ Plugin* p = (Plugin *) arg;
+ string match = p->maker();
+ match += '/';
+ match += p->name();
+
+ ret = str.find (match) != string::npos;
+
+ if (ret == false) {
+ string m = p->maker ();
+ string n = p->name ();
+ strip_whitespace_edges (m);
+ strip_whitespace_edges (n);
+ match = m;
+ match += '/';
+ match += n;
+
+ ret = str.find (match) != string::npos;
+ }
+ }
+
+ return ret;
+}
+
+bool
+check_and_get_preset_name (Component component, const string& pathstr, string& preset_name)
+{
+ OSStatus status;
+ CFPropertyListRef plist;
+ ComponentDescription presetDesc;
+ bool ret = false;
+
+ plist = load_property_list (pathstr);
+
+ if (!plist) {
+ return ret;
+ }
+
+ // get the ComponentDescription from the AU preset file
+
+ status = GetAUComponentDescriptionFromStateData(plist, &presetDesc);
+
+ if (status == noErr) {
+ if (ComponentAndDescriptionMatch_Loosely(component, &presetDesc)) {
+
+ /* try to get the preset name from the property list */
+
+ if (CFGetTypeID(plist) == CFDictionaryGetTypeID()) {
+
+ const void* psk = CFDictionaryGetValue ((CFMutableDictionaryRef)plist, CFSTR(kAUPresetNameKey));
+
+ if (psk) {
+
+ const char* p = CFStringGetCStringPtr ((CFStringRef) psk, kCFStringEncodingUTF8);
+
+ if (!p) {
+ char buf[PATH_MAX+1];
+
+ if (CFStringGetCString ((CFStringRef)psk, buf, sizeof (buf), kCFStringEncodingUTF8)) {
+ preset_name = buf;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ CFRelease (plist);
+
+ return true;
+}
+
+std::string
+AUPlugin::current_preset() const
+{
+ string preset_name;
+
+#ifdef AU_STATE_SUPPORT
+ CFPropertyListRef propertyList;
+
+ TRACE_API ("get current preset for current_preset()\n");
+ if (unit->GetAUPreset (propertyList) == noErr) {
+ preset_name = get_preset_name_in_plist (propertyList);
+ CFRelease(propertyList);
+ }
+#endif
+ return preset_name;
+}
+
+void
+AUPlugin::find_presets ()
+{
+#ifdef AU_STATE_SUPPORT
+ vector<string*>* preset_files;
+ PathScanner scanner;
+
+ user_preset_map.clear ();
+
+ preset_files = scanner (preset_search_path, au_preset_filter, this, true, true, -1, true);
+
+ if (!preset_files) {
+ return;
+ }
+
+ for (vector<string*>::iterator x = preset_files->begin(); x != preset_files->end(); ++x) {
+
+ string path = *(*x);
+ string preset_name;
+
+ /* make an initial guess at the preset name using the path */
+
+ preset_name = Glib::path_get_basename (path);
+ preset_name = preset_name.substr (0, preset_name.find_last_of ('.'));
+
+ /* check that this preset file really matches this plugin
+ and potentially get the "real" preset name from
+ within the file.
+ */
+
+ if (check_and_get_preset_name (get_comp()->Comp(), path, preset_name)) {
+ user_preset_map[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)));
+ }
+
+ /* add factory 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)));
+ }
+
+#endif