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