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