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