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