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