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