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