Expose virtual-keyboard port as async-port
[ardour.git] / libs / ardour / vst_info_file.cc
1 /*
2  * Copyright (C) 2014-2016 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2014-2019 Robin Gareus <robin@gareus.org>
4  * Copyright (C) 2015-2017 John Emmas <john@creativepost.co.uk>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 /** @file libs/ardour/vst_info_file.cc
22  *  @brief Code to manage info files containing cached information about a plugin.
23  *  e.g. its name, creator etc.
24  */
25
26 #include <cassert>
27
28 #include <sys/types.h>
29
30 #ifdef COMPILER_MSVC
31 #include <sys/utime.h>
32 #else
33 #include <unistd.h>
34 #include <utime.h>
35 #endif
36
37 #include <fcntl.h>
38 #include <errno.h>
39
40 #include <stdlib.h>
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <string.h>
44
45 #include <glib.h>
46 #include "pbd/gstdio_compat.h"
47 #include <glibmm.h>
48
49 #include "pbd/error.h"
50 #include "pbd/compose.h"
51
52 #ifndef VST_SCANNER_APP
53 #include "ardour/plugin_manager.h" // scanner_bin_path
54 #include "ardour/rc_configuration.h"
55 #include "ardour/system_exec.h"
56 #endif
57
58 #include "ardour/filesystem_paths.h"
59 #include "ardour/linux_vst_support.h"
60 #include "ardour/mac_vst_support.h"
61 #include "ardour/plugin_types.h"
62 #include "ardour/vst_info_file.h"
63
64 #include "pbd/i18n.h"
65 #include "sha1.c"
66
67 #define MAX_STRING_LEN 256
68 #define PLUGIN_SCAN_TIMEOUT (Config->get_vst_scan_timeout()) // in deciseconds
69
70 using namespace std;
71 #ifndef VST_SCANNER_APP
72 namespace ARDOUR {
73 #endif
74
75 /* prototypes */
76 #ifdef WINDOWS_VST_SUPPORT
77 #include <fst.h>
78 static bool
79 vstfx_instantiate_and_get_info_fst (const char* dllpath, vector<VSTInfo*> *infos, int uniqueID);
80 #endif
81
82 #ifdef LXVST_SUPPORT
83 static bool vstfx_instantiate_and_get_info_lx (const char* dllpath, vector<VSTInfo*> *infos, int uniqueID);
84 #endif
85
86 #ifdef MACVST_SUPPORT
87 static bool vstfx_instantiate_and_get_info_mac (const char* dllpath, vector<VSTInfo*> *infos, int uniqueID);
88 #endif
89
90 /* ID for shell plugins */
91 static int vstfx_current_loading_id = 0;
92
93 /* *** CACHE FILE PATHS *** */
94
95 static string
96 get_vst_info_cache_dir () {
97         string dir = Glib::build_filename (ARDOUR::user_cache_directory (), "vst");
98         /* if the directory doesn't exist, try to create it */
99         if (!Glib::file_test (dir, Glib::FILE_TEST_IS_DIR)) {
100                 if (g_mkdir (dir.c_str (), 0700)) {
101                         PBD::fatal << "Cannot create VST info folder '" << dir << "'" << endmsg;
102                 }
103         }
104         return dir;
105 }
106
107 static string
108 vstfx_infofile_path (const char* dllpath)
109 {
110         char hash[41];
111         Sha1Digest s;
112         sha1_init (&s);
113         sha1_write (&s, (const uint8_t *) dllpath, strlen (dllpath));
114         sha1_result_hash (&s, hash);
115         return Glib::build_filename (get_vst_info_cache_dir (), std::string (hash) + std::string (VST_EXT_INFOFILE));
116 }
117
118
119 /* *** VST Blacklist *** */
120
121 static void vstfx_read_blacklist (std::string &bl) {
122         FILE * blacklist_fd = NULL;
123         bl = "";
124
125         string fn = Glib::build_filename (ARDOUR::user_cache_directory (), VST_BLACKLIST);
126
127         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
128                 return;
129         }
130
131         if (! (blacklist_fd = g_fopen (fn.c_str (), "rb"))) {
132                 return;
133         }
134
135         while (!feof (blacklist_fd)) {
136                 char buf[1024];
137                 size_t s = fread (buf, sizeof(char), 1024, blacklist_fd);
138                 if (ferror (blacklist_fd)) {
139                         PBD::error << string_compose (_("error reading VST Blacklist file %1 (%2)"), fn, strerror (errno)) << endmsg;
140                         bl = "";
141                         break;
142                 }
143                 if (s == 0) {
144                         break;
145                 }
146                 bl.append (buf, s);
147         }
148         ::fclose (blacklist_fd);
149 }
150
151 /** mark plugin as blacklisted */
152 static void vstfx_blacklist (const char *id)
153 {
154         string fn = Glib::build_filename (ARDOUR::user_cache_directory (), VST_BLACKLIST);
155         FILE * blacklist_fd = NULL;
156         if (! (blacklist_fd = g_fopen (fn.c_str (), "a"))) {
157                 PBD::error << string_compose (_("Cannot append to VST blacklist for '%1'"), id) << endmsg;
158                 return;
159         }
160         assert (NULL == strchr (id, '\n'));
161         fprintf (blacklist_fd, "%s\n", id);
162         ::fclose (blacklist_fd);
163 }
164
165 /** mark plugin as not blacklisted */
166 static void vstfx_un_blacklist (const char *idcs)
167 {
168         string id (idcs);
169         string fn = Glib::build_filename (ARDOUR::user_cache_directory (), VST_BLACKLIST);
170         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
171                 PBD::warning << _("Expected VST Blacklist file does not exist.") << endmsg;
172                 return;
173         }
174
175         std::string bl;
176         vstfx_read_blacklist (bl);
177
178         ::g_unlink (fn.c_str ());
179
180         assert (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS));
181         assert (id.find ("\n") == string::npos);
182
183         id += "\n"; // add separator
184         const size_t rpl = bl.find (id);
185         if (rpl != string::npos) {
186                 bl.replace (rpl, id.size (), "");
187         }
188         if (bl.empty ()) {
189                 return;
190         }
191
192         FILE * blacklist_fd = NULL;
193         if (! (blacklist_fd = g_fopen (fn.c_str (), "w"))) {
194                 PBD::error << _("Cannot open VST blacklist.") << endmsg;;
195                 return;
196         }
197         fprintf (blacklist_fd, "%s", bl.c_str ());
198         ::fclose (blacklist_fd);
199 }
200
201 /* return true if plugin is blacklisted */
202 static bool vst_is_blacklisted (const char *idcs)
203 {
204         // TODO ideally we'd also check if the VST has been updated since blacklisting
205         string id (idcs);
206         string fn = Glib::build_filename (ARDOUR::user_cache_directory (), VST_BLACKLIST);
207         if (!Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
208                 return false;
209         }
210
211         std::string bl;
212         vstfx_read_blacklist (bl);
213
214         assert (id.find ("\n") == string::npos);
215
216         id += "\n"; // add separator
217         const size_t rpl = bl.find (id);
218         if (rpl != string::npos) {
219                 return true;
220         }
221         return false;
222 }
223
224
225
226 /* *** MEMORY MANAGEMENT *** */
227
228 /** cleanup single allocated VSTInfo */
229 static void
230 vstfx_free_info (VSTInfo *info)
231 {
232         for (int i = 0; i < info->numParams; i++) {
233                 free (info->ParamNames[i]);
234                 free (info->ParamLabels[i]);
235         }
236
237         free (info->name);
238         free (info->creator);
239         free (info->Category);
240         free (info->ParamNames);
241         free (info->ParamLabels);
242         free (info);
243 }
244
245 /** reset vector */
246 static void
247 vstfx_clear_info_list (vector<VSTInfo *> *infos)
248 {
249         for (vector<VSTInfo *>::iterator i = infos->begin (); i != infos->end (); ++i) {
250                 vstfx_free_info (*i);
251         }
252         infos->clear ();
253 }
254
255
256 /* *** CACHE FILE I/O *** */
257
258 /** Helper function to read a line from the cache file
259  * @return newly allocated string of NULL
260  */
261 static char *
262 read_string (FILE *fp)
263 {
264         char buf[MAX_STRING_LEN];
265
266         if (!fgets (buf, MAX_STRING_LEN, fp)) {
267                 return 0;
268         }
269
270         if (strlen (buf)) {
271                 /* strip lash char here: '\n',
272                  * since VST-params cannot be longer than 127 chars.
273                  */
274                 buf[strlen (buf)-1] = 0;
275                 return strdup (buf);
276         }
277         return 0;
278 }
279
280 /** Read an integer value from a line in fp into n,
281  *  @return true on failure, false on success.
282  */
283 static bool
284 read_int (FILE* fp, int* n)
285 {
286         char buf[MAX_STRING_LEN];
287
288         char* p = fgets (buf, MAX_STRING_LEN, fp);
289         if (p == 0) {
290                 return true;
291         }
292
293         return (sscanf (p, "%d", n) != 1);
294 }
295
296 /** parse a plugin-block from the cache info file */
297 static bool
298 vstfx_load_info_block (FILE* fp, VSTInfo *info)
299 {
300         if ((info->name = read_string (fp)) == 0) return false;
301         if ((info->creator = read_string (fp)) == 0) return false;
302         if (read_int (fp, &info->UniqueID)) return false;
303         if ((info->Category = read_string (fp)) == 0) return false;
304         if (read_int (fp, &info->numInputs)) return false;
305         if (read_int (fp, &info->numOutputs)) return false;
306         if (read_int (fp, &info->numParams)) return false;
307         if (read_int (fp, &info->wantMidi)) return false;
308         if (read_int (fp, &info->hasEditor)) return false;
309         if (read_int (fp, &info->canProcessReplacing)) return false;
310
311         /* backwards compatibility with old .fsi files */
312         if (info->wantMidi == -1) {
313                 info->wantMidi = 1;
314         }
315
316         info->isInstrument = (info->wantMidi & 4) ? 1 : 0;
317
318         info->isInstrument |= info->numInputs == 0 && info->numOutputs > 0 && 1 == (info->wantMidi & 1);
319         if (!strcmp (info->Category, "Instrument")) {
320                 info->isInstrument = 1;
321         }
322
323         if ((info->numParams) == 0) {
324                 info->ParamNames = NULL;
325                 info->ParamLabels = NULL;
326                 return true;
327         }
328
329         if ((info->ParamNames = (char **) malloc (sizeof (char*) * info->numParams)) == 0) {
330                 return false;
331         }
332
333         for (int i = 0; i < info->numParams; ++i) {
334                 if ((info->ParamNames[i] = read_string (fp)) == 0) return false;
335         }
336
337         if ((info->ParamLabels = (char **) malloc (sizeof (char*) * info->numParams)) == 0) {
338                 return false;
339         }
340
341         for (int i = 0; i < info->numParams; ++i) {
342                 if ((info->ParamLabels[i] = read_string (fp)) == 0) {
343                         return false;
344                 }
345         }
346         return true;
347 }
348
349 /** parse all blocks in a cache info file */
350 static bool
351 vstfx_load_info_file (FILE* fp, vector<VSTInfo*> *infos)
352 {
353         VSTInfo *info;
354         if ((info = (VSTInfo*) calloc (1, sizeof (VSTInfo))) == 0) {
355                 return false;
356         }
357         if (vstfx_load_info_block (fp, info)) {
358                 if (strncmp (info->Category, "Shell", 5)) {
359                         infos->push_back (info);
360                 } else {
361                         int plugin_cnt = 0;
362                         vstfx_free_info (info);
363                         if (!read_int (fp, &plugin_cnt)) {
364                                 for (int i = 0; i < plugin_cnt; i++) {
365                                         if ((info = (VSTInfo*) calloc (1, sizeof (VSTInfo))) == 0) {
366                                                 vstfx_clear_info_list (infos);
367                                                 return false;
368                                         }
369                                         if (vstfx_load_info_block (fp, info)) {
370                                                 infos->push_back (info);
371                                         } else {
372                                                 vstfx_free_info (info);
373                                                 vstfx_clear_info_list (infos);
374                                                 return false;
375                                         }
376                                 }
377                         } else {
378                                 return false; /* Bad file */
379                         }
380                 }
381                 return true;
382         }
383         vstfx_free_info (info);
384         vstfx_clear_info_list (infos);
385         return false;
386 }
387
388 static void
389 vstfx_write_info_block (FILE* fp, VSTInfo *info)
390 {
391         assert (info);
392         assert (fp);
393
394         fprintf (fp, "%s\n", info->name);
395         fprintf (fp, "%s\n", info->creator);
396         fprintf (fp, "%d\n", info->UniqueID);
397         fprintf (fp, "%s\n", info->Category);
398         fprintf (fp, "%d\n", info->numInputs);
399         fprintf (fp, "%d\n", info->numOutputs);
400         fprintf (fp, "%d\n", info->numParams);
401         fprintf (fp, "%d\n", info->wantMidi | (info->isInstrument ? 4 : 0));
402         fprintf (fp, "%d\n", info->hasEditor);
403         fprintf (fp, "%d\n", info->canProcessReplacing);
404
405         for (int i = 0; i < info->numParams; i++) {
406                 fprintf (fp, "%s\n", info->ParamNames[i]);
407         }
408
409         for (int i = 0; i < info->numParams; i++) {
410                 fprintf (fp, "%s\n", info->ParamLabels[i]);
411         }
412 }
413
414 static void
415 vstfx_write_info_file (FILE* fp, vector<VSTInfo *> *infos)
416 {
417         assert (infos);
418         assert (fp);
419
420         if (infos->size () > 1) {
421                 vector<VSTInfo *>::iterator x = infos->begin ();
422                 /* write out the shell info first along with count of the number of
423                  * plugins contained in this shell
424                  */
425                 vstfx_write_info_block (fp, *x);
426                 fprintf (fp, "%d\n", (int)infos->size () - 1 );
427                 ++x;
428                 /* Now write out the info for each plugin */
429                 for (; x != infos->end (); ++x) {
430                         vstfx_write_info_block (fp, *x);
431                 }
432         } else if (infos->size () == 1) {
433                 vstfx_write_info_block (fp, infos->front ());
434         } else {
435                 PBD::warning << _("VST object file contains no plugins.") << endmsg;
436         }
437 }
438
439
440 /* *** CACHE MANAGEMENT *** */
441
442 /** remove info file from cache */
443 static void
444 vstfx_remove_infofile (const char *dllpath)
445 {
446         ::g_unlink (vstfx_infofile_path (dllpath).c_str ());
447 }
448
449 /** cache file for given plugin
450  * @return FILE of the .fsi cache if found and up-to-date*/
451 static FILE *
452 vstfx_infofile_for_read (const char* dllpath)
453 {
454         const size_t slen = strlen (dllpath);
455         if (
456                         (slen <= 3 || g_ascii_strcasecmp (&dllpath[slen-3], ".so"))
457                         &&
458                         (slen <= 4 || g_ascii_strcasecmp (&dllpath[slen-4], ".vst"))
459                         &&
460                         (slen <= 4 || g_ascii_strcasecmp (&dllpath[slen-4], ".dll"))
461            ) {
462                 return 0;
463         }
464
465         string const path = vstfx_infofile_path (dllpath);
466
467         if (Glib::file_test (path, Glib::FileTest (Glib::FILE_TEST_EXISTS | Glib::FILE_TEST_IS_REGULAR))) {
468                 GStatBuf dllstat;
469                 GStatBuf fsistat;
470
471                 if (g_stat (dllpath, &dllstat) == 0) {
472                         if (g_stat (path.c_str (), &fsistat) == 0) {
473                                 if (dllstat.st_mtime <= fsistat.st_mtime) {
474                                         /* plugin is older than info file */
475                                         return g_fopen (path.c_str (), "rb");
476                                 }
477                         }
478                 }
479                 PBD::warning << string_compose (_("Ignored VST plugin which is newer than cache: '%1' (cache: '%2')"), dllpath, path) << endmsg;
480                 PBD::info << _("Re-Scan Plugins (Preferences > Plugins) to update the cache, also make sure your system-time is set correctly.") << endmsg;
481         }
482         return NULL;
483 }
484
485 /** newly created cache file for given plugin
486  * @return FILE for the .fsi cache or NULL on error
487  */
488 static FILE *
489 vstfx_infofile_for_write (const char* dllpath)
490 {
491         const size_t slen = strlen (dllpath);
492         if (
493                         (slen <= 3 || g_ascii_strcasecmp (&dllpath[slen-3], ".so"))
494                         &&
495                         (slen <= 4 || g_ascii_strcasecmp (&dllpath[slen-4], ".vst"))
496                         &&
497                         (slen <= 4 || g_ascii_strcasecmp (&dllpath[slen-4], ".dll"))
498            ) {
499                 return NULL;
500         }
501
502         string const path = vstfx_infofile_path (dllpath);
503         return g_fopen (path.c_str (), "wb");
504 }
505
506 /** check if cache-file exists, is up-to-date and parse cache file
507  * @param infos [return] loaded plugin info
508  * @return true if .fsi cache was read successfully, false otherwise
509  */
510 static bool
511 vstfx_get_info_from_file (const char* dllpath, vector<VSTInfo*> *infos)
512 {
513         FILE* infofile;
514         bool rv = false;
515         if ((infofile = vstfx_infofile_for_read (dllpath)) != 0) {
516                 rv = vstfx_load_info_file (infofile, infos);
517                 fclose (infofile);
518                 if (!rv) {
519                         PBD::warning << string_compose (_("Cannot get VST information for '%1': failed to load cache file."), dllpath) << endmsg;
520                 }
521         }
522         return rv;
523 }
524
525
526
527 /* *** VST system-under-test methods *** */
528
529 static
530 bool vstfx_midi_input (VSTState* vstfx)
531 {
532         AEffect* plugin = vstfx->plugin;
533
534         /* should we send it VST events (i.e. MIDI) */
535
536         if ((plugin->flags & effFlagsIsSynth)
537                         || (plugin->dispatcher (plugin, effCanDo, 0, 0, const_cast<char*> ("receiveVstEvents"), 0.0f) > 0)
538                         || (plugin->dispatcher (plugin, effCanDo, 0, 0, const_cast<char*> ("receiveVstMidiEvents"), 0.0f) > 0)
539                  ) {
540                 return true;
541         }
542
543         return false;
544 }
545
546 static
547 bool vstfx_midi_output (VSTState* vstfx)
548 {
549         AEffect* plugin = vstfx->plugin;
550
551         int const vst_version = plugin->dispatcher (plugin, effGetVstVersion, 0, 0, 0, 0.0f);
552
553         if (vst_version >= 2) {
554                 /* should we send it VST events (i.e. MIDI) */
555
556                 if (   (plugin->dispatcher (plugin, effCanDo, 0, 0, const_cast<char*> ("sendVstEvents"), 0.0f) > 0)
557                     || (plugin->dispatcher (plugin, effCanDo, 0, 0, const_cast<char*> ("sendVstMidiEvent"), 0.0f) > 0)
558                    ) {
559                         return true;
560                 }
561         }
562
563         return false;
564 }
565
566 /** simple 'dummy' audiomaster callback to instantiate the plugin
567  * and query information
568  */
569 static intptr_t
570 simple_master_callback (AEffect *, int32_t opcode, int32_t, intptr_t, void *ptr, float)
571 {
572         const char* vstfx_can_do_strings[] = {
573                 "supplyIdle",
574                 "sendVstTimeInfo",
575                 "sendVstEvents",
576                 "sendVstMidiEvent",
577                 "receiveVstEvents",
578                 "receiveVstMidiEvent",
579                 "supportShell",
580                 "shellCategory",
581                 "shellCategorycurID"
582         };
583         const int vstfx_can_do_string_count = 9;
584
585         if (opcode == audioMasterVersion) {
586                 return 2400;
587         }
588         else if (opcode == audioMasterCanDo) {
589                 for (int i = 0; i < vstfx_can_do_string_count; i++) {
590                         if (! strcmp (vstfx_can_do_strings[i], (const char*)ptr)) {
591                                 return 1;
592                         }
593                 }
594                 return 0;
595         }
596         else if (opcode == audioMasterCurrentId) {
597                 return vstfx_current_loading_id;
598         }
599         else {
600                 return 0;
601         }
602 }
603
604
605 /** main plugin query and test function */
606 static VSTInfo*
607 vstfx_parse_vst_state (VSTState* vstfx)
608 {
609         assert (vstfx);
610
611         VSTInfo* info = (VSTInfo*) malloc (sizeof (VSTInfo));
612         if (!info) {
613                 return 0;
614         }
615
616         /* We need to init the creator because some plugins
617          * fail to implement getVendorString, and so won't stuff the
618          * string with any name */
619
620         char creator[65] = "Unknown";
621         char name[65] = "";
622
623         AEffect* plugin = vstfx->plugin;
624
625
626         plugin->dispatcher (plugin, effGetEffectName, 0, 0, name, 0);
627
628         if (strlen (name) == 0) {
629                 plugin->dispatcher (plugin, effGetProductString, 0, 0, name, 0);
630         }
631
632         if (strlen (name) == 0) {
633                 info->name = strdup (vstfx->handle->name);
634         } else {
635                 info->name = strdup (name);
636         }
637
638         /*If the plugin doesn't bother to implement GetVendorString we will
639          * have pre-stuffed the string with 'Unknown' */
640
641         plugin->dispatcher (plugin, effGetVendorString, 0, 0, creator, 0);
642
643         /* Some plugins DO implement GetVendorString, but DON'T put a name in it
644          * so if its just a zero length string we replace it with 'Unknown' */
645
646         if (strlen (creator) == 0) {
647                 info->creator = strdup ("Unknown");
648         } else {
649                 info->creator = strdup (creator);
650         }
651
652
653         switch (plugin->dispatcher (plugin, effGetPlugCategory, 0, 0, 0, 0))
654         {
655                 case kPlugCategEffect:         info->Category = strdup ("Effect"); break;
656                 case kPlugCategSynth:          info->Category = strdup ("Instrument"); break;
657                 case kPlugCategAnalysis:       info->Category = strdup ("Analyser"); break;
658                 case kPlugCategMastering:      info->Category = strdup ("Mastering"); break;
659                 case kPlugCategSpacializer:    info->Category = strdup ("Spatial"); break;
660                 case kPlugCategRoomFx:         info->Category = strdup ("RoomFx"); break;
661                 case kPlugSurroundFx:          info->Category = strdup ("SurroundFx"); break;
662                 case kPlugCategRestoration:    info->Category = strdup ("Restoration"); break;
663                 case kPlugCategOfflineProcess: info->Category = strdup ("Offline"); break;
664                 case kPlugCategShell:          info->Category = strdup ("Shell"); break;
665                 case kPlugCategGenerator:      info->Category = strdup ("Generator"); break;
666                 default:                       info->Category = strdup ("Unknown"); break;
667         }
668
669         info->UniqueID = plugin->uniqueID;
670
671         info->numInputs = plugin->numInputs;
672         info->numOutputs = plugin->numOutputs;
673         info->numParams = plugin->numParams;
674         info->wantMidi = (vstfx_midi_input (vstfx) ? 1 : 0) | (vstfx_midi_output (vstfx) ? 2 : 0);
675         info->hasEditor = plugin->flags & effFlagsHasEditor ? true : false;
676         info->isInstrument = (plugin->flags & effFlagsIsSynth) ? 1 : 0;
677         info->canProcessReplacing = plugin->flags & effFlagsCanReplacing ? true : false;
678         info->ParamNames = (char **) malloc (sizeof (char*)*info->numParams);
679         info->ParamLabels = (char **) malloc (sizeof (char*)*info->numParams);
680
681 #ifdef __APPLE__
682         if (info->hasEditor) {
683                 /* we only support Cocoa UIs (just like Reaper) */
684                 info->hasEditor = (plugin->dispatcher (plugin, effCanDo, 0, 0, const_cast<char*> ("hasCockosViewAsConfig"), 0.0f) & 0xffff0000) == 0xbeef0000;
685         }
686 #endif
687
688         for (int i = 0; i < info->numParams; ++i) {
689                 char name[VestigeMaxLabelLen];
690                 char label[VestigeMaxLabelLen];
691
692                 /* Not all plugins give parameters labels as well as names */
693
694                 strcpy (name, "No Name");
695                 strcpy (label, "No Label");
696
697                 plugin->dispatcher (plugin, effGetParamName, i, 0, name, 0);
698                 info->ParamNames[i] = strdup (name);
699
700                 //NOTE: 'effGetParamLabel' is no longer defined in vestige headers
701                 //plugin->dispatcher (plugin, effGetParamLabel, i, 0, label, 0);
702                 info->ParamLabels[i] = strdup (label);
703         }
704         return info;
705 }
706
707 /** wrapper around \ref vstfx_parse_vst_state,
708  * iterate over plugins in shell, translate VST-info into ardour VSTState
709  */
710 static void
711 vstfx_info_from_plugin (const char *dllpath, VSTState* vstfx, vector<VSTInfo *> *infos, enum ARDOUR::PluginType type)
712 {
713         assert (vstfx);
714         VSTInfo *info;
715
716         if (!(info = vstfx_parse_vst_state (vstfx))) {
717                 return;
718         }
719
720         infos->push_back (info);
721 #if 1 // shell-plugin support
722         /* If this plugin is a Shell and we are not already inside a shell plugin
723          * read the info for all of the plugins contained in this shell.
724          */
725         if (!strncmp (info->Category, "Shell", 5)
726                         && vstfx->handle->plugincnt == 1) {
727                 int id;
728                 vector< pair<int, string> > ids;
729                 AEffect *plugin = vstfx->plugin;
730
731                 do {
732                         char name[65] = "Unknown";
733                         id = plugin->dispatcher (plugin, effShellGetNextPlugin, 0, 0, name, 0);
734                         ids.push_back (std::make_pair (id, name));
735                 } while ( id != 0 );
736
737                 switch (type) {
738 #ifdef WINDOWS_VST_SUPPORT
739                         case ARDOUR::Windows_VST:
740                                 fst_close (vstfx);
741                                 break;
742 #endif
743 #ifdef LXVST_SUPPORT
744                         case ARDOUR::LXVST:
745                                 vstfx_close (vstfx);
746                                 break;
747 #endif
748 #ifdef MACVST_SUPPORT
749                         case ARDOUR::MacVST:
750                                 mac_vst_close (vstfx);
751                                 break;
752 #endif
753                         default:
754                                 assert (0);
755                                 break;
756                 }
757
758                 for (vector< pair<int, string> >::iterator x = ids.begin (); x != ids.end (); ++x) {
759                         id = (*x).first;
760                         if (id == 0) continue;
761                         /* recurse vstfx_get_info() */
762
763                         bool ok;
764                         switch (type) {
765 #ifdef WINDOWS_VST_SUPPORT
766                                 case ARDOUR::Windows_VST:
767                                         ok = vstfx_instantiate_and_get_info_fst (dllpath, infos, id);
768                                         break;
769 #endif
770 #ifdef LXVST_SUPPORT
771                                 case ARDOUR::LXVST:
772                                         ok = vstfx_instantiate_and_get_info_lx (dllpath, infos, id);
773                                         break;
774 #endif
775 #ifdef MACVST_SUPPORT
776                                 case ARDOUR::MacVST:
777                                         ok = vstfx_instantiate_and_get_info_mac (dllpath, infos, id);
778                                         break;
779 #endif
780                                 default:
781                                         ok = false;
782                                         break;
783                         }
784                         if (ok) {
785                                 // One shell (some?, all?) does not report the actual plugin name
786                                 // even after the shelled plugin has been instantiated.
787                                 // Replace the name of the shell with the real name.
788                                 info = infos->back ();
789                                 free (info->name);
790
791                                 if ((*x).second.length () == 0) {
792                                         info->name = strdup ("Unknown");
793                                 }
794                                 else {
795                                         info->name = strdup ((*x).second.c_str ());
796                                 }
797                         }
798                 }
799         } else {
800                 switch (type) {
801 #ifdef WINDOWS_VST_SUPPORT
802                         case ARDOUR::Windows_VST:
803                                 fst_close (vstfx);
804                                 break;
805 #endif
806 #ifdef LXVST_SUPPORT
807                         case ARDOUR::LXVST:
808                                 vstfx_close (vstfx);
809                                 break;
810 #endif
811 #ifdef MACVST_SUPPORT
812                         case ARDOUR::MacVST:
813                                 mac_vst_close (vstfx);
814                                 break;
815 #endif
816                         default:
817                                 assert (0);
818                                 break;
819                 }
820         }
821 #endif
822 }
823
824
825
826 /* *** TOP-LEVEL PLUGIN INSTANTIATION FUNCTIONS *** */
827
828 #ifdef LXVST_SUPPORT
829 static bool
830 vstfx_instantiate_and_get_info_lx (
831                 const char* dllpath, vector<VSTInfo*> *infos, int uniqueID)
832 {
833         VSTHandle* h;
834         VSTState* vstfx;
835         if (!(h = vstfx_load (dllpath))) {
836                 PBD::warning << string_compose (_("Cannot get LinuxVST information from '%1': load failed."), dllpath) << endmsg;
837                 return false;
838         }
839
840         vstfx_current_loading_id = uniqueID;
841
842         if (!(vstfx = vstfx_instantiate (h, simple_master_callback, 0))) {
843                 vstfx_unload (h);
844                 PBD::warning << string_compose (_("Cannot get LinuxVST information from '%1': instantiation failed."), dllpath) << endmsg;
845                 return false;
846         }
847
848         vstfx_current_loading_id = 0;
849
850         vstfx_info_from_plugin (dllpath, vstfx, infos, ARDOUR::LXVST);
851
852         vstfx_unload (h);
853         return true;
854 }
855 #endif
856
857 #ifdef WINDOWS_VST_SUPPORT
858 static bool
859 vstfx_instantiate_and_get_info_fst (
860                 const char* dllpath, vector<VSTInfo*> *infos, int uniqueID)
861 {
862         VSTHandle* h;
863         VSTState* vstfx;
864         if (!(h = fst_load (dllpath))) {
865                 PBD::warning << string_compose (_("Cannot get Windows VST information from '%1': load failed."), dllpath) << endmsg;
866                 return false;
867         }
868
869         vstfx_current_loading_id = uniqueID;
870
871         if (!(vstfx = fst_instantiate (h, simple_master_callback, 0))) {
872                 fst_unload (&h);
873                 vstfx_current_loading_id = 0;
874                 PBD::warning << string_compose (_("Cannot get Windows VST information from '%1': instantiation failed."), dllpath) << endmsg;
875                 return false;
876         }
877         vstfx_current_loading_id = 0;
878
879         vstfx_info_from_plugin (dllpath, vstfx, infos, ARDOUR::Windows_VST);
880
881         return true;
882 }
883 #endif
884
885 #ifdef MACVST_SUPPORT
886 static bool
887 vstfx_instantiate_and_get_info_mac (
888                 const char* dllpath, vector<VSTInfo*> *infos, int uniqueID)
889 {
890         printf("vstfx_instantiate_and_get_info_mac %s\n", dllpath);
891         VSTHandle* h;
892         VSTState* vstfx;
893         if (!(h = mac_vst_load (dllpath))) {
894                 PBD::warning << string_compose (_("Cannot get MacVST information from '%1': load failed."), dllpath) << endmsg;
895                 return false;
896         }
897
898         vstfx_current_loading_id = uniqueID;
899
900         if (!(vstfx = mac_vst_instantiate (h, simple_master_callback, 0))) {
901                 mac_vst_unload (h);
902                 PBD::warning << string_compose (_("Cannot get MacVST information from '%1': instantiation failed."), dllpath) << endmsg;
903                 return false;
904         }
905
906         vstfx_current_loading_id = 0;
907
908         vstfx_info_from_plugin (dllpath, vstfx, infos, ARDOUR::MacVST);
909
910         mac_vst_unload (h);
911         return true;
912 }
913 #endif
914
915 /* *** ERROR LOGGING *** */
916 #ifndef VST_SCANNER_APP
917
918 static FILE * _errorlog_fd = 0;
919 static char * _errorlog_dll = 0;
920
921 static void parse_scanner_output (std::string msg, size_t /*len*/)
922 {
923         if (!_errorlog_fd && !_errorlog_dll) {
924                 PBD::error << "VST scanner: " << msg;
925                 return;
926         }
927
928 #if 0 // TODO
929         if (!_errorlog_fd) {
930                 if (!(_errorlog_fd = g_fopen (vstfx_errorfile_path (_errorlog_dll).c_str (), "w"))) {
931                         PBD::error << "Cannot create plugin error-log for plugin " << _errorlog_dll;
932                         free (_errorlog_dll);
933                         _errorlog_dll = NULL;
934                 }
935         }
936 #endif
937
938         if (_errorlog_fd) {
939                 fprintf (_errorlog_fd, "%s\n", msg.c_str ());
940         } else if (_errorlog_dll) {
941                 PBD::error << "VST '" << _errorlog_dll << "': " << msg;
942         } else {
943                 PBD::error << "VST scanner: " << msg;
944         }
945 }
946
947 static void
948 set_error_log (const char* dllpath) {
949         assert (!_errorlog_fd);
950         assert (!_errorlog_dll);
951         _errorlog_dll = strdup (dllpath);
952 }
953
954 static void
955 close_error_log () {
956         if (_errorlog_fd) {
957                 fclose (_errorlog_fd);
958                 _errorlog_fd = 0;
959         }
960         free (_errorlog_dll);
961         _errorlog_dll = 0;
962 }
963
964 #endif
965
966
967 /* *** the main function that uses all of the above *** */
968
969 static vector<VSTInfo *> *
970 vstfx_get_info (const char* dllpath, enum ARDOUR::PluginType type, enum VSTScanMode mode)
971 {
972         FILE* infofile;
973         vector<VSTInfo*> *infos = new vector<VSTInfo*>;
974
975         if (vst_is_blacklisted (dllpath)) {
976                 return infos;
977         }
978
979         if (vstfx_get_info_from_file (dllpath, infos)) {
980                 return infos;
981         }
982
983 #ifndef VST_SCANNER_APP
984         std::string scanner_bin_path = ARDOUR::PluginManager::scanner_bin_path;
985
986         if (mode == VST_SCAN_CACHE_ONLY) {
987                 /* never scan explicitly, use cache only */
988                 return infos;
989         }
990         else if (mode == VST_SCAN_USE_APP && scanner_bin_path != "") {
991                 /* use external scanner app */
992
993                 char **argp= (char**) calloc (3,sizeof (char*));
994                 argp[0] = strdup (scanner_bin_path.c_str ());
995                 argp[1] = strdup (dllpath);
996                 argp[2] = 0;
997
998                 set_error_log (dllpath);
999                 ARDOUR::SystemExec scanner (scanner_bin_path, argp);
1000                 PBD::ScopedConnectionList cons;
1001                 scanner.ReadStdout.connect_same_thread (cons, boost::bind (&parse_scanner_output, _1 ,_2));
1002                 if (scanner.start (ARDOUR::SystemExec::MergeWithStdin)) {
1003                         PBD::error << string_compose (_("Cannot launch VST scanner app '%1': %2"), scanner_bin_path, strerror (errno)) << endmsg;
1004                         close_error_log ();
1005                         return infos;
1006                 } else {
1007                         int timeout = PLUGIN_SCAN_TIMEOUT;
1008                         bool no_timeout = (timeout <= 0);
1009                         ARDOUR::PluginScanTimeout (timeout);
1010                         while (scanner.is_running () && (no_timeout || timeout > 0)) {
1011                                 if (!no_timeout && !ARDOUR::PluginManager::instance ().no_timeout ()) {
1012                                         if (timeout%5 == 0) {
1013                                                 ARDOUR::PluginScanTimeout (timeout);
1014                                         }
1015                                         --timeout;
1016                                 }
1017                                 ARDOUR::GUIIdle ();
1018                                 Glib::usleep (100000);
1019
1020                                 if (ARDOUR::PluginManager::instance ().cancelled ()) {
1021                                         // remove info file (might be incomplete)
1022                                         vstfx_remove_infofile (dllpath);
1023                                         // remove temporary blacklist file (scan incomplete)
1024                                         vstfx_un_blacklist (dllpath);
1025                                         scanner.terminate ();
1026                                         close_error_log ();
1027                                         return infos;
1028                                 }
1029                         }
1030                         scanner.terminate ();
1031                 }
1032                 close_error_log ();
1033                 /* re-read index (generated by external scanner) */
1034                 vstfx_clear_info_list (infos);
1035                 if (!vst_is_blacklisted (dllpath)) {
1036                         vstfx_get_info_from_file (dllpath, infos);
1037                 }
1038                 return infos;
1039         }
1040         /* else .. instantiate and check in in ardour process itself */
1041 #else
1042         (void) mode; // unused parameter
1043 #endif
1044
1045         bool ok;
1046         /* blacklist in case instantiation fails */
1047         vstfx_blacklist (dllpath);
1048
1049         switch (type) {
1050 #ifdef WINDOWS_VST_SUPPORT
1051                 case ARDOUR::Windows_VST:
1052                         ok = vstfx_instantiate_and_get_info_fst (dllpath, infos, 0);
1053                         break;
1054 #endif
1055 #ifdef LXVST_SUPPORT
1056                 case ARDOUR::LXVST:
1057                         ok = vstfx_instantiate_and_get_info_lx (dllpath, infos, 0);
1058                         break;
1059 #endif
1060 #ifdef MACVST_SUPPORT
1061                 case ARDOUR::MacVST:
1062                         ok = vstfx_instantiate_and_get_info_mac (dllpath, infos, 0);
1063                         break;
1064 #endif
1065                 default:
1066                         ok = false;
1067                         break;
1068         }
1069
1070         if (!ok) {
1071                 return infos;
1072         }
1073
1074         /* remove from blacklist */
1075         vstfx_un_blacklist (dllpath);
1076
1077         /* crate cache/whitelist */
1078         infofile = vstfx_infofile_for_write (dllpath);
1079         if (!infofile) {
1080                 PBD::warning << string_compose (_("Cannot cache VST information for '%1': cannot create cache file."), dllpath) << endmsg;
1081                 return infos;
1082         } else {
1083                 vstfx_write_info_file (infofile, infos);
1084                 fclose (infofile);
1085
1086                 /* In some cases the .dll may have a modification time in the future,
1087                  * (e.g. unzip a VST plugin: .zip files don't include timezones)
1088                  */
1089                 string const fsipath = vstfx_infofile_path (dllpath);
1090                 GStatBuf dllstat;
1091                 GStatBuf fsistat;
1092                 if (g_stat (dllpath, &dllstat) == 0 && g_stat (fsipath.c_str (), &fsistat) == 0) {
1093                         struct utimbuf utb;
1094                         utb.actime = fsistat.st_atime;
1095                         utb.modtime = std::max (dllstat.st_mtime, fsistat.st_mtime);
1096                         g_utime (fsipath.c_str (), &utb);
1097                 }
1098         }
1099         return infos;
1100 }
1101
1102
1103 /* *** public API *** */
1104
1105 void
1106 vstfx_free_info_list (vector<VSTInfo *> *infos)
1107 {
1108         for (vector<VSTInfo *>::iterator i = infos->begin (); i != infos->end (); ++i) {
1109                 vstfx_free_info (*i);
1110         }
1111         delete infos;
1112 }
1113
1114 #ifdef LXVST_SUPPORT
1115 vector<VSTInfo *> *
1116 vstfx_get_info_lx (char* dllpath, enum VSTScanMode mode)
1117 {
1118         return vstfx_get_info (dllpath, ARDOUR::LXVST, mode);
1119 }
1120 #endif
1121
1122 #ifdef MACVST_SUPPORT
1123 vector<VSTInfo *> *
1124 vstfx_get_info_mac (char* dllpath, enum VSTScanMode mode)
1125 {
1126         return vstfx_get_info (dllpath, ARDOUR::MacVST, mode);
1127 }
1128 #endif
1129
1130 #ifdef WINDOWS_VST_SUPPORT
1131 vector<VSTInfo *> *
1132 vstfx_get_info_fst (char* dllpath, enum VSTScanMode mode)
1133 {
1134         return vstfx_get_info (dllpath, ARDOUR::Windows_VST, mode);
1135 }
1136 #endif
1137
1138 #ifndef VST_SCANNER_APP
1139 } // namespace
1140 #endif