Add two functions to check and change the SIGSEGV behaviour when loading plugins.
[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 still very fluid and thus can be changed
42  * to increase the sanity/noise ratio.
43  *
44  * The <application>GStreamer</application> library should be initialized with
45  * gst_init() before it can be used. You should pass pointers to the main argc
46  * and argv variables so that GStreamer can process its own command line
47  * options, as shown in the following example.
48  *
49  * <example>
50  * <title>Initializing the gstreamer library</title>
51  * <programlisting language="c">
52  * int
53  * main (int argc, char *argv[])
54  * {
55  *   // initialize the GStreamer library
56  *   gst_init (&amp;argc, &amp;argv);
57  *   ...
58  * }
59  * </programlisting>
60  * </example>
61  *
62  * It's allowed to pass two NULL pointers to gst_init() in case you don't want
63  * to pass the command line args to GStreamer.
64  *
65  * You can also use GOption to initialize your own parameters as shown in
66  * the next code fragment:
67  * <example>
68  * <title>Initializing own parameters when initializing gstreamer</title>
69  * <programlisting>
70  * static gboolean stats = FALSE;
71  * ...
72  * int
73  * main (int argc, char *argv[])
74  * {
75  *  GOptionEntry options[] = {
76  *   {"tags", 't', 0, G_OPTION_ARG_NONE, &amp;tags,
77  *       N_("Output tags (also known as metadata)"), NULL},
78  *   {NULL}
79  *  };
80  *  ctx = g_option_context_new ("gst-launch");
81  *  g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
82  *  g_option_context_add_group (ctx, gst_init_get_option_group ());
83  *  if (!g_option_context_parse (ctx, &amp;argc, &amp;argv, &amp;err)) {
84  *    g_print ("Error initializing: &percnt;s\n", GST_STR_NULL (err->message));
85  *    exit (1);
86  *  }
87  *  g_option_context_free (ctx);
88  * ...
89  * }
90  * </programlisting>
91  * </example>
92  *
93  * Use gst_version() to query the library version at runtime or use the
94  * GST_VERSION_* macros to find the version at compile time. Optionally
95  * gst_version_string() returns a printable string.
96  *
97  * The gst_deinit() call is used to clean up all internal resources used
98  * by <application>GStreamer</application>. It is mostly used in unit tests 
99  * to check for leaks.
100  *
101  * Last reviewed on 2005-11-23 (0.9.5)
102  */
103
104 #include "gst_private.h"
105 #include <stdlib.h>
106 #include <stdio.h>
107 #include <sys/types.h>
108 #ifdef HAVE_FORK
109 #include <sys/wait.h>
110 #endif //HAVE_FORK
111 #include <unistd.h>
112
113 #include "gst-i18n-lib.h"
114 #include <locale.h>             /* for LC_ALL */
115
116 #include "gst.h"
117
118 #define GST_CAT_DEFAULT GST_CAT_GST_INIT
119
120 #define MAX_PATH_SPLIT  16
121 #define GST_PLUGIN_SEPARATOR ","
122
123 static gboolean gst_initialized = FALSE;
124
125 #ifndef GST_DISABLE_REGISTRY
126 static GList *plugin_paths = NULL;      /* for delayed processing in post_init */
127 #endif
128
129 extern gint _gst_trace_on;
130
131 /* set to TRUE when segfaults need to be left as is */
132 gboolean _gst_disable_segtrap = FALSE;
133
134 static void load_plugin_func (gpointer data, gpointer user_data);
135 static gboolean init_pre (void);
136 static gboolean init_post (void);
137 static gboolean parse_goption_arg (const gchar * s_opt,
138     const gchar * arg, gpointer data, GError ** err);
139
140 static GSList *preload_plugins = NULL;
141
142 const gchar g_log_domain_gstreamer[] = "GStreamer";
143
144 static void
145 debug_log_handler (const gchar * log_domain,
146     GLogLevelFlags log_level, const gchar * message, gpointer user_data)
147 {
148   g_log_default_handler (log_domain, log_level, message, user_data);
149   /* FIXME: do we still need this ? fatal errors these days are all
150    * other than core errors */
151   /* g_on_error_query (NULL); */
152 }
153
154 enum
155 {
156   ARG_VERSION = 1,
157   ARG_FATAL_WARNINGS,
158 #ifndef GST_DISABLE_GST_DEBUG
159   ARG_DEBUG_LEVEL,
160   ARG_DEBUG,
161   ARG_DEBUG_DISABLE,
162   ARG_DEBUG_NO_COLOR,
163   ARG_DEBUG_HELP,
164 #endif
165   ARG_PLUGIN_SPEW,
166   ARG_PLUGIN_PATH,
167   ARG_PLUGIN_LOAD,
168   ARG_SEGTRAP_DISABLE
169 };
170
171 /* debug-spec ::= category-spec [, category-spec]*
172  * category-spec ::= category:val | val
173  * category ::= [^:]+
174  * val ::= [0-5]
175  */
176
177 #ifndef NUL
178 #define NUL '\0'
179 #endif
180
181 #ifndef GST_DISABLE_GST_DEBUG
182 static gboolean
183 parse_debug_category (gchar * str, const gchar ** category)
184 {
185   if (!str)
186     return FALSE;
187
188   /* works in place */
189   g_strstrip (str);
190
191   if (str[0] != NUL) {
192     *category = str;
193     return TRUE;
194   }
195
196   return FALSE;
197 }
198
199 static gboolean
200 parse_debug_level (gchar * str, gint * level)
201 {
202   if (!str)
203     return FALSE;
204
205   /* works in place */
206   g_strstrip (str);
207
208   if (str[0] != NUL && str[1] == NUL
209       && str[0] >= '0' && str[0] < '0' + GST_LEVEL_COUNT) {
210     *level = str[0] - '0';
211     return TRUE;
212   }
213
214   return FALSE;
215 }
216
217 static void
218 parse_debug_list (const gchar * list)
219 {
220   gchar **split;
221   gchar **walk;
222
223   g_return_if_fail (list != NULL);
224
225   split = g_strsplit (list, ",", 0);
226
227   for (walk = split; *walk; walk++) {
228     if (strchr (*walk, ':')) {
229       gchar **values = g_strsplit (*walk, ":", 2);
230
231       if (values[0] && values[1]) {
232         gint level;
233         const gchar *category;
234
235         if (parse_debug_category (values[0], &category)
236             && parse_debug_level (values[1], &level))
237           gst_debug_set_threshold_for_name (category, level);
238       }
239
240       g_strfreev (values);
241     } else {
242       gint level;
243
244       if (parse_debug_level (*walk, &level))
245         gst_debug_set_default_threshold (level);
246     }
247   }
248
249   g_strfreev (split);
250 }
251 #endif
252
253 /**
254  * gst_init_get_option_group:
255  *
256  * Returns a #GOptionGroup with GStreamer's argument specifications. The
257  * group is set up to use standard GOption callbacks, so when using this
258  * group in combination with GOption parsing methods, all argument parsing
259  * and initialization is automated.
260  *
261  * This function is useful if you want to integrate GStreamer with other
262  * libraries that use GOption (see g_option_context_add_group() ).
263  *
264  * Returns: a pointer to GStreamer's option group. Should be dereferenced
265  * after use.
266  */
267
268 GOptionGroup *
269 gst_init_get_option_group (void)
270 {
271   GOptionGroup *group;
272   static GOptionEntry gst_args[] = {
273     {"gst-version", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
274         parse_goption_arg, N_("Print the GStreamer version"), NULL},
275     {"gst-fatal-warnings", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
276         parse_goption_arg, N_("Make all warnings fatal"), NULL},
277 #ifndef GST_DISABLE_GST_DEBUG
278     {"gst-debug-help", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
279           parse_goption_arg, N_("Print available debug categories and exit"),
280         NULL},
281     {"gst-debug-level", 0, 0, G_OPTION_ARG_CALLBACK, parse_goption_arg,
282           N_("Default debug level from 1 (only error) to 5 (anything) or "
283               "0 for no output"),
284         N_("LEVEL")},
285     {"gst-debug", 0, 0, G_OPTION_ARG_CALLBACK, parse_goption_arg,
286           N_("Comma-separated list of category_name:level pairs to set "
287               "specific levels for the individual categories. Example: "
288               "GST_AUTOPLUG:5,GST_ELEMENT_*:3"),
289         N_("LIST")},
290     {"gst-debug-no-color", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
291         parse_goption_arg, N_("Disable colored debugging output"), NULL},
292     {"gst-debug-disable", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
293         parse_goption_arg, N_("Disable debugging"), NULL},
294 #endif
295     {"gst-plugin-spew", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
296           parse_goption_arg, N_("Enable verbose plugin loading diagnostics"),
297         NULL},
298     {"gst-plugin-path", 0, 0, G_OPTION_ARG_CALLBACK, parse_goption_arg,
299         N_("Colon-separated paths containing plugins"), N_("PATHS")},
300     {"gst-plugin-load", 0, 0, G_OPTION_ARG_CALLBACK, parse_goption_arg,
301           N_("Comma-separated list of plugins to preload in addition to the "
302               "list stored in environment variable GST_PLUGIN_PATH"),
303         N_("PLUGINS")},
304     {"gst-disable-segtrap", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
305           parse_goption_arg,
306           N_("Disable trapping of segmentation faults during plugin loading"),
307         NULL},
308     {NULL}
309   };
310
311   group = g_option_group_new ("gst", _("GStreamer Options"),
312       _("Show GStreamer Options"), NULL, NULL);
313   g_option_group_set_parse_hooks (group, (GOptionParseFunc) init_pre,
314       (GOptionParseFunc) init_post);
315
316   g_option_group_add_entries (group, gst_args);
317   g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
318
319   return group;
320 }
321
322 /**
323  * gst_init_check:
324  * @argc: pointer to application's argc
325  * @argv: pointer to application's argv
326  * @err: pointer to a #GError to which a message will be posted on error
327  *
328  * Initializes the GStreamer library, setting up internal path lists,
329  * registering built-in elements, and loading standard plugins.
330  *
331  * This function will return %FALSE if GStreamer could not be initialized
332  * for some reason.  If you want your program to fail fatally,
333  * use gst_init() instead.
334  *
335  * Returns: %TRUE if GStreamer could be initialized.
336  */
337 gboolean
338 gst_init_check (int *argc, char **argv[], GError ** err)
339 {
340   GOptionGroup *group;
341   GOptionContext *ctx;
342   gboolean res;
343
344   if (gst_initialized) {
345     GST_DEBUG ("already initialized gst");
346     return TRUE;
347   }
348
349   ctx = g_option_context_new ("- GStreamer initialization");
350   g_option_context_set_ignore_unknown_options (ctx, TRUE);
351   group = gst_init_get_option_group ();
352   g_option_context_add_group (ctx, group);
353   res = g_option_context_parse (ctx, argc, argv, err);
354   g_option_context_free (ctx);
355
356   if (res) {
357     gst_initialized = TRUE;
358   }
359
360   return res;
361 }
362
363 /**
364  * gst_init:
365  * @argc: pointer to application's argc
366  * @argv: pointer to application's argv
367  *
368  * Initializes the GStreamer library, setting up internal path lists,
369  * registering built-in elements, and loading standard plugins.
370  *
371  * <note><para>
372  * This function will terminate your program if it was unable to initialize
373  * GStreamer for some reason.  If you want your program to fall back,
374  * use gst_init_check() instead.
375  * </para></note>
376  *
377  * WARNING: This function does not work in the same way as corresponding
378  * functions in other glib-style libraries, such as gtk_init().  In
379  * particular, unknown command line options cause this function to
380  * abort program execution.
381  */
382 void
383 gst_init (int *argc, char **argv[])
384 {
385   GError *err = NULL;
386
387   if (!gst_init_check (argc, argv, &err)) {
388     g_print ("Could not initialized GStreamer: %s\n",
389         err ? err->message : "unknown error occurred");
390     if (err) {
391       g_error_free (err);
392     }
393     exit (1);
394   }
395 }
396
397 #ifndef GST_DISABLE_REGISTRY
398 static void
399 add_path_func (gpointer data, gpointer user_data)
400 {
401   GST_INFO ("Adding plugin path: \"%s\", will scan later", (gchar *) data);
402   plugin_paths = g_list_append (plugin_paths, g_strdup (data));
403 }
404 #endif
405
406 static void
407 prepare_for_load_plugin_func (gpointer data, gpointer user_data)
408 {
409   preload_plugins = g_slist_prepend (preload_plugins, g_strdup (data));
410 }
411
412 static void
413 load_plugin_func (gpointer data, gpointer user_data)
414 {
415   GstPlugin *plugin;
416   const gchar *filename;
417   GError *err = NULL;
418
419   filename = (const gchar *) data;
420
421   plugin = gst_plugin_load_file (filename, &err);
422
423   if (plugin) {
424     GST_INFO ("Loaded plugin: \"%s\"", filename);
425
426     gst_default_registry_add_plugin (plugin);
427   } else {
428     if (err) {
429       /* Report error to user, and free error */
430       GST_ERROR ("Failed to load plugin: %s\n", err->message);
431       g_error_free (err);
432     } else {
433       GST_WARNING ("Failed to load plugin: \"%s\"", filename);
434     }
435   }
436
437   g_free (data);
438 }
439
440 static void
441 split_and_iterate (const gchar * stringlist, gchar * separator, GFunc iterator,
442     gpointer user_data)
443 {
444   gchar **strings;
445   gint j = 0;
446   gchar *lastlist = g_strdup (stringlist);
447
448   while (lastlist) {
449     strings = g_strsplit (lastlist, separator, MAX_PATH_SPLIT);
450     g_free (lastlist);
451     lastlist = NULL;
452
453     while (strings[j]) {
454       iterator (strings[j], user_data);
455       if (++j == MAX_PATH_SPLIT) {
456         lastlist = g_strdup (strings[j]);
457         j = 0;
458         break;
459       }
460     }
461     g_strfreev (strings);
462   }
463 }
464
465 /* we have no fail cases yet, but maybe in the future */
466 static gboolean
467 init_pre (void)
468 {
469   /* GStreamer was built against a GLib >= 2.8 and is therefore not doing
470    * the refcount hack. Check that it isn't being run against an older GLib */
471   if (glib_major_version < 2 ||
472       (glib_major_version == 2 && glib_minor_version < 8)) {
473     g_warning ("GStreamer was compiled against GLib %d.%d.%d but is running"
474         " against %d.%d.%d. This will cause reference counting issues",
475         GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION,
476         glib_major_version, glib_minor_version, glib_micro_version);
477   }
478
479   g_type_init ();
480
481   if (g_thread_supported ()) {
482     /* somebody already initialized threading */
483   } else {
484     g_thread_init (NULL);
485   }
486   /* we need threading to be enabled right here */
487   _gst_debug_init ();
488
489 #ifdef ENABLE_NLS
490   setlocale (LC_ALL, "");
491   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
492 #endif /* ENABLE_NLS */
493
494 #ifndef GST_DISABLE_GST_DEBUG
495   {
496     const gchar *debug_list;
497
498     if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
499       gst_debug_set_colored (FALSE);
500
501     debug_list = g_getenv ("GST_DEBUG");
502     if (debug_list) {
503       parse_debug_list (debug_list);
504     }
505   }
506 #endif
507   /* This is the earliest we can make stuff show up in the logs.
508    * So give some useful info about GStreamer here */
509   GST_INFO ("Initializing GStreamer Core Library version %s", VERSION);
510   GST_INFO ("Using library installed in %s", LIBDIR);
511
512   return TRUE;
513 }
514
515 static gboolean
516 gst_register_core_elements (GstPlugin * plugin)
517 {
518   /* register some standard builtin types */
519   if (!gst_element_register (plugin, "bin", GST_RANK_PRIMARY,
520           GST_TYPE_BIN) ||
521       !gst_element_register (plugin, "pipeline", GST_RANK_PRIMARY,
522           GST_TYPE_PIPELINE)
523       )
524     g_assert_not_reached ();
525
526   return TRUE;
527 }
528
529 static GstPluginDesc plugin_desc = {
530   GST_VERSION_MAJOR,
531   GST_VERSION_MINOR,
532   "staticelements",
533   "core elements linked into the GStreamer library",
534   gst_register_core_elements,
535   VERSION,
536   GST_LICENSE,
537   PACKAGE,
538   GST_PACKAGE_NAME,
539   GST_PACKAGE_ORIGIN,
540
541   GST_PADDING_INIT
542 };
543
544 #ifndef GST_DISABLE_REGISTRY
545
546 static gboolean
547 scan_and_update_registry (GstRegistry * default_registry,
548     const gchar * registry_file, gboolean write_changes)
549 {
550   const gchar *plugin_path;
551   gboolean changed = FALSE;
552   GList *l;
553
554   GST_DEBUG ("reading registry cache: %s", registry_file);
555   gst_registry_xml_read_cache (default_registry, registry_file);
556
557   /* scan paths specified via --gst-plugin-path */
558   GST_DEBUG ("scanning paths added via --gst-plugin-path");
559   for (l = plugin_paths; l != NULL; l = l->next) {
560     GST_INFO ("Scanning plugin path: \"%s\"", (gchar *) l->data);
561     /* CHECKME: add changed |= here as well? */
562     gst_registry_scan_path (default_registry, (gchar *) l->data);
563     g_free (l->data);
564   }
565   g_list_free (plugin_paths);
566   plugin_paths = NULL;
567
568   /* GST_PLUGIN_PATH specifies a list of directories to scan for
569    * additional plugins.  These take precedence over the system plugins */
570   plugin_path = g_getenv ("GST_PLUGIN_PATH");
571   if (plugin_path) {
572     char **list;
573     int i;
574
575     GST_DEBUG ("GST_PLUGIN_PATH set to %s", plugin_path);
576     list = g_strsplit (plugin_path, G_SEARCHPATH_SEPARATOR_S, 0);
577     for (i = 0; list[i]; i++) {
578       changed |= gst_registry_scan_path (default_registry, list[i]);
579     }
580     g_strfreev (list);
581   } else {
582     GST_DEBUG ("GST_PLUGIN_PATH not set");
583   }
584
585   /* GST_PLUGIN_SYSTEM_PATH specifies a list of plugins that are always
586    * loaded by default.  If not set, this defaults to the system-installed
587    * path, and the plugins installed in the user's home directory */
588   plugin_path = g_getenv ("GST_PLUGIN_SYSTEM_PATH");
589   if (plugin_path == NULL) {
590     char *home_plugins;
591
592     GST_DEBUG ("GST_PLUGIN_SYSTEM_PATH not set");
593
594     /* plugins in the user's home directory take precedence over
595      * system-installed ones */
596     home_plugins = g_build_filename (g_get_home_dir (),
597         ".gstreamer-" GST_MAJORMINOR, "plugins", NULL);
598     changed |= gst_registry_scan_path (default_registry, home_plugins);
599     g_free (home_plugins);
600
601     /* add the main (installed) library path */
602     changed |= gst_registry_scan_path (default_registry, PLUGINDIR);
603   } else {
604     gchar **list;
605     gint i;
606
607     GST_DEBUG ("GST_PLUGIN_SYSTEM_PATH set to %s", plugin_path);
608     list = g_strsplit (plugin_path, G_SEARCHPATH_SEPARATOR_S, 0);
609     for (i = 0; list[i]; i++) {
610       changed |= gst_registry_scan_path (default_registry, list[i]);
611     }
612     g_strfreev (list);
613   }
614
615   if (!changed) {
616     GST_DEBUG ("registry cache has not changed");
617     return TRUE;
618   }
619
620   if (!write_changes) {
621     GST_DEBUG ("not trying to write registry cache changes to file");
622     return TRUE;
623   }
624
625   GST_DEBUG ("writing registry cache");
626   if (!gst_registry_xml_write_cache (default_registry, registry_file)) {
627     g_warning ("Problem writing registry cache to %s: %s", registry_file,
628         g_strerror (errno));
629     return FALSE;
630   }
631
632   GST_DEBUG ("registry cache written successfully");
633   return TRUE;
634 }
635
636 static gboolean
637 ensure_current_registry_nonforking (GstRegistry * default_registry,
638     const gchar * registry_file)
639 {
640   /* fork() not available */
641   GST_DEBUG ("updating registry cache");
642   scan_and_update_registry (default_registry, registry_file, TRUE);
643   return TRUE;
644 }
645
646 #ifdef HAVE_FORK
647 static gboolean
648 ensure_current_registry_forking (GstRegistry * default_registry,
649     const gchar * registry_file)
650 {
651   pid_t pid;
652
653   /* We fork here, and let the child read and possibly rebuild the registry.
654    * After that, the parent will re-read the freshly generated registry. */
655
656   GST_DEBUG ("forking");
657   pid = fork ();
658   if (pid == -1) {
659     GST_ERROR ("Failed to fork()");
660     return FALSE;
661   }
662
663   if (pid == 0) {
664     gboolean res;
665
666     /* this is the child */
667     GST_DEBUG ("child reading registry cache");
668     res = scan_and_update_registry (default_registry, registry_file, TRUE);
669     _gst_registry_remove_cache_plugins (default_registry);
670
671     /* need to use _exit, so that any exit handlers registered don't
672      * bring down the main program */
673     GST_DEBUG ("child exiting: %s", (res) ? "SUCCESS" : "FAILURE");
674
675     /* make valgrind happy (yes, you can call it insane) */
676     g_free ((char *) registry_file);
677
678     _exit ((res) ? EXIT_SUCCESS : EXIT_FAILURE);
679   } else {
680     /* parent */
681     int status;
682     pid_t ret;
683
684     GST_DEBUG ("parent waiting on child");
685     ret = waitpid (pid, &status, 0);
686     GST_DEBUG ("parent done waiting on child");
687     if (ret == -1) {
688       GST_ERROR ("error during waitpid: %s", g_strerror (errno));
689       return FALSE;
690     }
691
692     if (!WIFEXITED (status)) {
693       GST_ERROR ("child did not exit normally, status: %d", status);
694       return FALSE;
695     }
696
697     GST_DEBUG ("child exited normally with return value %d",
698         WEXITSTATUS (status));
699
700     if (WEXITSTATUS (status) == EXIT_SUCCESS) {
701       GST_DEBUG ("parent reading registry cache");
702       gst_registry_xml_read_cache (default_registry, registry_file);
703     } else {
704       GST_DEBUG ("parent re-scanning registry");
705       scan_and_update_registry (default_registry, registry_file, FALSE);
706     }
707   }
708
709   return TRUE;
710 }
711 #endif /* HAVE_FORK */
712
713 static gboolean
714 ensure_current_registry (void)
715 {
716   char *registry_file;
717   GstRegistry *default_registry;
718   gboolean ret;
719
720   default_registry = gst_registry_get_default ();
721   registry_file = g_strdup (g_getenv ("GST_REGISTRY"));
722   if (registry_file == NULL) {
723     registry_file = g_build_filename (g_get_home_dir (),
724         ".gstreamer-" GST_MAJORMINOR, "registry." HOST_CPU ".xml", NULL);
725   }
726 #ifdef HAVE_FORK
727   if (g_getenv ("GST_REGISTRY_FORK") == NULL
728       || strcmp (g_getenv ("GST_REGISTRY_FORK"), "no") != 0) {
729     ret = ensure_current_registry_forking (default_registry, registry_file);
730   } else {
731     GST_DEBUG ("requested not to fork");
732 #endif /* HAVE_FORK */
733
734     ret = ensure_current_registry_nonforking (default_registry, registry_file);
735
736 #ifdef HAVE_FORK
737   }
738 #endif /* HAVE_FORK */
739
740   g_free (registry_file);
741
742   return ret;
743 }
744
745 #endif /* GST_DISABLE_REGISTRY */
746
747 /*
748  * this bit handles:
749  * - initalization of threads if we use them
750  * - log handler
751  * - initial output
752  * - initializes gst_format
753  * - registers a bunch of types for gst_objects
754  *
755  * - we don't have cases yet where this fails, but in the future
756  *   we might and then it's nice to be able to return that
757  */
758 static gboolean
759 init_post (void)
760 {
761   GLogLevelFlags llf;
762
763 #ifndef GST_DISABLE_TRACE
764   GstTrace *gst_trace;
765 #endif /* GST_DISABLE_TRACE */
766
767   llf = G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR | G_LOG_FLAG_FATAL;
768   g_log_set_handler (g_log_domain_gstreamer, llf, debug_log_handler, NULL);
769
770   _gst_format_initialize ();
771   _gst_query_initialize ();
772   gst_object_get_type ();
773   gst_pad_get_type ();
774   gst_element_factory_get_type ();
775   gst_element_get_type ();
776   gst_type_find_factory_get_type ();
777   gst_bin_get_type ();
778
779 #ifndef GST_DISABLE_INDEX
780   gst_index_factory_get_type ();
781 #endif /* GST_DISABLE_INDEX */
782 #ifndef GST_DISABLE_URI
783   gst_uri_handler_get_type ();
784 #endif /* GST_DISABLE_URI */
785
786   gst_structure_get_type ();
787   _gst_value_initialize ();
788   gst_caps_get_type ();
789   _gst_event_initialize ();
790   _gst_buffer_initialize ();
791   _gst_message_initialize ();
792   _gst_tag_initialize ();
793
794   /* register core plugins */
795   _gst_plugin_register_static (&plugin_desc);
796
797   _gst_plugin_initialize ();
798
799 #ifndef GST_DISABLE_REGISTRY
800   if (!ensure_current_registry ())
801     return FALSE;
802 #endif /* GST_DISABLE_REGISTRY */
803
804   /* if we need to preload plugins */
805   if (preload_plugins) {
806     g_slist_foreach (preload_plugins, load_plugin_func, NULL);
807     g_slist_free (preload_plugins);
808     preload_plugins = NULL;
809   }
810 #ifndef GST_DISABLE_TRACE
811   _gst_trace_on = 0;
812   if (_gst_trace_on) {
813     gst_trace = gst_trace_new ("gst.trace", 1024);
814     gst_trace_set_default (gst_trace);
815   }
816 #endif /* GST_DISABLE_TRACE */
817
818   return TRUE;
819 }
820
821 #ifndef GST_DISABLE_GST_DEBUG
822 static gboolean
823 select_all (GstPlugin * plugin, gpointer user_data)
824 {
825   return TRUE;
826 }
827
828 static gint
829 sort_by_category_name (gconstpointer a, gconstpointer b)
830 {
831   return strcmp (gst_debug_category_get_name ((GstDebugCategory *) a),
832       gst_debug_category_get_name ((GstDebugCategory *) b));
833 }
834 static void
835 gst_debug_help (void)
836 {
837   GSList *list, *walk;
838   GList *list2, *g;
839
840   if (!init_post ())
841     exit (1);
842
843   list2 = gst_registry_plugin_filter (gst_registry_get_default (),
844       select_all, FALSE, NULL);
845
846   /* FIXME this is gross.  why don't debug have categories PluginFeatures? */
847   for (g = list2; g; g = g_list_next (g)) {
848     GstPlugin *plugin = GST_PLUGIN_CAST (g->data);
849
850     gst_plugin_load (plugin);
851   }
852   g_list_free (list2);
853
854   list = gst_debug_get_all_categories ();
855   walk = list = g_slist_sort (list, sort_by_category_name);
856
857   g_print ("\n");
858   g_print ("name                  level    description\n");
859   g_print ("---------------------+--------+--------------------------------\n");
860
861   while (walk) {
862     GstDebugCategory *cat = (GstDebugCategory *) walk->data;
863
864     if (gst_debug_is_colored ()) {
865       gchar *color = gst_debug_construct_term_color (cat->color);
866
867       g_print ("%s%-20s\033[00m  %1d %s  %s%s\033[00m\n",
868           color,
869           gst_debug_category_get_name (cat),
870           gst_debug_category_get_threshold (cat),
871           gst_debug_level_get_name (gst_debug_category_get_threshold (cat)),
872           color, gst_debug_category_get_description (cat));
873       g_free (color);
874     } else {
875       g_print ("%-20s  %1d %s  %s\n", gst_debug_category_get_name (cat),
876           gst_debug_category_get_threshold (cat),
877           gst_debug_level_get_name (gst_debug_category_get_threshold (cat)),
878           gst_debug_category_get_description (cat));
879     }
880     walk = g_slist_next (walk);
881   }
882   g_slist_free (list);
883   g_print ("\n");
884 }
885 #endif
886
887 static gboolean
888 parse_one_option (gint opt, const gchar * arg, GError ** err)
889 {
890   switch (opt) {
891     case ARG_VERSION:
892       g_print ("GStreamer Core Library version %s\n", PACKAGE_VERSION);
893       exit (0);
894     case ARG_FATAL_WARNINGS:{
895       GLogLevelFlags fatal_mask;
896
897       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
898       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
899       g_log_set_always_fatal (fatal_mask);
900       break;
901     }
902 #ifndef GST_DISABLE_GST_DEBUG
903     case ARG_DEBUG_LEVEL:{
904       gint tmp = 0;
905
906       tmp = strtol (arg, NULL, 0);
907       if (tmp >= 0 && tmp < GST_LEVEL_COUNT) {
908         gst_debug_set_default_threshold (tmp);
909       }
910       break;
911     }
912     case ARG_DEBUG:
913       parse_debug_list (arg);
914       break;
915     case ARG_DEBUG_NO_COLOR:
916       gst_debug_set_colored (FALSE);
917       break;
918     case ARG_DEBUG_DISABLE:
919       gst_debug_set_active (FALSE);
920       break;
921     case ARG_DEBUG_HELP:
922       gst_debug_help ();
923       exit (0);
924 #endif
925     case ARG_PLUGIN_SPEW:
926       break;
927     case ARG_PLUGIN_PATH:
928 #ifndef GST_DISABLE_REGISTRY
929       split_and_iterate (arg, G_SEARCHPATH_SEPARATOR_S, add_path_func, NULL);
930 #endif /* GST_DISABLE_REGISTRY */
931       break;
932     case ARG_PLUGIN_LOAD:
933       split_and_iterate (arg, ",", prepare_for_load_plugin_func, NULL);
934       break;
935     case ARG_SEGTRAP_DISABLE:
936       _gst_disable_segtrap = TRUE;
937       break;
938     default:
939       g_set_error (err, G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
940           _("Unknown option"));
941       return FALSE;
942   }
943
944   return TRUE;
945 }
946
947 static gboolean
948 parse_goption_arg (const gchar * opt,
949     const gchar * arg, gpointer data, GError ** err)
950 {
951   const struct
952   {
953     gchar *opt;
954     int val;
955   } options[] = {
956     {
957     "--gst-version", ARG_VERSION}, {
958     "--gst-fatal-warnings", ARG_FATAL_WARNINGS},
959 #ifndef GST_DISABLE_GST_DEBUG
960     {
961     "--gst-debug-level", ARG_DEBUG_LEVEL}, {
962     "--gst-debug", ARG_DEBUG}, {
963     "--gst-debug-disable", ARG_DEBUG_DISABLE}, {
964     "--gst-debug-no-color", ARG_DEBUG_NO_COLOR}, {
965     "--gst-debug-help", ARG_DEBUG_HELP},
966 #endif
967     {
968     "--gst-plugin-spew", ARG_PLUGIN_SPEW}, {
969     "--gst-plugin-path", ARG_PLUGIN_PATH}, {
970     "--gst-plugin-load", ARG_PLUGIN_LOAD}, {
971     "--gst-disable-segtrap", ARG_SEGTRAP_DISABLE}, {
972     NULL}
973   };
974   gint val = 0, n;
975
976   for (n = 0; options[n].opt; n++) {
977     if (!strcmp (opt, options[n].opt)) {
978       val = options[n].val;
979       break;
980     }
981   }
982
983   return parse_one_option (val, arg, err);
984 }
985
986 /**
987  * gst_deinit:
988  *
989  * Clean up.
990  * Call only once, before exiting.
991  * After this call GStreamer should not be used anymore.
992  */
993
994 extern GstRegistry *_gst_registry_default;
995 void
996 gst_deinit (void)
997 {
998   GstClock *clock;
999
1000   GST_INFO ("deinitializing GStreamer");
1001   clock = gst_system_clock_obtain ();
1002   gst_object_unref (clock);
1003   gst_object_unref (clock);
1004
1005   _gst_registry_cleanup ();
1006
1007   gst_initialized = FALSE;
1008   GST_INFO ("deinitialized GStreamer");
1009 }
1010
1011 /**
1012  * gst_version:
1013  * @major: pointer to a guint to store the major version number
1014  * @minor: pointer to a guint to store the minor version number
1015  * @micro: pointer to a guint to store the micro version number
1016  * @nano:  pointer to a guint to store the nano version number
1017  *
1018  * Gets the version number of the GStreamer library.
1019  */
1020 void
1021 gst_version (guint * major, guint * minor, guint * micro, guint * nano)
1022 {
1023   g_return_if_fail (major);
1024   g_return_if_fail (minor);
1025   g_return_if_fail (micro);
1026   g_return_if_fail (nano);
1027
1028   *major = GST_VERSION_MAJOR;
1029   *minor = GST_VERSION_MINOR;
1030   *micro = GST_VERSION_MICRO;
1031   *nano = GST_VERSION_NANO;
1032 }
1033
1034 /**
1035  * gst_version_string:
1036  *
1037  * This function returns a string that is useful for describing this version
1038  * of GStreamer to the outside world: user agent strings, logging, ...
1039  *
1040  * Returns: a newly allocated string describing this version of GStreamer.
1041  */
1042
1043 gchar *
1044 gst_version_string ()
1045 {
1046   guint major, minor, micro, nano;
1047
1048   gst_version (&major, &minor, &micro, &nano);
1049   if (nano == 0)
1050     return g_strdup_printf ("GStreamer %d.%d.%d", major, minor, micro);
1051   else if (nano == 1)
1052     return g_strdup_printf ("GStreamer %d.%d.%d (CVS)", major, minor, micro);
1053   else
1054     return g_strdup_printf ("GStreamer %d.%d.%d (prerelease)", major, minor,
1055         micro);
1056 }
1057
1058 /**
1059  * gst_segtrap_is_enabled:
1060  *
1061  * Some functions in the GStreamer core might install a custom SIGSEGV handler to
1062  * better catch and report errors to the application. Currently this feature is 
1063  * enabled by default when loading plugins.
1064  *
1065  * Applications might want to disable this behaviour with the
1066  * gst_segtrap_set_enabled() function. This is typically done if the application
1067  * wants to install its own handler without GStreamer interfering.
1068  *
1069  * Returns: %TRUE if GStreamer is allowed to install a custom SIGSEGV handler.
1070  *
1071  * Since: 0.10.10
1072  */
1073 gboolean
1074 gst_segtrap_is_enabled (void)
1075 {
1076   /* yeps, it's enabled when it's not disabled */
1077   return !_gst_disable_segtrap;
1078 }
1079
1080 /**
1081  * gst_segtrap_set_enabled:
1082  * @enabled: whether a custom SIGSEGV handler should be installed.
1083  *
1084  * Applications might want to disable/enable the SIGSEGV handling of
1085  * the GStreamer core. See gst_segtrap_is_enabled() for more information.
1086  *
1087  * Since: 0.10.10
1088  */
1089 void
1090 gst_segtrap_set_enabled (gboolean enabled)
1091 {
1092   _gst_disable_segtrap = !enabled;
1093 }