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