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