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