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