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