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