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