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