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