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