do not offer combine operation for MIDI (see comment in libs/ardour/midi_playlist_sou...
[ardour.git] / libs / ardour / vst_plugin.cc
1 /*
2     Copyright (C) 2004 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 <algorithm>
21 #include <vector>
22 #include <string>
23 #include <cctype>
24
25 #include <cstdlib>
26 #include <cstdio> // so libraptor doesn't complain
27 #include <cmath>
28 #include <dirent.h>
29 #include <cstring> // for memmove
30 #include <sys/stat.h>
31 #include <cerrno>
32
33 #include <glibmm/miscutils.h>
34
35 #include <lrdf.h>
36 #include <fst.h>
37
38 #include "pbd/compose.h"
39 #include "pbd/error.h"
40 #include "pbd/pathscanner.h"
41 #include "pbd/xml++.h"
42
43 #include <fst.h>
44
45 #include "ardour/session.h"
46 #include "ardour/audioengine.h"
47 #include "ardour/filesystem_paths.h"
48 #include "ardour/vst_plugin.h"
49 #include "ardour/buffer_set.h"
50 #include "ardour/audio_buffer.h"
51 #include "ardour/midi_buffer.h"
52
53 #include "pbd/stl_delete.h"
54
55 #include "i18n.h"
56 #include <locale.h>
57
58 using namespace std;
59 using namespace ARDOUR;
60 using namespace PBD;
61 using std::min;
62 using std::max;
63
64 VSTPlugin::VSTPlugin (AudioEngine& e, Session& session, FSTHandle* h)
65         : Plugin (e, session)
66 {
67         handle = h;
68
69         if ((_fst = fst_instantiate (handle, Session::vst_callback, this)) == 0) {
70                 throw failed_constructor();
71         }
72
73         _plugin = _fst->plugin;
74         _plugin->user = this;
75
76         /* set rate and blocksize */
77
78         _plugin->dispatcher (_plugin, effSetSampleRate, 0, 0, NULL,
79                              (float) session.frame_rate());
80         _plugin->dispatcher (_plugin, effSetBlockSize, 0,
81                              session.get_block_size(), NULL, 0.0f);
82
83         /* set program to zero */
84
85         _plugin->dispatcher (_plugin, effSetProgram, 0, 0, NULL, 0.0f);
86
87         // Plugin::setup_controls ();
88 }
89
90 VSTPlugin::VSTPlugin (const VSTPlugin &other)
91         : Plugin (other)
92 {
93         handle = other.handle;
94
95         if ((_fst = fst_instantiate (handle, Session::vst_callback, this)) == 0) {
96                 throw failed_constructor();
97         }
98         _plugin = _fst->plugin;
99
100         // Plugin::setup_controls ();
101 }
102
103 VSTPlugin::~VSTPlugin ()
104 {
105         deactivate ();
106         fst_close (_fst);
107 }
108
109 int 
110 VSTPlugin::set_block_size (pframes_t nframes)
111 {
112         deactivate ();
113         _plugin->dispatcher (_plugin, effSetBlockSize, 0, nframes, NULL, 0.0f);
114         activate ();
115         return 0;
116 }
117
118 float
119 VSTPlugin::default_value (uint32_t port)
120 {
121         return 0;
122 }
123
124 void
125 VSTPlugin::set_parameter (uint32_t which, float val)
126 {
127         _plugin->setParameter (_plugin, which, val);
128
129         if (_fst->want_program == -1 && _fst->want_chunk == 0) {
130                 /* Heinous hack: Plugin::set_parameter below updates the `modified' status of the
131                    current preset, but if _fst->want_program is not -1 then there is a preset
132                    setup pending or in progress, which we don't want any `modified' updates
133                    to happen for.  So we only do this if _fst->want_program is -1.
134                 */
135                 Plugin::set_parameter (which, val);
136         }
137 }
138
139 float
140 VSTPlugin::get_parameter (uint32_t which) const
141 {
142         return _plugin->getParameter (_plugin, which);
143
144 }
145
146 uint32_t
147 VSTPlugin::nth_parameter (uint32_t n, bool& ok) const
148 {
149         ok = true;
150         return n;
151 }
152
153 /** Get VST chunk as base64-encoded data.
154  *  @param single true for single program, false for all programs.
155  *  @return 0-terminated base64-encoded data; must be passed to g_free () by caller.
156  */
157 gchar *
158 VSTPlugin::get_chunk (bool single) const
159 {
160         guchar* data;
161         int32_t data_size = _plugin->dispatcher (_plugin, 23 /* effGetChunk */, single ? 1 : 0, 0, &data, 0);
162         if (data_size == 0) {
163                 return 0;
164         }
165         
166         return g_base64_encode (data, data_size);
167 }
168
169 /** Set VST chunk from base64-encoded data.
170  *  @param 0-terminated base64-encoded data.
171  *  @param single true for single program, false for all programs.
172  *  @return 0 on success, non-0 on failure
173  */
174 int
175 VSTPlugin::set_chunk (gchar const * data, bool single)
176 {
177         gsize size = 0;
178         guchar* raw_data = g_base64_decode (data, &size);
179         int const r = _plugin->dispatcher (_plugin, 24 /* effSetChunk */, single ? 1 : 0, size, raw_data, 0);
180         g_free (raw_data);
181         return r;
182 }
183
184 void
185 VSTPlugin::add_state (XMLNode* root) const
186 {
187         LocaleGuard lg (X_("POSIX"));
188
189         if (_fst->current_program != -1) {
190                 char buf[32];
191                 snprintf (buf, sizeof (buf), "%d", _fst->current_program);
192                 root->add_property ("current-program", buf);
193         }
194
195         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
196
197                 gchar* data = get_chunk (false);
198                 if (data == 0) {
199                         return;
200                 }
201
202                 /* store information */
203
204                 XMLNode* chunk_node = new XMLNode (X_("chunk"));
205
206                 chunk_node->add_content (data);
207                 g_free (data);
208
209                 root->add_child_nocopy (*chunk_node);
210
211         } else {
212
213                 XMLNode* parameters = new XMLNode ("parameters");
214
215                 for (int32_t n = 0; n < _plugin->numParams; ++n) {
216                         char index[64];
217                         char val[32];
218                         snprintf (index, sizeof (index), "param_%d", n);
219                         snprintf (val, sizeof (val), "%.12g", _plugin->getParameter (_plugin, n));
220                         parameters->add_property (index, val);
221                 }
222
223                 root->add_child_nocopy (*parameters);
224         }
225 }
226
227 int
228 VSTPlugin::set_state (const XMLNode& node, int version)
229 {
230         LocaleGuard lg (X_("POSIX"));
231
232         if (node.name() != state_node_name()) {
233                 error << _("Bad node sent to VSTPlugin::set_state") << endmsg;
234                 return 0;
235         }
236
237         const XMLProperty* prop;
238
239         if ((prop = node.property ("current-program")) != 0) {
240                 _fst->want_program = atoi (prop->value().c_str());
241         }
242
243         XMLNode* child;
244         int ret = -1;
245
246         if ((child = find_named_node (node, X_("chunk"))) != 0) {
247
248                 XMLPropertyList::const_iterator i;
249                 XMLNodeList::const_iterator n;
250                 int ret = -1;
251
252                 for (n = child->children ().begin (); n != child->children ().end (); ++n) {
253                         if ((*n)->is_content ()) {
254                                 /* XXX: this may be dubious for the same reasons that we delay
255                                    execution of load_preset.
256                                 */
257                                 ret = set_chunk ((*n)->content().c_str(), false);
258                         }
259                 }
260
261         } else if ((child = find_named_node (node, X_("parameters"))) != 0) {
262
263                 XMLPropertyList::const_iterator i;
264
265                 for (i = child->properties().begin(); i != child->properties().end(); ++i) {
266                         int32_t param;
267                         float val;
268
269                         sscanf ((*i)->name().c_str(), "param_%d", &param);
270                         sscanf ((*i)->value().c_str(), "%f", &val);
271
272                         _plugin->setParameter (_plugin, param, val);
273                 }
274
275                 /* program number is not knowable */
276
277                 _fst->current_program = -1;
278
279                 ret = 0;
280
281         }
282
283         Plugin::set_state (node, version);
284         return ret;
285 }
286
287 int
288 VSTPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& desc) const
289 {
290         VstParameterProperties prop;
291
292         desc.min_unbound = false;
293         desc.max_unbound = false;
294         prop.flags = 0;
295
296         if (_plugin->dispatcher (_plugin, effGetParameterProperties, which, 0, &prop, 0)) {
297
298 #ifdef VESTIGE_COMPLETE
299
300                 /* i have yet to find or hear of a VST plugin that uses this */
301
302                 if (prop.flags & kVstParameterUsesIntegerMinMax) {
303                         desc.lower = prop.minInteger;
304                         desc.upper = prop.maxInteger;
305                 } else {
306                         desc.lower = 0;
307                         desc.upper = 1.0;
308                 }
309
310                 if (prop.flags & kVstParameterUsesIntStep) {
311
312                         desc.step = prop.stepInteger;
313                         desc.smallstep = prop.stepInteger;
314                         desc.largestep = prop.stepInteger;
315
316                 } else if (prop.flags & kVstParameterUsesFloatStep) {
317
318                         desc.step = prop.stepFloat;
319                         desc.smallstep = prop.smallStepFloat;
320                         desc.largestep = prop.largeStepFloat;
321
322                 } else {
323
324                         float range = desc.upper - desc.lower;
325
326                         desc.step = range / 100.0f;
327                         desc.smallstep = desc.step / 2.0f;
328                         desc.largestep = desc.step * 10.0f;
329                 }
330
331                 desc.toggled = prop.flags & kVstParameterIsSwitch;
332                 desc.logarithmic = false;
333                 desc.sr_dependent = false;
334                 desc.label = prop.label;
335 #endif
336
337         } else {
338
339                 /* old style */
340
341                 char label[64];
342                 label[0] = '\0';
343
344                 _plugin->dispatcher (_plugin, effGetParamName, which, 0, label, 0);
345
346                 desc.label = label;
347                 desc.integer_step = false;
348                 desc.lower = 0.0f;
349                 desc.upper = 1.0f;
350                 desc.step = 0.01f;
351                 desc.smallstep = 0.005f;
352                 desc.largestep = 0.1f;
353                 desc.toggled = false;
354                 desc.logarithmic = false;
355                 desc.sr_dependent = false;
356         }
357
358         return 0;
359 }
360
361 bool
362 VSTPlugin::load_preset (PresetRecord r)
363 {
364         bool s;
365
366         if (r.user) {
367                 s = load_user_preset (r);
368         } else {
369                 s = load_plugin_preset (r);
370         }
371
372         if (s) {
373                 Plugin::load_preset (r);
374         }
375
376         return s;
377 }
378
379 bool
380 VSTPlugin::load_plugin_preset (PresetRecord r)
381 {
382         /* This is a plugin-provided preset.
383            We can't dispatch directly here; too many plugins expects only one GUI thread.
384         */
385
386         /* Extract the index of this preset from the URI */
387         int id;
388         int index;
389         int const p = sscanf (r.uri.c_str(), "VST:%d:%d", &id, &index);
390         assert (p == 2);
391
392         _fst->want_program = index;
393         return true;
394 }
395
396 bool
397 VSTPlugin::load_user_preset (PresetRecord r)
398 {
399         /* This is a user preset; we load it, and this code also knows about the
400            non-direct-dispatch thing.
401         */
402         
403         boost::shared_ptr<XMLTree> t (presets_tree ());
404         if (t == 0) {
405                 return false;
406         }
407         
408         XMLNode* root = t->root ();
409         
410         for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
411                 
412                 XMLProperty* uri = (*i)->property (X_("uri"));
413                 XMLProperty* label = (*i)->property (X_("label"));
414                 
415                 assert (uri);
416                 assert (label);
417                 
418                 if (label->value() != r.label) {
419                         continue;
420                 }
421                         
422                 if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
423                         
424                         /* Load a user preset chunk from our XML file and send it via a circuitous route to the plugin */
425                         
426                         if (_fst->wanted_chunk) {
427                                 g_free (_fst->wanted_chunk);
428                         }
429                         
430                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
431                                 if ((*j)->is_content ()) {
432                                         /* we can't dispatch directly here; too many plugins expect only one GUI thread */
433                                         gsize size = 0;
434                                         guchar* raw_data = g_base64_decode ((*j)->content().c_str(), &size);
435                                         _fst->wanted_chunk = raw_data;
436                                         _fst->wanted_chunk_size = size;
437                                         _fst->want_chunk = 1;
438                                         return true;
439                                 }
440                         }
441                         
442                         return false;
443                                 
444                 } else {
445                         
446                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
447                                 if ((*j)->name() == X_("Parameter")) {
448                                         
449                                                 XMLProperty* index = (*j)->property (X_("index"));
450                                                 XMLProperty* value = (*j)->property (X_("value"));
451                                                 
452                                                 assert (index);
453                                                 assert (value);
454                                                 
455                                                 set_parameter (atoi (index->value().c_str()), atof (value->value().c_str ()));
456                                 }
457                         }
458                         
459                         return true;
460                 }
461         }
462                 
463         return false;
464 }
465
466 string
467 VSTPlugin::do_save_preset (string name)
468 {
469         boost::shared_ptr<XMLTree> t (presets_tree ());
470         if (t == 0) {
471                 return "";
472         }
473
474         XMLNode* p = 0;
475         /* XXX: use of _presets.size() + 1 for the unique ID here is dubious at best */
476         string const uri = string_compose (X_("VST:%1:%2"), unique_id (), _presets.size() + 1);
477
478         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
479
480                 p = new XMLNode (X_("ChunkPreset"));
481                 p->add_property (X_("uri"), uri);
482                 p->add_property (X_("label"), name);
483                 gchar* data = get_chunk (true);
484                 p->add_content (string (data));
485                 g_free (data);
486                 
487         } else {
488
489                 p = new XMLNode (X_("Preset"));
490                 p->add_property (X_("uri"), uri);
491                 p->add_property (X_("label"), name);
492
493                 for (uint32_t i = 0; i < parameter_count(); ++i) {
494                         if (parameter_is_input (i)) {
495                                 XMLNode* c = new XMLNode (X_("Parameter"));
496                                 c->add_property (X_("index"), string_compose ("%1", i));
497                                 c->add_property (X_("value"), string_compose ("%1", get_parameter (i)));
498                                 p->add_child_nocopy (*c);
499                         }
500                 }
501                 
502         }
503
504         t->root()->add_child_nocopy (*p);
505         
506         sys::path f = ARDOUR::user_config_directory ();
507         f /= "presets";
508         f /= presets_file ();
509         
510         t->write (f.to_string ());
511         return uri;
512 }
513
514 void
515 VSTPlugin::do_remove_preset (string name)
516 {
517         boost::shared_ptr<XMLTree> t (presets_tree ());
518         if (t == 0) {
519                 return;
520         }
521         
522         t->root()->remove_nodes_and_delete (X_("label"), name);
523         
524         sys::path f = ARDOUR::user_config_directory ();
525         f /= "presets";
526         f /= presets_file ();
527         
528         t->write (f.to_string ());
529 }
530
531 string
532 VSTPlugin::describe_parameter (Evoral::Parameter param)
533 {
534         char name[64];
535         _plugin->dispatcher (_plugin, effGetParamName, param.id(), 0, name, 0);
536         return name;
537 }
538
539 framecnt_t
540 VSTPlugin::signal_latency () const
541 {
542         if (_user_latency) {
543                 return _user_latency;
544         }
545
546 #ifdef VESTIGE_HEADER
547         return *((framecnt_t *) (((char *) &_plugin->flags) + 12)); /* initialDelay */
548 #else
549         return _plugin->initial_delay;
550 #endif
551 }
552
553 set<Evoral::Parameter>
554 VSTPlugin::automatable () const
555 {
556         set<Evoral::Parameter> ret;
557
558         for (uint32_t i = 0; i < parameter_count(); ++i){
559                 ret.insert (ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
560         }
561
562         return ret;
563 }
564
565 int
566 VSTPlugin::connect_and_run (BufferSet& bufs,
567                 ChanMapping in_map, ChanMapping out_map,
568                 pframes_t nframes, framecnt_t offset)
569 {
570         Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
571         
572         float *ins[_plugin->numInputs];
573         float *outs[_plugin->numOutputs];
574         int32_t i;
575
576         const uint32_t nbufs = bufs.count().n_audio();
577
578         int in_index = 0;
579         for (i = 0; i < (int32_t) _plugin->numInputs; ++i) {
580                 ins[i] = bufs.get_audio(min((uint32_t) in_index, nbufs - 1)).data() + offset;
581                 in_index++;
582         }
583
584         int out_index = 0;
585         for (i = 0; i < (int32_t) _plugin->numOutputs; ++i) {
586                 outs[i] = bufs.get_audio(min((uint32_t) out_index, nbufs - 1)).data() + offset;
587
588                 /* unbelievably, several VST plugins still rely on Cubase
589                    behaviour and do not silence the buffer in processReplacing
590                    when they have no output.
591                 */
592
593                 // memset (outs[i], 0, sizeof (Sample) * nframes);
594                 out_index++;
595         }
596
597
598         if (bufs.count().n_midi() > 0) {
599                 VstEvents* v = bufs.get_vst_midi (0);
600                 _plugin->dispatcher (_plugin, effProcessEvents, 0, 0, v, 0);
601         }
602
603         /* we already know it can support processReplacing */
604         _plugin->processReplacing (_plugin, ins, outs, nframes);
605
606         return 0;
607 }
608
609 void
610 VSTPlugin::deactivate ()
611 {
612         _plugin->dispatcher (_plugin, effMainsChanged, 0, 0, NULL, 0.0f);
613 }
614
615 void
616 VSTPlugin::activate ()
617 {
618         _plugin->dispatcher (_plugin, effMainsChanged, 0, 1, NULL, 0.0f);
619 }
620
621 string
622 VSTPlugin::unique_id() const
623 {
624         char buf[32];
625
626 #ifdef VESTIGE_HEADER
627        snprintf (buf, sizeof (buf), "%d", *((int32_t*) &_plugin->unused_id));
628 #else
629        snprintf (buf, sizeof (buf), "%d", _plugin->uniqueID);
630 #endif
631        return string (buf);
632 }
633
634
635 const char *
636 VSTPlugin::name () const
637 {
638         return handle->name;
639 }
640
641 const char *
642 VSTPlugin::maker () const
643 {
644         return _info->creator.c_str();
645 }
646
647 const char *
648 VSTPlugin::label () const
649 {
650         return handle->name;
651 }
652
653 uint32_t
654 VSTPlugin::parameter_count() const
655 {
656         return _plugin->numParams;
657 }
658
659 bool
660 VSTPlugin::has_editor () const
661 {
662         return _plugin->flags & effFlagsHasEditor;
663 }
664
665 void
666 VSTPlugin::print_parameter (uint32_t param, char *buf, uint32_t len) const
667 {
668         char *first_nonws;
669
670         _plugin->dispatcher (_plugin, 7 /* effGetParamDisplay */, param, 0, buf, 0);
671
672         if (buf[0] == '\0') {
673                 return;
674         }
675
676         first_nonws = buf;
677         while (*first_nonws && isspace (*first_nonws)) {
678                 first_nonws++;
679         }
680         if (*first_nonws == '\0') {
681                 return;
682         }
683
684         memmove (buf, first_nonws, strlen (buf) - (first_nonws - buf) + 1);
685 }
686
687 PluginPtr
688 VSTPluginInfo::load (Session& session)
689 {
690         try {
691                 PluginPtr plugin;
692
693                 if (Config->get_use_vst()) {
694                         FSTHandle* handle;
695
696                         handle = fst_load(path.c_str());
697
698                         if ( (int)handle == -1) {
699                                 error << string_compose(_("VST: cannot load module from \"%1\""), path) << endmsg;
700                         } else {
701                                 plugin.reset (new VSTPlugin (session.engine(), session, handle));
702                         }
703                 } else {
704                         error << _("You asked ardour to not use any VST plugins") << endmsg;
705                         return PluginPtr ((Plugin*) 0);
706                 }
707
708                 plugin->set_info(PluginInfoPtr(new VSTPluginInfo(*this)));
709                 return plugin;
710         }
711
712         catch (failed_constructor &err) {
713                 return PluginPtr ((Plugin*) 0);
714         }
715 }
716
717 void
718 VSTPlugin::find_presets ()
719 {
720         /* Built-in presets */
721         
722         int const vst_version = _plugin->dispatcher (_plugin, effGetVstVersion, 0, 0, NULL, 0);
723         for (int i = 0; i < _plugin->numPrograms; ++i) {
724                 PresetRecord r (string_compose (X_("VST:%1:%2"), unique_id (), i), "", false);
725                 
726                 if (vst_version >= 2) {
727                         char buf[256];
728                         if (_plugin->dispatcher (_plugin, 29, i, 0, buf, 0) == 1) {
729                                 r.label = buf;
730                         } else {
731                                 r.label = string_compose (_("Preset %1"), i);
732                         }
733                 } else {
734                         r.label = string_compose (_("Preset %1"), i);
735                 }
736
737                 _presets.insert (make_pair (r.uri, r));
738         }
739
740         /* User presets from our XML file */
741
742         boost::shared_ptr<XMLTree> t (presets_tree ());
743
744         if (t) {
745                 XMLNode* root = t->root ();
746                 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
747
748                         XMLProperty* uri = (*i)->property (X_("uri"));
749                         XMLProperty* label = (*i)->property (X_("label"));
750
751                         assert (uri);
752                         assert (label);
753
754                         PresetRecord r (uri->value(), label->value(), true);
755                         _presets.insert (make_pair (r.uri, r));
756                 }
757         }
758
759 }
760
761 /** @return XMLTree with our user presets; could be a new one if no existing
762  *  one was found, or 0 if one was present but badly-formatted.
763  */
764 XMLTree *
765 VSTPlugin::presets_tree () const
766 {
767         XMLTree* t = new XMLTree;
768
769         sys::path p = ARDOUR::user_config_directory ();
770         p /= "presets";
771
772         if (!is_directory (p)) {
773                 create_directory (p);
774         }
775
776         p /= presets_file ();
777
778         if (!exists (p)) {
779                 t->set_root (new XMLNode (X_("VSTPresets")));
780                 return t;
781         }
782         
783         t->set_filename (p.to_string ());
784         if (!t->read ()) {
785                 delete t;
786                 return 0;
787         }
788
789         return t;
790 }
791
792 /** @return Index of the first user preset in our lists */
793 int
794 VSTPlugin::first_user_preset_index () const
795 {
796         return _plugin->numPrograms;
797 }
798
799 string
800 VSTPlugin::presets_file () const
801 {
802         return string_compose ("vst-%1", unique_id ());
803 }
804
805 VSTPluginInfo::VSTPluginInfo()
806 {
807        type = ARDOUR::VST;
808 }
809