Avoid use of 'std::to_string
[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_plugin.h"
31 #include "ardour/vestige/vestige.h"
32 #include "ardour/session.h"
33 #include "ardour/vst_types.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 float
143 VSTPlugin::default_value (uint32_t which)
144 {
145         return _parameter_defaults[which];
146 }
147
148 float
149 VSTPlugin::get_parameter (uint32_t which) const
150 {
151         if (which == UINT32_MAX - 1) {
152                 // ardour uses enable-semantics: 1: enabled, 0: bypassed
153                 return _eff_bypassed ? 0.f : 1.f;
154         }
155         return _plugin->getParameter (_plugin, which);
156 }
157
158 void
159 VSTPlugin::set_parameter (uint32_t which, float newval)
160 {
161         if (which == UINT32_MAX - 1) {
162                 // ardour uses enable-semantics: 1: enabled, 0: bypassed
163                 intptr_t value = (newval <= 0.f) ? 1 : 0;
164                 cerr << "effSetBypass " << value << endl; // XXX DEBUG
165                 int rv = _plugin->dispatcher (_plugin, 44 /*effSetBypass*/, 0, value, NULL, 0);
166                 if (0 != rv) {
167                         _eff_bypassed = (value == 1);
168                 } else {
169                         cerr << "effSetBypass failed rv=" << rv << endl; // XXX DEBUG
170 #ifdef ALLOW_VST_BYPASS_TO_FAIL // yet unused, see also vst_plugin.cc
171                         // emit signal.. hard un/bypass from here?!
172 #endif
173                 }
174                 return;
175         }
176
177         float oldval = get_parameter (which);
178
179         if (PBD::floateq (oldval, newval, 1)) {
180                 return;
181         }
182
183         _plugin->setParameter (_plugin, which, newval);
184
185         float curval = get_parameter (which);
186
187         if (!PBD::floateq (curval, oldval, 1)) {
188                 /* value has changed, follow rest of the notification path */
189                 Plugin::set_parameter (which, newval);
190         }
191 }
192
193 void
194 VSTPlugin::parameter_changed_externally (uint32_t which, float value )
195 {
196         ParameterChangedExternally (which, value); /* EMIT SIGNAL */
197         Plugin::set_parameter (which, value);
198 }
199
200
201 uint32_t
202 VSTPlugin::nth_parameter (uint32_t n, bool& ok) const
203 {
204         ok = true;
205         return n;
206 }
207
208 /** Get VST chunk as base64-encoded data.
209  *  @param single true for single program, false for all programs.
210  *  @return 0-terminated base64-encoded data; must be passed to g_free () by caller.
211  */
212 gchar *
213 VSTPlugin::get_chunk (bool single) const
214 {
215         guchar* data;
216         int32_t data_size = _plugin->dispatcher (_plugin, 23 /* effGetChunk */, single ? 1 : 0, 0, &data, 0);
217         if (data_size == 0) {
218                 return 0;
219         }
220
221         return g_base64_encode (data, data_size);
222 }
223
224 /** Set VST chunk from base64-encoded data.
225  *  @param 0-terminated base64-encoded data.
226  *  @param single true for single program, false for all programs.
227  *  @return 0 on success, non-0 on failure
228  */
229 int
230 VSTPlugin::set_chunk (gchar const * data, bool single)
231 {
232         gsize size = 0;
233         int r = 0;
234         guchar* raw_data = g_base64_decode (data, &size);
235         {
236                 pthread_mutex_lock (&_state->state_lock);
237                 r = _plugin->dispatcher (_plugin, 24 /* effSetChunk */, single ? 1 : 0, size, raw_data, 0);
238                 pthread_mutex_unlock (&_state->state_lock);
239         }
240         g_free (raw_data);
241         return r;
242 }
243
244 void
245 VSTPlugin::add_state (XMLNode* root) const
246 {
247         LocaleGuard lg;
248
249         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
250
251                 gchar* data = get_chunk (false);
252                 if (data == 0) {
253                         return;
254                 }
255
256                 /* store information */
257
258                 XMLNode* chunk_node = new XMLNode (X_("chunk"));
259
260                 chunk_node->add_content (data);
261                 g_free (data);
262
263                 chunk_node->set_property ("program", (int) _plugin->dispatcher (_plugin, effGetProgram, 0, 0, NULL, 0));
264
265                 root->add_child_nocopy (*chunk_node);
266
267         } else {
268
269                 XMLNode* parameters = new XMLNode ("parameters");
270
271                 for (int32_t n = 0; n < _plugin->numParams; ++n) {
272                         char index[64];
273                         snprintf (index, sizeof (index), "param-%d", n);
274                         parameters->set_property (index, _plugin->getParameter (_plugin, n));
275                 }
276
277                 root->add_child_nocopy (*parameters);
278         }
279 }
280
281 int
282 VSTPlugin::set_state (const XMLNode& node, int version)
283 {
284         LocaleGuard lg;
285         int ret = -1;
286
287 #ifndef NO_PLUGIN_STATE
288         XMLNode* child;
289
290         if ((child = find_named_node (node, X_("chunk"))) != 0) {
291
292                 int pgm = -1;
293                 if (child->get_property (X_("program"), pgm)) {
294                         _plugin->dispatcher (_plugin, effSetProgram, 0, pgm, NULL, 0);
295                 };
296
297                 XMLPropertyList::const_iterator i;
298                 XMLNodeList::const_iterator n;
299
300                 for (n = child->children ().begin (); n != child->children ().end (); ++n) {
301                         if ((*n)->is_content ()) {
302                                 /* XXX: this may be dubious for the same reasons that we delay
303                                          execution of load_preset.
304                                          */
305                                 ret = set_chunk ((*n)->content().c_str(), false);
306                         }
307                 }
308
309         } else if ((child = find_named_node (node, X_("parameters"))) != 0) {
310
311                 XMLPropertyList::const_iterator i;
312
313                 for (i = child->properties().begin(); i != child->properties().end(); ++i) {
314                         int32_t param;
315
316                         sscanf ((*i)->name().c_str(), "param-%d", &param);
317                         float value = string_to<float>((*i)->value());
318
319                         _plugin->setParameter (_plugin, param, value);
320                 }
321
322                 ret = 0;
323
324         }
325 #endif
326
327         Plugin::set_state (node, version);
328         return ret;
329 }
330
331 int
332 VSTPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& desc) const
333 {
334         VstParameterProperties prop;
335
336         memset (&prop, 0, sizeof (VstParameterProperties));
337         prop.flags = 0;
338
339         if (_plugin->dispatcher (_plugin, effGetParameterProperties, which, 0, &prop, 0)) {
340
341                 /* i have yet to find or hear of a VST plugin that uses this */
342                 /* RG: faust2vsti does use this :) */
343
344                 if (prop.flags & kVstParameterUsesIntegerMinMax) {
345                         desc.lower = prop.minInteger;
346                         desc.upper = prop.maxInteger;
347                 } else {
348                         desc.lower = 0;
349                         desc.upper = 1.0;
350                 }
351
352                 const float range = desc.upper - desc.lower;
353
354                 if (prop.flags & kVstParameterUsesIntStep && prop.stepInteger < range) {
355                         desc.step = prop.stepInteger;
356                         desc.smallstep = prop.stepInteger;
357                         desc.largestep = prop.stepInteger;
358                         desc.integer_step = true;
359                         desc.rangesteps = 1 + ceilf (range / desc.step);
360                 } else if (prop.flags & kVstParameterUsesFloatStep && prop.stepFloat < range) {
361                         desc.step = prop.stepFloat;
362                         desc.smallstep = prop.smallStepFloat;
363                         desc.largestep = prop.largeStepFloat;
364                         desc.rangesteps = 1 + ceilf (range / desc.step);
365                 } else {
366                         desc.smallstep = desc.step = range / 300.0f;
367                         desc.largestep =  range / 30.0f;
368                 }
369
370                 if (strlen(prop.label) == 0) {
371                         _plugin->dispatcher (_plugin, effGetParamName, which, 0, prop.label, 0);
372                 }
373
374                 desc.toggled = prop.flags & kVstParameterIsSwitch;
375                 desc.label = Glib::locale_to_utf8 (prop.label);
376
377         } else {
378
379                 /* old style */
380
381                 char label[VestigeMaxLabelLen];
382                 /* some VST plugins expect this buffer to be zero-filled */
383                 memset (label, 0, sizeof (label));
384
385                 _plugin->dispatcher (_plugin, effGetParamName, which, 0, label, 0);
386
387                 desc.label = Glib::locale_to_utf8 (label);
388                 desc.lower = 0.0f;
389                 desc.upper = 1.0f;
390                 desc.smallstep = desc.step = 1.f / 300.f;
391                 desc.largestep = 1.f / 30.f;
392         }
393
394         /* TODO we should really call
395          *   desc.update_steps ()
396          * instead of manually assigning steps. Yet, VST prop is (again)
397          * the odd one out compared to other plugin formats.
398          */
399
400         if (_parameter_defaults.find (which) == _parameter_defaults.end ()) {
401                 _parameter_defaults[which] = get_parameter (which);
402         } else {
403                 desc.normal = _parameter_defaults[which];
404         }
405
406         return 0;
407 }
408
409 bool
410 VSTPlugin::load_preset (PresetRecord r)
411 {
412         bool s;
413
414         if (r.user) {
415                 s = load_user_preset (r);
416         } else {
417                 s = load_plugin_preset (r);
418         }
419
420         if (s) {
421                 Plugin::load_preset (r);
422         }
423
424         return s;
425 }
426
427 bool
428 VSTPlugin::load_plugin_preset (PresetRecord r)
429 {
430         /* This is a plugin-provided preset.
431            We can't dispatch directly here; too many plugins expects only one GUI thread.
432         */
433
434         /* Extract the index of this preset from the URI */
435         int id;
436         int index;
437 #ifndef NDEBUG
438         int const p = sscanf (r.uri.c_str(), "VST:%d:%d", &id, &index);
439         assert (p == 2);
440 #else
441         sscanf (r.uri.c_str(), "VST:%d:%d", &id, &index);
442 #endif
443         _state->want_program = index;
444         LoadPresetProgram (); /* EMIT SIGNAL */ /* used for macvst */
445         return true;
446 }
447
448 bool
449 VSTPlugin::load_user_preset (PresetRecord r)
450 {
451         /* This is a user preset; we load it, and this code also knows about the
452            non-direct-dispatch thing.
453         */
454
455         boost::shared_ptr<XMLTree> t (presets_tree ());
456         if (t == 0) {
457                 return false;
458         }
459
460         XMLNode* root = t->root ();
461
462         for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
463                 std::string label;
464                 (*i)->get_property (X_("label"), label);
465
466                 if (label != r.label) {
467                         continue;
468                 }
469
470                 if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
471
472                         /* Load a user preset chunk from our XML file and send it via a circuitous route to the plugin */
473
474                         if (_state->wanted_chunk) {
475                                 g_free (_state->wanted_chunk);
476                         }
477
478                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
479                                 if ((*j)->is_content ()) {
480                                         /* we can't dispatch directly here; too many plugins expect only one GUI thread */
481                                         gsize size = 0;
482                                         guchar* raw_data = g_base64_decode ((*j)->content().c_str(), &size);
483                                         _state->wanted_chunk = raw_data;
484                                         _state->wanted_chunk_size = size;
485                                         _state->want_chunk = 1;
486                                         LoadPresetProgram (); /* EMIT SIGNAL */ /* used for macvst */
487                                         return true;
488                                 }
489                         }
490
491                         return false;
492
493                 } else {
494
495                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
496                                 if ((*j)->name() == X_("Parameter")) {
497                                         uint32_t index;
498                                         float value;
499
500                                         if (!(*j)->get_property (X_("index"), index) ||
501                                             !(*j)->get_property (X_("value"), value)) {
502                                           // flag error and continue?
503                                                 assert (false);
504                                         }
505
506                                         set_parameter (index, value);
507                                         PresetPortSetValue (index, value); /* EMIT SIGNAL */
508                                 }
509                         }
510                         return true;
511                 }
512         }
513         return false;
514 }
515
516 #include "sha1.c"
517
518 string
519 VSTPlugin::do_save_preset (string name)
520 {
521         boost::shared_ptr<XMLTree> t (presets_tree ());
522         if (t == 0) {
523                 return "";
524         }
525
526         // prevent dups -- just in case
527         t->root()->remove_nodes_and_delete (X_("label"), name);
528
529         XMLNode* p = 0;
530
531         char tmp[32];
532         snprintf (tmp, 31, "%ld", _presets.size() + 1);
533         tmp[31] = 0;
534
535         char hash[41];
536         Sha1Digest s;
537         sha1_init (&s);
538         sha1_write (&s, (const uint8_t *) name.c_str(), name.size ());
539         sha1_write (&s, (const uint8_t *) tmp, strlen(tmp));
540         sha1_result_hash (&s, hash);
541
542         string const uri = string_compose (X_("VST:%1:x%2"), unique_id (), hash);
543
544         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
545                 p = new XMLNode (X_("ChunkPreset"));
546         } else {
547                 p = new XMLNode (X_("Preset"));
548         }
549
550         p->set_property (X_("uri"), uri);
551         p->set_property (X_("version"), version ());
552         p->set_property (X_("label"), name);
553         p->set_property (X_("numParams"), parameter_count ());
554
555         if (_plugin->flags & 32) {
556
557                 gchar* data = get_chunk (true);
558                 p->add_content (string (data));
559                 g_free (data);
560
561         } else {
562
563                 for (uint32_t i = 0; i < parameter_count(); ++i) {
564                         if (parameter_is_input (i)) {
565                                 XMLNode* c = new XMLNode (X_("Parameter"));
566                                 c->set_property (X_("index"), i);
567                                 c->set_property (X_("value"), get_parameter (i));
568                                 p->add_child_nocopy (*c);
569                         }
570                 }
571         }
572
573         t->root()->add_child_nocopy (*p);
574
575         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
576         f = Glib::build_filename (f, presets_file ());
577
578         t->write (f);
579         return uri;
580 }
581
582 void
583 VSTPlugin::do_remove_preset (string name)
584 {
585         boost::shared_ptr<XMLTree> t (presets_tree ());
586         if (t == 0) {
587                 return;
588         }
589
590         t->root()->remove_nodes_and_delete (X_("label"), name);
591
592         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
593         f = Glib::build_filename (f, presets_file ());
594
595         t->write (f);
596 }
597
598 string
599 VSTPlugin::describe_parameter (Evoral::Parameter param)
600 {
601         char name[VestigeMaxLabelLen];
602         if (param.id() == UINT32_MAX - 1) {
603                 strcpy (name, _("Plugin Enable"));
604                 return name;
605         }
606
607         memset (name, 0, sizeof (name));
608
609         /* some VST plugins expect this buffer to be zero-filled */
610
611         _plugin->dispatcher (_plugin, effGetParamName, param.id(), 0, name, 0);
612
613         if (name[0] == '\0') {
614                 strcpy (name, _("Unknown"));
615         }
616
617         return name;
618 }
619
620 samplecnt_t
621 VSTPlugin::signal_latency () const
622 {
623         if (_user_latency) {
624                 return _user_latency;
625         }
626
627 #if ( defined(__x86_64__) || defined(_M_X64) )
628         return *((int32_t *) (((char *) &_plugin->flags) + 24)); /* initialDelay */
629 #else
630         return *((int32_t *) (((char *) &_plugin->flags) + 12)); /* initialDelay */
631 #endif
632 }
633
634 set<Evoral::Parameter>
635 VSTPlugin::automatable () const
636 {
637         set<Evoral::Parameter> ret;
638
639         for (uint32_t i = 0; i < parameter_count(); ++i) {
640                 ret.insert (ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
641         }
642
643         return ret;
644 }
645
646 int
647 VSTPlugin::connect_and_run (BufferSet& bufs,
648                 samplepos_t start, samplepos_t end, double speed,
649                 ChanMapping in_map, ChanMapping out_map,
650                 pframes_t nframes, samplecnt_t offset)
651 {
652         Plugin::connect_and_run(bufs, start, end, speed, in_map, out_map, nframes, offset);
653
654         if (pthread_mutex_trylock (&_state->state_lock)) {
655                 /* by convention 'effSetChunk' should not be called while processing
656                  * http://www.reaper.fm/sdk/vst/vst_ext.php
657                  *
658                  * All VSTs don't use in-place, PluginInsert::connect_and_run()
659                  * does clear output buffers, so we can just return.
660                  */
661                 return 0;
662         }
663
664         _transport_sample = start;
665         _transport_speed = speed;
666
667         ChanCount bufs_count;
668         bufs_count.set(DataType::AUDIO, 1);
669         bufs_count.set(DataType::MIDI, 1);
670         _midi_out_buf = 0;
671
672         BufferSet& silent_bufs  = _session.get_silent_buffers(bufs_count);
673         BufferSet& scratch_bufs = _session.get_scratch_buffers(bufs_count);
674
675         /* VC++ doesn't support the C99 extension that allows
676
677            typeName foo[variableDefiningSize];
678
679            Use alloca instead of dynamic array (rather than std::vector which
680            allocs on the heap) because this is realtime code.
681         */
682
683         float** ins = (float**)alloca(_plugin->numInputs*sizeof(float*));
684         float** outs = (float**)alloca(_plugin->numOutputs*sizeof(float*));
685
686         int32_t i;
687
688         uint32_t in_index = 0;
689         for (i = 0; i < (int32_t) _plugin->numInputs; ++i) {
690                 uint32_t  index;
691                 bool      valid = false;
692                 index = in_map.get(DataType::AUDIO, in_index++, &valid);
693                 ins[i] = (valid)
694                                         ? bufs.get_audio(index).data(offset)
695                                         : silent_bufs.get_audio(0).data(offset);
696         }
697
698         uint32_t out_index = 0;
699         for (i = 0; i < (int32_t) _plugin->numOutputs; ++i) {
700                 uint32_t  index;
701                 bool      valid = false;
702                 index = out_map.get(DataType::AUDIO, out_index++, &valid);
703                 outs[i] = (valid)
704                         ? bufs.get_audio(index).data(offset)
705                         : scratch_bufs.get_audio(0).data(offset);
706         }
707
708         if (bufs.count().n_midi() > 0) {
709                 VstEvents* v = 0;
710                 bool valid = false;
711                 const uint32_t buf_index_in = in_map.get(DataType::MIDI, 0, &valid);
712                 if (valid) {
713                         v = bufs.get_vst_midi (buf_index_in);
714                 }
715                 valid = false;
716                 const uint32_t buf_index_out = out_map.get(DataType::MIDI, 0, &valid);
717                 if (valid) {
718                         _midi_out_buf = &bufs.get_midi(buf_index_out);
719                         _midi_out_buf->silence(0, 0);
720                 } else {
721                         _midi_out_buf = 0;
722                 }
723                 if (v) {
724                         _plugin->dispatcher (_plugin, effProcessEvents, 0, 0, v, 0);
725                 }
726         }
727
728         /* we already know it can support processReplacing */
729         _plugin->processReplacing (_plugin, &ins[0], &outs[0], nframes);
730         _midi_out_buf = 0;
731
732         pthread_mutex_unlock (&_state->state_lock);
733         return 0;
734 }
735
736 string
737 VSTPlugin::unique_id () const
738 {
739         char buf[32];
740
741         snprintf (buf, sizeof (buf), "%d", _plugin->uniqueID);
742
743         return string (buf);
744 }
745
746
747 const char *
748 VSTPlugin::name () const
749 {
750         if (!_info->name.empty ()) {
751                 return _info->name.c_str();
752         }
753         return _handle->name;
754 }
755
756 const char *
757 VSTPlugin::maker () const
758 {
759         return _info->creator.c_str();
760 }
761
762 const char *
763 VSTPlugin::label () const
764 {
765         return _handle->name;
766 }
767
768 int32_t
769 VSTPlugin::version () const
770 {
771         return _plugin->version;
772 }
773
774 uint32_t
775 VSTPlugin::parameter_count () const
776 {
777         return _plugin->numParams;
778 }
779
780 bool
781 VSTPlugin::has_editor () const
782 {
783         return _plugin->flags & effFlagsHasEditor;
784 }
785
786 void
787 VSTPlugin::print_parameter (uint32_t param, char *buf, uint32_t /*len*/) const
788 {
789         char *first_nonws;
790
791         _plugin->dispatcher (_plugin, 7 /* effGetParamDisplay */, param, 0, buf, 0);
792
793         if (buf[0] == '\0') {
794                 return;
795         }
796
797         first_nonws = buf;
798         while (*first_nonws && isspace (*first_nonws)) {
799                 first_nonws++;
800         }
801
802         if (*first_nonws == '\0') {
803                 return;
804         }
805
806         memmove (buf, first_nonws, strlen (buf) - (first_nonws - buf) + 1);
807 }
808
809 void
810 VSTPlugin::find_presets ()
811 {
812         /* Built-in presets */
813
814         int const vst_version = _plugin->dispatcher (_plugin, effGetVstVersion, 0, 0, NULL, 0);
815         for (int i = 0; i < _plugin->numPrograms; ++i) {
816                 PresetRecord r (string_compose (X_("VST:%1:%2"), unique_id (), i), "", false);
817
818                 if (vst_version >= 2) {
819                         char buf[256];
820                         if (_plugin->dispatcher (_plugin, 29, i, 0, buf, 0) == 1) {
821                                 r.label = buf;
822                         } else {
823                                 r.label = string_compose (_("Preset %1"), i);
824                         }
825                 } else {
826                         r.label = string_compose (_("Preset %1"), i);
827                 }
828
829                 _presets.insert (make_pair (r.uri, r));
830         }
831
832         /* User presets from our XML file */
833
834         boost::shared_ptr<XMLTree> t (presets_tree ());
835
836         if (t) {
837                 XMLNode* root = t->root ();
838                 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
839                         std::string uri;
840                         std::string label;
841
842                         if (!(*i)->get_property (X_("uri"), uri) || !(*i)->get_property (X_("label"), label)) {
843                                 assert(false);
844                         }
845
846                         PresetRecord r (uri, label, true);
847                         _presets.insert (make_pair (r.uri, r));
848                 }
849         }
850
851 }
852
853 /** @return XMLTree with our user presets; could be a new one if no existing
854  *  one was found, or 0 if one was present but badly-formatted.
855  */
856 XMLTree *
857 VSTPlugin::presets_tree () const
858 {
859         XMLTree* t = new XMLTree;
860
861         std::string p = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
862
863         if (!Glib::file_test (p, Glib::FILE_TEST_IS_DIR)) {
864                 if (g_mkdir_with_parents (p.c_str(), 0755) != 0) {
865                         error << _("Unable to make VST presets directory") << endmsg;
866                 };
867         }
868
869         p = Glib::build_filename (p, presets_file ());
870
871         if (!Glib::file_test (p, Glib::FILE_TEST_EXISTS)) {
872                 t->set_root (new XMLNode (X_("VSTPresets")));
873                 return t;
874         }
875
876         t->set_filename (p);
877         if (!t->read ()) {
878                 delete t;
879                 return 0;
880         }
881
882         return t;
883 }
884
885 /** @return Index of the first user preset in our lists */
886 int
887 VSTPlugin::first_user_preset_index () const
888 {
889         return _plugin->numPrograms;
890 }
891
892 string
893 VSTPlugin::presets_file () const
894 {
895         return string("vst-") + unique_id ();
896 }
897