cleanup up cleanup at session destruction; clarify the meaning of 3 signals (DropRefe...
[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/ustring.h>
34 #include <glibmm/miscutils.h>
35
36 #include <lrdf.h>
37 #include <fst.h>
38
39 #include "pbd/compose.h"
40 #include "pbd/error.h"
41 #include "pbd/pathscanner.h"
42 #include "pbd/xml++.h"
43
44 #include <fst.h>
45
46 #include "ardour/session.h"
47 #include "ardour/audioengine.h"
48 #include "ardour/filesystem_paths.h"
49 #include "ardour/vst_plugin.h"
50 #include "ardour/buffer_set.h"
51 #include "ardour/audio_buffer.h"
52
53 #include "pbd/stl_delete.h"
54
55 #include "i18n.h"
56 #include <locale.h>
57
58 using namespace ARDOUR;
59 using namespace PBD;
60 using std::min;
61 using std::max;
62
63 VSTPlugin::VSTPlugin (AudioEngine& e, Session& session, FSTHandle* h)
64         : Plugin (e, session)
65 {
66         handle = h;
67
68         if ((_fst = fst_instantiate (handle, Session::vst_callback, this)) == 0) {
69                 throw failed_constructor();
70         }
71
72         _plugin = _fst->plugin;
73         _plugin->user = this;
74
75         /* set rate and blocksize */
76
77         _plugin->dispatcher (_plugin, effSetSampleRate, 0, 0, NULL,
78                              (float) session.frame_rate());
79         _plugin->dispatcher (_plugin, effSetBlockSize, 0,
80                              session.get_block_size(), NULL, 0.0f);
81
82         /* set program to zero */
83
84         _plugin->dispatcher (_plugin, effSetProgram, 0, 0, NULL, 0.0f);
85
86         // Plugin::setup_controls ();
87 }
88
89 VSTPlugin::VSTPlugin (const VSTPlugin &other)
90         : Plugin (other)
91 {
92         handle = other.handle;
93
94         if ((_fst = fst_instantiate (handle, Session::vst_callback, this)) == 0) {
95                 throw failed_constructor();
96         }
97         _plugin = _fst->plugin;
98
99         // Plugin::setup_controls ();
100 }
101
102 VSTPlugin::~VSTPlugin ()
103 {
104         deactivate ();
105         fst_close (_fst);
106 }
107
108 void
109 VSTPlugin::set_block_size (nframes_t nframes)
110 {
111         deactivate ();
112         _plugin->dispatcher (_plugin, effSetBlockSize, 0, nframes, NULL, 0.0f);
113         activate ();
114 }
115
116 float
117 VSTPlugin::default_value (uint32_t port)
118 {
119         return 0;
120 }
121
122 void
123 VSTPlugin::set_parameter (uint32_t which, float val)
124 {
125         _plugin->setParameter (_plugin, which, val);
126         //ParameterChanged (which, val); /* EMIT SIGNAL */
127 }
128
129 float
130 VSTPlugin::get_parameter (uint32_t which) const
131 {
132         return _plugin->getParameter (_plugin, which);
133
134 }
135
136 uint32_t
137 VSTPlugin::nth_parameter (uint32_t n, bool& ok) const
138 {
139         ok = true;
140         return n;
141 }
142
143 XMLNode&
144 VSTPlugin::get_state()
145 {
146         XMLNode *root = new XMLNode (state_node_name());
147         LocaleGuard lg (X_("POSIX"));
148
149         if (_fst->current_program != -1) {
150                 char buf[32];
151                 snprintf (buf, sizeof (buf), "%d", _fst->current_program);
152                 root->add_property ("current-program", buf);
153         }
154
155         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
156
157                 /* fetch the current chunk */
158
159                 guchar* data;
160                 long  data_size;
161
162                 if ((data_size = _plugin->dispatcher (_plugin, 23 /* effGetChunk */, 0, 0, &data, false)) == 0) {
163                         return *root;
164                 }
165
166                 /* store information */
167
168                 XMLNode* chunk_node = new XMLNode (X_("chunk"));
169
170                 gchar * encoded_data = g_base64_encode (data, data_size);
171                 chunk_node->add_content (encoded_data);
172                 g_free (encoded_data);
173
174                 root->add_child_nocopy (*chunk_node);
175
176         } else {
177
178                 XMLNode* parameters = new XMLNode ("parameters");
179
180                 for (long n = 0; n < _plugin->numParams; ++n) {
181                         char index[64];
182                         char val[32];
183                         snprintf (index, sizeof (index), "param_%ld", n);
184                         snprintf (val, sizeof (val), "%.12g", _plugin->getParameter (_plugin, n));
185                         parameters->add_property (index, val);
186                 }
187
188                 root->add_child_nocopy (*parameters);
189         }
190
191         return *root;
192 }
193
194 int
195 VSTPlugin::set_state(const XMLNode& node)
196 {
197         LocaleGuard lg (X_("POSIX"));
198
199         if (node.name() != state_node_name()) {
200                 error << _("Bad node sent to VSTPlugin::set_state") << endmsg;
201                 return 0;
202         }
203
204         const XMLProperty* prop;
205
206         if ((prop = node.property ("current-program")) != 0) {
207                 _fst->current_program = atoi (prop->value());
208         }
209
210         XMLNode* child;
211         int ret = -1;
212
213         if ((child = find_named_node (node, X_("chunk"))) != 0) {
214
215                 XMLPropertyList::const_iterator i;
216                 XMLNodeList::const_iterator n;
217                 int ret = -1;
218
219                 for (n = child->children ().begin (); n != child->children ().end (); ++n) {
220                         if ((*n)->is_content ()) {
221                                 gsize chunk_size = 0;
222                                 guchar * data = g_base64_decode ((*n)->content ().c_str (), &chunk_size);
223                                 //cerr << "Dispatch setChunk for " << name() << endl;
224                                 ret = _plugin->dispatcher (_plugin, 24 /* effSetChunk */, 0, chunk_size, data, 0);
225                                 g_free (data);
226                         }
227                 }
228
229         } else if ((child = find_named_node (node, X_("parameters"))) != 0) {
230
231                 XMLPropertyList::const_iterator i;
232
233                 for (i = child->properties().begin(); i != child->properties().end(); ++i) {
234                         long param;
235                         float val;
236
237                         sscanf ((*i)->name().c_str(), "param_%ld", &param);
238                         sscanf ((*i)->value().c_str(), "%f", &val);
239
240                         _plugin->setParameter (_plugin, param, val);
241                 }
242
243                 /* program number is not knowable */
244
245                 _fst->current_program = -1;
246
247                 ret = 0;
248
249         }
250
251         return ret;
252 }
253
254 int
255 VSTPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& desc) const
256 {
257         VstParameterProperties prop;
258
259         desc.min_unbound = false;
260         desc.max_unbound = false;
261         prop.flags = 0;
262
263         if (_plugin->dispatcher (_plugin, effGetParameterProperties, which, 0, &prop, 0)) {
264
265 #ifdef VESTIGE_COMPLETE
266
267                 /* i have yet to find or hear of a VST plugin that uses this */
268
269                 if (prop.flags & kVstParameterUsesIntegerMinMax) {
270                         desc.lower = prop.minInteger;
271                         desc.upper = prop.maxInteger;
272                 } else {
273                         desc.lower = 0;
274                         desc.upper = 1.0;
275                 }
276
277                 if (prop.flags & kVstParameterUsesIntStep) {
278
279                         desc.step = prop.stepInteger;
280                         desc.smallstep = prop.stepInteger;
281                         desc.largestep = prop.stepInteger;
282
283                 } else if (prop.flags & kVstParameterUsesFloatStep) {
284
285                         desc.step = prop.stepFloat;
286                         desc.smallstep = prop.smallStepFloat;
287                         desc.largestep = prop.largeStepFloat;
288
289                 } else {
290
291                         float range = desc.upper - desc.lower;
292
293                         desc.step = range / 100.0f;
294                         desc.smallstep = desc.step / 2.0f;
295                         desc.largestep = desc.step * 10.0f;
296                 }
297
298                 desc.toggled = prop.flags & kVstParameterIsSwitch;
299                 desc.logarithmic = false;
300                 desc.sr_dependent = false;
301                 desc.label = prop.label;
302 #endif
303
304         } else {
305
306                 /* old style */
307
308                 char label[64];
309                 label[0] = '\0';
310
311                 _plugin->dispatcher (_plugin, effGetParamName, which, 0, label, 0);
312
313                 desc.label = label;
314                 desc.integer_step = false;
315                 desc.lower = 0.0f;
316                 desc.upper = 1.0f;
317                 desc.step = 0.01f;
318                 desc.smallstep = 0.005f;
319                 desc.largestep = 0.1f;
320                 desc.toggled = false;
321                 desc.logarithmic = false;
322                 desc.sr_dependent = false;
323         }
324
325         return 0;
326 }
327
328 bool
329 VSTPlugin::load_preset (string name)
330 {
331         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
332                 error << _("no support for presets using chunks at this time")
333                       << endmsg;
334                 return false;
335         }
336         return Plugin::load_preset (name);
337 }
338
339 bool
340 VSTPlugin::save_preset (string name)
341 {
342         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
343                 error << _("no support for presets using chunks at this time")
344                       << endmsg;
345                 return false;
346         }
347         return Plugin::save_preset (name, "vst");
348 }
349
350 string
351 VSTPlugin::describe_parameter (Evoral::Parameter param)
352 {
353         char name[64];
354         _plugin->dispatcher (_plugin, effGetParamName, param.id(), 0, name, 0);
355         return name;
356 }
357
358 nframes_t
359 VSTPlugin::signal_latency () const
360 {
361         if (_user_latency) {
362                 return _user_latency;
363         }
364
365 #ifdef VESTIGE_HEADER
366         return *((nframes_t *) (((char *) &_plugin->flags) + 12)); /* initialDelay */
367 #else
368         return _plugin->initial_delay;
369 #endif
370 }
371
372 set<Evoral::Parameter>
373 VSTPlugin::automatable () const
374 {
375         set<Evoral::Parameter> ret;
376
377         for (uint32_t i = 0; i < parameter_count(); ++i){
378                 ret.insert (ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
379         }
380
381         return ret;
382 }
383
384 int
385 VSTPlugin::connect_and_run (BufferSet& bufs,
386                 ChanMapping in_map, ChanMapping out_map,
387                 nframes_t nframes, nframes_t offset)
388 {
389         float *ins[_plugin->numInputs];
390         float *outs[_plugin->numOutputs];
391         int32_t i;
392
393         const uint32_t nbufs = bufs.count().n_audio();
394
395         for (i = 0; i < (int32_t) _plugin->numInputs; ++i) {
396                 ins[i] = bufs.get_audio(min((uint32_t) in_index, nbufs - 1)).data() + offset;
397                 in_index++;
398         }
399
400         for (i = 0; i < (int32_t) _plugin->numOutputs; ++i) {
401                 outs[i] = bufs.get_audio(min((uint32_t) out_index, nbufs - 1)).data() + offset;
402
403                 /* unbelievably, several VST plugins still rely on Cubase
404                    behaviour and do not silence the buffer in processReplacing
405                    when they have no output.
406                 */
407
408                 // memset (outs[i], 0, sizeof (Sample) * nframes);
409                 out_index++;
410         }
411
412
413         /* we already know it can support processReplacing */
414
415         _plugin->processReplacing (_plugin, ins, outs, nframes);
416
417         return 0;
418 }
419
420 void
421 VSTPlugin::deactivate ()
422 {
423         _plugin->dispatcher (_plugin, effMainsChanged, 0, 0, NULL, 0.0f);
424 }
425
426 void
427 VSTPlugin::activate ()
428 {
429         _plugin->dispatcher (_plugin, effMainsChanged, 0, 1, NULL, 0.0f);
430 }
431
432 string
433 VSTPlugin::unique_id() const
434 {
435         char buf[32];
436
437 #ifdef VESTIGE_HEADER
438        snprintf (buf, sizeof (buf), "%d", *((int32_t*) &_plugin->unused_id));
439 #else
440        snprintf (buf, sizeof (buf), "%d", _plugin->uniqueID);
441 #endif
442        return string (buf);
443 }
444
445
446 const char *
447 VSTPlugin::name () const
448 {
449         return handle->name;
450 }
451
452 const char *
453 VSTPlugin::maker () const
454 {
455         return "imadeit";
456 }
457
458 const char *
459 VSTPlugin::label () const
460 {
461         return handle->name;
462 }
463
464 uint32_t
465 VSTPlugin::parameter_count() const
466 {
467         return _plugin->numParams;
468 }
469
470 bool
471 VSTPlugin::has_editor () const
472 {
473         return _plugin->flags & effFlagsHasEditor;
474 }
475
476 void
477 VSTPlugin::print_parameter (uint32_t param, char *buf, uint32_t len) const
478 {
479         char *first_nonws;
480
481         _plugin->dispatcher (_plugin, 7 /* effGetParamDisplay */, param, 0, buf, 0);
482
483         if (buf[0] == '\0') {
484                 return;
485         }
486
487         first_nonws = buf;
488         while (*first_nonws && isspace (*first_nonws)) {
489                 first_nonws++;
490         }
491         if (*first_nonws == '\0') {
492                 return;
493         }
494
495         memmove (buf, first_nonws, strlen (buf) - (first_nonws - buf) + 1);
496 }
497
498 PluginPtr
499 VSTPluginInfo::load (Session& session)
500 {
501         try {
502                 PluginPtr plugin;
503
504                 if (Config->get_use_vst()) {
505                         FSTHandle* handle;
506
507                         handle = fst_load(path.c_str());
508
509                         if ( (int)handle == -1) {
510                                 error << string_compose(_("VST: cannot load module from \"%1\""), path) << endmsg;
511                         } else {
512                                 plugin.reset (new VSTPlugin (session.engine(), session, handle));
513                         }
514                 } else {
515                         error << _("You asked ardour to not use any VST plugins") << endmsg;
516                         return PluginPtr ((Plugin*) 0);
517                 }
518
519                 plugin->set_info(PluginInfoPtr(new VSTPluginInfo(*this)));
520                 return plugin;
521         }
522
523         catch (failed_constructor &err) {
524                 return PluginPtr ((Plugin*) 0);
525         }
526 }