Use PBD::ffs for portability
[ardour.git] / libs / ardour / vst_plugin.cc
1 /*
2     Copyright (C) 2010 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 <glib.h>
21 #include <glib/gstdio.h>
22
23 #include <glibmm/fileutils.h>
24 #include <glibmm/miscutils.h>
25
26 #include "pbd/floating.h"
27 #include "pbd/locale_guard.h"
28 #include "pbd/pathscanner.h"
29
30 #include "ardour/vst_plugin.h"
31 #include "ardour/vestige/aeffectx.h"
32 #include "ardour/session.h"
33 #include "ardour/vst_types.h"
34 #include "ardour/filesystem_paths.h"
35 #include "ardour/audio_buffer.h"
36
37 #include "i18n.h"
38
39 using namespace std;
40 using namespace PBD;
41 using namespace ARDOUR;
42
43 VSTPlugin::VSTPlugin (AudioEngine& engine, Session& session, VSTHandle* handle)
44         : Plugin (engine, session)
45         , _handle (handle)
46         , _state (0)
47         , _plugin (0)
48 {
49         
50 }
51
52 VSTPlugin::~VSTPlugin ()
53 {
54         
55 }
56
57 void
58 VSTPlugin::set_plugin (AEffect* e)
59 {
60         _plugin = e;
61         _plugin->user = this;
62
63         /* set rate and blocksize */
64
65         _plugin->dispatcher (_plugin, effSetSampleRate, 0, 0, NULL, (float) _session.frame_rate());
66         _plugin->dispatcher (_plugin, effSetBlockSize, 0, _session.get_block_size(), NULL, 0.0f);
67 }
68
69 void
70 VSTPlugin::deactivate ()
71 {
72         _plugin->dispatcher (_plugin, effMainsChanged, 0, 0, NULL, 0.0f);
73 }
74
75 void
76 VSTPlugin::activate ()
77 {
78         _plugin->dispatcher (_plugin, effMainsChanged, 0, 1, NULL, 0.0f);
79 }
80
81 int 
82 VSTPlugin::set_block_size (pframes_t nframes)
83 {
84         deactivate ();
85         _plugin->dispatcher (_plugin, effSetBlockSize, 0, nframes, NULL, 0.0f);
86         activate ();
87         return 0;
88 }
89
90 float
91 VSTPlugin::default_value (uint32_t)
92 {
93         return 0;
94 }
95
96 float 
97 VSTPlugin::get_parameter (uint32_t which) const
98 {
99         return _plugin->getParameter (_plugin, which);
100 }
101
102 void 
103 VSTPlugin::set_parameter (uint32_t which, float newval)
104 {
105         float oldval = get_parameter (which);
106
107         if (PBD::floateq (oldval, newval, 1)) {
108                 return;
109         }
110
111         _plugin->setParameter (_plugin, which, newval);
112         
113         float curval = get_parameter (which);
114
115         if (!PBD::floateq (curval, oldval, 1)) {
116                 /* value has changed, follow rest of the notification path */
117                 Plugin::set_parameter (which, newval);
118         }
119 }
120
121 uint32_t
122 VSTPlugin::nth_parameter (uint32_t n, bool& ok) const
123 {
124         ok = true;
125         return n;
126 }
127
128 /** Get VST chunk as base64-encoded data.
129  *  @param single true for single program, false for all programs.
130  *  @return 0-terminated base64-encoded data; must be passed to g_free () by caller.
131  */
132 gchar *
133 VSTPlugin::get_chunk (bool single) const
134 {
135         guchar* data;
136         int32_t data_size = _plugin->dispatcher (_plugin, 23 /* effGetChunk */, single ? 1 : 0, 0, &data, 0);
137         if (data_size == 0) {
138                 return 0;
139         }
140
141         return g_base64_encode (data, data_size);
142 }
143
144 /** Set VST chunk from base64-encoded data.
145  *  @param 0-terminated base64-encoded data.
146  *  @param single true for single program, false for all programs.
147  *  @return 0 on success, non-0 on failure
148  */
149 int
150 VSTPlugin::set_chunk (gchar const * data, bool single)
151 {
152         gsize size = 0;
153         guchar* raw_data = g_base64_decode (data, &size);
154         int const r = _plugin->dispatcher (_plugin, 24 /* effSetChunk */, single ? 1 : 0, size, raw_data, 0);
155         g_free (raw_data);
156         return r;
157 }
158
159 void
160 VSTPlugin::add_state (XMLNode* root) const
161 {
162         LocaleGuard lg (X_("POSIX"));
163
164         if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
165
166                 gchar* data = get_chunk (false);
167                 if (data == 0) {
168                         return;
169                 }
170
171                 /* store information */
172
173                 XMLNode* chunk_node = new XMLNode (X_("chunk"));
174
175                 chunk_node->add_content (data);
176                 g_free (data);
177
178                 root->add_child_nocopy (*chunk_node);
179
180         } else {
181
182                 XMLNode* parameters = new XMLNode ("parameters");
183
184                 for (int32_t n = 0; n < _plugin->numParams; ++n) {
185                         char index[64];
186                         char val[32];
187                         snprintf (index, sizeof (index), "param-%d", n);
188                         snprintf (val, sizeof (val), "%.12g", _plugin->getParameter (_plugin, n));
189                         parameters->add_property (index, val);
190                 }
191
192                 root->add_child_nocopy (*parameters);
193         }
194 }
195
196 int
197 VSTPlugin::set_state (const XMLNode& node, int version)
198 {
199         LocaleGuard lg (X_("POSIX"));
200
201         if (node.name() != state_node_name()) {
202                 error << _("Bad node sent to VSTPlugin::set_state") << endmsg;
203                 return 0;
204         }
205
206         XMLNode* child;
207         int ret = -1;
208
209         if ((child = find_named_node (node, X_("chunk"))) != 0) {
210
211                 XMLPropertyList::const_iterator i;
212                 XMLNodeList::const_iterator n;
213
214                 for (n = child->children ().begin (); n != child->children ().end (); ++n) {
215                         if ((*n)->is_content ()) {
216                                 /* XXX: this may be dubious for the same reasons that we delay
217                                    execution of load_preset.
218                                 */
219                                 ret = set_chunk ((*n)->content().c_str(), false);
220                         }
221                 }
222
223         } else if ((child = find_named_node (node, X_("parameters"))) != 0) {
224
225                 XMLPropertyList::const_iterator i;
226
227                 for (i = child->properties().begin(); i != child->properties().end(); ++i) {
228                         int32_t param;
229                         float val;
230
231                         sscanf ((*i)->name().c_str(), "param-%d", &param);
232                         sscanf ((*i)->value().c_str(), "%f", &val);
233
234                         _plugin->setParameter (_plugin, param, val);
235                 }
236
237                 ret = 0;
238
239         }
240
241         Plugin::set_state (node, version);
242         return ret;
243 }
244
245
246 int
247 VSTPlugin::get_parameter_descriptor (uint32_t which, ParameterDescriptor& desc) const
248 {
249         VstParameterProperties prop;
250
251         desc.min_unbound = false;
252         desc.max_unbound = false;
253         prop.flags = 0;
254
255         if (_plugin->dispatcher (_plugin, effGetParameterProperties, which, 0, &prop, 0)) {
256
257                 /* i have yet to find or hear of a VST plugin that uses this */
258
259                 if (prop.flags & kVstParameterUsesIntegerMinMax) {
260                         desc.lower = prop.minInteger;
261                         desc.upper = prop.maxInteger;
262                 } else {
263                         desc.lower = 0;
264                         desc.upper = 1.0;
265                 }
266
267                 if (prop.flags & kVstParameterUsesIntStep) {
268
269                         desc.step = prop.stepInteger;
270                         desc.smallstep = prop.stepInteger;
271                         desc.largestep = prop.stepInteger;
272
273                 } else if (prop.flags & kVstParameterUsesFloatStep) {
274
275                         desc.step = prop.stepFloat;
276                         desc.smallstep = prop.smallStepFloat;
277                         desc.largestep = prop.largeStepFloat;
278
279                 } else {
280
281                         float range = desc.upper - desc.lower;
282
283                         desc.step = range / 100.0f;
284                         desc.smallstep = desc.step / 2.0f;
285                         desc.largestep = desc.step * 10.0f;
286                 }
287
288                 desc.toggled = prop.flags & kVstParameterIsSwitch;
289                 desc.logarithmic = false;
290                 desc.sr_dependent = false;
291                 desc.label = prop.label;
292
293         } else {
294
295                 /* old style */
296
297                 char label[64];
298                 /* some VST plugins expect this buffer to be zero-filled */
299                 memset (label, sizeof (label), 0);
300
301                 _plugin->dispatcher (_plugin, effGetParamName, which, 0, label, 0);
302                 
303                 desc.label = label;
304                 desc.integer_step = false;
305                 desc.lower = 0.0f;
306                 desc.upper = 1.0f;
307                 desc.step = 0.01f;
308                 desc.smallstep = 0.005f;
309                 desc.largestep = 0.1f;
310                 desc.toggled = false;
311                 desc.logarithmic = false;
312                 desc.sr_dependent = false;
313         }
314
315         return 0;
316 }
317
318 bool
319 VSTPlugin::load_preset (PresetRecord r)
320 {
321         bool s;
322
323         if (r.user) {
324                 s = load_user_preset (r);
325         } else {
326                 s = load_plugin_preset (r);
327         }
328
329         if (s) {
330                 Plugin::load_preset (r);
331         }
332
333         return s;
334 }
335
336 bool 
337 VSTPlugin::load_plugin_preset (PresetRecord r)
338 {
339         /* This is a plugin-provided preset.
340            We can't dispatch directly here; too many plugins expects only one GUI thread.
341         */
342
343         /* Extract the index of this preset from the URI */
344         int id;
345         int index;
346 #ifndef NDEBUG
347         int const p = sscanf (r.uri.c_str(), "VST:%d:%d", &id, &index);
348         assert (p == 2);
349 #else 
350         sscanf (r.uri.c_str(), "VST:%d:%d", &id, &index);
351 #endif
352         
353         _state->want_program = index;
354         return true;
355 }
356
357 bool 
358 VSTPlugin::load_user_preset (PresetRecord r)
359 {
360         /* This is a user preset; we load it, and this code also knows about the
361            non-direct-dispatch thing.
362         */
363
364         boost::shared_ptr<XMLTree> t (presets_tree ());
365         if (t == 0) {
366                 return false;
367         }
368
369         XMLNode* root = t->root ();
370
371         for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
372                 XMLProperty* label = (*i)->property (X_("label"));
373
374                 assert (label);
375
376                 if (label->value() != r.label) {
377                         continue;
378                 }
379
380                 if (_plugin->flags & 32 /* effFlagsProgramsChunks */) {
381
382                         /* Load a user preset chunk from our XML file and send it via a circuitous route to the plugin */
383
384                         if (_state->wanted_chunk) {
385                                 g_free (_state->wanted_chunk);
386                         }
387
388                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
389                                 if ((*j)->is_content ()) {
390                                         /* we can't dispatch directly here; too many plugins expect only one GUI thread */
391                                         gsize size = 0;
392                                         guchar* raw_data = g_base64_decode ((*j)->content().c_str(), &size);
393                                         _state->wanted_chunk = raw_data;
394                                         _state->wanted_chunk_size = size;
395                                         _state->want_chunk = 1;
396                                         return true;
397                                 }
398                         }
399
400                         return false;
401
402                 } else {
403                         
404                         for (XMLNodeList::const_iterator j = (*i)->children().begin(); j != (*i)->children().end(); ++j) {
405                                 if ((*j)->name() == X_("Parameter")) {
406                                                 XMLProperty* index = (*j)->property (X_("index"));
407                                                 XMLProperty* value = (*j)->property (X_("value"));
408
409                                                 assert (index);
410                                                 assert (value);
411
412                                                 set_parameter (atoi (index->value().c_str()), atof (value->value().c_str ()));
413                                 }
414                         }
415                         return true;
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         t->root()->add_child_nocopy (*p);
459
460         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
461         f = Glib::build_filename (f, presets_file ());
462
463         t->write (f);
464         return uri;
465 }
466
467 void 
468 VSTPlugin::do_remove_preset (string name)
469 {
470         boost::shared_ptr<XMLTree> t (presets_tree ());
471         if (t == 0) {
472                 return;
473         }
474
475         t->root()->remove_nodes_and_delete (X_("label"), name);
476
477         std::string f = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
478         f = Glib::build_filename (f, presets_file ());
479
480         t->write (f);
481 }
482
483 string 
484 VSTPlugin::describe_parameter (Evoral::Parameter param)
485 {
486         char name[64];
487         memset (name, sizeof (name), 0);
488
489         /* some VST plugins expect this buffer to be zero-filled */
490
491         _plugin->dispatcher (_plugin, effGetParamName, param.id(), 0, name, 0);
492
493         if (name[0] == '\0') {
494                 strcpy (name, _("Unknown"));
495         }
496
497         return name;
498 }
499
500 framecnt_t 
501 VSTPlugin::signal_latency () const
502 {
503         if (_user_latency) {
504                 return _user_latency;
505         }
506
507         return *((int32_t *) (((char *) &_plugin->flags) + 12)); /* initialDelay */
508 }
509
510 set<Evoral::Parameter> 
511 VSTPlugin::automatable () const
512 {
513         set<Evoral::Parameter> ret;
514
515         for (uint32_t i = 0; i < parameter_count(); ++i) {
516                 ret.insert (ret.end(), Evoral::Parameter(PluginAutomation, 0, i));
517         }
518
519         return ret;
520 }
521
522 int
523 VSTPlugin::connect_and_run (BufferSet& bufs,
524                             ChanMapping in_map, ChanMapping out_map,
525                             pframes_t nframes, framecnt_t offset)
526 {
527         Plugin::connect_and_run (bufs, in_map, out_map, nframes, offset);
528
529         float *ins[_plugin->numInputs];
530         float *outs[_plugin->numOutputs];
531         int32_t i;
532
533         const uint32_t nbufs = bufs.count().n_audio();
534
535         int in_index = 0;
536         for (i = 0; i < (int32_t) _plugin->numInputs; ++i) {
537                 ins[i] = bufs.get_audio(min((uint32_t) in_index, nbufs - 1)).data() + offset;
538                 in_index++;
539         }
540
541         int out_index = 0;
542         for (i = 0; i < (int32_t) _plugin->numOutputs; ++i) {
543                 outs[i] = bufs.get_audio(min((uint32_t) out_index, nbufs - 1)).data() + offset;
544                 out_index++;
545         }
546
547         if (bufs.count().n_midi() > 0) {
548                 VstEvents* v = bufs.get_vst_midi (0);
549                 _plugin->dispatcher (_plugin, effProcessEvents, 0, 0, v, 0);
550         }
551
552         /* we already know it can support processReplacing */
553         _plugin->processReplacing (_plugin, ins, outs, nframes);
554
555         return 0;
556 }
557
558 string 
559 VSTPlugin::unique_id () const
560 {
561         char buf[32];
562
563         snprintf (buf, sizeof (buf), "%d", _plugin->uniqueID);
564         
565         return string (buf);
566 }
567
568
569 const char * 
570 VSTPlugin::name () const
571 {
572         return _handle->name;
573 }
574
575 const char * 
576 VSTPlugin::maker () const
577 {
578         return _info->creator.c_str();
579 }
580
581 const char * 
582 VSTPlugin::label () const
583 {
584         return _handle->name;
585 }
586
587 uint32_t 
588 VSTPlugin::parameter_count () const
589 {
590         return _plugin->numParams;
591 }
592
593 bool 
594 VSTPlugin::has_editor () const
595 {
596         return _plugin->flags & effFlagsHasEditor;
597 }
598
599 void 
600 VSTPlugin::print_parameter (uint32_t param, char *buf, uint32_t /*len*/) const
601 {
602         char *first_nonws;
603
604         _plugin->dispatcher (_plugin, 7 /* effGetParamDisplay */, param, 0, buf, 0);
605
606         if (buf[0] == '\0') {
607                 return;
608         }
609
610         first_nonws = buf;
611         while (*first_nonws && isspace (*first_nonws)) {
612                 first_nonws++;
613         }
614
615         if (*first_nonws == '\0') {
616                 return;
617         }
618
619         memmove (buf, first_nonws, strlen (buf) - (first_nonws - buf) + 1);
620 }
621
622 void
623 VSTPlugin::find_presets ()
624 {
625         /* Built-in presets */
626
627         int const vst_version = _plugin->dispatcher (_plugin, effGetVstVersion, 0, 0, NULL, 0);
628         for (int i = 0; i < _plugin->numPrograms; ++i) {
629                 PresetRecord r (string_compose (X_("VST:%1:%2"), unique_id (), i), "", -1, false);
630
631                 if (vst_version >= 2) {
632                         char buf[256];
633                         if (_plugin->dispatcher (_plugin, 29, i, 0, buf, 0) == 1) {
634                                 r.label = buf;
635                         } else {
636                                 r.label = string_compose (_("Preset %1"), i);
637                         }
638                 } else {
639                         r.label = string_compose (_("Preset %1"), i);
640                 }
641
642                 _presets.insert (make_pair (r.uri, r));
643         }
644
645         /* User presets from our XML file */
646
647         boost::shared_ptr<XMLTree> t (presets_tree ());
648
649         if (t) {
650                 XMLNode* root = t->root ();
651                 for (XMLNodeList::const_iterator i = root->children().begin(); i != root->children().end(); ++i) {
652
653                         XMLProperty* uri = (*i)->property (X_("uri"));
654                         XMLProperty* label = (*i)->property (X_("label"));
655
656                         assert (uri);
657                         assert (label);
658
659                         PresetRecord r (uri->value(), label->value(), -1, true);
660                         _presets.insert (make_pair (r.uri, r));
661                 }
662         }
663
664 }
665
666 /** @return XMLTree with our user presets; could be a new one if no existing
667  *  one was found, or 0 if one was present but badly-formatted.
668  */
669 XMLTree *
670 VSTPlugin::presets_tree () const
671 {
672         XMLTree* t = new XMLTree;
673
674         std::string p = Glib::build_filename (ARDOUR::user_config_directory (), "presets");
675
676         if (!Glib::file_test (p, Glib::FILE_TEST_IS_DIR)) {
677                 if (g_mkdir_with_parents (p.c_str(), 0755) != 0) {
678                         error << _("Unable to make VST presets directory") << endmsg;
679                 };
680         }
681
682         p = Glib::build_filename (p, presets_file ());
683
684         if (!Glib::file_test (p, Glib::FILE_TEST_EXISTS)) {
685                 t->set_root (new XMLNode (X_("VSTPresets")));
686                 return t;
687         }
688
689         t->set_filename (p);
690         if (!t->read ()) {
691                 delete t;
692                 return 0;
693         }
694
695         return t;
696 }
697
698 /** @return Index of the first user preset in our lists */
699 int
700 VSTPlugin::first_user_preset_index () const
701 {
702         return _plugin->numPrograms;
703 }
704
705 string
706 VSTPlugin::presets_file () const
707 {
708         return string_compose ("vst-%1", unique_id ());
709 }
710