gst/gst.c: init_pre() and init_post() might be called via our GOptionGroup or from...
[platform/upstream/gstreamer.git] / gst / gst.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *
5  * gst.c: Initialization and non-pipeline operations
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gst
25  * @short_description: Media library supporting arbitrary formats and filter
26  *                     graphs.
27  * @see_also: Check out both <ulink url="http://www.cse.ogi.edu/sysl/">OGI's
28  *            pipeline</ulink> and Microsoft's DirectShow for some background.
29  *
30  * GStreamer is a framework for constructing graphs of various filters
31  * (termed elements here) that will handle streaming media.  Any discreet
32  * (packetizable) media type is supported, with provisions for automatically
33  * determining source type.  Formatting/framing information is provided with
34  * a powerful negotiation framework.  Plugins are heavily used to provide for
35  * all elements, allowing one to construct plugins outside of the GST
36  * library, even released binary-only if license require (please don't).
37  *
38  * GStreamer borrows heavily from both the <ulink
39  * url="http://www.cse.ogi.edu/sysl/">OGI media pipeline</ulink> and
40  * Microsoft's DirectShow, hopefully taking the best of both and leaving the
41  * cruft behind. Its interface is slowly getting stable.
42  *
43  * The <application>GStreamer</application> library should be initialized with
44  * gst_init() before it can be used. You should pass pointers to the main argc
45  * and argv variables so that GStreamer can process its own command line
46  * options, as shown in the following example.
47  *
48  * <example>
49  * <title>Initializing the gstreamer library</title>
50  * <programlisting language="c">
51  * int
52  * main (int argc, char *argv[])
53  * {
54  *   // initialize the GStreamer library
55  *   gst_init (&amp;argc, &amp;argv);
56  *   ...
57  * }
58  * </programlisting>
59  * </example>
60  *
61  * It's allowed to pass two NULL pointers to gst_init() in case you don't want
62  * to pass the command line args to GStreamer.
63  *
64  * You can also use GOption to initialize your own parameters as shown in
65  * the next code fragment:
66  * <example>
67  * <title>Initializing own parameters when initializing gstreamer</title>
68  * <programlisting>
69  * static gboolean stats = FALSE;
70  * ...
71  * int
72  * main (int argc, char *argv[])
73  * {
74  *  GOptionEntry options[] = {
75  *   {"tags", 't', 0, G_OPTION_ARG_NONE, &amp;tags,
76  *       N_("Output tags (also known as metadata)"), NULL},
77  *   {NULL}
78  *  };
79  *  ctx = g_option_context_new ("gst-launch");
80  *  g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
81  *  g_option_context_add_group (ctx, gst_init_get_option_group ());
82  *  if (!g_option_context_parse (ctx, &amp;argc, &amp;argv, &amp;err)) {
83  *    g_print ("Error initializing: &percnt;s\n", GST_STR_NULL (err->message));
84  *    exit (1);
85  *  }
86  *  g_option_context_free (ctx);
87  * ...
88  * }
89  * </programlisting>
90  * </example>
91  *
92  * Use gst_version() to query the library version at runtime or use the
93  * GST_VERSION_* macros to find the version at compile time. Optionally
94  * gst_version_string() returns a printable string.
95  *
96  * The gst_deinit() call is used to clean up all internal resources used
97  * by <application>GStreamer</application>. It is mostly used in unit tests 
98  * to check for leaks.
99  *
100  * Last reviewed on 2006-08-11 (0.10.10)
101  */
102
103 #include "gst_private.h"
104 #include <stdlib.h>
105 #include <stdio.h>
106 #include <sys/types.h>
107 #ifdef HAVE_FORK
108 #include <sys/wait.h>
109 #endif /* HAVE_FORK */
110 #ifdef HAVE_SYS_UTSNAME_H
111 #include <sys/utsname.h>
112 #endif
113 #ifdef HAVE_UNISTD_H
114 #include <unistd.h>
115 #endif
116
117 #include "gst-i18n-lib.h"
118 #include <locale.h>             /* for LC_ALL */
119
120 #include "gst.h"
121
122 #define GST_CAT_DEFAULT GST_CAT_GST_INIT
123
124 #define MAX_PATH_SPLIT  16
125 #define GST_PLUGIN_SEPARATOR ","
126
127 static gboolean gst_initialized = FALSE;
128
129 #ifndef GST_DISABLE_REGISTRY
130 static GList *plugin_paths = NULL;      /* for delayed processing in post_init */
131 #endif
132
133 extern gint _gst_trace_on;
134
135 /* defaults */
136 #ifdef HAVE_FORK
137 #define DEFAULT_FORK TRUE
138 #else
139 #define DEFAULT_FORK FALSE
140 #endif /* HAVE_FORK */
141
142 /* set to TRUE when segfaults need to be left as is, FIXME, this variable is
143  * global. */
144 gboolean _gst_disable_segtrap = FALSE;
145
146 /* control the behaviour of registry rebuild */
147 static gboolean _gst_enable_registry_fork = DEFAULT_FORK;
148
149 static void load_plugin_func (gpointer data, gpointer user_data);
150 static gboolean init_pre (GOptionContext * context, GOptionGroup * group,
151     gpointer data, GError ** error);
152 static gboolean init_post (GOptionContext * context, GOptionGroup * group,
153     gpointer data, GError ** error);
154 static gboolean parse_goption_arg (const gchar * s_opt,
155     const gchar * arg, gpointer data, GError ** err);
156
157 static GSList *preload_plugins = NULL;
158
159 const gchar g_log_domain_gstreamer[] = "GStreamer";
160
161 static void
162 debug_log_handler (const gchar * log_domain,
163     GLogLevelFlags log_level, const gchar * message, gpointer user_data)
164 {
165   g_log_default_handler (log_domain, log_level, message, user_data);
166   /* FIXME: do we still need this ? fatal errors these days are all
167    * other than core errors */
168   /* g_on_error_query (NULL); */
169 }
170
171 enum
172 {
173   ARG_VERSION = 1,
174   ARG_FATAL_WARNINGS,
175 #ifndef GST_DISABLE_GST_DEBUG
176   ARG_DEBUG_LEVEL,
177   ARG_DEBUG,
178   ARG_DEBUG_DISABLE,
179   ARG_DEBUG_NO_COLOR,
180   ARG_DEBUG_HELP,
181 #endif
182   ARG_PLUGIN_SPEW,
183   ARG_PLUGIN_PATH,
184   ARG_PLUGIN_LOAD,
185   ARG_SEGTRAP_DISABLE,
186   ARG_REGISTRY_FORK_DISABLE
187 };
188
189 /* debug-spec ::= category-spec [, category-spec]*
190  * category-spec ::= category:val | val
191  * category ::= [^:]+
192  * val ::= [0-5]
193  */
194
195 #ifndef NUL
196 #define NUL '\0'
197 #endif
198
199 #ifndef GST_DISABLE_GST_DEBUG
200 static gboolean
201 parse_debug_category (gchar * str, const gchar ** category)
202 {
203   if (!str)
204     return FALSE;
205
206   /* works in place */
207   g_strstrip (str);
208
209   if (str[0] != NUL) {
210     *category = str;
211     return TRUE;
212   }
213
214   return FALSE;
215 }
216
217 static gboolean
218 parse_debug_level (gchar * str, gint * level)
219 {
220   if (!str)
221     return FALSE;
222
223   /* works in place */
224   g_strstrip (str);
225
226   if (str[0] != NUL && str[1] == NUL
227       && str[0] >= '0' && str[0] < '0' + GST_LEVEL_COUNT) {
228     *level = str[0] - '0';
229     return TRUE;
230   }
231
232   return FALSE;
233 }
234
235 static void
236 parse_debug_list (const gchar * list)
237 {
238   gchar **split;
239   gchar **walk;
240
241   g_return_if_fail (list != NULL);
242
243   split = g_strsplit (list, ",", 0);
244
245   for (walk = split; *walk; walk++) {
246     if (strchr (*walk, ':')) {
247       gchar **values = g_strsplit (*walk, ":", 2);
248
249       if (values[0] && values[1]) {
250         gint level;
251         const gchar *category;
252
253         if (parse_debug_category (values[0], &category)
254             && parse_debug_level (values[1], &level))
255           gst_debug_set_threshold_for_name (category, level);
256       }
257
258       g_strfreev (values);
259     } else {
260       gint level;
261
262       if (parse_debug_level (*walk, &level))
263         gst_debug_set_default_threshold (level);
264     }
265   }
266
267   g_strfreev (split);
268 }
269 #endif
270
271 /**
272  * gst_init_get_option_group:
273  *
274  * Returns a #GOptionGroup with GStreamer's argument specifications. The
275  * group is set up to use standard GOption callbacks, so when using this
276  * group in combination with GOption parsing methods, all argument parsing
277  * and initialization is automated.
278  *
279  * This function is useful if you want to integrate GStreamer with other
280  * libraries that use GOption (see g_option_context_add_group() ).
281  *
282  * Returns: a pointer to GStreamer's option group. Should be dereferenced
283  * after use.
284  */
285
286 GOptionGroup *
287 gst_init_get_option_group (void)
288 {
289   GOptionGroup *group;
290   const static GOptionEntry gst_args[] = {
291     {"gst-version", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
292         (gpointer) parse_goption_arg, N_("Print the GStreamer version"), NULL},
293     {"gst-fatal-warnings", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
294         (gpointer) parse_goption_arg, N_("Make all warnings fatal"), NULL},
295 #ifndef GST_DISABLE_GST_DEBUG
296     {"gst-debug-help", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
297           (gpointer) parse_goption_arg,
298           N_("Print available debug categories and exit"),
299         NULL},
300     {"gst-debug-level", 0, 0, G_OPTION_ARG_CALLBACK,
301           (gpointer) parse_goption_arg,
302           N_("Default debug level from 1 (only error) to 5 (anything) or "
303               "0 for no output"),
304         N_("LEVEL")},
305     {"gst-debug", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) parse_goption_arg,
306           N_("Comma-separated list of category_name:level pairs to set "
307               "specific levels for the individual categories. Example: "
308               "GST_AUTOPLUG:5,GST_ELEMENT_*:3"),
309         N_("LIST")},
310     {"gst-debug-no-color", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
311           (gpointer) parse_goption_arg, N_("Disable colored debugging output"),
312         NULL},
313     {"gst-debug-disable", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
314         (gpointer) parse_goption_arg, N_("Disable debugging"), NULL},
315 #endif
316     {"gst-plugin-spew", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
317           (gpointer) parse_goption_arg,
318           N_("Enable verbose plugin loading diagnostics"),
319         NULL},
320     {"gst-plugin-path", 0, 0, G_OPTION_ARG_CALLBACK,
321           (gpointer) parse_goption_arg,
322         N_("Colon-separated paths containing plugins"), N_("PATHS")},
323     {"gst-plugin-load", 0, 0, G_OPTION_ARG_CALLBACK,
324           (gpointer) parse_goption_arg,
325           N_("Comma-separated list of plugins to preload in addition to the "
326               "list stored in environment variable GST_PLUGIN_PATH"),
327         N_("PLUGINS")},
328     {"gst-disable-segtrap", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
329           (gpointer) parse_goption_arg,
330           N_("Disable trapping of segmentation faults during plugin loading"),
331         NULL},
332     {"gst-disable-registry-fork", 0, G_OPTION_FLAG_NO_ARG,
333           G_OPTION_ARG_CALLBACK,
334           (gpointer) parse_goption_arg,
335           N_("Disable the use of fork() while scanning the registry"),
336         NULL},
337     {NULL}
338   };
339
340   group = g_option_group_new ("gst", _("GStreamer Options"),
341       _("Show GStreamer Options"), NULL, NULL);
342   g_option_group_set_parse_hooks (group, (GOptionParseFunc) init_pre,
343       (GOptionParseFunc) init_post);
344
345   g_option_group_add_entries (group, gst_args);
346   g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
347
348   return group;
349 }
350
351 /**
352  * gst_init_check:
353  * @argc: pointer to application's argc
354  * @argv: pointer to application's argv
355  * @err: pointer to a #GError to which a message will be posted on error
356  *
357  * Initializes the GStreamer library, setting up internal path lists,
358  * registering built-in elements, and loading standard plugins.
359  *
360  * This function will return %FALSE if GStreamer could not be initialized
361  * for some reason.  If you want your program to fail fatally,
362  * use gst_init() instead.
363  *
364  * Returns: %TRUE if GStreamer could be initialized.
365  */
366 gboolean
367 gst_init_check (int *argc, char **argv[], GError ** err)
368 {
369   GOptionGroup *group;
370   GOptionContext *ctx;
371   gboolean res;
372
373   GST_INFO ("initializing GStreamer");
374
375   if (gst_initialized) {
376     GST_DEBUG ("already initialized gst");
377     return TRUE;
378   }
379
380   ctx = g_option_context_new ("- GStreamer initialization");
381   g_option_context_set_ignore_unknown_options (ctx, TRUE);
382   group = gst_init_get_option_group ();
383   g_option_context_add_group (ctx, group);
384   res = g_option_context_parse (ctx, argc, argv, err);
385   g_option_context_free (ctx);
386
387   gst_initialized = res;
388
389   if (res) {
390     GST_INFO ("initialized GStreamer successfully");
391   } else {
392     GST_INFO ("failed to initialize GStreamer");
393   }
394
395   return res;
396 }
397
398 /**
399  * gst_init:
400  * @argc: pointer to application's argc
401  * @argv: pointer to application's argv
402  *
403  * Initializes the GStreamer library, setting up internal path lists,
404  * registering built-in elements, and loading standard plugins.
405  *
406  * <note><para>
407  * This function will terminate your program if it was unable to initialize
408  * GStreamer for some reason.  If you want your program to fall back,
409  * use gst_init_check() instead.
410  * </para></note>
411  *
412  * WARNING: This function does not work in the same way as corresponding
413  * functions in other glib-style libraries, such as gtk_init().  In
414  * particular, unknown command line options cause this function to
415  * abort program execution.
416  */
417 void
418 gst_init (int *argc, char **argv[])
419 {
420   GError *err = NULL;
421
422   if (!gst_init_check (argc, argv, &err)) {
423     g_print ("Could not initialize GStreamer: %s\n",
424         err ? err->message : "unknown error occurred");
425     if (err) {
426       g_error_free (err);
427     }
428     exit (1);
429   }
430 }
431
432 #ifndef GST_DISABLE_REGISTRY
433 static void
434 add_path_func (gpointer data, gpointer user_data)
435 {
436   GST_INFO ("Adding plugin path: \"%s\", will scan later", (gchar *) data);
437   plugin_paths = g_list_append (plugin_paths, g_strdup (data));
438 }
439 #endif
440
441 static void
442 prepare_for_load_plugin_func (gpointer data, gpointer user_data)
443 {
444   preload_plugins = g_slist_prepend (preload_plugins, g_strdup (data));
445 }
446
447 static void
448 load_plugin_func (gpointer data, gpointer user_data)
449 {
450   GstPlugin *plugin;
451   const gchar *filename;
452   GError *err = NULL;
453
454   filename = (const gchar *) data;
455
456   plugin = gst_plugin_load_file (filename, &err);
457
458   if (plugin) {
459     GST_INFO ("Loaded plugin: \"%s\"", filename);
460
461     gst_default_registry_add_plugin (plugin);
462   } else {
463     if (err) {
464       /* Report error to user, and free error */
465       GST_ERROR ("Failed to load plugin: %s\n", err->message);
466       g_error_free (err);
467     } else {
468       GST_WARNING ("Failed to load plugin: \"%s\"", filename);
469     }
470   }
471
472   g_free (data);
473 }
474
475 static void
476 split_and_iterate (const gchar * stringlist, gchar * separator, GFunc iterator,
477     gpointer user_data)
478 {
479   gchar **strings;
480   gint j = 0;
481   gchar *lastlist = g_strdup (stringlist);
482
483   while (lastlist) {
484     strings = g_strsplit (lastlist, separator, MAX_PATH_SPLIT);
485     g_free (lastlist);
486     lastlist = NULL;
487
488     while (strings[j]) {
489       iterator (strings[j], user_data);
490       if (++j == MAX_PATH_SPLIT) {
491         lastlist = g_strdup (strings[j]);
492         j = 0;
493         break;
494       }
495     }
496     g_strfreev (strings);
497   }
498 }
499
500 /* we have no fail cases yet, but maybe in the future */
501 static gboolean
502 init_pre (GOptionContext * context, GOptionGroup * group, gpointer data,
503     GError ** error)
504 {
505   if (gst_initialized) {
506     GST_DEBUG ("already initialized");
507     return TRUE;
508   }
509
510   /* GStreamer was built against a GLib >= 2.8 and is therefore not doing
511    * the refcount hack. Check that it isn't being run against an older GLib */
512   if (glib_major_version < 2 ||
513       (glib_major_version == 2 && glib_minor_version < 8)) {
514     g_warning ("GStreamer was compiled against GLib %d.%d.%d but is running"
515         " against %d.%d.%d. This will cause reference counting issues",
516         GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION,
517         glib_major_version, glib_minor_version, glib_micro_version);
518   }
519
520   g_type_init ();
521
522   if (g_thread_supported ()) {
523     /* somebody already initialized threading */
524   } else {
525     g_thread_init (NULL);
526   }
527   /* we need threading to be enabled right here */
528   _gst_debug_init ();
529
530 #ifdef ENABLE_NLS
531   setlocale (LC_ALL, "");
532   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
533 #endif /* ENABLE_NLS */
534
535 #ifndef GST_DISABLE_GST_DEBUG
536   {
537     const gchar *debug_list;
538
539     if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
540       gst_debug_set_colored (FALSE);
541
542     debug_list = g_getenv ("GST_DEBUG");
543     if (debug_list) {
544       parse_debug_list (debug_list);
545     }
546   }
547 #endif
548   /* This is the earliest we can make stuff show up in the logs.
549    * So give some useful info about GStreamer here */
550   GST_INFO ("Initializing GStreamer Core Library version %s", VERSION);
551   GST_INFO ("Using library installed in %s", LIBDIR);
552
553   /* Print some basic system details if possible (OS/architecture) */
554 #ifdef HAVE_SYS_UTSNAME_H
555   {
556     struct utsname sys_details;
557
558     if (uname (&sys_details) == 0) {
559       GST_INFO ("%s %s %s %s %s", sys_details.sysname,
560           sys_details.nodename, sys_details.release, sys_details.version,
561           sys_details.machine);
562     }
563   }
564 #endif
565
566   return TRUE;
567 }
568
569 static gboolean
570 gst_register_core_elements (GstPlugin * plugin)
571 {
572   /* register some standard builtin types */
573   if (!gst_element_register (plugin, "bin", GST_RANK_PRIMARY,
574           GST_TYPE_BIN) ||
575       !gst_element_register (plugin, "pipeline", GST_RANK_PRIMARY,
576           GST_TYPE_PIPELINE)
577       )
578     g_assert_not_reached ();
579
580   return TRUE;
581 }
582
583 static GstPluginDesc plugin_desc = {
584   GST_VERSION_MAJOR,
585   GST_VERSION_MINOR,
586   "staticelements",
587   "core elements linked into the GStreamer library",
588   gst_register_core_elements,
589   VERSION,
590   GST_LICENSE,
591   PACKAGE,
592   GST_PACKAGE_NAME,
593   GST_PACKAGE_ORIGIN,
594
595   GST_PADDING_INIT
596 };
597
598 #ifndef GST_DISABLE_REGISTRY
599
600 /*
601  * scan_and_update_registry:
602  * @default_registry: the #GstRegistry
603  * @registry_file: registry filename
604  * @write_changes: write registry if it has changed?
605  *
606  * Scans for registry changes and evntualy updates the registry cache. 
607  *
608  * Return: %TRUE if the registry could be updated
609  */
610 static gboolean
611 scan_and_update_registry (GstRegistry * default_registry,
612     const gchar * registry_file, gboolean write_changes, GError ** error)
613 {
614   const gchar *plugin_path;
615   gboolean changed = FALSE;
616   GList *l;
617
618   GST_DEBUG ("reading registry cache: %s", registry_file);
619   gst_registry_xml_read_cache (default_registry, registry_file);
620
621   /* scan paths specified via --gst-plugin-path */
622   GST_DEBUG ("scanning paths added via --gst-plugin-path");
623   for (l = plugin_paths; l != NULL; l = l->next) {
624     GST_INFO ("Scanning plugin path: \"%s\"", (gchar *) l->data);
625     /* CHECKME: add changed |= here as well? */
626     gst_registry_scan_path (default_registry, (gchar *) l->data);
627     g_free (l->data);
628   }
629   g_list_free (plugin_paths);
630   plugin_paths = NULL;
631
632   /* GST_PLUGIN_PATH specifies a list of directories to scan for
633    * additional plugins.  These take precedence over the system plugins */
634   plugin_path = g_getenv ("GST_PLUGIN_PATH");
635   if (plugin_path) {
636     char **list;
637     int i;
638
639     GST_DEBUG ("GST_PLUGIN_PATH set to %s", plugin_path);
640     list = g_strsplit (plugin_path, G_SEARCHPATH_SEPARATOR_S, 0);
641     for (i = 0; list[i]; i++) {
642       changed |= gst_registry_scan_path (default_registry, list[i]);
643     }
644     g_strfreev (list);
645   } else {
646     GST_DEBUG ("GST_PLUGIN_PATH not set");
647   }
648
649   /* GST_PLUGIN_SYSTEM_PATH specifies a list of plugins that are always
650    * loaded by default.  If not set, this defaults to the system-installed
651    * path, and the plugins installed in the user's home directory */
652   plugin_path = g_getenv ("GST_PLUGIN_SYSTEM_PATH");
653   if (plugin_path == NULL) {
654     char *home_plugins;
655
656     GST_DEBUG ("GST_PLUGIN_SYSTEM_PATH not set");
657
658     /* plugins in the user's home directory take precedence over
659      * system-installed ones */
660     home_plugins = g_build_filename (g_get_home_dir (),
661         ".gstreamer-" GST_MAJORMINOR, "plugins", NULL);
662     changed |= gst_registry_scan_path (default_registry, home_plugins);
663     g_free (home_plugins);
664
665     /* add the main (installed) library path */
666     changed |= gst_registry_scan_path (default_registry, PLUGINDIR);
667   } else {
668     gchar **list;
669     gint i;
670
671     GST_DEBUG ("GST_PLUGIN_SYSTEM_PATH set to %s", plugin_path);
672     list = g_strsplit (plugin_path, G_SEARCHPATH_SEPARATOR_S, 0);
673     for (i = 0; list[i]; i++) {
674       changed |= gst_registry_scan_path (default_registry, list[i]);
675     }
676     g_strfreev (list);
677   }
678
679   /* Remove cached plugins so stale info is cleared. */
680   changed |= _priv_gst_registry_remove_cache_plugins (default_registry);
681
682   if (!changed) {
683     GST_INFO ("Registry cache has not changed");
684     return TRUE;
685   }
686
687   if (!write_changes) {
688     GST_INFO ("Registry cached changed, but writing is disabled. Not writing.");
689     return TRUE;
690   }
691
692   GST_INFO ("Registry cache changed. Writing new registry cache");
693   if (!gst_registry_xml_write_cache (default_registry, registry_file)) {
694     g_set_error (error, GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
695         _("Error writing registry cache to %s: %s"),
696         registry_file, g_strerror (errno));
697     return FALSE;
698   }
699
700   GST_INFO ("Registry cache written successfully");
701   return TRUE;
702 }
703
704 static gboolean
705 ensure_current_registry_nonforking (GstRegistry * default_registry,
706     const gchar * registry_file, GError ** error)
707 {
708   /* fork() not available */
709   GST_DEBUG ("Updating registry cache in-process");
710   scan_and_update_registry (default_registry, registry_file, TRUE, error);
711   return TRUE;
712 }
713
714 /* when forking is not available this function always does nothing but return
715  * TRUE immediatly */
716 static gboolean
717 ensure_current_registry_forking (GstRegistry * default_registry,
718     const gchar * registry_file, GError ** error)
719 {
720 #ifdef HAVE_FORK
721   pid_t pid;
722   int pfd[2];
723   int ret;
724
725   /* We fork here, and let the child read and possibly rebuild the registry.
726    * After that, the parent will re-read the freshly generated registry. */
727   GST_DEBUG ("forking to update registry");
728
729   if (pipe (pfd) == -1) {
730     g_set_error (error, GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
731         _("Error re-scanning registry %s: %s"),
732         ", could not create pipes. Error", g_strerror (errno));
733     return FALSE;
734   }
735
736   pid = fork ();
737   if (pid == -1) {
738     GST_ERROR ("Failed to fork()");
739     g_set_error (error, GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
740         _("Error re-scanning registry %s: %s"),
741         ", failed to fork. Error", g_strerror (errno));
742     return FALSE;
743   }
744
745   if (pid == 0) {
746     gboolean res;
747     gchar res_byte;
748
749     /* this is the child. Close the read pipe */
750     (void) close (pfd[0]);
751
752     GST_DEBUG ("child reading registry cache");
753     res =
754         scan_and_update_registry (default_registry, registry_file, TRUE, NULL);
755
756     /* need to use _exit, so that any exit handlers registered don't
757      * bring down the main program */
758     GST_DEBUG ("child exiting: %s", (res) ? "SUCCESS" : "FAILURE");
759
760     /* make valgrind happy (yes, you can call it insane) */
761     g_free ((char *) registry_file);
762
763     /* write a result byte to the pipe */
764     res_byte = res ? '1' : '0';
765     do {
766       ret = write (pfd[1], &res_byte, 1);
767     } while (ret == -1 && errno == EINTR);
768     /* if ret == -1 now, we could not write to pipe, probably 
769      * means parent has exited before us */
770     (void) close (pfd[1]);
771
772     _exit (0);
773   } else {
774     gchar res_byte;
775
776     /* parent. Close write pipe */
777     (void) close (pfd[1]);
778
779     /* Wait for result from the pipe */
780     GST_DEBUG ("Waiting for data from child");
781     do {
782       ret = read (pfd[0], &res_byte, 1);
783     } while (ret == -1 && errno == EINTR);
784
785     if (ret == -1) {
786       g_set_error (error, GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
787           _("Error re-scanning registry %s: %s"),
788           ", read returned error", g_strerror (errno));
789       close (pfd[0]);
790       return FALSE;
791     }
792     (void) close (pfd[0]);
793
794     /* Wait to ensure the child is reaped, but ignore the result */
795     GST_DEBUG ("parent waiting on child");
796     waitpid (pid, NULL, 0);
797     GST_DEBUG ("parent done waiting on child");
798
799     if (ret == 0) {
800       GST_ERROR ("child did not exit normally, terminated by signal");
801       g_set_error (error, GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
802           _("Error re-scanning registry %s"), ", child terminated by signal");
803       return FALSE;
804     }
805
806     if (res_byte == '1') {
807       GST_DEBUG ("Child succeeded. Parent reading registry cache");
808       gst_registry_xml_read_cache (default_registry, registry_file);
809     } else {
810       GST_DEBUG ("Child failed. Parent re-scanning registry, ignoring errors.");
811       scan_and_update_registry (default_registry, registry_file, FALSE, NULL);
812     }
813   }
814 #endif /* HAVE_FORK */
815   return TRUE;
816 }
817
818 static gboolean
819 ensure_current_registry (GError ** error)
820 {
821   char *registry_file;
822   GstRegistry *default_registry;
823   gboolean ret;
824   gboolean do_fork;
825
826   default_registry = gst_registry_get_default ();
827   registry_file = g_strdup (g_getenv ("GST_REGISTRY"));
828   if (registry_file == NULL) {
829     registry_file = g_build_filename (g_get_home_dir (),
830         ".gstreamer-" GST_MAJORMINOR, "registry." HOST_CPU ".xml", NULL);
831   }
832
833   /* first see if forking is enabled */
834   do_fork = _gst_enable_registry_fork;
835   if (do_fork) {
836     const gchar *fork_env;
837
838     /* forking enabled, see if it is disabled with an env var */
839     if ((fork_env = g_getenv ("GST_REGISTRY_FORK"))) {
840       /* fork enabled for any value different from "no" */
841       do_fork = strcmp (fork_env, "no") != 0;
842     }
843   }
844
845   /* now check registry with or without forking */
846   if (do_fork) {
847     GST_DEBUG ("forking for registry rebuild");
848     ret = ensure_current_registry_forking (default_registry, registry_file,
849         error);
850   } else {
851     GST_DEBUG ("requested not to fork for registry rebuild");
852     ret = ensure_current_registry_nonforking (default_registry, registry_file,
853         error);
854   }
855
856   g_free (registry_file);
857
858   return ret;
859 }
860 #endif /* GST_DISABLE_REGISTRY */
861
862 /*
863  * this bit handles:
864  * - initalization of threads if we use them
865  * - log handler
866  * - initial output
867  * - initializes gst_format
868  * - registers a bunch of types for gst_objects
869  *
870  * - we don't have cases yet where this fails, but in the future
871  *   we might and then it's nice to be able to return that
872  */
873 static gboolean
874 init_post (GOptionContext * context, GOptionGroup * group, gpointer data,
875     GError ** error)
876 {
877   GLogLevelFlags llf;
878
879 #ifndef GST_DISABLE_TRACE
880   GstTrace *gst_trace;
881 #endif /* GST_DISABLE_TRACE */
882
883   if (gst_initialized) {
884     GST_DEBUG ("already initialized");
885     return TRUE;
886   }
887
888   llf = G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR | G_LOG_FLAG_FATAL;
889   g_log_set_handler (g_log_domain_gstreamer, llf, debug_log_handler, NULL);
890
891   _priv_gst_quarks_initialize ();
892   _gst_format_initialize ();
893   _gst_query_initialize ();
894   gst_object_get_type ();
895   gst_pad_get_type ();
896   gst_element_factory_get_type ();
897   gst_element_get_type ();
898   gst_type_find_factory_get_type ();
899   gst_bin_get_type ();
900
901 #ifndef GST_DISABLE_INDEX
902   gst_index_factory_get_type ();
903 #endif /* GST_DISABLE_INDEX */
904 #ifndef GST_DISABLE_URI
905   gst_uri_handler_get_type ();
906 #endif /* GST_DISABLE_URI */
907
908   gst_structure_get_type ();
909   _gst_value_initialize ();
910   gst_caps_get_type ();
911   _gst_event_initialize ();
912   _gst_buffer_initialize ();
913   _gst_message_initialize ();
914   _gst_tag_initialize ();
915
916   /* register core plugins */
917   _gst_plugin_register_static (&plugin_desc);
918
919   _gst_plugin_initialize ();
920
921   /*
922    * Any errors happening below this point are non-fatal, we therefore mark
923    * gstreamer as being initialized, since it is the case from a plugin point of
924    * view.
925    *
926    * If anything fails, it will be put back to FALSE in gst_init_check().
927    * This allows some special plugins that would call gst_init() to not cause a
928    * looping effect (i.e. initializing GStreamer twice).
929    */
930   gst_initialized = TRUE;
931
932 #ifndef GST_DISABLE_REGISTRY
933   if (!ensure_current_registry (error))
934     return FALSE;
935 #endif /* GST_DISABLE_REGISTRY */
936
937   /* if we need to preload plugins */
938   if (preload_plugins) {
939     g_slist_foreach (preload_plugins, load_plugin_func, NULL);
940     g_slist_free (preload_plugins);
941     preload_plugins = NULL;
942   }
943 #ifndef GST_DISABLE_TRACE
944   _gst_trace_on = 0;
945   if (_gst_trace_on) {
946     gst_trace = gst_trace_new ("gst.trace", 1024);
947     gst_trace_set_default (gst_trace);
948   }
949 #endif /* GST_DISABLE_TRACE */
950
951   return TRUE;
952 }
953
954 #ifndef GST_DISABLE_GST_DEBUG
955 static gboolean
956 select_all (GstPlugin * plugin, gpointer user_data)
957 {
958   return TRUE;
959 }
960
961 static gint
962 sort_by_category_name (gconstpointer a, gconstpointer b)
963 {
964   return strcmp (gst_debug_category_get_name ((GstDebugCategory *) a),
965       gst_debug_category_get_name ((GstDebugCategory *) b));
966 }
967 static void
968 gst_debug_help (void)
969 {
970   GSList *list, *walk;
971   GList *list2, *g;
972
973   /* Need to ensure the registry is loaded to get debug categories */
974   if (!init_post (NULL, NULL, NULL, NULL))
975     exit (1);
976
977   list2 = gst_registry_plugin_filter (gst_registry_get_default (),
978       select_all, FALSE, NULL);
979
980   /* FIXME this is gross.  why don't debug have categories PluginFeatures? */
981   for (g = list2; g; g = g_list_next (g)) {
982     GstPlugin *plugin = GST_PLUGIN_CAST (g->data);
983
984     gst_plugin_load (plugin);
985   }
986   g_list_free (list2);
987
988   list = gst_debug_get_all_categories ();
989   walk = list = g_slist_sort (list, sort_by_category_name);
990
991   g_print ("\n");
992   g_print ("name                  level    description\n");
993   g_print ("---------------------+--------+--------------------------------\n");
994
995   while (walk) {
996     GstDebugCategory *cat = (GstDebugCategory *) walk->data;
997
998     if (gst_debug_is_colored ()) {
999       gchar *color = gst_debug_construct_term_color (cat->color);
1000
1001       g_print ("%s%-20s\033[00m  %1d %s  %s%s\033[00m\n",
1002           color,
1003           gst_debug_category_get_name (cat),
1004           gst_debug_category_get_threshold (cat),
1005           gst_debug_level_get_name (gst_debug_category_get_threshold (cat)),
1006           color, gst_debug_category_get_description (cat));
1007       g_free (color);
1008     } else {
1009       g_print ("%-20s  %1d %s  %s\n", gst_debug_category_get_name (cat),
1010           gst_debug_category_get_threshold (cat),
1011           gst_debug_level_get_name (gst_debug_category_get_threshold (cat)),
1012           gst_debug_category_get_description (cat));
1013     }
1014     walk = g_slist_next (walk);
1015   }
1016   g_slist_free (list);
1017   g_print ("\n");
1018 }
1019 #endif
1020
1021 static gboolean
1022 parse_one_option (gint opt, const gchar * arg, GError ** err)
1023 {
1024   switch (opt) {
1025     case ARG_VERSION:
1026       g_print ("GStreamer Core Library version %s\n", PACKAGE_VERSION);
1027       exit (0);
1028     case ARG_FATAL_WARNINGS:{
1029       GLogLevelFlags fatal_mask;
1030
1031       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1032       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1033       g_log_set_always_fatal (fatal_mask);
1034       break;
1035     }
1036 #ifndef GST_DISABLE_GST_DEBUG
1037     case ARG_DEBUG_LEVEL:{
1038       gint tmp = 0;
1039
1040       tmp = strtol (arg, NULL, 0);
1041       if (tmp >= 0 && tmp < GST_LEVEL_COUNT) {
1042         gst_debug_set_default_threshold (tmp);
1043       }
1044       break;
1045     }
1046     case ARG_DEBUG:
1047       parse_debug_list (arg);
1048       break;
1049     case ARG_DEBUG_NO_COLOR:
1050       gst_debug_set_colored (FALSE);
1051       break;
1052     case ARG_DEBUG_DISABLE:
1053       gst_debug_set_active (FALSE);
1054       break;
1055     case ARG_DEBUG_HELP:
1056       gst_debug_help ();
1057       exit (0);
1058 #endif
1059     case ARG_PLUGIN_SPEW:
1060       break;
1061     case ARG_PLUGIN_PATH:
1062 #ifndef GST_DISABLE_REGISTRY
1063       split_and_iterate (arg, G_SEARCHPATH_SEPARATOR_S, add_path_func, NULL);
1064 #endif /* GST_DISABLE_REGISTRY */
1065       break;
1066     case ARG_PLUGIN_LOAD:
1067       split_and_iterate (arg, ",", prepare_for_load_plugin_func, NULL);
1068       break;
1069     case ARG_SEGTRAP_DISABLE:
1070       _gst_disable_segtrap = TRUE;
1071       break;
1072     case ARG_REGISTRY_FORK_DISABLE:
1073       _gst_enable_registry_fork = FALSE;
1074       break;
1075     default:
1076       g_set_error (err, G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1077           _("Unknown option"));
1078       return FALSE;
1079   }
1080
1081   return TRUE;
1082 }
1083
1084 static gboolean
1085 parse_goption_arg (const gchar * opt,
1086     const gchar * arg, gpointer data, GError ** err)
1087 {
1088   static const struct
1089   {
1090     gchar *opt;
1091     int val;
1092   } options[] = {
1093     {
1094     "--gst-version", ARG_VERSION}, {
1095     "--gst-fatal-warnings", ARG_FATAL_WARNINGS},
1096 #ifndef GST_DISABLE_GST_DEBUG
1097     {
1098     "--gst-debug-level", ARG_DEBUG_LEVEL}, {
1099     "--gst-debug", ARG_DEBUG}, {
1100     "--gst-debug-disable", ARG_DEBUG_DISABLE}, {
1101     "--gst-debug-no-color", ARG_DEBUG_NO_COLOR}, {
1102     "--gst-debug-help", ARG_DEBUG_HELP},
1103 #endif
1104     {
1105     "--gst-plugin-spew", ARG_PLUGIN_SPEW}, {
1106     "--gst-plugin-path", ARG_PLUGIN_PATH}, {
1107     "--gst-plugin-load", ARG_PLUGIN_LOAD}, {
1108     "--gst-disable-segtrap", ARG_SEGTRAP_DISABLE}, {
1109     "--gst-disable-registry-fork", ARG_REGISTRY_FORK_DISABLE}, {
1110     NULL}
1111   };
1112   gint val = 0, n;
1113
1114   for (n = 0; options[n].opt; n++) {
1115     if (!strcmp (opt, options[n].opt)) {
1116       val = options[n].val;
1117       break;
1118     }
1119   }
1120
1121   return parse_one_option (val, arg, err);
1122 }
1123
1124 extern GstRegistry *_gst_registry_default;
1125
1126 /**
1127  * gst_deinit:
1128  *
1129  * Clean up any resources created by GStreamer in gst_init().
1130  *
1131  * It is normally not needed to call this function in a normal application
1132  * as the resources will automatically be freed when the program terminates.
1133  * This function is therefore mostly used by testsuites and other memory
1134  * profiling tools.
1135  *
1136  * After this call GStreamer (including this method) should not be used anymore. 
1137  */
1138 void
1139 gst_deinit (void)
1140 {
1141   GstClock *clock;
1142
1143   GST_INFO ("deinitializing GStreamer");
1144
1145   if (!gst_initialized) {
1146     GST_DEBUG ("already deinitialized");
1147     return;
1148   }
1149
1150   clock = gst_system_clock_obtain ();
1151   gst_object_unref (clock);
1152   gst_object_unref (clock);
1153
1154   _priv_gst_registry_cleanup ();
1155
1156   gst_initialized = FALSE;
1157   GST_INFO ("deinitialized GStreamer");
1158 }
1159
1160 /**
1161  * gst_version:
1162  * @major: pointer to a guint to store the major version number
1163  * @minor: pointer to a guint to store the minor version number
1164  * @micro: pointer to a guint to store the micro version number
1165  * @nano:  pointer to a guint to store the nano version number
1166  *
1167  * Gets the version number of the GStreamer library.
1168  */
1169 void
1170 gst_version (guint * major, guint * minor, guint * micro, guint * nano)
1171 {
1172   g_return_if_fail (major);
1173   g_return_if_fail (minor);
1174   g_return_if_fail (micro);
1175   g_return_if_fail (nano);
1176
1177   *major = GST_VERSION_MAJOR;
1178   *minor = GST_VERSION_MINOR;
1179   *micro = GST_VERSION_MICRO;
1180   *nano = GST_VERSION_NANO;
1181 }
1182
1183 /**
1184  * gst_version_string:
1185  *
1186  * This function returns a string that is useful for describing this version
1187  * of GStreamer to the outside world: user agent strings, logging, ...
1188  *
1189  * Returns: a newly allocated string describing this version of GStreamer.
1190  */
1191
1192 gchar *
1193 gst_version_string ()
1194 {
1195   guint major, minor, micro, nano;
1196
1197   gst_version (&major, &minor, &micro, &nano);
1198   if (nano == 0)
1199     return g_strdup_printf ("GStreamer %d.%d.%d", major, minor, micro);
1200   else if (nano == 1)
1201     return g_strdup_printf ("GStreamer %d.%d.%d (CVS)", major, minor, micro);
1202   else
1203     return g_strdup_printf ("GStreamer %d.%d.%d (prerelease)", major, minor,
1204         micro);
1205 }
1206
1207 /**
1208  * gst_segtrap_is_enabled:
1209  *
1210  * Some functions in the GStreamer core might install a custom SIGSEGV handler
1211  * to better catch and report errors to the application. Currently this feature
1212  * is enabled by default when loading plugins.
1213  *
1214  * Applications might want to disable this behaviour with the
1215  * gst_segtrap_set_enabled() function. This is typically done if the application
1216  * wants to install its own handler without GStreamer interfering.
1217  *
1218  * Returns: %TRUE if GStreamer is allowed to install a custom SIGSEGV handler.
1219  *
1220  * Since: 0.10.10
1221  */
1222 gboolean
1223 gst_segtrap_is_enabled (void)
1224 {
1225   /* yeps, it's enabled when it's not disabled */
1226   return !_gst_disable_segtrap;
1227 }
1228
1229 /**
1230  * gst_segtrap_set_enabled:
1231  * @enabled: whether a custom SIGSEGV handler should be installed.
1232  *
1233  * Applications might want to disable/enable the SIGSEGV handling of
1234  * the GStreamer core. See gst_segtrap_is_enabled() for more information.
1235  *
1236  * Since: 0.10.10
1237  */
1238 void
1239 gst_segtrap_set_enabled (gboolean enabled)
1240 {
1241   _gst_disable_segtrap = !enabled;
1242 }
1243
1244 /**
1245  * gst_registry_fork_is_enabled:
1246  *
1247  * By default GStreamer will perform a fork() when scanning and rebuilding the
1248  * registry file. 
1249  *
1250  * Applications might want to disable this behaviour with the
1251  * gst_registry_fork_set_enabled() function. 
1252  *
1253  * Returns: %TRUE if GStreamer will use fork() when rebuilding the registry. On
1254  * platforms without fork(), this function will always return %FALSE.
1255  *
1256  * Since: 0.10.10
1257  */
1258 gboolean
1259 gst_registry_fork_is_enabled (void)
1260 {
1261   return _gst_enable_registry_fork;
1262 }
1263
1264 /**
1265  * gst_registry_fork_set_enabled:
1266  * @enabled: whether rebuilding the registry may fork
1267  *
1268  * Applications might want to disable/enable the usage of fork() when rebuilding
1269  * the registry. See gst_registry_fork_is_enabled() for more information.
1270  *
1271  * On platforms without fork(), this function will have no effect on the return
1272  * value of gst_registry_fork_is_enabled().
1273  *
1274  * Since: 0.10.10
1275  */
1276 void
1277 gst_registry_fork_set_enabled (gboolean enabled)
1278 {
1279 #ifdef HAVE_FORK
1280   _gst_enable_registry_fork = enabled;
1281 #endif /* HAVE_FORK */
1282 }