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