plugin: API: GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_RELATIVE_TO_EXE
[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., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:gstplugin
25  * @title: GstPlugin
26  * @short_description: Container for features loaded from a shared object module
27  * @see_also: #GstPluginFeature, #GstElementFactory
28  *
29  * GStreamer is extensible, so #GstElement instances can be loaded at runtime.
30  * A plugin system can provide one or more of the basic
31  * <application>GStreamer</application> #GstPluginFeature subclasses.
32  *
33  * A plugin should export a symbol <symbol>gst_plugin_desc</symbol> that is a
34  * struct of type #GstPluginDesc.
35  * the plugin loader will check the version of the core library the plugin was
36  * linked against and will create a new #GstPlugin. It will then call the
37  * #GstPluginInitFunc function that was provided in the
38  * <symbol>gst_plugin_desc</symbol>.
39  *
40  * Once you have a handle to a #GstPlugin (e.g. from the #GstRegistry), you
41  * can add any object that subclasses #GstPluginFeature.
42  *
43  * Usually plugins are always automatically loaded so you don't need to call
44  * gst_plugin_load() explicitly to bring it into memory. There are options to
45  * statically link plugins to an app or even use GStreamer without a plugin
46  * repository in which case gst_plugin_load() can be needed to bring the plugin
47  * into memory.
48  */
49
50 #ifdef HAVE_CONFIG_H
51 #include "config.h"
52 #endif
53
54 #include "gst_private.h"
55
56 #include <glib/gstdio.h>
57 #include <sys/types.h>
58 #ifdef HAVE_DIRENT_H
59 #include <dirent.h>
60 #endif
61 #ifdef HAVE_UNISTD_H
62 #include <unistd.h>
63 #endif
64 #include <signal.h>
65 #include <errno.h>
66 #include <string.h>
67
68 #include "glib-compat-private.h"
69
70 #include <gst/gst.h>
71
72 #define GST_CAT_DEFAULT GST_CAT_PLUGIN_LOADING
73
74 static guint _num_static_plugins;       /* 0    */
75 static GstPluginDesc *_static_plugins;  /* NULL */
76 static gboolean _gst_plugin_inited;
77 static gchar **_plugin_loading_whitelist;       /* NULL */
78
79 /* static variables for segfault handling of plugin loading */
80 static char *_gst_plugin_fault_handler_filename = NULL;
81
82 /* list of valid licenses.
83  * One of these must be specified or the plugin won't be loaded
84  * Please file a bug to request any additional license be 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_new (GST_TYPE_PLUGIN, 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_new (GST_TYPE_PLUGIN, 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 (const 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 (const 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 ^= 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 "
484           "(plugin: %d.%d, gst: %d,%d), not loading",
485           GST_STR_NULL (plugin->filename), desc->major_version,
486           desc->minor_version, GST_VERSION_MAJOR, GST_VERSION_MINOR);
487     return NULL;
488   }
489
490   if (!desc->license || !desc->description || !desc->source ||
491       !desc->package || !desc->origin) {
492     if (GST_CAT_DEFAULT)
493       GST_WARNING ("plugin \"%s\" has missing detail in GstPluginDesc, not "
494           "loading", GST_STR_NULL (plugin->filename));
495     return NULL;
496   }
497
498   if (!gst_plugin_check_license (desc->license)) {
499     if (GST_CAT_DEFAULT)
500       GST_WARNING ("plugin \"%s\" has invalid license \"%s\", not loading",
501           GST_STR_NULL (plugin->filename), desc->license);
502     return NULL;
503   }
504
505   if (GST_CAT_DEFAULT)
506     GST_LOG ("plugin \"%s\" looks good", GST_STR_NULL (plugin->filename));
507
508   gst_plugin_desc_copy (&plugin->desc, desc);
509
510   /* make resident so we're really sure it never gets unloaded again.
511    * Theoretically this is not needed, but practically it doesn't hurt.
512    * And we're rather safe than sorry. */
513   if (plugin->module)
514     g_module_make_resident (plugin->module);
515
516   if (user_data) {
517     if (!(((GstPluginInitFullFunc) (desc->plugin_init)) (plugin, user_data))) {
518       if (GST_CAT_DEFAULT)
519         GST_WARNING ("plugin \"%s\" failed to initialise",
520             GST_STR_NULL (plugin->filename));
521       return NULL;
522     }
523   } else {
524     if (!((desc->plugin_init) (plugin))) {
525       if (GST_CAT_DEFAULT)
526         GST_WARNING ("plugin \"%s\" failed to initialise",
527             GST_STR_NULL (plugin->filename));
528       return NULL;
529     }
530   }
531
532   if (GST_CAT_DEFAULT)
533     GST_LOG ("plugin \"%s\" initialised", GST_STR_NULL (plugin->filename));
534
535   return plugin;
536 }
537
538 #ifdef HAVE_SIGACTION
539 static struct sigaction oldaction;
540 static gboolean _gst_plugin_fault_handler_is_setup = FALSE;
541
542 /*
543  * _gst_plugin_fault_handler_restore:
544  * segfault handler restorer
545  */
546 static void
547 _gst_plugin_fault_handler_restore (void)
548 {
549   if (!_gst_plugin_fault_handler_is_setup)
550     return;
551
552   _gst_plugin_fault_handler_is_setup = FALSE;
553
554   sigaction (SIGSEGV, &oldaction, NULL);
555 }
556
557 /*
558  * _gst_plugin_fault_handler_sighandler:
559  * segfault handler implementation
560  */
561 static void
562 _gst_plugin_fault_handler_sighandler (int signum)
563 {
564   /* We need to restore the fault handler or we'll keep getting it */
565   _gst_plugin_fault_handler_restore ();
566
567   switch (signum) {
568     case SIGSEGV:
569       g_print ("\nERROR: ");
570       g_print ("Caught a segmentation fault while loading plugin file:\n");
571       g_print ("%s\n\n", _gst_plugin_fault_handler_filename);
572       g_print ("Please either:\n");
573       g_print ("- remove it and restart.\n");
574       g_print
575           ("- run with --gst-disable-segtrap --gst-disable-registry-fork and debug.\n");
576       exit (-1);
577       break;
578     default:
579       g_print ("Caught unhandled signal on plugin loading\n");
580       break;
581   }
582 }
583
584 /*
585  * _gst_plugin_fault_handler_setup:
586  * sets up the segfault handler
587  */
588 static void
589 _gst_plugin_fault_handler_setup (void)
590 {
591   struct sigaction action;
592
593   /* if asked to leave segfaults alone, just return */
594   if (!gst_segtrap_is_enabled ())
595     return;
596
597   if (_gst_plugin_fault_handler_is_setup)
598     return;
599
600   _gst_plugin_fault_handler_is_setup = TRUE;
601
602   memset (&action, 0, sizeof (action));
603   action.sa_handler = _gst_plugin_fault_handler_sighandler;
604
605   sigaction (SIGSEGV, &action, &oldaction);
606 }
607 #else /* !HAVE_SIGACTION */
608 static void
609 _gst_plugin_fault_handler_restore (void)
610 {
611 }
612
613 static void
614 _gst_plugin_fault_handler_setup (void)
615 {
616 }
617 #endif /* HAVE_SIGACTION */
618
619 /* g_time_val_from_iso8601() doesn't do quite what we want */
620 static gboolean
621 check_release_datetime (const gchar * date_time)
622 {
623   guint64 val;
624
625   /* we require YYYY-MM-DD or YYYY-MM-DDTHH:MMZ format */
626   if (!g_ascii_isdigit (*date_time))
627     return FALSE;
628
629   val = g_ascii_strtoull (date_time, (gchar **) & date_time, 10);
630   if (val < 2000 || val > 2100 || *date_time != '-')
631     return FALSE;
632
633   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
634   if (val == 0 || val > 12 || *date_time != '-')
635     return FALSE;
636
637   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
638   if (val == 0 || val > 32)
639     return FALSE;
640
641   /* end of string or date/time separator + HH:MMZ */
642   if (*date_time == 'T' || *date_time == ' ') {
643     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
644     if (val > 24 || *date_time != ':')
645       return FALSE;
646
647     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
648     if (val > 59 || *date_time != 'Z')
649       return FALSE;
650
651     ++date_time;
652   }
653
654   return (*date_time == '\0');
655 }
656
657 static GMutex gst_plugin_loading_mutex;
658
659 #define CHECK_PLUGIN_DESC_FIELD(desc,field,fn)                               \
660   if (G_UNLIKELY ((desc)->field == NULL || *(desc)->field == '\0')) {        \
661     g_warning ("Plugin description for '%s' has no valid %s field", fn, G_STRINGIFY (field)); \
662     g_set_error (error, GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE, \
663         "Plugin %s has invalid plugin description field '%s'", \
664         filename, G_STRINGIFY (field)); \
665     goto return_error;                                                       \
666   }
667
668 /**
669  * gst_plugin_load_file:
670  * @filename: the plugin filename to load
671  * @error: pointer to a %NULL-valued GError
672  *
673  * Loads the given plugin and refs it.  Caller needs to unref after use.
674  *
675  * Returns: (transfer full): a reference to the existing loaded GstPlugin, a
676  * reference to the newly-loaded GstPlugin, or %NULL if an error occurred.
677  */
678 GstPlugin *
679 gst_plugin_load_file (const gchar * filename, GError ** error)
680 {
681   return _priv_gst_plugin_load_file_for_registry (filename, NULL, error);
682 }
683
684 static gchar *
685 extract_symname (const char *filename)
686 {
687   gchar *bname, *name, *symname;
688   const gchar *dot;
689   gsize prefix_len, len;
690   int i;
691
692   bname = g_path_get_basename (filename);
693   for (i = 0; bname[i]; ++i) {
694     if (bname[i] == '-')
695       bname[i] = '_';
696   }
697
698   if (g_str_has_prefix (bname, "libgst"))
699     prefix_len = 6;
700   else if (g_str_has_prefix (bname, "lib"))
701     prefix_len = 3;
702   else if (g_str_has_prefix (bname, "gst"))
703     prefix_len = 3;
704   else
705     prefix_len = 0;             /* use whole name (minus suffix) as plugin name */
706
707   dot = g_utf8_strchr (bname, -1, '.');
708   if (dot)
709     len = dot - bname - prefix_len;
710   else
711     len = g_utf8_strlen (bname + prefix_len, -1);
712
713   name = g_strndup (bname + prefix_len, len);
714   g_free (bname);
715
716   symname = g_strconcat ("gst_plugin_", name, "_get_desc", NULL);
717   g_free (name);
718
719   return symname;
720 }
721
722 /* Note: The return value is (transfer full) although we work with floating
723  * references here. If a new plugin instance is created, it is always sinked
724  * in the registry first and a new reference is returned
725  */
726 GstPlugin *
727 _priv_gst_plugin_load_file_for_registry (const gchar * filename,
728     GstRegistry * registry, GError ** error)
729 {
730   const GstPluginDesc *desc;
731   GstPlugin *plugin;
732   gchar *symname;
733   GModule *module;
734   gboolean ret;
735   gpointer ptr;
736   GStatBuf file_status;
737   gboolean new_plugin = TRUE;
738   GModuleFlags flags;
739
740   g_return_val_if_fail (filename != NULL, NULL);
741
742   if (registry == NULL)
743     registry = gst_registry_get ();
744
745   g_mutex_lock (&gst_plugin_loading_mutex);
746
747   plugin = gst_registry_lookup (registry, filename);
748   if (plugin) {
749     if (plugin->module) {
750       /* already loaded */
751       g_mutex_unlock (&gst_plugin_loading_mutex);
752       return plugin;
753     } else {
754       /* load plugin and update fields */
755       new_plugin = FALSE;
756     }
757   }
758
759   GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "attempt to load plugin \"%s\"",
760       filename);
761
762   if (!g_module_supported ()) {
763     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "module loading not supported");
764     g_set_error (error,
765         GST_PLUGIN_ERROR,
766         GST_PLUGIN_ERROR_MODULE, "Dynamic loading not supported");
767     goto return_error;
768   }
769
770   if (g_stat (filename, &file_status)) {
771     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "problem accessing file");
772     g_set_error (error,
773         GST_PLUGIN_ERROR,
774         GST_PLUGIN_ERROR_MODULE, "Problem accessing file %s: %s", filename,
775         g_strerror (errno));
776     goto return_error;
777   }
778
779   flags = G_MODULE_BIND_LOCAL;
780   /* libgstpython.so is the gst-python plugin loader. It needs to be loaded with
781    * G_MODULE_BIND_LAZY.
782    *
783    * Ideally there should be a generic way for plugins to specify that they
784    * need to be loaded with _LAZY.
785    * */
786   if (strstr (filename, "libgstpython"))
787     flags |= G_MODULE_BIND_LAZY;
788
789   module = g_module_open (filename, flags);
790   if (module == NULL) {
791     GST_CAT_WARNING (GST_CAT_PLUGIN_LOADING, "module_open failed: %s",
792         g_module_error ());
793     g_set_error (error,
794         GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE, "Opening module failed: %s",
795         g_module_error ());
796     /* If we failed to open the shared object, then it's probably because a
797      * plugin is linked against the wrong libraries. Print out an easy-to-see
798      * message in this case. */
799     g_warning ("Failed to load plugin '%s': %s", filename, g_module_error ());
800     goto return_error;
801   }
802
803   symname = extract_symname (filename);
804   ret = g_module_symbol (module, symname, &ptr);
805
806   if (ret) {
807     GstPluginDesc *(*get_desc) (void) = ptr;
808     ptr = get_desc ();
809   } else {
810     GST_DEBUG ("Could not find symbol '%s', falling back to gst_plugin_desc",
811         symname);
812     ret = g_module_symbol (module, "gst_plugin_desc", &ptr);
813   }
814
815   g_free (symname);
816
817   if (!ret) {
818     GST_DEBUG ("Could not find plugin entry point in \"%s\"", filename);
819     g_set_error (error,
820         GST_PLUGIN_ERROR,
821         GST_PLUGIN_ERROR_MODULE,
822         "File \"%s\" is not a GStreamer plugin", filename);
823     g_module_close (module);
824     goto return_error;
825   }
826
827   desc = (const GstPluginDesc *) ptr;
828
829   if (priv_gst_plugin_loading_have_whitelist () &&
830       !priv_gst_plugin_desc_is_whitelisted (desc, filename)) {
831     GST_INFO ("Whitelist specified and plugin not in whitelist, not loading: "
832         "name=%s, package=%s, file=%s", desc->name, desc->source, filename);
833     g_set_error (error, GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE,
834         "Not loading plugin file \"%s\", not in whitelist", filename);
835     g_module_close (module);
836     goto return_error;
837   }
838
839   if (new_plugin) {
840     plugin = g_object_new (GST_TYPE_PLUGIN, NULL);
841     plugin->file_mtime = file_status.st_mtime;
842     plugin->file_size = file_status.st_size;
843     plugin->filename = g_strdup (filename);
844     plugin->basename = g_path_get_basename (filename);
845   }
846
847   plugin->module = module;
848
849   if (new_plugin) {
850     /* check plugin description: complain about bad values and fail */
851     CHECK_PLUGIN_DESC_FIELD (desc, name, filename);
852     CHECK_PLUGIN_DESC_FIELD (desc, description, filename);
853     CHECK_PLUGIN_DESC_FIELD (desc, version, filename);
854     CHECK_PLUGIN_DESC_FIELD (desc, license, filename);
855     CHECK_PLUGIN_DESC_FIELD (desc, source, filename);
856     CHECK_PLUGIN_DESC_FIELD (desc, package, filename);
857     CHECK_PLUGIN_DESC_FIELD (desc, origin, filename);
858
859     if (desc->name != NULL && desc->name[0] == '"') {
860       g_warning ("Invalid plugin name '%s' - fix your GST_PLUGIN_DEFINE "
861           "(remove quotes around plugin name)", desc->name);
862     }
863
864     if (desc->release_datetime != NULL &&
865         !check_release_datetime (desc->release_datetime)) {
866       g_warning ("GstPluginDesc for '%s' has invalid datetime '%s'",
867           filename, desc->release_datetime);
868       g_set_error (error, GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE,
869           "Plugin %s has invalid plugin description field 'release_datetime'",
870           filename);
871       goto return_error;
872     }
873   }
874
875   GST_LOG ("Plugin %p for file \"%s\" prepared, calling entry function...",
876       plugin, filename);
877
878   /* this is where we load the actual .so, so let's trap SIGSEGV */
879   _gst_plugin_fault_handler_setup ();
880   _gst_plugin_fault_handler_filename = plugin->filename;
881
882   GST_LOG ("Plugin %p for file \"%s\" prepared, registering...",
883       plugin, filename);
884
885   if (!gst_plugin_register_func (plugin, desc, NULL)) {
886     /* remove signal handler */
887     _gst_plugin_fault_handler_restore ();
888     GST_DEBUG ("gst_plugin_register_func failed for plugin \"%s\"", filename);
889     /* plugin == NULL */
890     g_set_error (error,
891         GST_PLUGIN_ERROR,
892         GST_PLUGIN_ERROR_MODULE,
893         "File \"%s\" appears to be a GStreamer plugin, but it failed to initialize",
894         filename);
895     goto return_error;
896   }
897
898   /* remove signal handler */
899   _gst_plugin_fault_handler_restore ();
900   _gst_plugin_fault_handler_filename = NULL;
901   GST_INFO ("plugin \"%s\" loaded", plugin->filename);
902
903   if (new_plugin) {
904     gst_object_ref (plugin);
905     gst_registry_add_plugin (registry, plugin);
906   }
907
908   g_mutex_unlock (&gst_plugin_loading_mutex);
909   return plugin;
910
911 return_error:
912   {
913     if (plugin)
914       gst_object_unref (plugin);
915     g_mutex_unlock (&gst_plugin_loading_mutex);
916     return NULL;
917   }
918 }
919
920 static void
921 gst_plugin_desc_copy (GstPluginDesc * dest, const GstPluginDesc * src)
922 {
923   dest->major_version = src->major_version;
924   dest->minor_version = src->minor_version;
925   dest->name = g_intern_string (src->name);
926   dest->description = g_intern_string (src->description);
927   dest->plugin_init = src->plugin_init;
928   dest->version = g_intern_string (src->version);
929   dest->license = g_intern_string (src->license);
930   dest->source = g_intern_string (src->source);
931   dest->package = g_intern_string (src->package);
932   dest->origin = g_intern_string (src->origin);
933   dest->release_datetime = g_intern_string (src->release_datetime);
934 }
935
936 /**
937  * gst_plugin_get_name:
938  * @plugin: plugin to get the name of
939  *
940  * Get the short name of the plugin
941  *
942  * Returns: the name of the plugin
943  */
944 const gchar *
945 gst_plugin_get_name (GstPlugin * plugin)
946 {
947   g_return_val_if_fail (plugin != NULL, NULL);
948
949   return plugin->desc.name;
950 }
951
952 /**
953  * gst_plugin_get_description:
954  * @plugin: plugin to get long name of
955  *
956  * Get the long descriptive name of the plugin
957  *
958  * Returns: the long name of the plugin
959  */
960 const gchar *
961 gst_plugin_get_description (GstPlugin * plugin)
962 {
963   g_return_val_if_fail (plugin != NULL, NULL);
964
965   return plugin->desc.description;
966 }
967
968 /**
969  * gst_plugin_get_filename:
970  * @plugin: plugin to get the filename of
971  *
972  * get the filename of the plugin
973  *
974  * Returns: the filename of the plugin
975  */
976 const gchar *
977 gst_plugin_get_filename (GstPlugin * plugin)
978 {
979   g_return_val_if_fail (plugin != NULL, NULL);
980
981   return plugin->filename;
982 }
983
984 /**
985  * gst_plugin_get_version:
986  * @plugin: plugin to get the version of
987  *
988  * get the version of the plugin
989  *
990  * Returns: the version of the plugin
991  */
992 const gchar *
993 gst_plugin_get_version (GstPlugin * plugin)
994 {
995   g_return_val_if_fail (plugin != NULL, NULL);
996
997   return plugin->desc.version;
998 }
999
1000 /**
1001  * gst_plugin_get_license:
1002  * @plugin: plugin to get the license of
1003  *
1004  * get the license of the plugin
1005  *
1006  * Returns: the license of the plugin
1007  */
1008 const gchar *
1009 gst_plugin_get_license (GstPlugin * plugin)
1010 {
1011   g_return_val_if_fail (plugin != NULL, NULL);
1012
1013   return plugin->desc.license;
1014 }
1015
1016 /**
1017  * gst_plugin_get_source:
1018  * @plugin: plugin to get the source of
1019  *
1020  * get the source module the plugin belongs to.
1021  *
1022  * Returns: the source of the plugin
1023  */
1024 const gchar *
1025 gst_plugin_get_source (GstPlugin * plugin)
1026 {
1027   g_return_val_if_fail (plugin != NULL, NULL);
1028
1029   return plugin->desc.source;
1030 }
1031
1032 /**
1033  * gst_plugin_get_package:
1034  * @plugin: plugin to get the package of
1035  *
1036  * get the package the plugin belongs to.
1037  *
1038  * Returns: the package of the plugin
1039  */
1040 const gchar *
1041 gst_plugin_get_package (GstPlugin * plugin)
1042 {
1043   g_return_val_if_fail (plugin != NULL, NULL);
1044
1045   return plugin->desc.package;
1046 }
1047
1048 /**
1049  * gst_plugin_get_origin:
1050  * @plugin: plugin to get the origin of
1051  *
1052  * get the URL where the plugin comes from
1053  *
1054  * Returns: the origin of the plugin
1055  */
1056 const gchar *
1057 gst_plugin_get_origin (GstPlugin * plugin)
1058 {
1059   g_return_val_if_fail (plugin != NULL, NULL);
1060
1061   return plugin->desc.origin;
1062 }
1063
1064 /**
1065  * gst_plugin_get_release_date_string:
1066  * @plugin: plugin to get the release date of
1067  *
1068  * Get the release date (and possibly time) in form of a string, if available.
1069  *
1070  * For normal GStreamer plugin releases this will usually just be a date in
1071  * the form of "YYYY-MM-DD", while pre-releases and builds from git may contain
1072  * a time component after the date as well, in which case the string will be
1073  * formatted like "YYYY-MM-DDTHH:MMZ" (e.g. "2012-04-30T09:30Z").
1074  *
1075  * There may be plugins that do not have a valid release date set on them.
1076  *
1077  * Returns: (nullable): the date string of the plugin, or %NULL if not
1078  * available.
1079  */
1080 const gchar *
1081 gst_plugin_get_release_date_string (GstPlugin * plugin)
1082 {
1083   g_return_val_if_fail (plugin != NULL, NULL);
1084
1085   return plugin->desc.release_datetime;
1086 }
1087
1088 /**
1089  * gst_plugin_is_loaded:
1090  * @plugin: plugin to query
1091  *
1092  * queries if the plugin is loaded into memory
1093  *
1094  * Returns: %TRUE is loaded, %FALSE otherwise
1095  */
1096 gboolean
1097 gst_plugin_is_loaded (GstPlugin * plugin)
1098 {
1099   g_return_val_if_fail (plugin != NULL, FALSE);
1100
1101   return (plugin->module != NULL || plugin->filename == NULL);
1102 }
1103
1104 /**
1105  * gst_plugin_get_cache_data:
1106  * @plugin: a plugin
1107  *
1108  * Gets the plugin specific data cache. If it is %NULL there is no cached data
1109  * stored. This is the case when the registry is getting rebuilt.
1110  *
1111  * Returns: (transfer none) (nullable): The cached data as a
1112  * #GstStructure or %NULL.
1113  */
1114 const GstStructure *
1115 gst_plugin_get_cache_data (GstPlugin * plugin)
1116 {
1117   g_return_val_if_fail (GST_IS_PLUGIN (plugin), NULL);
1118
1119   return plugin->priv->cache_data;
1120 }
1121
1122 /**
1123  * gst_plugin_set_cache_data:
1124  * @plugin: a plugin
1125  * @cache_data: (transfer full): a structure containing the data to cache
1126  *
1127  * Adds plugin specific data to cache. Passes the ownership of the structure to
1128  * the @plugin.
1129  *
1130  * The cache is flushed every time the registry is rebuilt.
1131  */
1132 void
1133 gst_plugin_set_cache_data (GstPlugin * plugin, GstStructure * cache_data)
1134 {
1135   g_return_if_fail (GST_IS_PLUGIN (plugin));
1136   g_return_if_fail (GST_IS_STRUCTURE (cache_data));
1137
1138   if (plugin->priv->cache_data) {
1139     gst_structure_free (plugin->priv->cache_data);
1140   }
1141   plugin->priv->cache_data = cache_data;
1142 }
1143
1144 #if 0
1145 /**
1146  * gst_plugin_feature_list:
1147  * @plugin: plugin to query
1148  * @filter: the filter to use
1149  * @first: only return first match
1150  * @user_data: user data passed to the filter function
1151  *
1152  * Runs a filter against all plugin features and returns a GList with
1153  * the results. If the first flag is set, only the first match is
1154  * returned (as a list with a single object).
1155  *
1156  * Returns: a GList of features, g_list_free after use.
1157  */
1158 GList *
1159 gst_plugin_feature_filter (GstPlugin * plugin,
1160     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1161 {
1162   GList *list;
1163   GList *g;
1164
1165   list = gst_filter_run (plugin->features, (GstFilterFunc) filter, first,
1166       user_data);
1167   for (g = list; g; g = g->next) {
1168     gst_object_ref (plugin);
1169   }
1170
1171   return list;
1172 }
1173
1174 typedef struct
1175 {
1176   GstPluginFeatureFilter filter;
1177   gboolean first;
1178   gpointer user_data;
1179   GList *result;
1180 }
1181 FeatureFilterData;
1182
1183 static gboolean
1184 _feature_filter (GstPlugin * plugin, gpointer user_data)
1185 {
1186   GList *result;
1187   FeatureFilterData *data = (FeatureFilterData *) user_data;
1188
1189   result = gst_plugin_feature_filter (plugin, data->filter, data->first,
1190       data->user_data);
1191   if (result) {
1192     data->result = g_list_concat (data->result, result);
1193     return TRUE;
1194   }
1195   return FALSE;
1196 }
1197
1198 /**
1199  * gst_plugin_list_feature_filter:
1200  * @list: a #GList of plugins to query
1201  * @filter: the filter function to use
1202  * @first: only return first match
1203  * @user_data: user data passed to the filter function
1204  *
1205  * Runs a filter against all plugin features of the plugins in the given
1206  * list and returns a GList with the results.
1207  * If the first flag is set, only the first match is
1208  * returned (as a list with a single object).
1209  *
1210  * Returns: a GList of features, g_list_free after use.
1211  */
1212 GList *
1213 gst_plugin_list_feature_filter (GList * list,
1214     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1215 {
1216   FeatureFilterData data;
1217   GList *result;
1218
1219   data.filter = filter;
1220   data.first = first;
1221   data.user_data = user_data;
1222   data.result = NULL;
1223
1224   result = gst_filter_run (list, (GstFilterFunc) _feature_filter, first, &data);
1225   g_list_free (result);
1226
1227   return data.result;
1228 }
1229
1230 /**
1231  * gst_plugin_find_feature:
1232  * @plugin: plugin to get the feature from
1233  * @name: The name of the feature to find
1234  * @type: The type of the feature to find
1235  *
1236  * Find a feature of the given name and type in the given plugin.
1237  *
1238  * Returns: a GstPluginFeature or %NULL if the feature was not found.
1239  */
1240 GstPluginFeature *
1241 gst_plugin_find_feature (GstPlugin * plugin, const gchar * name, GType type)
1242 {
1243   GList *walk;
1244   GstPluginFeature *result = NULL;
1245   GstTypeNameData data;
1246
1247   g_return_val_if_fail (name != NULL, NULL);
1248
1249   data.type = type;
1250   data.name = name;
1251
1252   walk = gst_filter_run (plugin->features,
1253       (GstFilterFunc) gst_plugin_feature_type_name_filter, TRUE, &data);
1254
1255   if (walk) {
1256     result = GST_PLUGIN_FEATURE (walk->data);
1257
1258     gst_object_ref (result);
1259     gst_plugin_feature_list_free (walk);
1260   }
1261
1262   return result;
1263 }
1264 #endif
1265
1266 #if 0
1267 static gboolean
1268 gst_plugin_feature_name_filter (GstPluginFeature * feature, const gchar * name)
1269 {
1270   return !strcmp (name, GST_PLUGIN_FEATURE_NAME (feature));
1271 }
1272 #endif
1273
1274 #if 0
1275 /**
1276  * gst_plugin_find_feature_by_name:
1277  * @plugin: plugin to get the feature from
1278  * @name: The name of the feature to find
1279  *
1280  * Find a feature of the given name in the given plugin.
1281  *
1282  * Returns: a GstPluginFeature or %NULL if the feature was not found.
1283  */
1284 GstPluginFeature *
1285 gst_plugin_find_feature_by_name (GstPlugin * plugin, const gchar * name)
1286 {
1287   GList *walk;
1288   GstPluginFeature *result = NULL;
1289
1290   g_return_val_if_fail (name != NULL, NULL);
1291
1292   walk = gst_filter_run (plugin->features,
1293       (GstFilterFunc) gst_plugin_feature_name_filter, TRUE, (void *) name);
1294
1295   if (walk) {
1296     result = GST_PLUGIN_FEATURE (walk->data);
1297
1298     gst_object_ref (result);
1299     gst_plugin_feature_list_free (walk);
1300   }
1301
1302   return result;
1303 }
1304 #endif
1305
1306 /**
1307  * gst_plugin_load_by_name:
1308  * @name: name of plugin to load
1309  *
1310  * Load the named plugin. Refs the plugin.
1311  *
1312  * Returns: (transfer full): a reference to a loaded plugin, or %NULL on error.
1313  */
1314 GstPlugin *
1315 gst_plugin_load_by_name (const gchar * name)
1316 {
1317   GstPlugin *plugin, *newplugin;
1318   GError *error = NULL;
1319
1320   GST_DEBUG ("looking up plugin %s in default registry", name);
1321   plugin = gst_registry_find_plugin (gst_registry_get (), name);
1322   if (plugin) {
1323     GST_DEBUG ("loading plugin %s from file %s", name, plugin->filename);
1324     newplugin = gst_plugin_load_file (plugin->filename, &error);
1325     gst_object_unref (plugin);
1326
1327     if (!newplugin) {
1328       GST_WARNING ("load_plugin error: %s", error->message);
1329       g_error_free (error);
1330       return NULL;
1331     }
1332     /* newplugin was reffed by load_file */
1333     return newplugin;
1334   }
1335
1336   GST_DEBUG ("Could not find plugin %s in registry", name);
1337   return NULL;
1338 }
1339
1340 /**
1341  * gst_plugin_load:
1342  * @plugin: (transfer none): plugin to load
1343  *
1344  * Loads @plugin. Note that the *return value* is the loaded plugin; @plugin is
1345  * untouched. The normal use pattern of this function goes like this:
1346  *
1347  * |[
1348  * GstPlugin *loaded_plugin;
1349  * loaded_plugin = gst_plugin_load (plugin);
1350  * // presumably, we're no longer interested in the potentially-unloaded plugin
1351  * gst_object_unref (plugin);
1352  * plugin = loaded_plugin;
1353  * ]|
1354  *
1355  * Returns: (transfer full): a reference to a loaded plugin, or %NULL on error.
1356  */
1357 GstPlugin *
1358 gst_plugin_load (GstPlugin * plugin)
1359 {
1360   GError *error = NULL;
1361   GstPlugin *newplugin;
1362
1363   if (gst_plugin_is_loaded (plugin)) {
1364     return plugin;
1365   }
1366
1367   if (!(newplugin = gst_plugin_load_file (plugin->filename, &error)))
1368     goto load_error;
1369
1370   return newplugin;
1371
1372 load_error:
1373   {
1374     GST_WARNING ("load_plugin error: %s", error->message);
1375     g_error_free (error);
1376     return NULL;
1377   }
1378 }
1379
1380 /**
1381  * gst_plugin_list_free:
1382  * @list: (transfer full) (element-type Gst.Plugin): list of #GstPlugin
1383  *
1384  * Unrefs each member of @list, then frees the list.
1385  */
1386 void
1387 gst_plugin_list_free (GList * list)
1388 {
1389   GList *g;
1390
1391   for (g = list; g; g = g->next) {
1392     gst_object_unref (GST_PLUGIN_CAST (g->data));
1393   }
1394   g_list_free (list);
1395 }
1396
1397 /* ===== plugin dependencies ===== */
1398
1399 /* Scenarios:
1400  * ENV + xyz     where ENV can contain multiple values separated by SEPARATOR
1401  *               xyz may be "" (if ENV contains path to file rather than dir)
1402  * ENV + *xyz   same as above, but xyz acts as suffix filter
1403  * ENV + xyz*   same as above, but xyz acts as prefix filter (is this needed?)
1404  * ENV + *xyz*  same as above, but xyz acts as strstr filter (is this needed?)
1405  * 
1406  * same as above, with additional paths hard-coded at compile-time:
1407  *   - only check paths + ... if ENV is not set or yields not paths
1408  *   - always check paths + ... in addition to ENV
1409  *
1410  * When user specifies set of environment variables, he/she may also use e.g.
1411  * "HOME/.mystuff/plugins", and we'll expand the content of $HOME with the
1412  * remainder 
1413  */
1414
1415 /* we store in registry:
1416  *  sets of:
1417  *   { 
1418  *     - environment variables (array of strings)
1419  *     - last hash of env variable contents (uint) (so we can avoid doing stats
1420  *       if one of the env vars has changed; premature optimisation galore)
1421  *     - hard-coded paths (array of strings)
1422  *     - xyz filename/suffix/prefix strings (array of strings)
1423  *     - flags (int)
1424  *     - last hash of file/dir stats (int)
1425  *   }
1426  *   (= struct GstPluginDep)
1427  */
1428
1429 static guint
1430 gst_plugin_ext_dep_get_env_vars_hash (GstPlugin * plugin, GstPluginDep * dep)
1431 {
1432   gchar **e;
1433   guint hash;
1434
1435   /* there's no deeper logic to what we do here; all we want to know (when
1436    * checking if the plugin needs to be rescanned) is whether the content of
1437    * one of the environment variables in the list is different from when it
1438    * was last scanned */
1439   hash = 0;
1440   for (e = dep->env_vars; e != NULL && *e != NULL; ++e) {
1441     const gchar *val;
1442     gchar env_var[256];
1443
1444     /* order matters: "val",NULL needs to yield a different hash than
1445      * NULL,"val", so do a shift here whether the var is set or not */
1446     hash = hash << 5;
1447
1448     /* want environment variable at beginning of string */
1449     if (!g_ascii_isalnum (**e)) {
1450       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1451           "variable string: %s", *e);
1452       continue;
1453     }
1454
1455     /* user is allowed to specify e.g. "HOME/.pitivi/plugins" */
1456     g_strlcpy (env_var, *e, sizeof (env_var));
1457     g_strdelimit (env_var, "/\\", '\0');
1458
1459     if ((val = g_getenv (env_var)))
1460       hash += g_str_hash (val);
1461   }
1462
1463   return hash;
1464 }
1465
1466 gboolean
1467 _priv_plugin_deps_env_vars_changed (GstPlugin * plugin)
1468 {
1469   GList *l;
1470
1471   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1472     GstPluginDep *dep = l->data;
1473
1474     if (dep->env_hash != gst_plugin_ext_dep_get_env_vars_hash (plugin, dep))
1475       return TRUE;
1476   }
1477
1478   return FALSE;
1479 }
1480
1481 static void
1482 gst_plugin_ext_dep_extract_env_vars_paths (GstPlugin * plugin,
1483     GstPluginDep * dep, GQueue * paths)
1484 {
1485   gchar **evars;
1486
1487   for (evars = dep->env_vars; evars != NULL && *evars != NULL; ++evars) {
1488     const gchar *e;
1489     gchar **components;
1490
1491     /* want environment variable at beginning of string */
1492     if (!g_ascii_isalnum (**evars)) {
1493       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1494           "variable string: %s", *evars);
1495       continue;
1496     }
1497
1498     /* user is allowed to specify e.g. "HOME/.pitivi/plugins", which we want to
1499      * split into the env_var name component and the path component */
1500     components = g_strsplit_set (*evars, "/\\", 2);
1501     g_assert (components != NULL);
1502
1503     e = g_getenv (components[0]);
1504     GST_LOG_OBJECT (plugin, "expanding %s = '%s' (path suffix: %s)",
1505         components[0], GST_STR_NULL (e), GST_STR_NULL (components[1]));
1506
1507     if (components[1] != NULL) {
1508       g_strdelimit (components[1], "/\\", G_DIR_SEPARATOR);
1509     }
1510
1511     if (e != NULL && *e != '\0') {
1512       gchar **arr;
1513       guint i;
1514
1515       arr = g_strsplit (e, G_SEARCHPATH_SEPARATOR_S, -1);
1516
1517       for (i = 0; arr != NULL && arr[i] != NULL; ++i) {
1518         gchar *full_path;
1519
1520         if (!g_path_is_absolute (arr[i])) {
1521           GST_INFO_OBJECT (plugin, "ignoring environment variable content '%s'"
1522               ": either not an absolute path or not a path at all", arr[i]);
1523           continue;
1524         }
1525
1526         if (components[1] != NULL) {
1527           full_path = g_build_filename (arr[i], components[1], NULL);
1528         } else {
1529           full_path = g_strdup (arr[i]);
1530         }
1531
1532         if (!g_queue_find_custom (paths, full_path, (GCompareFunc) strcmp)) {
1533           GST_LOG_OBJECT (plugin, "path: '%s'", full_path);
1534           g_queue_push_tail (paths, full_path);
1535           full_path = NULL;
1536         } else {
1537           GST_LOG_OBJECT (plugin, "path: '%s' (duplicate,ignoring)", full_path);
1538           g_free (full_path);
1539         }
1540       }
1541
1542       g_strfreev (arr);
1543     }
1544
1545     g_strfreev (components);
1546   }
1547
1548   GST_LOG_OBJECT (plugin, "Extracted %d paths from environment", paths->length);
1549 }
1550
1551 static guint
1552 gst_plugin_ext_dep_get_hash_from_stat_entry (GStatBuf * s)
1553 {
1554 #ifdef S_IFBLK
1555   if (!(s->st_mode & (S_IFDIR | S_IFREG | S_IFBLK | S_IFCHR)))
1556 #else
1557   /* MSVC does not have S_IFBLK */
1558   if (!(s->st_mode & (S_IFDIR | S_IFREG | S_IFCHR)))
1559 #endif
1560     return (guint) - 1;
1561
1562   /* completely random formula */
1563   return ((s->st_size << 3) + (s->st_mtime << 5)) ^ s->st_ctime;
1564 }
1565
1566 static gboolean
1567 gst_plugin_ext_dep_direntry_matches (GstPlugin * plugin, const gchar * entry,
1568     const gchar ** filenames, GstPluginDependencyFlags flags)
1569 {
1570   /* no filenames specified, match all entries for now (could probably
1571    * optimise by just taking the dir stat hash or so) */
1572   if (filenames == NULL || *filenames == NULL || **filenames == '\0')
1573     return TRUE;
1574
1575   while (*filenames != NULL) {
1576     /* suffix match? */
1577     if (((flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX)) &&
1578         g_str_has_suffix (entry, *filenames)) {
1579       return TRUE;
1580     } else if (((flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_PREFIX)) &&
1581         g_str_has_prefix (entry, *filenames)) {
1582       return TRUE;
1583       /* else it's an exact match that's needed */
1584     } else if (strcmp (entry, *filenames) == 0) {
1585       return TRUE;
1586     }
1587     GST_LOG ("%s does not match %s, flags=0x%04x", entry, *filenames, flags);
1588     ++filenames;
1589   }
1590   return FALSE;
1591 }
1592
1593 static guint
1594 gst_plugin_ext_dep_scan_dir_and_match_names (GstPlugin * plugin,
1595     const gchar * path, const gchar ** filenames,
1596     GstPluginDependencyFlags flags, int depth)
1597 {
1598   const gchar *entry;
1599   gboolean recurse_dirs;
1600   GError *err = NULL;
1601   GDir *dir;
1602   guint hash = 0;
1603
1604   recurse_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1605
1606   dir = g_dir_open (path, 0, &err);
1607   if (dir == NULL) {
1608     GST_DEBUG_OBJECT (plugin, "g_dir_open(%s) failed: %s", path, err->message);
1609     g_error_free (err);
1610     return (guint) - 1;
1611   }
1612
1613   /* FIXME: we're assuming here that we always get the directory entries in
1614    * the same order, and not in a random order */
1615   while ((entry = g_dir_read_name (dir))) {
1616     gboolean have_match;
1617     GStatBuf s;
1618     gchar *full_path;
1619     guint fhash;
1620
1621     have_match =
1622         gst_plugin_ext_dep_direntry_matches (plugin, entry, filenames, flags);
1623
1624     /* avoid the stat if possible */
1625     if (!have_match && !recurse_dirs)
1626       continue;
1627
1628     full_path = g_build_filename (path, entry, NULL);
1629     if (g_stat (full_path, &s) < 0) {
1630       fhash = (guint) - 1;
1631       GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1632           g_strerror (errno));
1633     } else if (have_match) {
1634       fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1635       GST_LOG_OBJECT (plugin, "stat: %s (result: %u)", full_path, fhash);
1636     } else if ((s.st_mode & (S_IFDIR))) {
1637       fhash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, full_path,
1638           filenames, flags, depth + 1);
1639     } else {
1640       /* it's not a name match, we want to recurse, but it's not a directory */
1641       g_free (full_path);
1642       continue;
1643     }
1644
1645     hash = hash + fhash;
1646     g_free (full_path);
1647   }
1648
1649   g_dir_close (dir);
1650   return hash;
1651 }
1652
1653 static guint
1654 gst_plugin_ext_dep_scan_path_with_filenames (GstPlugin * plugin,
1655     const gchar * path, const gchar ** filenames,
1656     GstPluginDependencyFlags flags)
1657 {
1658   const gchar *empty_filenames[] = { "", NULL };
1659   gboolean recurse_into_dirs, partial_names = FALSE;
1660   guint i, hash = 0;
1661
1662   /* to avoid special-casing below (FIXME?) */
1663   if (filenames == NULL || *filenames == NULL)
1664     filenames = empty_filenames;
1665
1666   recurse_into_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1667
1668   if ((flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX) ||
1669       (flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_PREFIX))
1670     partial_names = TRUE;
1671
1672   /* if we can construct the exact paths to check with the data we have, just
1673    * stat them one by one; this is more efficient than opening the directory
1674    * and going through each entry to see if it matches one of our filenames. */
1675   if (!recurse_into_dirs && !partial_names) {
1676     for (i = 0; filenames[i] != NULL; ++i) {
1677       GStatBuf s;
1678       gchar *full_path;
1679       guint fhash;
1680
1681       full_path = g_build_filename (path, filenames[i], NULL);
1682       if (g_stat (full_path, &s) < 0) {
1683         fhash = (guint) - 1;
1684         GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1685             g_strerror (errno));
1686       } else {
1687         fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1688         GST_LOG_OBJECT (plugin, "stat: %s (result: %08x)", full_path, fhash);
1689       }
1690       hash += fhash;
1691       g_free (full_path);
1692     }
1693   } else {
1694     hash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, path,
1695         filenames, flags, 0);
1696   }
1697
1698   return hash;
1699 }
1700
1701 static guint
1702 gst_plugin_ext_dep_get_stat_hash (GstPlugin * plugin, GstPluginDep * dep)
1703 {
1704   gboolean paths_are_default_only;
1705   gboolean paths_are_relative_to_exe;
1706   GQueue scan_paths = G_QUEUE_INIT;
1707   guint scan_hash = 0;
1708   gchar *path;
1709
1710   GST_LOG_OBJECT (plugin, "start");
1711
1712   paths_are_default_only =
1713       dep->flags & GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_DEFAULT_ONLY;
1714   paths_are_relative_to_exe =
1715       dep->flags & GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_RELATIVE_TO_EXE;
1716
1717   gst_plugin_ext_dep_extract_env_vars_paths (plugin, dep, &scan_paths);
1718
1719   if (g_queue_is_empty (&scan_paths) || !paths_are_default_only) {
1720     gchar **paths;
1721
1722     for (paths = dep->paths; paths != NULL && *paths != NULL; ++paths) {
1723       const gchar *path = *paths;
1724       gchar *full_path;
1725
1726       if (paths_are_relative_to_exe && !g_path_is_absolute (path)) {
1727         if (!_gst_executable_path) {
1728           GST_FIXME_OBJECT (plugin,
1729               "Path dependency %s relative to executable path but could not retrieve executable path",
1730               path);
1731           continue;
1732         }
1733         full_path = g_build_filename (_gst_executable_path, path, NULL);
1734       } else {
1735         full_path = g_strdup (path);
1736       }
1737
1738       if (!g_queue_find_custom (&scan_paths, full_path, (GCompareFunc) strcmp)) {
1739         GST_LOG_OBJECT (plugin, "path: '%s'", full_path);
1740         g_queue_push_tail (&scan_paths, full_path);
1741       } else {
1742         GST_LOG_OBJECT (plugin, "path: '%s' (duplicate, ignoring)", full_path);
1743         g_free (full_path);
1744       }
1745     }
1746   }
1747
1748   while ((path = g_queue_pop_head (&scan_paths))) {
1749     scan_hash += gst_plugin_ext_dep_scan_path_with_filenames (plugin, path,
1750         (const gchar **) dep->names, dep->flags);
1751     g_free (path);
1752   }
1753
1754   GST_LOG_OBJECT (plugin, "done, scan_hash: %08x", scan_hash);
1755   return scan_hash;
1756 }
1757
1758 gboolean
1759 _priv_plugin_deps_files_changed (GstPlugin * plugin)
1760 {
1761   GList *l;
1762
1763   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1764     GstPluginDep *dep = l->data;
1765
1766     if (dep->stat_hash != gst_plugin_ext_dep_get_stat_hash (plugin, dep))
1767       return TRUE;
1768   }
1769
1770   return FALSE;
1771 }
1772
1773 static void
1774 gst_plugin_ext_dep_free (GstPluginDep * dep)
1775 {
1776   g_strfreev (dep->env_vars);
1777   g_strfreev (dep->paths);
1778   g_strfreev (dep->names);
1779   g_slice_free (GstPluginDep, dep);
1780 }
1781
1782 static gboolean
1783 gst_plugin_ext_dep_strv_equal (gchar ** arr1, gchar ** arr2)
1784 {
1785   if (arr1 == arr2)
1786     return TRUE;
1787   if (arr1 == NULL || arr2 == NULL)
1788     return FALSE;
1789   for (; *arr1 != NULL && *arr2 != NULL; ++arr1, ++arr2) {
1790     if (strcmp (*arr1, *arr2) != 0)
1791       return FALSE;
1792   }
1793   return (*arr1 == *arr2);
1794 }
1795
1796 static gboolean
1797 gst_plugin_ext_dep_equals (GstPluginDep * dep, const gchar ** env_vars,
1798     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1799 {
1800   if (dep->flags != flags)
1801     return FALSE;
1802
1803   return gst_plugin_ext_dep_strv_equal (dep->env_vars, (gchar **) env_vars) &&
1804       gst_plugin_ext_dep_strv_equal (dep->paths, (gchar **) paths) &&
1805       gst_plugin_ext_dep_strv_equal (dep->names, (gchar **) names);
1806 }
1807
1808 /**
1809  * gst_plugin_add_dependency:
1810  * @plugin: a #GstPlugin
1811  * @env_vars: (allow-none): %NULL-terminated array of environment variables affecting the
1812  *     feature set of the plugin (e.g. an environment variable containing
1813  *     paths where to look for additional modules/plugins of a library),
1814  *     or %NULL. Environment variable names may be followed by a path component
1815  *      which will be added to the content of the environment variable, e.g.
1816  *      "HOME/.mystuff/plugins".
1817  * @paths: (allow-none): %NULL-terminated array of directories/paths where dependent files
1818  *     may be, or %NULL.
1819  * @names: (allow-none): %NULL-terminated array of file names (or file name suffixes,
1820  *     depending on @flags) to be used in combination with the paths from
1821  *     @paths and/or the paths extracted from the environment variables in
1822  *     @env_vars, or %NULL.
1823  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1824  *
1825  * Make GStreamer aware of external dependencies which affect the feature
1826  * set of this plugin (ie. the elements or typefinders associated with it).
1827  *
1828  * GStreamer will re-inspect plugins with external dependencies whenever any
1829  * of the external dependencies change. This is useful for plugins which wrap
1830  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1831  * library and makes visualisations available as GStreamer elements, or a
1832  * codec loader which exposes elements and/or caps dependent on what external
1833  * codec libraries are currently installed.
1834  */
1835 void
1836 gst_plugin_add_dependency (GstPlugin * plugin, const gchar ** env_vars,
1837     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1838 {
1839   GstPluginDep *dep;
1840   GList *l;
1841
1842   g_return_if_fail (GST_IS_PLUGIN (plugin));
1843
1844   if ((env_vars == NULL || env_vars[0] == NULL) &&
1845       (paths == NULL || paths[0] == NULL)) {
1846     GST_DEBUG_OBJECT (plugin,
1847         "plugin registered empty dependency set. Ignoring");
1848     return;
1849   }
1850
1851   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1852     if (gst_plugin_ext_dep_equals (l->data, env_vars, paths, names, flags)) {
1853       GST_LOG_OBJECT (plugin, "dependency already registered");
1854       return;
1855     }
1856   }
1857
1858   dep = g_slice_new (GstPluginDep);
1859
1860   dep->env_vars = g_strdupv ((gchar **) env_vars);
1861   dep->paths = g_strdupv ((gchar **) paths);
1862   dep->names = g_strdupv ((gchar **) names);
1863   dep->flags = flags;
1864
1865   dep->env_hash = gst_plugin_ext_dep_get_env_vars_hash (plugin, dep);
1866   dep->stat_hash = gst_plugin_ext_dep_get_stat_hash (plugin, dep);
1867
1868   plugin->priv->deps = g_list_append (plugin->priv->deps, dep);
1869
1870   GST_DEBUG_OBJECT (plugin, "added dependency:");
1871   for (; env_vars != NULL && *env_vars != NULL; ++env_vars)
1872     GST_DEBUG_OBJECT (plugin, " evar: %s", *env_vars);
1873   for (; paths != NULL && *paths != NULL; ++paths)
1874     GST_DEBUG_OBJECT (plugin, " path: %s", *paths);
1875   for (; names != NULL && *names != NULL; ++names)
1876     GST_DEBUG_OBJECT (plugin, " name: %s", *names);
1877 }
1878
1879 /**
1880  * gst_plugin_add_dependency_simple:
1881  * @plugin: the #GstPlugin
1882  * @env_vars: (allow-none): one or more environment variables (separated by ':', ';' or ','),
1883  *      or %NULL. Environment variable names may be followed by a path component
1884  *      which will be added to the content of the environment variable, e.g.
1885  *      "HOME/.mystuff/plugins:MYSTUFF_PLUGINS_PATH"
1886  * @paths: (allow-none): one ore more directory paths (separated by ':' or ';' or ','),
1887  *      or %NULL. Example: "/usr/lib/mystuff/plugins"
1888  * @names: (allow-none): one or more file names or file name suffixes (separated by commas),
1889  *      or %NULL
1890  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1891  *
1892  * Make GStreamer aware of external dependencies which affect the feature
1893  * set of this plugin (ie. the elements or typefinders associated with it).
1894  *
1895  * GStreamer will re-inspect plugins with external dependencies whenever any
1896  * of the external dependencies change. This is useful for plugins which wrap
1897  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1898  * library and makes visualisations available as GStreamer elements, or a
1899  * codec loader which exposes elements and/or caps dependent on what external
1900  * codec libraries are currently installed.
1901  *
1902  * Convenience wrapper function for gst_plugin_add_dependency() which
1903  * takes simple strings as arguments instead of string arrays, with multiple
1904  * arguments separated by predefined delimiters (see above).
1905  */
1906 void
1907 gst_plugin_add_dependency_simple (GstPlugin * plugin,
1908     const gchar * env_vars, const gchar * paths, const gchar * names,
1909     GstPluginDependencyFlags flags)
1910 {
1911   gchar **a_evars = NULL;
1912   gchar **a_paths = NULL;
1913   gchar **a_names = NULL;
1914
1915   if (env_vars)
1916     a_evars = g_strsplit_set (env_vars, ":;,", -1);
1917   if (paths)
1918     a_paths = g_strsplit_set (paths, ":;,", -1);
1919   if (names)
1920     a_names = g_strsplit_set (names, ",", -1);
1921
1922   gst_plugin_add_dependency (plugin, (const gchar **) a_evars,
1923       (const gchar **) a_paths, (const gchar **) a_names, flags);
1924
1925   if (a_evars)
1926     g_strfreev (a_evars);
1927   if (a_paths)
1928     g_strfreev (a_paths);
1929   if (a_names)
1930     g_strfreev (a_names);
1931 }