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