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