Merge remote-tracking branch 'origin/master' into 0.11
[platform/upstream/gstreamer.git] / gst / gstplugin.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *
5  * gstplugin.c: Plugin subsystem for loading elements, types, and libs
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gstplugin
25  * @short_description: Container for features loaded from a shared object module
26  * @see_also: #GstPluginFeature, #GstElementFactory
27  *
28  * GStreamer is extensible, so #GstElement instances can be loaded at runtime.
29  * A plugin system can provide one or more of the basic
30  * <application>GStreamer</application> #GstPluginFeature subclasses.
31  *
32  * A plugin should export a symbol <symbol>gst_plugin_desc</symbol> that is a
33  * struct of type #GstPluginDesc.
34  * the plugin loader will check the version of the core library the plugin was
35  * linked against and will create a new #GstPlugin. It will then call the
36  * #GstPluginInitFunc function that was provided in the
37  * <symbol>gst_plugin_desc</symbol>.
38  *
39  * Once you have a handle to a #GstPlugin (e.g. from the #GstRegistry), you
40  * can add any object that subclasses #GstPluginFeature.
41  *
42  * Usually plugins are always automaticlly loaded so you don't need to call
43  * gst_plugin_load() explicitly to bring it into memory. There are options to
44  * statically link plugins to an app or even use GStreamer without a plugin
45  * repository in which case gst_plugin_load() can be needed to bring the plugin
46  * into memory.
47  */
48
49 #ifdef HAVE_CONFIG_H
50 #include "config.h"
51 #endif
52
53 #include "gst_private.h"
54
55 #include <glib/gstdio.h>
56 #include <sys/types.h>
57 #ifdef HAVE_DIRENT_H
58 #include <dirent.h>
59 #endif
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #endif
63 #include <signal.h>
64 #include <errno.h>
65 #include <string.h>
66
67 #include "glib-compat-private.h"
68
69 #include <gst/gst.h>
70
71 #define GST_CAT_DEFAULT GST_CAT_PLUGIN_LOADING
72
73 static guint _num_static_plugins;       /* 0    */
74 static GstPluginDesc *_static_plugins;  /* NULL */
75 static gboolean _gst_plugin_inited;
76 static gchar **_plugin_loading_whitelist;       /* NULL */
77
78 /* static variables for segfault handling of plugin loading */
79 static char *_gst_plugin_fault_handler_filename = NULL;
80
81 /* list of valid licenses.
82  * One of these must be specified or the plugin won't be loaded
83  * Contact gstreamer-devel@lists.sourceforge.net if your license should be
84  * added.
85  *
86  * GPL: http://www.gnu.org/copyleft/gpl.html
87  * LGPL: http://www.gnu.org/copyleft/lesser.html
88  * QPL: http://www.trolltech.com/licenses/qpl.html
89  * MPL: http://www.opensource.org/licenses/mozilla1.1.php
90  * MIT/X11: http://www.opensource.org/licenses/mit-license.php
91  * 3-clause BSD: http://www.opensource.org/licenses/bsd-license.php
92  */
93 static const gchar *valid_licenses[] = {
94   "LGPL",                       /* GNU Lesser General Public License */
95   "GPL",                        /* GNU General Public License */
96   "QPL",                        /* Trolltech Qt Public License */
97   "GPL/QPL",                    /* Combi-license of GPL + QPL */
98   "MPL",                        /* MPL 1.1 license */
99   "BSD",                        /* 3-clause BSD license */
100   "MIT/X11",                    /* MIT/X11 license */
101   "Proprietary",                /* Proprietary license */
102   GST_LICENSE_UNKNOWN,          /* some other license */
103   NULL
104 };
105
106 static GstPlugin *gst_plugin_register_func (GstPlugin * plugin,
107     const GstPluginDesc * desc, gpointer user_data);
108 static void gst_plugin_desc_copy (GstPluginDesc * dest,
109     const GstPluginDesc * src);
110
111 static void gst_plugin_ext_dep_free (GstPluginDep * dep);
112
113 G_DEFINE_TYPE (GstPlugin, gst_plugin, GST_TYPE_OBJECT);
114
115 static void
116 gst_plugin_init (GstPlugin * plugin)
117 {
118   plugin->priv =
119       G_TYPE_INSTANCE_GET_PRIVATE (plugin, GST_TYPE_PLUGIN, GstPluginPrivate);
120 }
121
122 static void
123 gst_plugin_finalize (GObject * object)
124 {
125   GstPlugin *plugin = GST_PLUGIN_CAST (object);
126
127   GST_DEBUG ("finalizing plugin %" GST_PTR_FORMAT, plugin);
128
129   /* FIXME: make registry add a weak ref instead */
130 #if 0
131   GstRegistry *registry = gst_registry_get_default ();
132   GList *g;
133   for (g = registry->plugins; g; g = g->next) {
134     if (g->data == (gpointer) plugin) {
135       g_warning ("removing plugin that is still in registry");
136     }
137   }
138 #endif
139
140   g_free (plugin->filename);
141   g_free (plugin->basename);
142
143   g_list_foreach (plugin->priv->deps, (GFunc) gst_plugin_ext_dep_free, NULL);
144   g_list_free (plugin->priv->deps);
145   plugin->priv->deps = NULL;
146
147   if (plugin->priv->cache_data) {
148     gst_structure_free (plugin->priv->cache_data);
149   }
150
151   G_OBJECT_CLASS (gst_plugin_parent_class)->finalize (object);
152 }
153
154 static void
155 gst_plugin_class_init (GstPluginClass * klass)
156 {
157   G_OBJECT_CLASS (klass)->finalize = gst_plugin_finalize;
158
159   g_type_class_add_private (klass, sizeof (GstPluginPrivate));
160 }
161
162 GQuark
163 gst_plugin_error_quark (void)
164 {
165   static GQuark quark = 0;
166
167   if (!quark)
168     quark = g_quark_from_static_string ("gst_plugin_error");
169   return quark;
170 }
171
172 /**
173  * gst_plugin_register_static:
174  * @major_version: the major version number of the GStreamer core that the
175  *     plugin was compiled for, you can just use GST_VERSION_MAJOR here
176  * @minor_version: the minor version number of the GStreamer core that the
177  *     plugin was compiled for, you can just use GST_VERSION_MINOR here
178  * @name: a unique name of the plugin (ideally prefixed with an application- or
179  *     library-specific namespace prefix in order to avoid name conflicts in
180  *     case a similar plugin with the same name ever gets added to GStreamer)
181  * @description: description of the plugin
182  * @init_func: (scope call): pointer to the init function of this plugin.
183  * @version: version string of the plugin
184  * @license: effective license of plugin. Must be one of the approved licenses
185  *     (see #GstPluginDesc above) or the plugin will not be registered.
186  * @source: source module plugin belongs to
187  * @package: shipped package plugin belongs to
188  * @origin: URL to provider of plugin
189  *
190  * Registers a static plugin, ie. a plugin which is private to an application
191  * or library and contained within the application or library (as opposed to
192  * being shipped as a separate module file).
193  *
194  * You must make sure that GStreamer has been initialised (with gst_init() or
195  * via gst_init_get_option_group()) before calling this function.
196  *
197  * Returns: TRUE if the plugin was registered correctly, otherwise FALSE.
198  *
199  * Since: 0.10.16
200  */
201 gboolean
202 gst_plugin_register_static (gint major_version, gint minor_version,
203     const gchar * name, const gchar * description, GstPluginInitFunc init_func,
204     const gchar * version, const gchar * license, const gchar * source,
205     const gchar * package, const gchar * origin)
206 {
207   GstPluginDesc desc = { major_version, minor_version, name, description,
208     init_func, version, license, source, package, origin, NULL,
209   };
210   GstPlugin *plugin;
211   gboolean res = FALSE;
212
213   g_return_val_if_fail (name != NULL, FALSE);
214   g_return_val_if_fail (description != NULL, FALSE);
215   g_return_val_if_fail (init_func != NULL, FALSE);
216   g_return_val_if_fail (version != NULL, FALSE);
217   g_return_val_if_fail (license != NULL, FALSE);
218   g_return_val_if_fail (source != NULL, FALSE);
219   g_return_val_if_fail (package != NULL, FALSE);
220   g_return_val_if_fail (origin != NULL, FALSE);
221
222   /* make sure gst_init() has been called */
223   g_return_val_if_fail (_gst_plugin_inited != FALSE, FALSE);
224
225   GST_LOG ("attempting to load static plugin \"%s\" now...", name);
226   plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
227   if (gst_plugin_register_func (plugin, &desc, NULL) != NULL) {
228     GST_INFO ("registered static plugin \"%s\"", name);
229     res = gst_default_registry_add_plugin (plugin);
230     GST_INFO ("added static plugin \"%s\", result: %d", name, res);
231   }
232   return res;
233 }
234
235 /**
236  * gst_plugin_register_static_full:
237  * @major_version: the major version number of the GStreamer core that the
238  *     plugin was compiled for, you can just use GST_VERSION_MAJOR here
239  * @minor_version: the minor version number of the GStreamer core that the
240  *     plugin was compiled for, you can just use GST_VERSION_MINOR here
241  * @name: a unique name of the plugin (ideally prefixed with an application- or
242  *     library-specific namespace prefix in order to avoid name conflicts in
243  *     case a similar plugin with the same name ever gets added to GStreamer)
244  * @description: description of the plugin
245  * @init_full_func: (scope call): pointer to the init function with user data
246  *     of this plugin.
247  * @version: version string of the plugin
248  * @license: effective license of plugin. Must be one of the approved licenses
249  *     (see #GstPluginDesc above) or the plugin will not be registered.
250  * @source: source module plugin belongs to
251  * @package: shipped package plugin belongs to
252  * @origin: URL to provider of plugin
253  * @user_data: gpointer to user data
254  *
255  * Registers a static plugin, ie. a plugin which is private to an application
256  * or library and contained within the application or library (as opposed to
257  * being shipped as a separate module file) with a #GstPluginInitFullFunc
258  * which allows user data to be passed to the callback function (useful
259  * for bindings).
260  *
261  * You must make sure that GStreamer has been initialised (with gst_init() or
262  * via gst_init_get_option_group()) before calling this function.
263  *
264  * Returns: TRUE if the plugin was registered correctly, otherwise FALSE.
265  *
266  * Since: 0.10.24
267  *
268  */
269 gboolean
270 gst_plugin_register_static_full (gint major_version, gint minor_version,
271     const gchar * name, const gchar * description,
272     GstPluginInitFullFunc init_full_func, const gchar * version,
273     const gchar * license, const gchar * source, const gchar * package,
274     const gchar * origin, gpointer user_data)
275 {
276   GstPluginDesc desc = { major_version, minor_version, name, description,
277     (GstPluginInitFunc) init_full_func, version, license, source, package,
278     origin, NULL,
279   };
280   GstPlugin *plugin;
281   gboolean res = FALSE;
282
283   g_return_val_if_fail (name != NULL, FALSE);
284   g_return_val_if_fail (description != NULL, FALSE);
285   g_return_val_if_fail (init_full_func != NULL, FALSE);
286   g_return_val_if_fail (version != NULL, FALSE);
287   g_return_val_if_fail (license != NULL, FALSE);
288   g_return_val_if_fail (source != NULL, FALSE);
289   g_return_val_if_fail (package != NULL, FALSE);
290   g_return_val_if_fail (origin != NULL, FALSE);
291
292   /* make sure gst_init() has been called */
293   g_return_val_if_fail (_gst_plugin_inited != FALSE, FALSE);
294
295   GST_LOG ("attempting to load static plugin \"%s\" now...", name);
296   plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
297   if (gst_plugin_register_func (plugin, &desc, user_data) != NULL) {
298     GST_INFO ("registered static plugin \"%s\"", name);
299     res = gst_default_registry_add_plugin (plugin);
300     GST_INFO ("added static plugin \"%s\", result: %d", name, res);
301   }
302   return res;
303 }
304
305 void
306 _priv_gst_plugin_initialize (void)
307 {
308   const gchar *whitelist;
309   guint i;
310
311   _gst_plugin_inited = TRUE;
312
313   whitelist = g_getenv ("GST_PLUGIN_LOADING_WHITELIST");
314   if (whitelist != NULL && *whitelist != '\0') {
315     _plugin_loading_whitelist = g_strsplit (whitelist,
316         G_SEARCHPATH_SEPARATOR_S, -1);
317     for (i = 0; _plugin_loading_whitelist[i] != NULL; ++i) {
318       GST_INFO ("plugins whitelist entry: %s", _plugin_loading_whitelist[i]);
319     }
320   }
321
322   /* now register all static plugins */
323   GST_INFO ("registering %u static plugins", _num_static_plugins);
324   for (i = 0; i < _num_static_plugins; ++i) {
325     gst_plugin_register_static (_static_plugins[i].major_version,
326         _static_plugins[i].minor_version, _static_plugins[i].name,
327         _static_plugins[i].description, _static_plugins[i].plugin_init,
328         _static_plugins[i].version, _static_plugins[i].license,
329         _static_plugins[i].source, _static_plugins[i].package,
330         _static_plugins[i].origin);
331   }
332
333   if (_static_plugins) {
334     free (_static_plugins);
335     _static_plugins = NULL;
336     _num_static_plugins = 0;
337   }
338 }
339
340 /* Whitelist entry format:
341  *
342  *   plugin1,plugin2@pathprefix or
343  *   plugin1,plugin2@* or just
344  *   plugin1,plugin2 or
345  *   source-package@pathprefix or
346  *   source-package@* or just
347  *   source-package
348  *
349  * ie. the bit before the path will be checked against both the plugin
350  * name and the plugin's source package name, to keep the format simple.
351  */
352 static gboolean
353 gst_plugin_desc_matches_whitelist_entry (GstPluginDesc * desc,
354     const gchar * filename, const gchar * pattern)
355 {
356   const gchar *sep;
357   gboolean ret = FALSE;
358   gchar *name;
359
360   GST_LOG ("Whitelist pattern '%s', plugin: %s of %s@%s", pattern, desc->name,
361       desc->source, GST_STR_NULL (filename));
362
363   /* do we have a path prefix? */
364   sep = strchr (pattern, '@');
365   if (sep != NULL && strcmp (sep, "@*") != 0 && strcmp (sep, "@") != 0) {
366     /* paths are not canonicalised or treated with realpath() here. This
367      * should be good enough for our use case, since we just use the paths
368      * autotools uses, and those will be constructed from the same prefix. */
369     if (filename != NULL && !g_str_has_prefix (filename, sep + 1))
370       return FALSE;
371
372     GST_LOG ("%s matches path prefix %s", GST_STR_NULL (filename), sep + 1);
373   }
374
375   if (sep != NULL) {
376     name = g_strndup (pattern, (gsize) (sep - pattern));
377   } else {
378     name = g_strdup (pattern);
379   }
380
381   g_strstrip (name);
382   if (!g_ascii_isalnum (*name)) {
383     GST_WARNING ("Invalid whitelist pattern: %s", pattern);
384     goto done;
385   }
386
387   /* now check plugin names / source package name */
388   if (strchr (name, ',') == NULL) {
389     /* only a single name: either a plugin name or the source package name */
390     ret = (strcmp (desc->source, name) == 0 || strcmp (desc->name, name) == 0);
391   } else {
392     gchar **n, **names;
393
394     /* multiple names: assume these are plugin names */
395     names = g_strsplit (name, ",", -1);
396     for (n = names; n != NULL && *n != NULL; ++n) {
397       g_strstrip (*n);
398       if (strcmp (desc->name, *n) == 0) {
399         ret = TRUE;
400         break;
401       }
402     }
403     g_strfreev (names);
404   }
405
406   GST_LOG ("plugin / source package name match: %d", ret);
407
408 done:
409
410   g_free (name);
411   return ret;
412 }
413
414 gboolean
415 priv_gst_plugin_desc_is_whitelisted (GstPluginDesc * desc,
416     const gchar * filename)
417 {
418   gchar **entry;
419
420   if (_plugin_loading_whitelist == NULL)
421     return TRUE;
422
423   for (entry = _plugin_loading_whitelist; *entry != NULL; ++entry) {
424     if (gst_plugin_desc_matches_whitelist_entry (desc, filename, *entry)) {
425       GST_LOG ("Plugin %s is in whitelist", filename);
426       return TRUE;
427     }
428   }
429
430   GST_LOG ("Plugin %s (package %s, file %s) not in whitelist", desc->name,
431       desc->source, filename);
432   return FALSE;
433 }
434
435 gboolean
436 priv_gst_plugin_loading_have_whitelist (void)
437 {
438   return (_plugin_loading_whitelist != NULL);
439 }
440
441 guint32
442 priv_gst_plugin_loading_get_whitelist_hash (void)
443 {
444   guint32 hash = 0;
445
446   if (_plugin_loading_whitelist != NULL) {
447     gchar **w;
448
449     for (w = _plugin_loading_whitelist; *w != NULL; ++w)
450       hash = (hash << 1) ^ g_str_hash (*w);
451   }
452
453   return hash;
454 }
455
456 /* this function could be extended to check if the plugin license matches the
457  * applications license (would require the app to register its license somehow).
458  * We'll wait for someone who's interested in it to code it :)
459  */
460 static gboolean
461 gst_plugin_check_license (const gchar * license)
462 {
463   const gchar **check_license = valid_licenses;
464
465   g_assert (check_license);
466
467   while (*check_license) {
468     if (strcmp (license, *check_license) == 0)
469       return TRUE;
470     check_license++;
471   }
472   return FALSE;
473 }
474
475 static gboolean
476 gst_plugin_check_version (gint major, gint minor)
477 {
478   /* return NULL if the major and minor version numbers are not compatible */
479   /* with ours. */
480   if (major != GST_VERSION_MAJOR || minor != GST_VERSION_MINOR)
481     return FALSE;
482
483   return TRUE;
484 }
485
486 static GstPlugin *
487 gst_plugin_register_func (GstPlugin * plugin, const GstPluginDesc * desc,
488     gpointer user_data)
489 {
490   if (!gst_plugin_check_version (desc->major_version, desc->minor_version)) {
491     if (GST_CAT_DEFAULT)
492       GST_WARNING ("plugin \"%s\" has incompatible version, not loading",
493           plugin->filename);
494     return NULL;
495   }
496
497   if (!desc->license || !desc->description || !desc->source ||
498       !desc->package || !desc->origin) {
499     if (GST_CAT_DEFAULT)
500       GST_WARNING ("plugin \"%s\" has incorrect GstPluginDesc, not loading",
501           plugin->filename);
502     return NULL;
503   }
504
505   if (!gst_plugin_check_license (desc->license)) {
506     if (GST_CAT_DEFAULT)
507       GST_WARNING ("plugin \"%s\" has invalid license \"%s\", not loading",
508           plugin->filename, desc->license);
509     return NULL;
510   }
511
512   if (GST_CAT_DEFAULT)
513     GST_LOG ("plugin \"%s\" looks good", GST_STR_NULL (plugin->filename));
514
515   gst_plugin_desc_copy (&plugin->desc, desc);
516
517   /* make resident so we're really sure it never gets unloaded again.
518    * Theoretically this is not needed, but practically it doesn't hurt.
519    * And we're rather safe than sorry. */
520   if (plugin->module)
521     g_module_make_resident (plugin->module);
522
523   if (user_data) {
524     if (!(((GstPluginInitFullFunc) (desc->plugin_init)) (plugin, user_data))) {
525       if (GST_CAT_DEFAULT)
526         GST_WARNING ("plugin \"%s\" failed to initialise", plugin->filename);
527       return NULL;
528     }
529   } else {
530     if (!((desc->plugin_init) (plugin))) {
531       if (GST_CAT_DEFAULT)
532         GST_WARNING ("plugin \"%s\" failed to initialise", plugin->filename);
533       return NULL;
534     }
535   }
536
537   if (GST_CAT_DEFAULT)
538     GST_LOG ("plugin \"%s\" initialised", GST_STR_NULL (plugin->filename));
539
540   return plugin;
541 }
542
543 #ifdef HAVE_SIGACTION
544 static struct sigaction oldaction;
545 static gboolean _gst_plugin_fault_handler_is_setup = FALSE;
546
547 /*
548  * _gst_plugin_fault_handler_restore:
549  * segfault handler restorer
550  */
551 static void
552 _gst_plugin_fault_handler_restore (void)
553 {
554   if (!_gst_plugin_fault_handler_is_setup)
555     return;
556
557   _gst_plugin_fault_handler_is_setup = FALSE;
558
559   sigaction (SIGSEGV, &oldaction, NULL);
560 }
561
562 /*
563  * _gst_plugin_fault_handler_sighandler:
564  * segfault handler implementation
565  */
566 static void
567 _gst_plugin_fault_handler_sighandler (int signum)
568 {
569   /* We need to restore the fault handler or we'll keep getting it */
570   _gst_plugin_fault_handler_restore ();
571
572   switch (signum) {
573     case SIGSEGV:
574       g_print ("\nERROR: ");
575       g_print ("Caught a segmentation fault while loading plugin file:\n");
576       g_print ("%s\n\n", _gst_plugin_fault_handler_filename);
577       g_print ("Please either:\n");
578       g_print ("- remove it and restart.\n");
579       g_print
580           ("- run with --gst-disable-segtrap --gst-disable-registry-fork and debug.\n");
581       exit (-1);
582       break;
583     default:
584       g_print ("Caught unhandled signal on plugin loading\n");
585       break;
586   }
587 }
588
589 /*
590  * _gst_plugin_fault_handler_setup:
591  * sets up the segfault handler
592  */
593 static void
594 _gst_plugin_fault_handler_setup (void)
595 {
596   struct sigaction action;
597
598   /* if asked to leave segfaults alone, just return */
599   if (!gst_segtrap_is_enabled ())
600     return;
601
602   if (_gst_plugin_fault_handler_is_setup)
603     return;
604
605   _gst_plugin_fault_handler_is_setup = TRUE;
606
607   memset (&action, 0, sizeof (action));
608   action.sa_handler = _gst_plugin_fault_handler_sighandler;
609
610   sigaction (SIGSEGV, &action, &oldaction);
611 }
612 #else /* !HAVE_SIGACTION */
613 static void
614 _gst_plugin_fault_handler_restore (void)
615 {
616 }
617
618 static void
619 _gst_plugin_fault_handler_setup (void)
620 {
621 }
622 #endif /* HAVE_SIGACTION */
623
624 /* g_time_val_from_iso8601() doesn't do quite what we want */
625 static gboolean
626 check_release_datetime (const gchar * date_time)
627 {
628   guint64 val;
629
630   /* we require YYYY-MM-DD or YYYY-MM-DDTHH:MMZ format */
631   if (!g_ascii_isdigit (*date_time))
632     return FALSE;
633
634   val = g_ascii_strtoull (date_time, (gchar **) & date_time, 10);
635   if (val < 2000 || val > 2100 || *date_time != '-')
636     return FALSE;
637
638   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
639   if (val == 0 || val > 12 || *date_time != '-')
640     return FALSE;
641
642   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
643   if (val == 0 || val > 32)
644     return FALSE;
645
646   /* end of string or date/time separator + HH:MMZ */
647   if (*date_time == 'T' || *date_time == ' ') {
648     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
649     if (val > 24 || *date_time != ':')
650       return FALSE;
651
652     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
653     if (val > 59 || *date_time != 'Z')
654       return FALSE;
655
656     ++date_time;
657   }
658
659   return (*date_time == '\0');
660 }
661
662 static GStaticMutex gst_plugin_loading_mutex = G_STATIC_MUTEX_INIT;
663
664 #define CHECK_PLUGIN_DESC_FIELD(desc,field,fn)                               \
665   if (G_UNLIKELY ((desc)->field == NULL)) {                                  \
666     GST_ERROR ("GstPluginDesc for '%s' has no %s", fn, G_STRINGIFY (field)); \
667   }
668
669 /**
670  * gst_plugin_load_file:
671  * @filename: the plugin filename to load
672  * @error: pointer to a NULL-valued GError
673  *
674  * Loads the given plugin and refs it.  Caller needs to unref after use.
675  *
676  * Returns: (transfer full): a reference to the existing loaded GstPlugin, a 
677  * reference to the newly-loaded GstPlugin, or NULL if an error occurred.
678  */
679 GstPlugin *
680 gst_plugin_load_file (const gchar * filename, GError ** error)
681 {
682   GstPluginDesc *desc;
683   GstPlugin *plugin;
684   GModule *module;
685   gboolean ret;
686   gpointer ptr;
687   GStatBuf file_status;
688   GstRegistry *registry;
689   gboolean new_plugin = TRUE;
690   GModuleFlags flags;
691
692   g_return_val_if_fail (filename != NULL, NULL);
693
694   registry = gst_registry_get_default ();
695   g_static_mutex_lock (&gst_plugin_loading_mutex);
696
697   plugin = gst_registry_lookup (registry, filename);
698   if (plugin) {
699     if (plugin->module) {
700       /* already loaded */
701       g_static_mutex_unlock (&gst_plugin_loading_mutex);
702       return plugin;
703     } else {
704       /* load plugin and update fields */
705       new_plugin = FALSE;
706     }
707   }
708
709   GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "attempt to load plugin \"%s\"",
710       filename);
711
712   if (g_module_supported () == FALSE) {
713     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "module loading not supported");
714     g_set_error (error,
715         GST_PLUGIN_ERROR,
716         GST_PLUGIN_ERROR_MODULE, "Dynamic loading not supported");
717     goto return_error;
718   }
719
720   if (g_stat (filename, &file_status)) {
721     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "problem accessing file");
722     g_set_error (error,
723         GST_PLUGIN_ERROR,
724         GST_PLUGIN_ERROR_MODULE, "Problem accessing file %s: %s", filename,
725         g_strerror (errno));
726     goto return_error;
727   }
728
729   flags = G_MODULE_BIND_LOCAL;
730   /* libgstpython.so is the gst-python plugin loader. It needs to be loaded with
731    * G_MODULE_BIND_LAZY.
732    *
733    * Ideally there should be a generic way for plugins to specify that they
734    * need to be loaded with _LAZY.
735    * */
736   if (strstr (filename, "libgstpython"))
737     flags |= G_MODULE_BIND_LAZY;
738
739   module = g_module_open (filename, flags);
740   if (module == NULL) {
741     GST_CAT_WARNING (GST_CAT_PLUGIN_LOADING, "module_open failed: %s",
742         g_module_error ());
743     g_set_error (error,
744         GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE, "Opening module failed: %s",
745         g_module_error ());
746     /* If we failed to open the shared object, then it's probably because a
747      * plugin is linked against the wrong libraries. Print out an easy-to-see
748      * message in this case. */
749     g_warning ("Failed to load plugin '%s': %s", filename, g_module_error ());
750     goto return_error;
751   }
752
753   ret = g_module_symbol (module, "gst_plugin_desc", &ptr);
754   if (!ret) {
755     GST_DEBUG ("Could not find plugin entry point in \"%s\"", filename);
756     g_set_error (error,
757         GST_PLUGIN_ERROR,
758         GST_PLUGIN_ERROR_MODULE,
759         "File \"%s\" is not a GStreamer plugin", filename);
760     g_module_close (module);
761     goto return_error;
762   }
763
764   desc = (GstPluginDesc *) ptr;
765
766   if (priv_gst_plugin_loading_have_whitelist () &&
767       !priv_gst_plugin_desc_is_whitelisted (desc, filename)) {
768     GST_INFO ("Whitelist specified and plugin not in whitelist, not loading: "
769         "name=%s, package=%s, file=%s", desc->name, desc->source, filename);
770     g_set_error (error, GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE,
771         "Not loading plugin file \"%s\", not in whitelist", filename);
772     g_module_close (module);
773     goto return_error;
774   }
775
776   if (new_plugin) {
777     plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
778     plugin->file_mtime = file_status.st_mtime;
779     plugin->file_size = file_status.st_size;
780     plugin->filename = g_strdup (filename);
781     plugin->basename = g_path_get_basename (filename);
782   }
783
784   plugin->module = module;
785   plugin->orig_desc = desc;
786
787   if (new_plugin) {
788     /* check plugin description: complain about bad values but accept them, to
789      * maintain backwards compatibility (FIXME: 0.11) */
790     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, name, filename);
791     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, description, filename);
792     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, version, filename);
793     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, license, filename);
794     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, source, filename);
795     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, package, filename);
796     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, origin, filename);
797
798     if (plugin->orig_desc->release_datetime != NULL &&
799         !check_release_datetime (plugin->orig_desc->release_datetime)) {
800       GST_ERROR ("GstPluginDesc for '%s' has invalid datetime '%s'",
801           filename, plugin->orig_desc->release_datetime);
802       plugin->orig_desc->release_datetime = NULL;
803     }
804   }
805
806   GST_LOG ("Plugin %p for file \"%s\" prepared, calling entry function...",
807       plugin, filename);
808
809   /* this is where we load the actual .so, so let's trap SIGSEGV */
810   _gst_plugin_fault_handler_setup ();
811   _gst_plugin_fault_handler_filename = plugin->filename;
812
813   GST_LOG ("Plugin %p for file \"%s\" prepared, registering...",
814       plugin, filename);
815
816   if (!gst_plugin_register_func (plugin, plugin->orig_desc, NULL)) {
817     /* remove signal handler */
818     _gst_plugin_fault_handler_restore ();
819     GST_DEBUG ("gst_plugin_register_func failed for plugin \"%s\"", filename);
820     /* plugin == NULL */
821     g_set_error (error,
822         GST_PLUGIN_ERROR,
823         GST_PLUGIN_ERROR_MODULE,
824         "File \"%s\" appears to be a GStreamer plugin, but it failed to initialize",
825         filename);
826     goto return_error;
827   }
828
829   /* remove signal handler */
830   _gst_plugin_fault_handler_restore ();
831   _gst_plugin_fault_handler_filename = NULL;
832   GST_INFO ("plugin \"%s\" loaded", plugin->filename);
833
834   if (new_plugin) {
835     gst_object_ref (plugin);
836     gst_default_registry_add_plugin (plugin);
837   }
838
839   g_static_mutex_unlock (&gst_plugin_loading_mutex);
840   return plugin;
841
842 return_error:
843   {
844     if (plugin)
845       gst_object_unref (plugin);
846     g_static_mutex_unlock (&gst_plugin_loading_mutex);
847     return NULL;
848   }
849 }
850
851 static void
852 gst_plugin_desc_copy (GstPluginDesc * dest, const GstPluginDesc * src)
853 {
854   dest->major_version = src->major_version;
855   dest->minor_version = src->minor_version;
856   dest->name = g_intern_string (src->name);
857   dest->description = g_intern_string (src->description);
858   dest->plugin_init = src->plugin_init;
859   dest->version = g_intern_string (src->version);
860   dest->license = g_intern_string (src->license);
861   dest->source = g_intern_string (src->source);
862   dest->package = g_intern_string (src->package);
863   dest->origin = g_intern_string (src->origin);
864   dest->release_datetime = g_intern_string (src->release_datetime);
865 }
866
867 /**
868  * gst_plugin_get_name:
869  * @plugin: plugin to get the name of
870  *
871  * Get the short name of the plugin
872  *
873  * Returns: the name of the plugin
874  */
875 const gchar *
876 gst_plugin_get_name (GstPlugin * plugin)
877 {
878   g_return_val_if_fail (plugin != NULL, NULL);
879
880   return plugin->desc.name;
881 }
882
883 /**
884  * gst_plugin_get_description:
885  * @plugin: plugin to get long name of
886  *
887  * Get the long descriptive name of the plugin
888  *
889  * Returns: the long name of the plugin
890  */
891 const gchar *
892 gst_plugin_get_description (GstPlugin * plugin)
893 {
894   g_return_val_if_fail (plugin != NULL, NULL);
895
896   return plugin->desc.description;
897 }
898
899 /**
900  * gst_plugin_get_filename:
901  * @plugin: plugin to get the filename of
902  *
903  * get the filename of the plugin
904  *
905  * Returns: the filename of the plugin
906  */
907 const gchar *
908 gst_plugin_get_filename (GstPlugin * plugin)
909 {
910   g_return_val_if_fail (plugin != NULL, NULL);
911
912   return plugin->filename;
913 }
914
915 /**
916  * gst_plugin_get_version:
917  * @plugin: plugin to get the version of
918  *
919  * get the version of the plugin
920  *
921  * Returns: the version of the plugin
922  */
923 const gchar *
924 gst_plugin_get_version (GstPlugin * plugin)
925 {
926   g_return_val_if_fail (plugin != NULL, NULL);
927
928   return plugin->desc.version;
929 }
930
931 /**
932  * gst_plugin_get_license:
933  * @plugin: plugin to get the license of
934  *
935  * get the license of the plugin
936  *
937  * Returns: the license of the plugin
938  */
939 const gchar *
940 gst_plugin_get_license (GstPlugin * plugin)
941 {
942   g_return_val_if_fail (plugin != NULL, NULL);
943
944   return plugin->desc.license;
945 }
946
947 /**
948  * gst_plugin_get_source:
949  * @plugin: plugin to get the source of
950  *
951  * get the source module the plugin belongs to.
952  *
953  * Returns: the source of the plugin
954  */
955 const gchar *
956 gst_plugin_get_source (GstPlugin * plugin)
957 {
958   g_return_val_if_fail (plugin != NULL, NULL);
959
960   return plugin->desc.source;
961 }
962
963 /**
964  * gst_plugin_get_package:
965  * @plugin: plugin to get the package of
966  *
967  * get the package the plugin belongs to.
968  *
969  * Returns: the package of the plugin
970  */
971 const gchar *
972 gst_plugin_get_package (GstPlugin * plugin)
973 {
974   g_return_val_if_fail (plugin != NULL, NULL);
975
976   return plugin->desc.package;
977 }
978
979 /**
980  * gst_plugin_get_origin:
981  * @plugin: plugin to get the origin of
982  *
983  * get the URL where the plugin comes from
984  *
985  * Returns: the origin of the plugin
986  */
987 const gchar *
988 gst_plugin_get_origin (GstPlugin * plugin)
989 {
990   g_return_val_if_fail (plugin != NULL, NULL);
991
992   return plugin->desc.origin;
993 }
994
995 /**
996  * gst_plugin_get_module:
997  * @plugin: plugin to query
998  *
999  * Gets the #GModule of the plugin. If the plugin isn't loaded yet, NULL is
1000  * returned.
1001  *
1002  * Returns: (transfer none): module belonging to the plugin or NULL if the
1003  *          plugin isn't loaded yet.
1004  */
1005 GModule *
1006 gst_plugin_get_module (GstPlugin * plugin)
1007 {
1008   g_return_val_if_fail (plugin != NULL, NULL);
1009
1010   return plugin->module;
1011 }
1012
1013 /**
1014  * gst_plugin_is_loaded:
1015  * @plugin: plugin to query
1016  *
1017  * queries if the plugin is loaded into memory
1018  *
1019  * Returns: TRUE is loaded, FALSE otherwise
1020  */
1021 gboolean
1022 gst_plugin_is_loaded (GstPlugin * plugin)
1023 {
1024   g_return_val_if_fail (plugin != NULL, FALSE);
1025
1026   return (plugin->module != NULL || plugin->filename == NULL);
1027 }
1028
1029 /**
1030  * gst_plugin_get_cache_data:
1031  * @plugin: a plugin
1032  *
1033  * Gets the plugin specific data cache. If it is %NULL there is no cached data
1034  * stored. This is the case when the registry is getting rebuilt.
1035  *
1036  * Returns: (transfer none): The cached data as a #GstStructure or %NULL.
1037  *
1038  * Since: 0.10.24
1039  */
1040 const GstStructure *
1041 gst_plugin_get_cache_data (GstPlugin * plugin)
1042 {
1043   g_return_val_if_fail (GST_IS_PLUGIN (plugin), NULL);
1044
1045   return plugin->priv->cache_data;
1046 }
1047
1048 /**
1049  * gst_plugin_set_cache_data:
1050  * @plugin: a plugin
1051  * @cache_data: (transfer full): a structure containing the data to cache
1052  *
1053  * Adds plugin specific data to cache. Passes the ownership of the structure to
1054  * the @plugin.
1055  *
1056  * The cache is flushed every time the registry is rebuilt.
1057  *
1058  * Since: 0.10.24
1059  */
1060 void
1061 gst_plugin_set_cache_data (GstPlugin * plugin, GstStructure * cache_data)
1062 {
1063   g_return_if_fail (GST_IS_PLUGIN (plugin));
1064   g_return_if_fail (GST_IS_STRUCTURE (cache_data));
1065
1066   if (plugin->priv->cache_data) {
1067     gst_structure_free (plugin->priv->cache_data);
1068   }
1069   plugin->priv->cache_data = cache_data;
1070 }
1071
1072 #if 0
1073 /**
1074  * gst_plugin_feature_list:
1075  * @plugin: plugin to query
1076  * @filter: the filter to use
1077  * @first: only return first match
1078  * @user_data: user data passed to the filter function
1079  *
1080  * Runs a filter against all plugin features and returns a GList with
1081  * the results. If the first flag is set, only the first match is
1082  * returned (as a list with a single object).
1083  *
1084  * Returns: a GList of features, g_list_free after use.
1085  */
1086 GList *
1087 gst_plugin_feature_filter (GstPlugin * plugin,
1088     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1089 {
1090   GList *list;
1091   GList *g;
1092
1093   list = gst_filter_run (plugin->features, (GstFilterFunc) filter, first,
1094       user_data);
1095   for (g = list; g; g = g->next) {
1096     gst_object_ref (plugin);
1097   }
1098
1099   return list;
1100 }
1101
1102 typedef struct
1103 {
1104   GstPluginFeatureFilter filter;
1105   gboolean first;
1106   gpointer user_data;
1107   GList *result;
1108 }
1109 FeatureFilterData;
1110
1111 static gboolean
1112 _feature_filter (GstPlugin * plugin, gpointer user_data)
1113 {
1114   GList *result;
1115   FeatureFilterData *data = (FeatureFilterData *) user_data;
1116
1117   result = gst_plugin_feature_filter (plugin, data->filter, data->first,
1118       data->user_data);
1119   if (result) {
1120     data->result = g_list_concat (data->result, result);
1121     return TRUE;
1122   }
1123   return FALSE;
1124 }
1125
1126 /**
1127  * gst_plugin_list_feature_filter:
1128  * @list: a #GList of plugins to query
1129  * @filter: the filter function to use
1130  * @first: only return first match
1131  * @user_data: user data passed to the filter function
1132  *
1133  * Runs a filter against all plugin features of the plugins in the given
1134  * list and returns a GList with the results.
1135  * If the first flag is set, only the first match is
1136  * returned (as a list with a single object).
1137  *
1138  * Returns: a GList of features, g_list_free after use.
1139  */
1140 GList *
1141 gst_plugin_list_feature_filter (GList * list,
1142     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1143 {
1144   FeatureFilterData data;
1145   GList *result;
1146
1147   data.filter = filter;
1148   data.first = first;
1149   data.user_data = user_data;
1150   data.result = NULL;
1151
1152   result = gst_filter_run (list, (GstFilterFunc) _feature_filter, first, &data);
1153   g_list_free (result);
1154
1155   return data.result;
1156 }
1157 #endif
1158
1159 /**
1160  * gst_plugin_name_filter:
1161  * @plugin: the plugin to check
1162  * @name: the name of the plugin
1163  *
1164  * A standard filter that returns TRUE when the plugin is of the
1165  * given name.
1166  *
1167  * Returns: TRUE if the plugin is of the given name.
1168  */
1169 gboolean
1170 gst_plugin_name_filter (GstPlugin * plugin, const gchar * name)
1171 {
1172   return (plugin->desc.name && !strcmp (plugin->desc.name, name));
1173 }
1174
1175 #if 0
1176 /**
1177  * gst_plugin_find_feature:
1178  * @plugin: plugin to get the feature from
1179  * @name: The name of the feature to find
1180  * @type: The type of the feature to find
1181  *
1182  * Find a feature of the given name and type in the given plugin.
1183  *
1184  * Returns: a GstPluginFeature or NULL if the feature was not found.
1185  */
1186 GstPluginFeature *
1187 gst_plugin_find_feature (GstPlugin * plugin, const gchar * name, GType type)
1188 {
1189   GList *walk;
1190   GstPluginFeature *result = NULL;
1191   GstTypeNameData data;
1192
1193   g_return_val_if_fail (name != NULL, NULL);
1194
1195   data.type = type;
1196   data.name = name;
1197
1198   walk = gst_filter_run (plugin->features,
1199       (GstFilterFunc) gst_plugin_feature_type_name_filter, TRUE, &data);
1200
1201   if (walk) {
1202     result = GST_PLUGIN_FEATURE (walk->data);
1203
1204     gst_object_ref (result);
1205     gst_plugin_feature_list_free (walk);
1206   }
1207
1208   return result;
1209 }
1210 #endif
1211
1212 #if 0
1213 static gboolean
1214 gst_plugin_feature_name_filter (GstPluginFeature * feature, const gchar * name)
1215 {
1216   return !strcmp (name, GST_PLUGIN_FEATURE_NAME (feature));
1217 }
1218 #endif
1219
1220 #if 0
1221 /**
1222  * gst_plugin_find_feature_by_name:
1223  * @plugin: plugin to get the feature from
1224  * @name: The name of the feature to find
1225  *
1226  * Find a feature of the given name in the given plugin.
1227  *
1228  * Returns: a GstPluginFeature or NULL if the feature was not found.
1229  */
1230 GstPluginFeature *
1231 gst_plugin_find_feature_by_name (GstPlugin * plugin, const gchar * name)
1232 {
1233   GList *walk;
1234   GstPluginFeature *result = NULL;
1235
1236   g_return_val_if_fail (name != NULL, NULL);
1237
1238   walk = gst_filter_run (plugin->features,
1239       (GstFilterFunc) gst_plugin_feature_name_filter, TRUE, (void *) name);
1240
1241   if (walk) {
1242     result = GST_PLUGIN_FEATURE (walk->data);
1243
1244     gst_object_ref (result);
1245     gst_plugin_feature_list_free (walk);
1246   }
1247
1248   return result;
1249 }
1250 #endif
1251
1252 /**
1253  * gst_plugin_load_by_name:
1254  * @name: name of plugin to load
1255  *
1256  * Load the named plugin. Refs the plugin.
1257  *
1258  * Returns: (transfer full): a reference to a loaded plugin, or NULL on error.
1259  */
1260 GstPlugin *
1261 gst_plugin_load_by_name (const gchar * name)
1262 {
1263   GstPlugin *plugin, *newplugin;
1264   GError *error = NULL;
1265
1266   GST_DEBUG ("looking up plugin %s in default registry", name);
1267   plugin = gst_registry_find_plugin (gst_registry_get_default (), name);
1268   if (plugin) {
1269     GST_DEBUG ("loading plugin %s from file %s", name, plugin->filename);
1270     newplugin = gst_plugin_load_file (plugin->filename, &error);
1271     gst_object_unref (plugin);
1272
1273     if (!newplugin) {
1274       GST_WARNING ("load_plugin error: %s", error->message);
1275       g_error_free (error);
1276       return NULL;
1277     }
1278     /* newplugin was reffed by load_file */
1279     return newplugin;
1280   }
1281
1282   GST_DEBUG ("Could not find plugin %s in registry", name);
1283   return NULL;
1284 }
1285
1286 /**
1287  * gst_plugin_load:
1288  * @plugin: (transfer none): plugin to load
1289  *
1290  * Loads @plugin. Note that the *return value* is the loaded plugin; @plugin is
1291  * untouched. The normal use pattern of this function goes like this:
1292  *
1293  * <programlisting>
1294  * GstPlugin *loaded_plugin;
1295  * loaded_plugin = gst_plugin_load (plugin);
1296  * // presumably, we're no longer interested in the potentially-unloaded plugin
1297  * gst_object_unref (plugin);
1298  * plugin = loaded_plugin;
1299  * </programlisting>
1300  *
1301  * Returns: (transfer full): a reference to a loaded plugin, or NULL on error.
1302  */
1303 GstPlugin *
1304 gst_plugin_load (GstPlugin * plugin)
1305 {
1306   GError *error = NULL;
1307   GstPlugin *newplugin;
1308
1309   if (gst_plugin_is_loaded (plugin)) {
1310     return plugin;
1311   }
1312
1313   if (!(newplugin = gst_plugin_load_file (plugin->filename, &error)))
1314     goto load_error;
1315
1316   return newplugin;
1317
1318 load_error:
1319   {
1320     GST_WARNING ("load_plugin error: %s", error->message);
1321     g_error_free (error);
1322     return NULL;
1323   }
1324 }
1325
1326 /**
1327  * gst_plugin_list_free:
1328  * @list: (transfer full) (element-type Gst.Plugin): list of #GstPlugin
1329  *
1330  * Unrefs each member of @list, then frees the list.
1331  */
1332 void
1333 gst_plugin_list_free (GList * list)
1334 {
1335   GList *g;
1336
1337   for (g = list; g; g = g->next) {
1338     gst_object_unref (GST_PLUGIN_CAST (g->data));
1339   }
1340   g_list_free (list);
1341 }
1342
1343 /* ===== plugin dependencies ===== */
1344
1345 /* Scenarios:
1346  * ENV + xyz     where ENV can contain multiple values separated by SEPARATOR
1347  *               xyz may be "" (if ENV contains path to file rather than dir)
1348  * ENV + *xyz   same as above, but xyz acts as suffix filter
1349  * ENV + xyz*   same as above, but xyz acts as prefix filter (is this needed?)
1350  * ENV + *xyz*  same as above, but xyz acts as strstr filter (is this needed?)
1351  * 
1352  * same as above, with additional paths hard-coded at compile-time:
1353  *   - only check paths + ... if ENV is not set or yields not paths
1354  *   - always check paths + ... in addition to ENV
1355  *
1356  * When user specifies set of environment variables, he/she may also use e.g.
1357  * "HOME/.mystuff/plugins", and we'll expand the content of $HOME with the
1358  * remainder 
1359  */
1360
1361 /* we store in registry:
1362  *  sets of:
1363  *   { 
1364  *     - environment variables (array of strings)
1365  *     - last hash of env variable contents (uint) (so we can avoid doing stats
1366  *       if one of the env vars has changed; premature optimisation galore)
1367  *     - hard-coded paths (array of strings)
1368  *     - xyz filename/suffix/prefix strings (array of strings)
1369  *     - flags (int)
1370  *     - last hash of file/dir stats (int)
1371  *   }
1372  *   (= struct GstPluginDep)
1373  */
1374
1375 static guint
1376 gst_plugin_ext_dep_get_env_vars_hash (GstPlugin * plugin, GstPluginDep * dep)
1377 {
1378   gchar **e;
1379   guint hash;
1380
1381   /* there's no deeper logic to what we do here; all we want to know (when
1382    * checking if the plugin needs to be rescanned) is whether the content of
1383    * one of the environment variables in the list is different from when it
1384    * was last scanned */
1385   hash = 0;
1386   for (e = dep->env_vars; e != NULL && *e != NULL; ++e) {
1387     const gchar *val;
1388     gchar env_var[256];
1389
1390     /* order matters: "val",NULL needs to yield a different hash than
1391      * NULL,"val", so do a shift here whether the var is set or not */
1392     hash = hash << 5;
1393
1394     /* want environment variable at beginning of string */
1395     if (!g_ascii_isalnum (**e)) {
1396       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1397           "variable string: %s", *e);
1398       continue;
1399     }
1400
1401     /* user is allowed to specify e.g. "HOME/.pitivi/plugins" */
1402     g_strlcpy (env_var, *e, sizeof (env_var));
1403     g_strdelimit (env_var, "/\\", '\0');
1404
1405     if ((val = g_getenv (env_var)))
1406       hash += g_str_hash (val);
1407   }
1408
1409   return hash;
1410 }
1411
1412 gboolean
1413 _priv_plugin_deps_env_vars_changed (GstPlugin * plugin)
1414 {
1415   GList *l;
1416
1417   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1418     GstPluginDep *dep = l->data;
1419
1420     if (dep->env_hash != gst_plugin_ext_dep_get_env_vars_hash (plugin, dep))
1421       return TRUE;
1422   }
1423
1424   return FALSE;
1425 }
1426
1427 static void
1428 gst_plugin_ext_dep_extract_env_vars_paths (GstPlugin * plugin,
1429     GstPluginDep * dep, GQueue * paths)
1430 {
1431   gchar **evars;
1432
1433   for (evars = dep->env_vars; evars != NULL && *evars != NULL; ++evars) {
1434     const gchar *e;
1435     gchar **components;
1436
1437     /* want environment variable at beginning of string */
1438     if (!g_ascii_isalnum (**evars)) {
1439       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1440           "variable string: %s", *evars);
1441       continue;
1442     }
1443
1444     /* user is allowed to specify e.g. "HOME/.pitivi/plugins", which we want to
1445      * split into the env_var name component and the path component */
1446     components = g_strsplit_set (*evars, "/\\", 2);
1447     g_assert (components != NULL);
1448
1449     e = g_getenv (components[0]);
1450     GST_LOG_OBJECT (plugin, "expanding %s = '%s' (path suffix: %s)",
1451         components[0], GST_STR_NULL (e), GST_STR_NULL (components[1]));
1452
1453     if (components[1] != NULL) {
1454       g_strdelimit (components[1], "/\\", G_DIR_SEPARATOR);
1455     }
1456
1457     if (e != NULL && *e != '\0') {
1458       gchar **arr;
1459       guint i;
1460
1461       arr = g_strsplit (e, G_SEARCHPATH_SEPARATOR_S, -1);
1462
1463       for (i = 0; arr != NULL && arr[i] != NULL; ++i) {
1464         gchar *full_path;
1465
1466         if (!g_path_is_absolute (arr[i])) {
1467           GST_INFO_OBJECT (plugin, "ignoring environment variable content '%s'"
1468               ": either not an absolute path or not a path at all", arr[i]);
1469           continue;
1470         }
1471
1472         if (components[1] != NULL) {
1473           full_path = g_build_filename (arr[i], components[1], NULL);
1474         } else {
1475           full_path = g_strdup (arr[i]);
1476         }
1477
1478         if (!g_queue_find_custom (paths, full_path, (GCompareFunc) strcmp)) {
1479           GST_LOG_OBJECT (plugin, "path: '%s'", full_path);
1480           g_queue_push_tail (paths, full_path);
1481           full_path = NULL;
1482         } else {
1483           GST_LOG_OBJECT (plugin, "path: '%s' (duplicate,ignoring)", full_path);
1484           g_free (full_path);
1485         }
1486       }
1487
1488       g_strfreev (arr);
1489     }
1490
1491     g_strfreev (components);
1492   }
1493
1494   GST_LOG_OBJECT (plugin, "Extracted %d paths from environment", paths->length);
1495 }
1496
1497 static guint
1498 gst_plugin_ext_dep_get_hash_from_stat_entry (GStatBuf * s)
1499 {
1500   if (!(s->st_mode & (S_IFDIR | S_IFREG)))
1501     return (guint) - 1;
1502
1503   /* completely random formula */
1504   return ((s->st_size << 3) + (s->st_mtime << 5)) ^ s->st_ctime;
1505 }
1506
1507 static gboolean
1508 gst_plugin_ext_dep_direntry_matches (GstPlugin * plugin, const gchar * entry,
1509     const gchar ** filenames, GstPluginDependencyFlags flags)
1510 {
1511   /* no filenames specified, match all entries for now (could probably
1512    * optimise by just taking the dir stat hash or so) */
1513   if (filenames == NULL || *filenames == NULL || **filenames == '\0')
1514     return TRUE;
1515
1516   while (*filenames != NULL) {
1517     /* suffix match? */
1518     if (((flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX)) &&
1519         g_str_has_suffix (entry, *filenames)) {
1520       return TRUE;
1521       /* else it's an exact match that's needed */
1522     } else if (strcmp (entry, *filenames) == 0) {
1523       return TRUE;
1524     }
1525     GST_LOG ("%s does not match %s, flags=0x%04x", entry, *filenames, flags);
1526     ++filenames;
1527   }
1528   return FALSE;
1529 }
1530
1531 static guint
1532 gst_plugin_ext_dep_scan_dir_and_match_names (GstPlugin * plugin,
1533     const gchar * path, const gchar ** filenames,
1534     GstPluginDependencyFlags flags, int depth)
1535 {
1536   const gchar *entry;
1537   gboolean recurse_dirs;
1538   GError *err = NULL;
1539   GDir *dir;
1540   guint hash = 0;
1541
1542   recurse_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1543
1544   dir = g_dir_open (path, 0, &err);
1545   if (dir == NULL) {
1546     GST_DEBUG_OBJECT (plugin, "g_dir_open(%s) failed: %s", path, err->message);
1547     g_error_free (err);
1548     return (guint) - 1;
1549   }
1550
1551   /* FIXME: we're assuming here that we always get the directory entries in
1552    * the same order, and not in a random order */
1553   while ((entry = g_dir_read_name (dir))) {
1554     gboolean have_match;
1555     GStatBuf s;
1556     gchar *full_path;
1557     guint fhash;
1558
1559     have_match =
1560         gst_plugin_ext_dep_direntry_matches (plugin, entry, filenames, flags);
1561
1562     /* avoid the stat if possible */
1563     if (!have_match && !recurse_dirs)
1564       continue;
1565
1566     full_path = g_build_filename (path, entry, NULL);
1567     if (g_stat (full_path, &s) < 0) {
1568       fhash = (guint) - 1;
1569       GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1570           g_strerror (errno));
1571     } else if (have_match) {
1572       fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1573       GST_LOG_OBJECT (plugin, "stat: %s (result: %u)", full_path, fhash);
1574     } else if ((s.st_mode & (S_IFDIR))) {
1575       fhash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, full_path,
1576           filenames, flags, depth + 1);
1577     } else {
1578       /* it's not a name match, we want to recurse, but it's not a directory */
1579       g_free (full_path);
1580       continue;
1581     }
1582
1583     hash = (hash + fhash) << 1;
1584     g_free (full_path);
1585   }
1586
1587   g_dir_close (dir);
1588   return hash;
1589 }
1590
1591 static guint
1592 gst_plugin_ext_dep_scan_path_with_filenames (GstPlugin * plugin,
1593     const gchar * path, const gchar ** filenames,
1594     GstPluginDependencyFlags flags)
1595 {
1596   const gchar *empty_filenames[] = { "", NULL };
1597   gboolean recurse_into_dirs, partial_names;
1598   guint i, hash = 0;
1599
1600   /* to avoid special-casing below (FIXME?) */
1601   if (filenames == NULL || *filenames == NULL)
1602     filenames = empty_filenames;
1603
1604   recurse_into_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1605   partial_names = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX);
1606
1607   /* if we can construct the exact paths to check with the data we have, just
1608    * stat them one by one; this is more efficient than opening the directory
1609    * and going through each entry to see if it matches one of our filenames. */
1610   if (!recurse_into_dirs && !partial_names) {
1611     for (i = 0; filenames[i] != NULL; ++i) {
1612       GStatBuf s;
1613       gchar *full_path;
1614       guint fhash;
1615
1616       full_path = g_build_filename (path, filenames[i], NULL);
1617       if (g_stat (full_path, &s) < 0) {
1618         fhash = (guint) - 1;
1619         GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1620             g_strerror (errno));
1621       } else {
1622         fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1623         GST_LOG_OBJECT (plugin, "stat: %s (result: %08x)", full_path, fhash);
1624       }
1625       hash = (hash + fhash) << 1;
1626       g_free (full_path);
1627     }
1628   } else {
1629     hash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, path,
1630         filenames, flags, 0);
1631   }
1632
1633   return hash;
1634 }
1635
1636 static guint
1637 gst_plugin_ext_dep_get_stat_hash (GstPlugin * plugin, GstPluginDep * dep)
1638 {
1639   gboolean paths_are_default_only;
1640   GQueue scan_paths = G_QUEUE_INIT;
1641   guint scan_hash = 0;
1642   gchar *path;
1643
1644   GST_LOG_OBJECT (plugin, "start");
1645
1646   paths_are_default_only =
1647       dep->flags & GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_DEFAULT_ONLY;
1648
1649   gst_plugin_ext_dep_extract_env_vars_paths (plugin, dep, &scan_paths);
1650
1651   if (g_queue_is_empty (&scan_paths) || !paths_are_default_only) {
1652     gchar **paths;
1653
1654     for (paths = dep->paths; paths != NULL && *paths != NULL; ++paths) {
1655       const gchar *path = *paths;
1656
1657       if (!g_queue_find_custom (&scan_paths, path, (GCompareFunc) strcmp)) {
1658         GST_LOG_OBJECT (plugin, "path: '%s'", path);
1659         g_queue_push_tail (&scan_paths, g_strdup (path));
1660       } else {
1661         GST_LOG_OBJECT (plugin, "path: '%s' (duplicate, ignoring)", path);
1662       }
1663     }
1664   }
1665
1666   while ((path = g_queue_pop_head (&scan_paths))) {
1667     scan_hash += gst_plugin_ext_dep_scan_path_with_filenames (plugin, path,
1668         (const gchar **) dep->names, dep->flags);
1669     scan_hash = scan_hash << 1;
1670     g_free (path);
1671   }
1672
1673   GST_LOG_OBJECT (plugin, "done, scan_hash: %08x", scan_hash);
1674   return scan_hash;
1675 }
1676
1677 gboolean
1678 _priv_plugin_deps_files_changed (GstPlugin * plugin)
1679 {
1680   GList *l;
1681
1682   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1683     GstPluginDep *dep = l->data;
1684
1685     if (dep->stat_hash != gst_plugin_ext_dep_get_stat_hash (plugin, dep))
1686       return TRUE;
1687   }
1688
1689   return FALSE;
1690 }
1691
1692 static void
1693 gst_plugin_ext_dep_free (GstPluginDep * dep)
1694 {
1695   g_strfreev (dep->env_vars);
1696   g_strfreev (dep->paths);
1697   g_strfreev (dep->names);
1698   g_slice_free (GstPluginDep, dep);
1699 }
1700
1701 static gboolean
1702 gst_plugin_ext_dep_strv_equal (gchar ** arr1, gchar ** arr2)
1703 {
1704   if (arr1 == arr2)
1705     return TRUE;
1706   if (arr1 == NULL || arr2 == NULL)
1707     return FALSE;
1708   for (; *arr1 != NULL && *arr2 != NULL; ++arr1, ++arr2) {
1709     if (strcmp (*arr1, *arr2) != 0)
1710       return FALSE;
1711   }
1712   return (*arr1 == *arr2);
1713 }
1714
1715 static gboolean
1716 gst_plugin_ext_dep_equals (GstPluginDep * dep, const gchar ** env_vars,
1717     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1718 {
1719   if (dep->flags != flags)
1720     return FALSE;
1721
1722   return gst_plugin_ext_dep_strv_equal (dep->env_vars, (gchar **) env_vars) &&
1723       gst_plugin_ext_dep_strv_equal (dep->paths, (gchar **) paths) &&
1724       gst_plugin_ext_dep_strv_equal (dep->names, (gchar **) names);
1725 }
1726
1727 /**
1728  * gst_plugin_add_dependency:
1729  * @plugin: a #GstPlugin
1730  * @env_vars: NULL-terminated array of environment variables affecting the
1731  *     feature set of the plugin (e.g. an environment variable containing
1732  *     paths where to look for additional modules/plugins of a library),
1733  *     or NULL. Environment variable names may be followed by a path component
1734  *      which will be added to the content of the environment variable, e.g.
1735  *      "HOME/.mystuff/plugins".
1736  * @paths: NULL-terminated array of directories/paths where dependent files
1737  *     may be.
1738  * @names: NULL-terminated array of file names (or file name suffixes,
1739  *     depending on @flags) to be used in combination with the paths from
1740  *     @paths and/or the paths extracted from the environment variables in
1741  *     @env_vars, or NULL.
1742  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1743  *
1744  * Make GStreamer aware of external dependencies which affect the feature
1745  * set of this plugin (ie. the elements or typefinders associated with it).
1746  *
1747  * GStreamer will re-inspect plugins with external dependencies whenever any
1748  * of the external dependencies change. This is useful for plugins which wrap
1749  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1750  * library and makes visualisations available as GStreamer elements, or a
1751  * codec loader which exposes elements and/or caps dependent on what external
1752  * codec libraries are currently installed.
1753  *
1754  * Since: 0.10.22
1755  */
1756 void
1757 gst_plugin_add_dependency (GstPlugin * plugin, const gchar ** env_vars,
1758     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1759 {
1760   GstPluginDep *dep;
1761   GList *l;
1762
1763   g_return_if_fail (GST_IS_PLUGIN (plugin));
1764
1765   if ((env_vars == NULL || env_vars[0] == NULL) &&
1766       (paths == NULL || paths[0] == NULL)) {
1767     GST_DEBUG_OBJECT (plugin,
1768         "plugin registered empty dependency set. Ignoring");
1769     return;
1770   }
1771
1772   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1773     if (gst_plugin_ext_dep_equals (l->data, env_vars, paths, names, flags)) {
1774       GST_LOG_OBJECT (plugin, "dependency already registered");
1775       return;
1776     }
1777   }
1778
1779   dep = g_slice_new (GstPluginDep);
1780
1781   dep->env_vars = g_strdupv ((gchar **) env_vars);
1782   dep->paths = g_strdupv ((gchar **) paths);
1783   dep->names = g_strdupv ((gchar **) names);
1784   dep->flags = flags;
1785
1786   dep->env_hash = gst_plugin_ext_dep_get_env_vars_hash (plugin, dep);
1787   dep->stat_hash = gst_plugin_ext_dep_get_stat_hash (plugin, dep);
1788
1789   plugin->priv->deps = g_list_append (plugin->priv->deps, dep);
1790
1791   GST_DEBUG_OBJECT (plugin, "added dependency:");
1792   for (; env_vars != NULL && *env_vars != NULL; ++env_vars)
1793     GST_DEBUG_OBJECT (plugin, " evar: %s", *env_vars);
1794   for (; paths != NULL && *paths != NULL; ++paths)
1795     GST_DEBUG_OBJECT (plugin, " path: %s", *paths);
1796   for (; names != NULL && *names != NULL; ++names)
1797     GST_DEBUG_OBJECT (plugin, " name: %s", *names);
1798 }
1799
1800 /**
1801  * gst_plugin_add_dependency_simple:
1802  * @plugin: the #GstPlugin
1803  * @env_vars: one or more environment variables (separated by ':', ';' or ','),
1804  *      or NULL. Environment variable names may be followed by a path component
1805  *      which will be added to the content of the environment variable, e.g.
1806  *      "HOME/.mystuff/plugins:MYSTUFF_PLUGINS_PATH"
1807  * @paths: one ore more directory paths (separated by ':' or ';' or ','),
1808  *      or NULL. Example: "/usr/lib/mystuff/plugins"
1809  * @names: one or more file names or file name suffixes (separated by commas),
1810  *   or NULL
1811  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1812  *
1813  * Make GStreamer aware of external dependencies which affect the feature
1814  * set of this plugin (ie. the elements or typefinders associated with it).
1815  *
1816  * GStreamer will re-inspect plugins with external dependencies whenever any
1817  * of the external dependencies change. This is useful for plugins which wrap
1818  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1819  * library and makes visualisations available as GStreamer elements, or a
1820  * codec loader which exposes elements and/or caps dependent on what external
1821  * codec libraries are currently installed.
1822  *
1823  * Convenience wrapper function for gst_plugin_add_dependency() which
1824  * takes simple strings as arguments instead of string arrays, with multiple
1825  * arguments separated by predefined delimiters (see above).
1826  *
1827  * Since: 0.10.22
1828  */
1829 void
1830 gst_plugin_add_dependency_simple (GstPlugin * plugin,
1831     const gchar * env_vars, const gchar * paths, const gchar * names,
1832     GstPluginDependencyFlags flags)
1833 {
1834   gchar **a_evars = NULL;
1835   gchar **a_paths = NULL;
1836   gchar **a_names = NULL;
1837
1838   if (env_vars)
1839     a_evars = g_strsplit_set (env_vars, ":;,", -1);
1840   if (paths)
1841     a_paths = g_strsplit_set (paths, ":;,", -1);
1842   if (names)
1843     a_names = g_strsplit_set (names, ",", -1);
1844
1845   gst_plugin_add_dependency (plugin, (const gchar **) a_evars,
1846       (const gchar **) a_paths, (const gchar **) a_names, flags);
1847
1848   if (a_evars)
1849     g_strfreev (a_evars);
1850   if (a_paths)
1851     g_strfreev (a_paths);
1852   if (a_names)
1853     g_strfreev (a_names);
1854 }