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