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