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