Only show user-presets in favorite sidebar
[ardour.git] / libs / ardour / vst_plugin.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <glib.h>
21 #include "pbd/gstdio_compat.h"
22
23 #include <glibmm/fileutils.h>
24 #include <glibmm/miscutils.h>
25 #include <glibmm/convert.h>
26
27 #include "pbd/floating.h"
28 #include "pbd/locale_guard.h"
29
30 #include "ardour/vst_types.h"
31 #include "ardour/vst_plugin.h"
32 #include "ardour/vestige/vestige.h"
33 #include "ardour/session.h"
34 #include "ardour/filesystem_paths.h"
35 #include "ardour/audio_buffer.h"
36
37 #include "pbd/i18n.h"
38
39 using namespace std;
40 using namespace PBD;
41 using namespace ARDOUR;
42
43 VSTPlugin::VSTPlugin (AudioEngine& engine, Session& session, VSTHandle* handle)
44         : Plugin (engine, session)
45         , _handle (handle)
46         , _state (0)
47         , _plugin (0)
48         , _pi (0)
49         , _num (0)
50         , _transport_sample (0)
51         , _transport_speed (0.f)
52         , _eff_bypassed (false)
53 {
54         memset (&_timeInfo, 0, sizeof(_timeInfo));
55 }
56
57 VSTPlugin::VSTPlugin (const VSTPlugin& other)
58         : Plugin (other)
59         , _handle (other._handle)
60         , _state (other._state)
61         , _plugin (other._plugin)
62         , _pi (other._pi)
63         , _num (other._num)
64         , _midi_out_buf (other._midi_out_buf)
65         , _transport_sample (0)
66         , _transport_speed (0.f)
67         , _parameter_defaults (other._parameter_defaults)
68         , _eff_bypassed (other._eff_bypassed)
69 {
70         memset (&_timeInfo, 0, sizeof(_timeInfo));
71 }
72
73 VSTPlugin::~VSTPlugin ()
74 {
75
76 }
77
78 void
79 VSTPlugin::open_plugin ()
80 {
81         _plugin = _state->plugin;
82         assert (_plugin->ptr1 == this); // should have been set by {mac_vst|fst|lxvst}_instantiate
83         _plugin->ptr1 = this;
84         _state->plugin->dispatcher (_plugin, effOpen, 0, 0, 0, 0);
85         _state->vst_version = _plugin->dispatcher (_plugin, effGetVstVersion, 0, 0, 0, 0);
86 }
87
88 void
89 VSTPlugin::init_plugin ()
90 {
91         /* set rate and blocksize */
92         _plugin->dispatcher (_plugin, effSetSampleRate, 0, 0, NULL, (float) _session.sample_rate());
93         _plugin->dispatcher (_plugin, effSetBlockSize, 0, _session.get_block_size(), NULL, 0.0f);
94 }
95
96
97 uint32_t
98 VSTPlugin::designated_bypass_port ()
99 {
100         if (_plugin->dispatcher (_plugin, effCanDo, 0, 0, const_cast<char*> ("bypass"), 0.0f) != 0) {
101 #ifdef ALLOW_VST_BYPASS_TO_FAIL // yet unused, see also plugin_insert.cc
102                 return UINT32_MAX - 1; // emulate a port
103 #else
104                 /* check if plugin actually supports it,
105                  * e.g. u-he Presswerk  CanDo "bypass"  but calling effSetBypass is a NO-OP.
106                  * (presumably the plugin-author thinks hard-bypassing is a bad idea,
107                  * particularly since the plugin itself provides a bypass-port)
108                  */
109                 intptr_t value = 0; // not bypassed
110                 if (0 != _plugin->dispatcher (_plugin, 44 /*effSetBypass*/, 0, value, NULL, 0)) {
111                         cerr << "Emulate VST Bypass Port for " << name() << endl; // XXX DEBUG
112                         return UINT32_MAX - 1; // emulate a port
113                 } else {
114                         cerr << "Do *not* Emulate VST Bypass Port for " << name() << endl; // XXX DEBUG
115                 }
116 #endif
117         }
118         return UINT32_MAX;
119 }
120
121 void
122 VSTPlugin::deactivate ()
123 {
124         _plugin->dispatcher (_plugin, effMainsChanged, 0, 0, NULL, 0.0f);
125 }
126
127 void
128 VSTPlugin::activate ()
129 {
130         _plugin->dispatcher (_plugin, effMainsChanged, 0, 1, NULL, 0.0f);
131 }
132
133 int
134 VSTPlugin::set_block_size (pframes_t nframes)
135 {
136         deactivate ();
137         _plugin->dispatcher (_plugin, effSetBlockSize, 0, nframes, NULL, 0.0f);
138         activate ();
139         return 0;
140 }
141
142 bool
143 VSTPlugin::requires_fixed_sized_buffers () const
144 {
145         /* This controls if Ardour will split the plugin's run()
146          * on automation events in order to pass sample-accurate automation
147          * via standard control-ports.
148          *
149          * When returning true Ardour will *not* sub-divide the process-cycle.
150          * Automation events that happen between cycle-start and cycle-end will be
151          * ignored (ctrl values are interpolated to cycle-start).
152          *
153          * Note: This does not guarantee a fixed block-size.
154          * e.g The process cycle may be split when looping, also
155          * the period-size may change any time: see set_block_size()
156          */
157         if (get_info()->n_inputs.n_midi() > 0) {
158                 /* we don't yet implement midi buffer offsets (for split cycles).
159                  * Also session_vst callbacls uses _session.transport_sample() directly
160                  * (for BBT) which is not offset for plugin cycle split.
161                  */
162                 return true;
163         }
164         return false;
165 }
166
167 float
168 VSTPlugin::default_value (uint32_t which)
169 {
170         return _parameter_defaults[which];
171 }
172
173 float
174 VSTPlugin::get_parameter (uint32_t which) const
175 {
176         if (which == UINT32_MAX - 1) {
177                 // ardour uses enable-semantics: 1: enabled, 0: bypassed
178                 return _eff_bypassed ? 0.f : 1.f;
179         }
180         return _plugin->getParameter (_plugin, which);
181 }
182
183 void
184 VSTPlugin::set_parameter (uint32_t which, float newval)
185 {
186         if (which == UINT32_MAX - 1) {
187                 // ardour uses enable-semantics: 1: enabled, 0: bypassed
188                 intptr_t value = (newval <= 0.f) ? 1 : 0;
189                 cerr << "effSetBypass " << value << endl; // XXX DEBUG
190                 int rv = _plugin->dispatcher (_plugin, 44 /*effSetBypass*/, 0, value, NULL, 0);
191                 if (0 != rv) {
192                         _eff_bypassed = (value == 1);
193                 } else {
194                         cerr << "effSetBypass failed rv=" << rv << endl; // XXX DEBUG
195 #ifdef ALLOW_VST_BYPASS_TO_FAIL // yet unused, see also vst_plugin.cc
196                         // emit signal.. hard un/bypass from here?!
197 #endif
198                 }
199                 return;
200         }
201
202         float oldval = get_parameter (which);
203
204         if (PBD::floateq (oldval, newval, 1)) {
205                 return;
206         }
207
208         _plugin->setParameter (_plugin, which, newval);
209
210         float curval = get_parameter (which);
211
212         if (!PBD::floateq (curval, oldval, 1)) {
213                 /* value has changed, follow rest of the notification path */
214                 Plugin::set_parameter (which, newval);
215         }
216 }
217
218 void
219 VSTPlugin::parameter_changed_externally (uint32_t which, float value )
220 {
221         ParameterChangedExternally (which, value); /* EMIT SIGNAL */
222         Plugin::set_parameter (which, value);
223 }
224
225
226 uint32_t
227 VSTPlugin::nth_parameter (uint32_t n, bool& ok) const
228 {
229         ok = true;
230         return n;
231 }
232
233 /** Get VST chunk as base64-encoded data.
234  *  @param single true for single program, false for all programs.
235  *  @return 0-terminated base64-encoded data; must be passed to g_free () by caller.
236  */
237 gchar *
238 VSTPlugin::get_chunk (bool single) const
239 {
240         guchar* data;
241         int32_t data_size = _plugin->dispatcher (_plugin, 23 /* effGetChunk */, single ? 1 : 0, 0, &data, 0);
242         if (data_size == 0) {
243                 return 0;
244         }
245
246         return g_base64_encode (data, data_size);
247 }
248
249 /** Set VST chunk from base64-encoded data.
250  *  @param 0-terminated base64-encoded data.
251  *  @param single true for single program, false for all programs.
252  *  @return 0 on success, non-0 on failure
253  */
254 int
255 VSTPlugin::set_chunk (gchar const * data, bool single)
256 {
257         gsize size = 0;
258         int r = 0;
259         guchar* raw_data = g_base64_decode (data, &size);
260         {
261                 pthread_mutex_lock (&_state->state_lock);
262                 r = _plugin->dispatcher (_plugin, 24 /* effSetChunk */, single ? 1 : 0, size, raw_data, 0);
263                 pthread_mutex_unlock (&_state->state_lock);
264         }
265         g_free (raw_data);
266         return r;
267 }
268
269 void
270 VSTPlugin::add_state (XMLNode* root) const
271 {
272         LocaleGuard lg;
273
274         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
275
276                 gchar* data = get_chunk (false);
277                 if (data == 0) {
278                         return;
279                 }
280
281                 /* store information */
282
283                 XMLNode* chunk_node = new XMLNode (X_("chunk"));
284
285                 chunk_node->add_content (data);
286                 g_free (data);
287
288                 chunk_node->set_property ("program", (int) _plugin->dispatcher (_plugin, effGetProgram, 0, 0, NULL, 0));
289
290                 root->add_child_nocopy (*chunk_node);
291
292         } else {
293
294                 XMLNode* parameters = new XMLNode ("parameters");
295
296                 for (int32_t n = 0; n < _plugin->numParams; ++n) {
297                         char index[64];
298                         snprintf (index, sizeof (index), "param-%d", n);
299                         parameters->set_property (index, _plugin->getParameter (_plugin, n));
300                 }
301
302                 root->add_child_nocopy (*parameters);
303         }
304 }
305
306 int
307 VSTPlugin::set_state (const XMLNode& node, int version)
308 {
309         LocaleGuard lg;
310         int ret = -1;
311
312 #ifndef NO_PLUGIN_STATE
313         XMLNode* child;
314
315         if ((child = find_named_node (node, X_("chunk"))) != 0) {
316
317                 int pgm = -1;
318                 if (child->get_property (X_("program"), pgm)) {
319                         _plugin->dispatcher (_plugin, effSetProgram, 0, pgm, NULL, 0);
320                 };
321
322                 XMLPropertyList::const_iterator i;
323                 XMLNodeList::const_iterator n;
324
325                 for (n = child->children ().begin (); n != child->children ().end (); ++n) {
326                         if ((*n)->is_content ()) {
327                                 /* XXX: this may be dubious for the same reasons that we delay
328                                          execution of load_preset.
329                                          */
330                                 ret = set_chunk ((*n)->content().c_str(), false);
331                         }
332                 }
333
334         } else if ((child = find_named_node (node, X_("parameters"))) != 0) {
335
336                 XMLPropertyList::const_iterator i;
337
338                 for (i = child->properties().begin(); i != child->properties().end(); ++i) {
339                         int32_t param;
340
341                         sscanf ((*i)->name().c_str(), "param-%d", &param);
342                         float value = string_to<float>((*i)->value());
343
344                         _plugin->setParameter (_plugin, param, value);
345                 }
346
347                 ret = 0;
348
349         }
350 #endif
351
352         Plugin::set_state (node, version);
353         return ret;
354 }
355
356 int
357 VSTPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& desc) const
358 {
359         VstParameterProperties prop;
360
361         memset (&prop, 0, sizeof (VstParameterProperties));
362         prop.flags = 0;
363
364         if (_plugin->dispatcher (_plugin, effGetParameterProperties, which, 0, &prop, 0)) {
365
366                 /* i have yet to find or hear of a VST plugin that uses this */
367                 /* RG: faust2vsti does use this :) */
368
369                 if (prop.flags & kVstParameterUsesIntegerMinMax) {
370                         desc.lower = prop.minInteger;
371                         desc.upper = prop.maxInteger;
372                 } else {
373                         desc.lower = 0;
374                         desc.upper = 1.0;
375                 }
376
377                 const float range = desc.upper - desc.lower;
378
379                 if (prop.flags & kVstParameterUsesIntStep && prop.stepInteger < range) {
380                         desc.step = prop.stepInteger;
381                         desc.smallstep = prop.stepInteger;
382                         desc.largestep = prop.stepInteger;
383                         desc.integer_step = true;
384                         desc.rangesteps = 1 + ceilf (range / desc.step);
385                 } else if (prop.flags & kVstParameterUsesFloatStep && prop.stepFloat < range) {
386                         desc.step = prop.stepFloat;
387                         desc.smallstep = prop.smallStepFloat;
388                         desc.largestep = prop.largeStepFloat;
389                         desc.rangesteps = 1 + ceilf (range / desc.step);
390                 } else {
391                         desc.smallstep = desc.step = range / 300.0f;
392                         desc.largestep =  range / 30.0f;
393                 }
394
395                 if (strlen(prop.label) == 0) {
396                         _plugin->dispatcher (_plugin, effGetParamName, which, 0, prop.label, 0);
397                 }
398
399                 desc.toggled = prop.flags & kVstParameterIsSwitch;
400                 desc.label = Glib::locale_to_utf8 (prop.label);
401
402         } else {
403
404                 /* old style */
405
406                 char label[VestigeMaxLabelLen];
407                 /* some VST plugins expect this buffer to be zero-filled */
408                 memset (label, 0, sizeof (label));
409
410                 _plugin->dispatcher (_plugin, effGetParamName, which, 0, label, 0);
411
412                 desc.label = Glib::locale_to_utf8 (label);
413                 desc.lower = 0.0f;
414                 desc.upper = 1.0f;
415                 desc.smallstep = desc.step = 1.f / 300.f;
416                 desc.largestep = 1.f / 30.f;
417         }
418
419         /* TODO we should really call
420          *   desc.update_steps ()
421          * instead of manually assigning steps. Yet, VST prop is (again)
422          * the odd one out compared to other plugin formats.
423          */
424
425         if (_parameter_defaults.find (which) == _parameter_defaults.end ()) {
426                 _parameter_defaults[which] = get_parameter (which);
427         } else {
428                 desc.normal = _parameter_defaults[which];
429         }
430
431         return 0;
432 }
433
434 bool
435 VSTPlugin::load_preset (PresetRecord r)
436 {
437         bool s;
438
439         if (r.user) {
440                 s = load_user_preset (r);
441         } else {
442                 s = load_plugin_preset (r);
443         }
444
445         if (s) {
446                 Plugin::load_preset (r);
447         }
448
449         return s;
450 }
451
452 bool
453 VSTPlugin::load_plugin_preset (PresetRecord r)
454 {
455         /* This is a plugin-provided preset.
456            We can't dispatch directly here; too many plugins expects only one GUI thread.
457         */
458
459         /* Extract the index of this preset from the URI */
460         int id;
461         int index;
462 #ifndef NDEBUG
463         int const p = sscanf (r.uri.c_str(), "VST:%d:%d", &id, &index);
464         assert (p == 2);
465 #else
466         sscanf (r.uri.c_str(), "VST:%d:%d", &id, &index);
467 #endif
468         _state->want_program = index;
469         LoadPresetProgram (); /* EMIT SIGNAL */ /* used for macvst */
470         return true;
471 }
472
473 bool
474 VSTPlugin::load_user_preset (PresetRecord r)
475 {
476         /* This is a user preset; we load it, and this code also knows about the
477            non-direct-dispatch thing.
478         */
479
480         boost::shared_ptr<XMLTree> t (presets_tree ());
481         if (t == 0) {
482                 return false;
483         }
484
485         XMLNode* root = t->root ();
486
487         for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
488                 std::string label;
489                 (*i)->get_property (X_("label"), label);
490
491                 if (label != r.label) {
492                         continue;
493                 }
494
495                 if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
496
497                         /* Load a user preset chunk from our XML file and send it via a circuitous route to the plugin */
498
499                         if (_state->wanted_chunk) {
500                                 g_free (_state->wanted_chunk);
501                         }
502
503                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
504                                 if ((*j)->is_content ()) {
505                                         /* we can't dispatch directly here; too many plugins expect only one GUI thread */
506                                         gsize size = 0;
507                                         guchar* raw_data = g_base64_decode ((*j)->content().c_str(), &size);
508                                         _state->wanted_chunk = raw_data;
509                                         _state->wanted_chunk_size = size;
510                                         _state->want_chunk = 1;
511                                         LoadPresetProgram (); /* EMIT SIGNAL */ /* used for macvst */
512                                         return true;
513                                 }
514                         }
515
516                         return false;
517
518                 } else {
519
520                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
521                                 if ((*j)->name() == X_("Parameter")) {
522                                         uint32_t index;
523                                         float value;
524
525                                         if (!(*j)->get_property (X_("index"), index) ||
526                                             !(*j)->get_property (X_("value"), value)) {
527                                           // flag error and continue?
528                                                 assert (false);
529                                         }
530
531                                         set_parameter (index, value);
532                                         PresetPortSetValue (index, value); /* EMIT SIGNAL */
533                                 }
534                         }
535                         return true;
536                 }
537         }
538         return false;
539 }
540
541 #include "sha1.c"
542
543 string
544 VSTPlugin::do_save_preset (string name)
545 {
546         boost::shared_ptr<XMLTree> t (presets_tree ());
547         if (t == 0) {
548                 return "";
549         }
550
551         // prevent dups -- just in case
552         t->root()->remove_nodes_and_delete (X_("label"), name);
553
554         XMLNode* p = 0;
555
556         char tmp[32];
557         snprintf (tmp, 31, "%ld", _presets.size() + 1);
558         tmp[31] = 0;
559
560         char hash[41];
561         Sha1Digest s;
562         sha1_init (&s);
563         sha1_write (&s, (const uint8_t *) name.c_str(), name.size ());
564         sha1_write (&s, (const uint8_t *) tmp, strlen(tmp));
565         sha1_result_hash (&s, hash);
566
567         string const uri = string_compose (X_("VST:%1:x%2"), unique_id (), hash);
568
569         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
570                 p = new XMLNode (X_("ChunkPreset"));
571         } else {
572                 p = new XMLNode (X_("Preset"));
573         }
574
575         p->set_property (X_("uri"), uri);
576         p->set_property (X_("version"), version ());
577         p->set_property (X_("label"), name);
578         p->set_property (X_("numParams"), parameter_count ());
579
580         if (_plugin->flags & 32) {
581
582                 gchar* data = get_chunk (true);
583                 p->add_content (string (data));
584                 g_free (data);
585
586         } else {
587
588                 for (uint32_t i = 0; i < parameter_count(); ++i) {
589                         if (parameter_is_input (i)) {
590                                 XMLNode* c = new XMLNode (X_("Parameter"));
591                                 c->set_property (X_("index"), i);
592                                 c->set_property (X_("value"), get_parameter (i));
593                                 p->add_child_nocopy (*c);
594                         }
595                 }
596         }
597
598         t->root()->add_child_nocopy (*p);
599
600         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
601         f = Glib::build_filename (f, presets_file ());
602
603         t->write (f);
604         return uri;
605 }
606
607 void
608 VSTPlugin::do_remove_preset (string name)
609 {
610         boost::shared_ptr<XMLTree> t (presets_tree ());
611         if (t == 0) {
612                 return;
613         }
614
615         t->root()->remove_nodes_and_delete (X_("label"), name);
616
617         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
618         f = Glib::build_filename (f, presets_file ());
619
620         t->write (f);
621 }
622
623 string
624 VSTPlugin::describe_parameter (Evoral::Parameter param)
625 {
626         char name[VestigeMaxLabelLen];
627         if (param.id() == UINT32_MAX - 1) {
628                 strcpy (name, _("Plugin Enable"));
629                 return name;
630         }
631
632         memset (name, 0, sizeof (name));
633
634         /* some VST plugins expect this buffer to be zero-filled */
635
636         _plugin->dispatcher (_plugin, effGetParamName, param.id(), 0, name, 0);
637
638         if (name[0] == '\0') {
639                 strcpy (name, _("Unknown"));
640         }
641
642         return name;
643 }
644
645 samplecnt_t
646 VSTPlugin::signal_latency () const
647 {
648         if (_user_latency) {
649                 return _user_latency;
650         }
651
652 #if ( defined(__x86_64__) || defined(_M_X64) )
653         return *((int32_t *) (((char *) &_plugin->flags) + 24)); /* initialDelay */
654 #else
655         return *((int32_t *) (((char *) &_plugin->flags) + 12)); /* initialDelay */
656 #endif
657 }
658
659 set<Evoral::Parameter>
660 VSTPlugin::automatable () const
661 {
662         set<Evoral::Parameter> ret;
663
664         for (uint32_t i = 0; i < parameter_count(); ++i) {
665                 ret.insert (ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
666         }
667
668         return ret;
669 }
670
671 int
672 VSTPlugin::connect_and_run (BufferSet& bufs,
673                 samplepos_t start, samplepos_t end, double speed,
674                 ChanMapping const& in_map, ChanMapping const& out_map,
675                 pframes_t nframes, samplecnt_t offset)
676 {
677         Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
678
679         if (pthread_mutex_trylock (&_state->state_lock)) {
680                 /* by convention 'effSetChunk' should not be called while processing
681                  * http://www.reaper.fm/sdk/vst/vst_ext.php
682                  *
683                  * All VSTs don't use in-place, PluginInsert::connect_and_run()
684                  * does clear output buffers, so we can just return.
685                  */
686                 return 0;
687         }
688
689         _transport_sample = start;
690         _transport_speed = speed;
691
692         ChanCount bufs_count;
693         bufs_count.set(DataType::AUDIO, 1);
694         bufs_count.set(DataType::MIDI, 1);
695         _midi_out_buf = 0;
696
697         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
698         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
699
700         /* VC++ doesn't support the C99 extension that allows
701
702            typeName foo[variableDefiningSize];
703
704            Use alloca instead of dynamic array (rather than std::vector which
705            allocs on the heap) because this is realtime code.
706         */
707
708         float** ins = (float**)alloca(_plugin->numInputs*sizeof(float*));
709         float** outs = (float**)alloca(_plugin->numOutputs*sizeof(float*));
710
711         int32_t i;
712
713         uint32_t in_index = 0;
714         for (i = 0; i < (int32_t) _plugin->numInputs; ++i) {
715                 uint32_t  index;
716                 bool      valid = false;
717                 index = in_map.get(DataType::AUDIO, in_index++, &valid);
718                 ins[i] = (valid)
719                                         ? bufs.get_audio(index).data(offset)
720                                         : silent_bufs.get_audio(0).data(offset);
721         }
722
723         uint32_t out_index = 0;
724         for (i = 0; i < (int32_t) _plugin->numOutputs; ++i) {
725                 uint32_t  index;
726                 bool      valid = false;
727                 index = out_map.get(DataType::AUDIO, out_index++, &valid);
728                 outs[i] = (valid)
729                         ? bufs.get_audio(index).data(offset)
730                         : scratch_bufs.get_audio(0).data(offset);
731         }
732
733         if (bufs.count().n_midi() > 0) {
734                 VstEvents* v = 0;
735                 bool valid = false;
736                 const uint32_t buf_index_in = in_map.get(DataType::MIDI, 0, &valid);
737                 /* TODO: apply offset to MIDI buffer and trim at nframes */
738                 if (valid) {
739                         v = bufs.get_vst_midi (buf_index_in);
740                 }
741                 valid = false;
742                 const uint32_t buf_index_out = out_map.get(DataType::MIDI, 0, &valid);
743                 if (valid) {
744                         _midi_out_buf = &bufs.get_midi(buf_index_out);
745                         /* TODO: apply offset to MIDI buffer and trim at nframes */
746                         _midi_out_buf->silence(nframes, offset);
747                 } else {
748                         _midi_out_buf = 0;
749                 }
750                 if (v) {
751                         _plugin->dispatcher (_plugin, effProcessEvents, 0, 0, v, 0);
752                 }
753         }
754
755         /* we already know it can support processReplacing */
756         _plugin->processReplacing (_plugin, &ins[0], &outs[0], nframes);
757         _midi_out_buf = 0;
758
759         pthread_mutex_unlock (&_state->state_lock);
760         return 0;
761 }
762
763 string
764 VSTPlugin::unique_id () const
765 {
766         char buf[32];
767
768         snprintf (buf, sizeof (buf), "%d", _plugin->uniqueID);
769
770         return string (buf);
771 }
772
773
774 const char *
775 VSTPlugin::name () const
776 {
777         if (!_info->name.empty ()) {
778                 return _info->name.c_str();
779         }
780         return _handle->name;
781 }
782
783 const char *
784 VSTPlugin::maker () const
785 {
786         return _info->creator.c_str();
787 }
788
789 const char *
790 VSTPlugin::label () const
791 {
792         return _handle->name;
793 }
794
795 int32_t
796 VSTPlugin::version () const
797 {
798         return _plugin->version;
799 }
800
801 uint32_t
802 VSTPlugin::parameter_count () const
803 {
804         return _plugin->numParams;
805 }
806
807 bool
808 VSTPlugin::has_editor () const
809 {
810         return _plugin->flags & effFlagsHasEditor;
811 }
812
813 void
814 VSTPlugin::print_parameter (uint32_t param, char *buf, uint32_t /*len*/) const
815 {
816         char *first_nonws;
817
818         _plugin->dispatcher (_plugin, 7 /* effGetParamDisplay */, param, 0, buf, 0);
819
820         if (buf[0] == '\0') {
821                 return;
822         }
823
824         first_nonws = buf;
825         while (*first_nonws && isspace (*first_nonws)) {
826                 first_nonws++;
827         }
828
829         if (*first_nonws == '\0') {
830                 return;
831         }
832
833         memmove (buf, first_nonws, strlen (buf) - (first_nonws - buf) + 1);
834 }
835
836 void
837 VSTPlugin::find_presets ()
838 {
839         /* Built-in presets */
840
841         int const vst_version = _plugin->dispatcher (_plugin, effGetVstVersion, 0, 0, NULL, 0);
842         for (int i = 0; i < _plugin->numPrograms; ++i) {
843
844                 PresetRecord r (string_compose (X_("VST:%1:%2"), unique_id (), std::setw(4), std::setfill('0'), i), "", false);
845
846                 if (vst_version >= 2) {
847                         char buf[256];
848                         if (_plugin->dispatcher (_plugin, 29, i, 0, buf, 0) == 1) {
849                                 r.label = buf;
850                         } else {
851                                 r.label = string_compose (_("Preset %1"), i);
852                         }
853                 } else {
854                         r.label = string_compose (_("Preset %1"), i);
855                 }
856
857                 _presets.insert (make_pair (r.uri, r));
858         }
859
860         /* User presets from our XML file */
861
862         boost::shared_ptr<XMLTree> t (presets_tree ());
863
864         if (t) {
865                 XMLNode* root = t->root ();
866                 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
867                         std::string uri;
868                         std::string label;
869
870                         if (!(*i)->get_property (X_("uri"), uri) || !(*i)->get_property (X_("label"), label)) {
871                                 assert(false);
872                         }
873
874                         PresetRecord r (uri, label, true);
875                         _presets.insert (make_pair (r.uri, r));
876                 }
877         }
878
879 }
880
881 /** @return XMLTree with our user presets; could be a new one if no existing
882  *  one was found, or 0 if one was present but badly-formatted.
883  */
884 XMLTree *
885 VSTPlugin::presets_tree () const
886 {
887         XMLTree* t = new XMLTree;
888
889         std::string p = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
890
891         if (!Glib::file_test (p, Glib::FILE_TEST_IS_DIR)) {
892                 if (g_mkdir_with_parents (p.c_str(), 0755) != 0) {
893                         error << _("Unable to make VST presets directory") << endmsg;
894                 };
895         }
896
897         p = Glib::build_filename (p, presets_file ());
898
899         if (!Glib::file_test (p, Glib::FILE_TEST_EXISTS)) {
900                 t->set_root (new XMLNode (X_("VSTPresets")));
901                 return t;
902         }
903
904         t->set_filename (p);
905         if (!t->read ()) {
906                 delete t;
907                 return 0;
908         }
909
910         return t;
911 }
912
913 /** @return Index of the first user preset in our lists */
914 int
915 VSTPlugin::first_user_preset_index () const
916 {
917         return _plugin->numPrograms;
918 }
919
920 string
921 VSTPlugin::presets_file () const
922 {
923         return string("vst-") + unique_id ();
924 }
925
926
927 VSTPluginInfo::VSTPluginInfo (VSTInfo* nfo)
928 {
929
930         char buf[32];
931         snprintf (buf, sizeof (buf), "%d", nfo->UniqueID);
932         unique_id = buf;
933
934         index = 0;
935
936         name = nfo->name;
937         creator = nfo->creator;
938         n_inputs.set_audio  (nfo->numInputs);
939         n_outputs.set_audio (nfo->numOutputs);
940         n_inputs.set_midi  ((nfo->wantMidi & 1) ? 1 : 0);
941         n_outputs.set_midi ((nfo->wantMidi & 2) ? 1 : 0);
942
943         _is_instrument = nfo->isInstrument;
944 }
945
946 bool
947 VSTPluginInfo::is_instrument () const
948 {
949         if (_is_instrument) {
950                 return true;
951         }
952         return PluginInfo::is_instrument ();
953 }