Move dataurisrc element from -bad
[platform/upstream/gstreamer.git] / gst / gstinfo.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
5  * Copyright (C) 2008-2009 Tim-Philipp Müller <tim centricular net>
6  *
7  * gstinfo.c: debugging functions
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /**
26  * SECTION:gstinfo
27  * @short_description: Debugging and logging facilities
28  * @see_also: #gst-running for command line parameters
29  * and environment variables that affect the debugging output.
30  *
31  * GStreamer's debugging subsystem is an easy way to get information about what
32  * the application is doing.  It is not meant for programming errors. Use GLib
33  * methods (g_warning and friends) for that.
34  *
35  * The debugging subsystem works only after GStreamer has been initialized
36  * - for example by calling gst_init().
37  *
38  * The debugging subsystem is used to log informational messages while the
39  * application runs.  Each messages has some properties attached to it. Among
40  * these properties are the debugging category, the severity (called "level"
41  * here) and an optional #GObject it belongs to. Each of these messages is sent
42  * to all registered debugging handlers, which then handle the messages.
43  * GStreamer attaches a default handler on startup, which outputs requested
44  * messages to stderr.
45  *
46  * Messages are output by using shortcut macros like #GST_DEBUG,
47  * #GST_CAT_ERROR_OBJECT or similar. These all expand to calling gst_debug_log()
48  * with the right parameters.
49  * The only thing a developer will probably want to do is define his own
50  * categories. This is easily done with 3 lines. At the top of your code,
51  * declare
52  * the variables and set the default category.
53  * |[<!-- language="C" -->
54  *   GST_DEBUG_CATEGORY_STATIC (my_category);  // define category (statically)
55  *   #define GST_CAT_DEFAULT my_category       // set as default
56  * ]|
57  * After that you only need to initialize the category.
58  * |[<!-- language="C" -->
59  *   GST_DEBUG_CATEGORY_INIT (my_category, "my category",
60  *                            0, "This is my very own");
61  * ]|
62  * Initialization must be done before the category is used first.
63  * Plugins do this
64  * in their plugin_init function, libraries and applications should do that
65  * during their initialization.
66  *
67  * The whole debugging subsystem can be disabled at build time with passing the
68  * --disable-gst-debug switch to configure. If this is done, every function,
69  * macro and even structs described in this file evaluate to default values or
70  * nothing at all.
71  * So don't take addresses of these functions or use other tricks.
72  * If you must do that for some reason, there is still an option.
73  * If the debugging
74  * subsystem was compiled out, #GST_DISABLE_GST_DEBUG is defined in
75  * &lt;gst/gst.h&gt;,
76  * so you can check that before doing your trick.
77  * Disabling the debugging subsystem will give you a slight (read: unnoticeable)
78  * speed increase and will reduce the size of your compiled code. The GStreamer
79  * library itself becomes around 10% smaller.
80  *
81  * Please note that there are naming conventions for the names of debugging
82  * categories. These are explained at GST_DEBUG_CATEGORY_INIT().
83  */
84
85 #define GST_INFO_C
86 #include "gst_private.h"
87 #include "gstinfo.h"
88
89 #undef gst_debug_remove_log_function
90 #undef gst_debug_add_log_function
91
92 #ifndef GST_DISABLE_GST_DEBUG
93 #ifdef HAVE_DLFCN_H
94 #  include <dlfcn.h>
95 #endif
96 #include <stdio.h>              /* fprintf */
97 #include <glib/gstdio.h>
98 #include <errno.h>
99 #ifdef HAVE_UNISTD_H
100 #  include <unistd.h>           /* getpid on UNIX */
101 #endif
102 #ifdef HAVE_PROCESS_H
103 #  include <process.h>          /* getpid on win32 */
104 #endif
105 #include <string.h>             /* G_VA_COPY */
106 #ifdef G_OS_WIN32
107 #  define WIN32_LEAN_AND_MEAN   /* prevents from including too many things */
108 #  include <windows.h>          /* GetStdHandle, windows console */
109 #endif
110
111 #include "gst_private.h"
112 #include "gstutils.h"
113 #include "gstquark.h"
114 #include "gstsegment.h"
115 #include "gstvalue.h"
116 #include "gstcapsfeatures.h"
117
118 #ifdef HAVE_VALGRIND_VALGRIND_H
119 #  include <valgrind/valgrind.h>
120 #endif
121 #include <glib/gprintf.h>       /* g_sprintf */
122
123 /* our own printf implementation with custom extensions to %p for caps etc. */
124 #include "printf/printf.h"
125 #include "printf/printf-extension.h"
126
127 static char *gst_info_printf_pointer_extension_func (const char *format,
128     void *ptr);
129 #else /* GST_DISABLE_GST_DEBUG */
130
131 #include <glib/gprintf.h>
132 #endif /* !GST_DISABLE_GST_DEBUG */
133
134 #ifdef HAVE_UNWIND
135 /* No need for remote debugging so turn on the 'local only' optimizations in
136  * libunwind */
137 #define UNW_LOCAL_ONLY
138
139 #include <libunwind.h>
140 #include <stdio.h>
141 #include <stdlib.h>
142 #include <string.h>
143 #include <stdarg.h>
144 #include <unistd.h>
145 #include <errno.h>
146
147 #ifdef HAVE_DW
148 #include <elfutils/libdwfl.h>
149 #endif /* HAVE_DW */
150 #endif /* HAVE_UNWIND */
151
152 #ifdef HAVE_BACKTRACE
153 #include <execinfo.h>
154 #define BT_BUF_SIZE 100
155 #endif /* HAVE_BACKTRACE */
156
157 extern gboolean gst_is_initialized (void);
158
159 /* we want these symbols exported even if debug is disabled, to maintain
160  * ABI compatibility. Unless GST_REMOVE_DISABLED is defined. */
161 #if !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED)
162
163 /* disabled by default, as soon as some threshold is set > NONE,
164  * it becomes enabled. */
165 gboolean _gst_debug_enabled = FALSE;
166 GstDebugLevel _gst_debug_min = GST_LEVEL_NONE;
167
168 GstDebugCategory *GST_CAT_DEFAULT = NULL;
169
170 GstDebugCategory *GST_CAT_GST_INIT = NULL;
171 GstDebugCategory *GST_CAT_MEMORY = NULL;
172 GstDebugCategory *GST_CAT_PARENTAGE = NULL;
173 GstDebugCategory *GST_CAT_STATES = NULL;
174 GstDebugCategory *GST_CAT_SCHEDULING = NULL;
175
176 GstDebugCategory *GST_CAT_BUFFER = NULL;
177 GstDebugCategory *GST_CAT_BUFFER_LIST = NULL;
178 GstDebugCategory *GST_CAT_BUS = NULL;
179 GstDebugCategory *GST_CAT_CAPS = NULL;
180 GstDebugCategory *GST_CAT_CLOCK = NULL;
181 GstDebugCategory *GST_CAT_ELEMENT_PADS = NULL;
182 GstDebugCategory *GST_CAT_PADS = NULL;
183 GstDebugCategory *GST_CAT_PERFORMANCE = NULL;
184 GstDebugCategory *GST_CAT_PIPELINE = NULL;
185 GstDebugCategory *GST_CAT_PLUGIN_LOADING = NULL;
186 GstDebugCategory *GST_CAT_PLUGIN_INFO = NULL;
187 GstDebugCategory *GST_CAT_PROPERTIES = NULL;
188 GstDebugCategory *GST_CAT_NEGOTIATION = NULL;
189 GstDebugCategory *GST_CAT_REFCOUNTING = NULL;
190 GstDebugCategory *GST_CAT_ERROR_SYSTEM = NULL;
191 GstDebugCategory *GST_CAT_EVENT = NULL;
192 GstDebugCategory *GST_CAT_MESSAGE = NULL;
193 GstDebugCategory *GST_CAT_PARAMS = NULL;
194 GstDebugCategory *GST_CAT_CALL_TRACE = NULL;
195 GstDebugCategory *GST_CAT_SIGNAL = NULL;
196 GstDebugCategory *GST_CAT_PROBE = NULL;
197 GstDebugCategory *GST_CAT_REGISTRY = NULL;
198 GstDebugCategory *GST_CAT_QOS = NULL;
199 GstDebugCategory *_priv_GST_CAT_POLL = NULL;
200 GstDebugCategory *GST_CAT_META = NULL;
201 GstDebugCategory *GST_CAT_LOCKING = NULL;
202 GstDebugCategory *GST_CAT_CONTEXT = NULL;
203 GstDebugCategory *_priv_GST_CAT_PROTECTION = NULL;
204
205
206 #endif /* !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED) */
207
208 #ifndef GST_DISABLE_GST_DEBUG
209
210 /* underscore is to prevent conflict with GST_CAT_DEBUG define */
211 GST_DEBUG_CATEGORY_STATIC (_GST_CAT_DEBUG);
212
213 #if 0
214 #if defined __sgi__
215 #include <rld_interface.h>
216 typedef struct DL_INFO
217 {
218   const char *dli_fname;
219   void *dli_fbase;
220   const char *dli_sname;
221   void *dli_saddr;
222   int dli_version;
223   int dli_reserved1;
224   long dli_reserved[4];
225 }
226 Dl_info;
227
228 #define _RLD_DLADDR             14
229 int dladdr (void *address, Dl_info * dl);
230
231 int
232 dladdr (void *address, Dl_info * dl)
233 {
234   void *v;
235
236   v = _rld_new_interface (_RLD_DLADDR, address, dl);
237   return (int) v;
238 }
239 #endif /* __sgi__ */
240 #endif
241
242 static void gst_debug_reset_threshold (gpointer category, gpointer unused);
243 static void gst_debug_reset_all_thresholds (void);
244
245 struct _GstDebugMessage
246 {
247   gchar *message;
248   const gchar *format;
249   va_list arguments;
250 };
251
252 /* list of all name/level pairs from --gst-debug and GST_DEBUG */
253 static GMutex __level_name_mutex;
254 static GSList *__level_name = NULL;
255 typedef struct
256 {
257   GPatternSpec *pat;
258   GstDebugLevel level;
259 }
260 LevelNameEntry;
261
262 /* list of all categories */
263 static GMutex __cat_mutex;
264 static GSList *__categories = NULL;
265
266 static GstDebugCategory *_gst_debug_get_category_locked (const gchar * name);
267
268
269 /* all registered debug handlers */
270 typedef struct
271 {
272   GstLogFunction func;
273   gpointer user_data;
274   GDestroyNotify notify;
275 }
276 LogFuncEntry;
277 static GMutex __log_func_mutex;
278 static GSList *__log_functions = NULL;
279
280 /* whether to add the default log function in gst_init() */
281 static gboolean add_default_log_func = TRUE;
282
283 #define PRETTY_TAGS_DEFAULT  TRUE
284 static gboolean pretty_tags = PRETTY_TAGS_DEFAULT;
285
286 static volatile gint G_GNUC_MAY_ALIAS __default_level = GST_LEVEL_DEFAULT;
287 static volatile gint G_GNUC_MAY_ALIAS __use_color = GST_DEBUG_COLOR_MODE_ON;
288
289 /* FIXME: export this? */
290 gboolean
291 _priv_gst_in_valgrind (void)
292 {
293   static enum
294   {
295     GST_VG_UNCHECKED,
296     GST_VG_NO_VALGRIND,
297     GST_VG_INSIDE
298   }
299   in_valgrind = GST_VG_UNCHECKED;
300
301   if (in_valgrind == GST_VG_UNCHECKED) {
302 #ifdef HAVE_VALGRIND_VALGRIND_H
303     if (RUNNING_ON_VALGRIND) {
304       GST_CAT_INFO (GST_CAT_GST_INIT, "we're running inside valgrind");
305       in_valgrind = GST_VG_INSIDE;
306     } else {
307       GST_CAT_LOG (GST_CAT_GST_INIT, "not doing extra valgrind stuff");
308       in_valgrind = GST_VG_NO_VALGRIND;
309     }
310 #else
311     in_valgrind = GST_VG_NO_VALGRIND;
312 #endif
313     g_assert (in_valgrind == GST_VG_NO_VALGRIND ||
314         in_valgrind == GST_VG_INSIDE);
315   }
316   return (in_valgrind == GST_VG_INSIDE);
317 }
318
319 static gchar *
320 _replace_pattern_in_gst_debug_file_name (gchar * name, const char * token, guint val)
321 {
322   gchar * token_start;
323   if ((token_start = strstr (name, token))) {
324     gsize token_len = strlen (token);
325     gchar * name_prefix = name;
326     gchar * name_suffix = token_start + token_len;
327     token_start[0] = '\0';
328     name = g_strdup_printf ("%s%u%s", name_prefix, val, name_suffix);
329     g_free (name_prefix);
330   }
331   return name;
332 }
333
334 static gchar *
335 _priv_gst_debug_file_name (const gchar * env)
336 {
337   gchar *name;
338
339   name = g_strdup (env);
340   name = _replace_pattern_in_gst_debug_file_name (name, "%p", getpid ());
341   name = _replace_pattern_in_gst_debug_file_name (name, "%r", g_random_int ());
342
343   return name;
344 }
345
346 /* Initialize the debugging system */
347 void
348 _priv_gst_debug_init (void)
349 {
350   const gchar *env;
351   FILE *log_file;
352
353   if (add_default_log_func) {
354     env = g_getenv ("GST_DEBUG_FILE");
355     if (env != NULL && *env != '\0') {
356       if (strcmp (env, "-") == 0) {
357         log_file = stdout;
358       } else {
359         gchar *name = _priv_gst_debug_file_name (env);
360         log_file = g_fopen (name, "w");
361         g_free (name);
362         if (log_file == NULL) {
363           g_printerr ("Could not open log file '%s' for writing: %s\n", env,
364               g_strerror (errno));
365           log_file = stderr;
366         }
367       }
368     } else {
369       log_file = stderr;
370     }
371
372     gst_debug_add_log_function (gst_debug_log_default, log_file, NULL);
373   }
374
375   __gst_printf_pointer_extension_set_func
376       (gst_info_printf_pointer_extension_func);
377
378   /* do NOT use a single debug function before this line has been run */
379   GST_CAT_DEFAULT = _gst_debug_category_new ("default",
380       GST_DEBUG_UNDERLINE, NULL);
381   _GST_CAT_DEBUG = _gst_debug_category_new ("GST_DEBUG",
382       GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, "debugging subsystem");
383
384   /* FIXME: add descriptions here */
385   GST_CAT_GST_INIT = _gst_debug_category_new ("GST_INIT",
386       GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
387   GST_CAT_MEMORY = _gst_debug_category_new ("GST_MEMORY",
388       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, "memory");
389   GST_CAT_PARENTAGE = _gst_debug_category_new ("GST_PARENTAGE",
390       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
391   GST_CAT_STATES = _gst_debug_category_new ("GST_STATES",
392       GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
393   GST_CAT_SCHEDULING = _gst_debug_category_new ("GST_SCHEDULING",
394       GST_DEBUG_BOLD | GST_DEBUG_FG_MAGENTA, NULL);
395   GST_CAT_BUFFER = _gst_debug_category_new ("GST_BUFFER",
396       GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
397   GST_CAT_BUFFER_LIST = _gst_debug_category_new ("GST_BUFFER_LIST",
398       GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
399   GST_CAT_BUS = _gst_debug_category_new ("GST_BUS", GST_DEBUG_BG_YELLOW, NULL);
400   GST_CAT_CAPS = _gst_debug_category_new ("GST_CAPS",
401       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
402   GST_CAT_CLOCK = _gst_debug_category_new ("GST_CLOCK",
403       GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, NULL);
404   GST_CAT_ELEMENT_PADS = _gst_debug_category_new ("GST_ELEMENT_PADS",
405       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
406   GST_CAT_PADS = _gst_debug_category_new ("GST_PADS",
407       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_RED, NULL);
408   GST_CAT_PERFORMANCE = _gst_debug_category_new ("GST_PERFORMANCE",
409       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
410   GST_CAT_PIPELINE = _gst_debug_category_new ("GST_PIPELINE",
411       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
412   GST_CAT_PLUGIN_LOADING = _gst_debug_category_new ("GST_PLUGIN_LOADING",
413       GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
414   GST_CAT_PLUGIN_INFO = _gst_debug_category_new ("GST_PLUGIN_INFO",
415       GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
416   GST_CAT_PROPERTIES = _gst_debug_category_new ("GST_PROPERTIES",
417       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_BLUE, NULL);
418   GST_CAT_NEGOTIATION = _gst_debug_category_new ("GST_NEGOTIATION",
419       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
420   GST_CAT_REFCOUNTING = _gst_debug_category_new ("GST_REFCOUNTING",
421       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
422   GST_CAT_ERROR_SYSTEM = _gst_debug_category_new ("GST_ERROR_SYSTEM",
423       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_WHITE, NULL);
424
425   GST_CAT_EVENT = _gst_debug_category_new ("GST_EVENT",
426       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
427   GST_CAT_MESSAGE = _gst_debug_category_new ("GST_MESSAGE",
428       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
429   GST_CAT_PARAMS = _gst_debug_category_new ("GST_PARAMS",
430       GST_DEBUG_BOLD | GST_DEBUG_FG_BLACK | GST_DEBUG_BG_YELLOW, NULL);
431   GST_CAT_CALL_TRACE = _gst_debug_category_new ("GST_CALL_TRACE",
432       GST_DEBUG_BOLD, NULL);
433   GST_CAT_SIGNAL = _gst_debug_category_new ("GST_SIGNAL",
434       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
435   GST_CAT_PROBE = _gst_debug_category_new ("GST_PROBE",
436       GST_DEBUG_BOLD | GST_DEBUG_FG_GREEN, "pad probes");
437   GST_CAT_REGISTRY = _gst_debug_category_new ("GST_REGISTRY", 0, "registry");
438   GST_CAT_QOS = _gst_debug_category_new ("GST_QOS", 0, "QoS");
439   _priv_GST_CAT_POLL = _gst_debug_category_new ("GST_POLL", 0, "poll");
440   GST_CAT_META = _gst_debug_category_new ("GST_META", 0, "meta");
441   GST_CAT_LOCKING = _gst_debug_category_new ("GST_LOCKING", 0, "locking");
442   GST_CAT_CONTEXT = _gst_debug_category_new ("GST_CONTEXT", 0, NULL);
443   _priv_GST_CAT_PROTECTION =
444       _gst_debug_category_new ("GST_PROTECTION", 0, "protection");
445
446   /* print out the valgrind message if we're in valgrind */
447   _priv_gst_in_valgrind ();
448
449   env = g_getenv ("GST_DEBUG_OPTIONS");
450   if (env != NULL) {
451     if (strstr (env, "full_tags") || strstr (env, "full-tags"))
452       pretty_tags = FALSE;
453     else if (strstr (env, "pretty_tags") || strstr (env, "pretty-tags"))
454       pretty_tags = TRUE;
455   }
456
457   if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
458     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
459   env = g_getenv ("GST_DEBUG_COLOR_MODE");
460   if (env)
461     gst_debug_set_color_mode_from_string (env);
462
463   env = g_getenv ("GST_DEBUG");
464   if (env) {
465     gst_debug_set_threshold_from_string (env, FALSE);
466   }
467 }
468
469 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
470 #define GST_CAT_DEFAULT _GST_CAT_DEBUG
471
472 /**
473  * gst_debug_log:
474  * @category: category to log
475  * @level: level of the message is in
476  * @file: the file that emitted the message, usually the __FILE__ identifier
477  * @function: the function that emitted the message
478  * @line: the line from that the message was emitted, usually __LINE__
479  * @object: (transfer none) (allow-none): the object this message relates to,
480  *     or %NULL if none
481  * @format: a printf style format string
482  * @...: optional arguments for the format
483  *
484  * Logs the given message using the currently registered debugging handlers.
485  */
486 void
487 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
488     const gchar * file, const gchar * function, gint line,
489     GObject * object, const gchar * format, ...)
490 {
491   va_list var_args;
492
493   va_start (var_args, format);
494   gst_debug_log_valist (category, level, file, function, line, object, format,
495       var_args);
496   va_end (var_args);
497 }
498
499 /* based on g_basename(), which we can't use because it was deprecated */
500 static inline const gchar *
501 gst_path_basename (const gchar * file_name)
502 {
503   register const gchar *base;
504
505   base = strrchr (file_name, G_DIR_SEPARATOR);
506
507   {
508     const gchar *q = strrchr (file_name, '/');
509     if (base == NULL || (q != NULL && q > base))
510       base = q;
511   }
512
513   if (base)
514     return base + 1;
515
516   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
517     return file_name + 2;
518
519   return file_name;
520 }
521
522 /**
523  * gst_debug_log_valist:
524  * @category: category to log
525  * @level: level of the message is in
526  * @file: the file that emitted the message, usually the __FILE__ identifier
527  * @function: the function that emitted the message
528  * @line: the line from that the message was emitted, usually __LINE__
529  * @object: (transfer none) (allow-none): the object this message relates to,
530  *     or %NULL if none
531  * @format: a printf style format string
532  * @args: optional arguments for the format
533  *
534  * Logs the given message using the currently registered debugging handlers.
535  */
536 void
537 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
538     const gchar * file, const gchar * function, gint line,
539     GObject * object, const gchar * format, va_list args)
540 {
541   GstDebugMessage message;
542   LogFuncEntry *entry;
543   GSList *handler;
544
545   g_return_if_fail (category != NULL);
546
547   if (level > gst_debug_category_get_threshold (category))
548     return;
549
550   g_return_if_fail (file != NULL);
551   g_return_if_fail (function != NULL);
552   g_return_if_fail (format != NULL);
553
554   message.message = NULL;
555   message.format = format;
556   G_VA_COPY (message.arguments, args);
557
558   handler = __log_functions;
559   while (handler) {
560     entry = handler->data;
561     handler = g_slist_next (handler);
562     entry->func (category, level, file, function, line, object, &message,
563         entry->user_data);
564   }
565   g_free (message.message);
566   va_end (message.arguments);
567 }
568
569 /**
570  * gst_debug_message_get:
571  * @message: a debug message
572  *
573  * Gets the string representation of a #GstDebugMessage. This function is used
574  * in debug handlers to extract the message.
575  *
576  * Returns: the string representation of a #GstDebugMessage.
577  */
578 const gchar *
579 gst_debug_message_get (GstDebugMessage * message)
580 {
581   if (message->message == NULL) {
582     int len;
583
584     len = __gst_vasprintf (&message->message, message->format,
585         message->arguments);
586
587     if (len < 0)
588       message->message = NULL;
589   }
590   return message->message;
591 }
592
593 #define MAX_BUFFER_DUMP_STRING_LEN  100
594
595 /* structure_to_pretty_string:
596  * @str: a serialized #GstStructure
597  *
598  * If the serialized structure contains large buffers such as images the hex
599  * representation of those buffers will be shortened so that the string remains
600  * readable.
601  *
602  * Returns: the filtered string
603  */
604 static gchar *
605 prettify_structure_string (gchar * str)
606 {
607   gchar *pos = str, *end;
608
609   while ((pos = strstr (pos, "(buffer)"))) {
610     guint count = 0;
611
612     pos += strlen ("(buffer)");
613     for (end = pos; *end != '\0' && *end != ';' && *end != ' '; ++end)
614       ++count;
615     if (count > MAX_BUFFER_DUMP_STRING_LEN) {
616       memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 6, "..", 2);
617       memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 4, pos + count - 4, 4);
618       memmove (pos + MAX_BUFFER_DUMP_STRING_LEN, pos + count,
619           strlen (pos + count) + 1);
620       pos += MAX_BUFFER_DUMP_STRING_LEN;
621     }
622   }
623
624   return str;
625 }
626
627 static inline gchar *
628 gst_info_structure_to_string (const GstStructure * s)
629 {
630   if (G_LIKELY (s)) {
631     gchar *str = gst_structure_to_string (s);
632     if (G_UNLIKELY (pretty_tags && s->name == GST_QUARK (TAGLIST)))
633       return prettify_structure_string (str);
634     else
635       return str;
636   }
637   return NULL;
638 }
639
640 static inline gchar *
641 gst_info_describe_buffer (GstBuffer * buffer)
642 {
643   const gchar *offset_str = "none";
644   const gchar *offset_end_str = "none";
645   gchar offset_buf[32], offset_end_buf[32];
646
647   if (GST_BUFFER_OFFSET_IS_VALID (buffer)) {
648     g_snprintf (offset_buf, sizeof (offset_buf), "%" G_GUINT64_FORMAT,
649         GST_BUFFER_OFFSET (buffer));
650     offset_str = offset_buf;
651   }
652   if (GST_BUFFER_OFFSET_END_IS_VALID (buffer)) {
653     g_snprintf (offset_end_buf, sizeof (offset_end_buf), "%" G_GUINT64_FORMAT,
654         GST_BUFFER_OFFSET_END (buffer));
655     offset_end_str = offset_end_buf;
656   }
657
658   return g_strdup_printf ("buffer: %p, pts %" GST_TIME_FORMAT ", dts %"
659       GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT
660       ", offset %s, offset_end %s, flags 0x%x", buffer,
661       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
662       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
663       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
664       gst_buffer_get_size (buffer), offset_str, offset_end_str,
665       GST_BUFFER_FLAGS (buffer));
666 }
667
668 static inline gchar *
669 gst_info_describe_buffer_list (GstBufferList * list)
670 {
671   GstClockTime pts = GST_CLOCK_TIME_NONE;
672   GstClockTime dts = GST_CLOCK_TIME_NONE;
673   gsize total_size = 0;
674   guint n, i;
675
676   n = gst_buffer_list_length (list);
677   for (i = 0; i < n; ++i) {
678     GstBuffer *buf = gst_buffer_list_get (list, i);
679
680     if (i == 0) {
681       pts = GST_BUFFER_PTS (buf);
682       dts = GST_BUFFER_DTS (buf);
683     }
684
685     total_size += gst_buffer_get_size (buf);
686   }
687
688   return g_strdup_printf ("bufferlist: %p, %u buffers, pts %" GST_TIME_FORMAT
689       ", dts %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT, list, n,
690       GST_TIME_ARGS (pts), GST_TIME_ARGS (dts), total_size);
691 }
692
693 static inline gchar *
694 gst_info_describe_event (GstEvent * event)
695 {
696   gchar *s, *ret;
697
698   s = gst_info_structure_to_string (gst_event_get_structure (event));
699   ret = g_strdup_printf ("%s event: %p, time %" GST_TIME_FORMAT
700       ", seq-num %d, %s", GST_EVENT_TYPE_NAME (event), event,
701       GST_TIME_ARGS (GST_EVENT_TIMESTAMP (event)), GST_EVENT_SEQNUM (event),
702       (s ? s : "(NULL)"));
703   g_free (s);
704   return ret;
705 }
706
707 static inline gchar *
708 gst_info_describe_message (GstMessage * message)
709 {
710   gchar *s, *ret;
711
712   s = gst_info_structure_to_string (gst_message_get_structure (message));
713   ret = g_strdup_printf ("%s message: %p, time %" GST_TIME_FORMAT
714       ", seq-num %d, element '%s', %s", GST_MESSAGE_TYPE_NAME (message),
715       message, GST_TIME_ARGS (GST_MESSAGE_TIMESTAMP (message)),
716       GST_MESSAGE_SEQNUM (message),
717       ((message->src) ? GST_ELEMENT_NAME (message->src) : "(NULL)"),
718       (s ? s : "(NULL)"));
719   g_free (s);
720   return ret;
721 }
722
723 static inline gchar *
724 gst_info_describe_query (GstQuery * query)
725 {
726   gchar *s, *ret;
727
728   s = gst_info_structure_to_string (gst_query_get_structure (query));
729   ret = g_strdup_printf ("%s query: %p, %s", GST_QUERY_TYPE_NAME (query),
730       query, (s ? s : "(NULL)"));
731   g_free (s);
732   return ret;
733 }
734
735 static inline gchar *
736 gst_info_describe_stream (GstStream * stream)
737 {
738   gchar *ret, *caps_str = NULL, *tags_str = NULL;
739   GstCaps *caps;
740   GstTagList *tags;
741
742   caps = gst_stream_get_caps (stream);
743   if (caps) {
744     caps_str = gst_caps_to_string (caps);
745     gst_caps_unref (caps);
746   }
747
748   tags = gst_stream_get_tags (stream);
749   if (tags) {
750     tags_str = gst_tag_list_to_string (tags);
751     gst_tag_list_unref (tags);
752   }
753
754   ret =
755       g_strdup_printf ("stream %s %p, ID %s, flags 0x%x, caps [%s], tags [%s]",
756       gst_stream_type_get_name (gst_stream_get_stream_type (stream)), stream,
757       gst_stream_get_stream_id (stream), gst_stream_get_stream_flags (stream),
758       caps_str ? caps_str : "", tags_str ? tags_str : "");
759
760   g_free (caps_str);
761   g_free (tags_str);
762
763   return ret;
764 }
765
766 static inline gchar *
767 gst_info_describe_stream_collection (GstStreamCollection * collection)
768 {
769   gchar *ret;
770   GString *streams_str;
771   guint i;
772
773   streams_str = g_string_new ("<");
774   for (i = 0; i < gst_stream_collection_get_size (collection); i++) {
775     GstStream *stream = gst_stream_collection_get_stream (collection, i);
776     gchar *s;
777
778     s = gst_info_describe_stream (stream);
779     g_string_append_printf (streams_str, " %s,", s);
780     g_free (s);
781   }
782   g_string_append (streams_str, " >");
783
784   ret = g_strdup_printf ("collection %p (%d streams) %s", collection,
785       gst_stream_collection_get_size (collection), streams_str->str);
786
787   g_string_free (streams_str, TRUE);
788   return ret;
789 }
790
791 static gchar *
792 gst_debug_print_object (gpointer ptr)
793 {
794   GObject *object = (GObject *) ptr;
795
796 #ifdef unused
797   /* This is a cute trick to detect unmapped memory, but is unportable,
798    * slow, screws around with madvise, and not actually that useful. */
799   {
800     int ret;
801
802     ret = madvise ((void *) ((unsigned long) ptr & (~0xfff)), 4096, 0);
803     if (ret == -1 && errno == ENOMEM) {
804       buffer = g_strdup_printf ("%p (unmapped memory)", ptr);
805     }
806   }
807 #endif
808
809   /* nicely printed object */
810   if (object == NULL) {
811     return g_strdup ("(NULL)");
812   }
813   if (GST_IS_CAPS (ptr)) {
814     return gst_caps_to_string ((const GstCaps *) ptr);
815   }
816   if (GST_IS_STRUCTURE (ptr)) {
817     return gst_info_structure_to_string ((const GstStructure *) ptr);
818   }
819   if (*(GType *) ptr == GST_TYPE_CAPS_FEATURES) {
820     return gst_caps_features_to_string ((const GstCapsFeatures *) ptr);
821   }
822   if (GST_IS_TAG_LIST (ptr)) {
823     gchar *str = gst_tag_list_to_string ((GstTagList *) ptr);
824     if (G_UNLIKELY (pretty_tags))
825       return prettify_structure_string (str);
826     else
827       return str;
828   }
829   if (*(GType *) ptr == GST_TYPE_DATE_TIME) {
830     return __gst_date_time_serialize ((GstDateTime *) ptr, TRUE);
831   }
832   if (GST_IS_BUFFER (ptr)) {
833     return gst_info_describe_buffer (GST_BUFFER_CAST (ptr));
834   }
835   if (GST_IS_BUFFER_LIST (ptr)) {
836     return gst_info_describe_buffer_list (GST_BUFFER_LIST_CAST (ptr));
837   }
838 #ifdef USE_POISONING
839   if (*(guint32 *) ptr == 0xffffffff) {
840     return g_strdup_printf ("<poisoned@%p>", ptr);
841   }
842 #endif
843   if (GST_IS_MESSAGE (object)) {
844     return gst_info_describe_message (GST_MESSAGE_CAST (object));
845   }
846   if (GST_IS_QUERY (object)) {
847     return gst_info_describe_query (GST_QUERY_CAST (object));
848   }
849   if (GST_IS_EVENT (object)) {
850     return gst_info_describe_event (GST_EVENT_CAST (object));
851   }
852   if (GST_IS_CONTEXT (object)) {
853     GstContext *context = GST_CONTEXT_CAST (object);
854     gchar *s, *ret;
855     const gchar *type;
856     const GstStructure *structure;
857
858     type = gst_context_get_context_type (context);
859     structure = gst_context_get_structure (context);
860
861     s = gst_info_structure_to_string (structure);
862
863     ret = g_strdup_printf ("context '%s'='%s'", type, s);
864     g_free (s);
865     return ret;
866   }
867   if (GST_IS_STREAM (object)) {
868     return gst_info_describe_stream (GST_STREAM_CAST (object));
869   }
870   if (GST_IS_STREAM_COLLECTION (object)) {
871     return
872         gst_info_describe_stream_collection (GST_STREAM_COLLECTION_CAST
873         (object));
874   }
875   if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
876     return g_strdup_printf ("<%s:%s>", GST_DEBUG_PAD_NAME (object));
877   }
878   if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object)) {
879     return g_strdup_printf ("<%s>", GST_OBJECT_NAME (object));
880   }
881   if (G_IS_OBJECT (object)) {
882     return g_strdup_printf ("<%s@%p>", G_OBJECT_TYPE_NAME (object), object);
883   }
884
885   return g_strdup_printf ("%p", ptr);
886 }
887
888 static gchar *
889 gst_debug_print_segment (gpointer ptr)
890 {
891   GstSegment *segment = (GstSegment *) ptr;
892
893   /* nicely printed segment */
894   if (segment == NULL) {
895     return g_strdup ("(NULL)");
896   }
897
898   switch (segment->format) {
899     case GST_FORMAT_UNDEFINED:{
900       return g_strdup_printf ("UNDEFINED segment");
901     }
902     case GST_FORMAT_TIME:{
903       return g_strdup_printf ("time segment start=%" GST_TIME_FORMAT
904           ", offset=%" GST_TIME_FORMAT ", stop=%" GST_TIME_FORMAT
905           ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" GST_TIME_FORMAT
906           ", base=%" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT
907           ", duration %" GST_TIME_FORMAT, GST_TIME_ARGS (segment->start),
908           GST_TIME_ARGS (segment->offset), GST_TIME_ARGS (segment->stop),
909           segment->rate, segment->applied_rate, (guint) segment->flags,
910           GST_TIME_ARGS (segment->time), GST_TIME_ARGS (segment->base),
911           GST_TIME_ARGS (segment->position), GST_TIME_ARGS (segment->duration));
912     }
913     default:{
914       const gchar *format_name;
915
916       format_name = gst_format_get_name (segment->format);
917       if (G_UNLIKELY (format_name == NULL))
918         format_name = "(UNKNOWN FORMAT)";
919       return g_strdup_printf ("%s segment start=%" G_GINT64_FORMAT
920           ", offset=%" G_GINT64_FORMAT ", stop=%" G_GINT64_FORMAT
921           ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" G_GINT64_FORMAT
922           ", base=%" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT
923           ", duration %" G_GINT64_FORMAT, format_name, segment->start,
924           segment->offset, segment->stop, segment->rate, segment->applied_rate,
925           (guint) segment->flags, segment->time, segment->base,
926           segment->position, segment->duration);
927     }
928   }
929 }
930
931 static char *
932 gst_info_printf_pointer_extension_func (const char *format, void *ptr)
933 {
934   char *s = NULL;
935
936   if (format[0] == 'p' && format[1] == '\a') {
937     switch (format[2]) {
938       case 'A':                /* GST_PTR_FORMAT     */
939         s = gst_debug_print_object (ptr);
940         break;
941       case 'B':                /* GST_SEGMENT_FORMAT */
942         s = gst_debug_print_segment (ptr);
943         break;
944       case 'a':                /* GST_WRAPPED_PTR_FORMAT */
945         s = priv_gst_string_take_and_wrap (gst_debug_print_object (ptr));
946         break;
947       default:
948         /* must have been compiled against a newer version with an extension
949          * we don't known about yet - just ignore and fallback to %p below */
950         break;
951     }
952   }
953   if (s == NULL)
954     s = g_strdup_printf ("%p", ptr);
955
956   return s;
957 }
958
959 /**
960  * gst_debug_construct_term_color:
961  * @colorinfo: the color info
962  *
963  * Constructs a string that can be used for getting the desired color in color
964  * terminals.
965  * You need to free the string after use.
966  *
967  * Returns: (transfer full) (type gchar*): a string containing the color
968  *     definition
969  */
970 gchar *
971 gst_debug_construct_term_color (guint colorinfo)
972 {
973   GString *color;
974
975   color = g_string_new ("\033[00");
976
977   if (colorinfo & GST_DEBUG_BOLD) {
978     g_string_append_len (color, ";01", 3);
979   }
980   if (colorinfo & GST_DEBUG_UNDERLINE) {
981     g_string_append_len (color, ";04", 3);
982   }
983   if (colorinfo & GST_DEBUG_FG_MASK) {
984     g_string_append_printf (color, ";3%1d", colorinfo & GST_DEBUG_FG_MASK);
985   }
986   if (colorinfo & GST_DEBUG_BG_MASK) {
987     g_string_append_printf (color, ";4%1d",
988         (colorinfo & GST_DEBUG_BG_MASK) >> 4);
989   }
990   g_string_append_c (color, 'm');
991
992   return g_string_free (color, FALSE);
993 }
994
995 /**
996  * gst_debug_construct_win_color:
997  * @colorinfo: the color info
998  *
999  * Constructs an integer that can be used for getting the desired color in
1000  * windows' terminals (cmd.exe). As there is no mean to underline, we simply
1001  * ignore this attribute.
1002  *
1003  * This function returns 0 on non-windows machines.
1004  *
1005  * Returns: an integer containing the color definition
1006  */
1007 gint
1008 gst_debug_construct_win_color (guint colorinfo)
1009 {
1010   gint color = 0;
1011 #ifdef G_OS_WIN32
1012   static const guchar ansi_to_win_fg[8] = {
1013     0,                          /* black   */
1014     FOREGROUND_RED,             /* red     */
1015     FOREGROUND_GREEN,           /* green   */
1016     FOREGROUND_RED | FOREGROUND_GREEN,  /* yellow  */
1017     FOREGROUND_BLUE,            /* blue    */
1018     FOREGROUND_RED | FOREGROUND_BLUE,   /* magenta */
1019     FOREGROUND_GREEN | FOREGROUND_BLUE, /* cyan    */
1020     FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE /* white   */
1021   };
1022   static const guchar ansi_to_win_bg[8] = {
1023     0,
1024     BACKGROUND_RED,
1025     BACKGROUND_GREEN,
1026     BACKGROUND_RED | BACKGROUND_GREEN,
1027     BACKGROUND_BLUE,
1028     BACKGROUND_RED | BACKGROUND_BLUE,
1029     BACKGROUND_GREEN | FOREGROUND_BLUE,
1030     BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
1031   };
1032
1033   /* we draw black as white, as cmd.exe can only have black bg */
1034   if ((colorinfo & (GST_DEBUG_FG_MASK | GST_DEBUG_BG_MASK)) == 0) {
1035     color = ansi_to_win_fg[7];
1036   }
1037   if (colorinfo & GST_DEBUG_UNDERLINE) {
1038     color |= BACKGROUND_INTENSITY;
1039   }
1040   if (colorinfo & GST_DEBUG_BOLD) {
1041     color |= FOREGROUND_INTENSITY;
1042   }
1043   if (colorinfo & GST_DEBUG_FG_MASK) {
1044     color |= ansi_to_win_fg[colorinfo & GST_DEBUG_FG_MASK];
1045   }
1046   if (colorinfo & GST_DEBUG_BG_MASK) {
1047     color |= ansi_to_win_bg[(colorinfo & GST_DEBUG_BG_MASK) >> 4];
1048   }
1049 #endif
1050   return color;
1051 }
1052
1053 /* width of %p varies depending on actual value of pointer, which can make
1054  * output unevenly aligned if multiple threads are involved, hence the %14p
1055  * (should really be %18p, but %14p seems a good compromise between too many
1056  * white spaces and likely unalignment on my system) */
1057 #if defined (GLIB_SIZEOF_VOID_P) && GLIB_SIZEOF_VOID_P == 8
1058 #define PTR_FMT "%14p"
1059 #else
1060 #define PTR_FMT "%10p"
1061 #endif
1062 #define PID_FMT "%5d"
1063 #define CAT_FMT "%20s %s:%d:%s:%s"
1064
1065 #ifdef G_OS_WIN32
1066 static const guchar levelcolormap_w32[GST_LEVEL_COUNT] = {
1067   /* GST_LEVEL_NONE */
1068   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1069   /* GST_LEVEL_ERROR */
1070   FOREGROUND_RED | FOREGROUND_INTENSITY,
1071   /* GST_LEVEL_WARNING */
1072   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1073   /* GST_LEVEL_INFO */
1074   FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1075   /* GST_LEVEL_DEBUG */
1076   FOREGROUND_GREEN | FOREGROUND_BLUE,
1077   /* GST_LEVEL_LOG */
1078   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1079   /* GST_LEVEL_FIXME */
1080   FOREGROUND_RED | FOREGROUND_GREEN,
1081   /* GST_LEVEL_TRACE */
1082   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1083   /* placeholder for log level 8 */
1084   0,
1085   /* GST_LEVEL_MEMDUMP */
1086   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
1087 };
1088
1089 static const guchar available_colors[] = {
1090   FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_RED | FOREGROUND_GREEN,
1091   FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_BLUE,
1092   FOREGROUND_GREEN | FOREGROUND_BLUE,
1093 };
1094 #endif /* G_OS_WIN32 */
1095 static const gchar *levelcolormap[GST_LEVEL_COUNT] = {
1096   "\033[37m",                   /* GST_LEVEL_NONE */
1097   "\033[31;01m",                /* GST_LEVEL_ERROR */
1098   "\033[33;01m",                /* GST_LEVEL_WARNING */
1099   "\033[32;01m",                /* GST_LEVEL_INFO */
1100   "\033[36m",                   /* GST_LEVEL_DEBUG */
1101   "\033[37m",                   /* GST_LEVEL_LOG */
1102   "\033[33;01m",                /* GST_LEVEL_FIXME */
1103   "\033[37m",                   /* GST_LEVEL_TRACE */
1104   "\033[37m",                   /* placeholder for log level 8 */
1105   "\033[37m"                    /* GST_LEVEL_MEMDUMP */
1106 };
1107
1108 /**
1109  * gst_debug_log_default:
1110  * @category: category to log
1111  * @level: level of the message
1112  * @file: the file that emitted the message, usually the __FILE__ identifier
1113  * @function: the function that emitted the message
1114  * @line: the line from that the message was emitted, usually __LINE__
1115  * @message: the actual message
1116  * @object: (transfer none) (allow-none): the object this message relates to,
1117  *     or %NULL if none
1118  * @user_data: the FILE* to log to
1119  *
1120  * The default logging handler used by GStreamer. Logging functions get called
1121  * whenever a macro like GST_DEBUG or similar is used. By default this function
1122  * is setup to output the message and additional info to stderr (or the log file
1123  * specified via the GST_DEBUG_FILE environment variable) as received via
1124  * @user_data.
1125  *
1126  * You can add other handlers by using gst_debug_add_log_function().
1127  * And you can remove this handler by calling
1128  * gst_debug_remove_log_function(gst_debug_log_default);
1129  */
1130 void
1131 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
1132     const gchar * file, const gchar * function, gint line,
1133     GObject * object, GstDebugMessage * message, gpointer user_data)
1134 {
1135   gint pid;
1136   GstClockTime elapsed;
1137   gchar *obj = NULL;
1138   GstDebugColorMode color_mode;
1139   FILE *log_file = user_data ? user_data : stderr;
1140   gchar c;
1141
1142   /* __FILE__ might be a file name or an absolute path or a
1143    * relative path, irrespective of the exact compiler used,
1144    * in which case we want to shorten it to the filename for
1145    * readability. */
1146   c = file[0];
1147   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
1148     file = gst_path_basename (file);
1149   }
1150
1151   pid = getpid ();
1152   color_mode = gst_debug_get_color_mode ();
1153
1154   if (object) {
1155     obj = gst_debug_print_object (object);
1156   } else {
1157     obj = (gchar *) "";
1158   }
1159
1160   elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
1161
1162   if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
1163 #ifdef G_OS_WIN32
1164     /* We take a lock to keep colors and content together.
1165      * Maybe there is a better way but for now this will do the right
1166      * thing. */
1167     static GMutex win_print_mutex;
1168     g_mutex_lock (&win_print_mutex);
1169     if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
1170 #endif
1171       /* colors, non-windows */
1172       gchar *color = NULL;
1173       const gchar *clear;
1174       gchar pidcolor[10];
1175       const gchar *levelcolor;
1176
1177       color = gst_debug_construct_term_color (gst_debug_category_get_color
1178           (category));
1179       clear = "\033[00m";
1180       g_sprintf (pidcolor, "\033[3%1dm", pid % 6 + 31);
1181       levelcolor = levelcolormap[level];
1182
1183 #define PRINT_FMT " %s"PID_FMT"%s "PTR_FMT" %s%s%s %s"CAT_FMT"%s %s\n"
1184       fprintf (log_file, "%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
1185           pidcolor, pid, clear, g_thread_self (), levelcolor,
1186           gst_debug_level_get_name (level), clear, color,
1187           gst_debug_category_get_name (category), file, line, function, obj,
1188           clear, gst_debug_message_get (message));
1189       fflush (log_file);
1190 #undef PRINT_FMT
1191       g_free (color);
1192 #ifdef G_OS_WIN32
1193     } else {
1194       /* colors, windows. */
1195       const gint clear = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
1196 #define SET_COLOR(c) G_STMT_START { \
1197   if (log_file == stderr) \
1198     SetConsoleTextAttribute (GetStdHandle (STD_ERROR_HANDLE), (c)); \
1199   } G_STMT_END
1200       /* timestamp */
1201       fprintf (log_file, "%" GST_TIME_FORMAT " ", GST_TIME_ARGS (elapsed));
1202       fflush (log_file);
1203       /* pid */
1204       SET_COLOR (available_colors[pid % G_N_ELEMENTS (available_colors)]);
1205       fprintf (log_file, PID_FMT, pid);
1206       fflush (log_file);
1207       /* thread */
1208       SET_COLOR (clear);
1209       fprintf (log_file, " " PTR_FMT " ", g_thread_self ());
1210       fflush (log_file);
1211       /* level */
1212       SET_COLOR (levelcolormap_w32[level]);
1213       fprintf (log_file, "%s ", gst_debug_level_get_name (level));
1214       fflush (log_file);
1215       /* category */
1216       SET_COLOR (gst_debug_construct_win_color (gst_debug_category_get_color
1217               (category)));
1218       fprintf (log_file, CAT_FMT, gst_debug_category_get_name (category),
1219           file, line, function, obj);
1220       fflush (log_file);
1221       /* message */
1222       SET_COLOR (clear);
1223       fprintf (log_file, " %s\n", gst_debug_message_get (message));
1224       fflush (log_file);
1225     }
1226     g_mutex_unlock (&win_print_mutex);
1227 #endif
1228   } else {
1229     /* no color, all platforms */
1230 #define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
1231     fprintf (log_file, "%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
1232         pid, g_thread_self (), gst_debug_level_get_name (level),
1233         gst_debug_category_get_name (category), file, line, function, obj,
1234         gst_debug_message_get (message));
1235     fflush (log_file);
1236 #undef PRINT_FMT
1237   }
1238
1239   if (object != NULL)
1240     g_free (obj);
1241 }
1242
1243 /**
1244  * gst_debug_level_get_name:
1245  * @level: the level to get the name for
1246  *
1247  * Get the string representation of a debugging level
1248  *
1249  * Returns: the name
1250  */
1251 const gchar *
1252 gst_debug_level_get_name (GstDebugLevel level)
1253 {
1254   switch (level) {
1255     case GST_LEVEL_NONE:
1256       return "";
1257     case GST_LEVEL_ERROR:
1258       return "ERROR  ";
1259     case GST_LEVEL_WARNING:
1260       return "WARN   ";
1261     case GST_LEVEL_INFO:
1262       return "INFO   ";
1263     case GST_LEVEL_DEBUG:
1264       return "DEBUG  ";
1265     case GST_LEVEL_LOG:
1266       return "LOG    ";
1267     case GST_LEVEL_FIXME:
1268       return "FIXME  ";
1269     case GST_LEVEL_TRACE:
1270       return "TRACE  ";
1271     case GST_LEVEL_MEMDUMP:
1272       return "MEMDUMP";
1273     default:
1274       g_warning ("invalid level specified for gst_debug_level_get_name");
1275       return "";
1276   }
1277 }
1278
1279 /**
1280  * gst_debug_add_log_function:
1281  * @func: the function to use
1282  * @user_data: user data
1283  * @notify: called when @user_data is not used anymore
1284  *
1285  * Adds the logging function to the list of logging functions.
1286  * Be sure to use #G_GNUC_NO_INSTRUMENT on that function, it is needed.
1287  */
1288 void
1289 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
1290     GDestroyNotify notify)
1291 {
1292   LogFuncEntry *entry;
1293   GSList *list;
1294
1295   if (func == NULL)
1296     func = gst_debug_log_default;
1297
1298   entry = g_slice_new (LogFuncEntry);
1299   entry->func = func;
1300   entry->user_data = user_data;
1301   entry->notify = notify;
1302   /* FIXME: we leak the old list here - other threads might access it right now
1303    * in gst_debug_logv. Another solution is to lock the mutex in gst_debug_logv,
1304    * but that is waaay costly.
1305    * It'd probably be clever to use some kind of RCU here, but I don't know
1306    * anything about that.
1307    */
1308   g_mutex_lock (&__log_func_mutex);
1309   list = g_slist_copy (__log_functions);
1310   __log_functions = g_slist_prepend (list, entry);
1311   g_mutex_unlock (&__log_func_mutex);
1312
1313   if (gst_is_initialized ())
1314     GST_DEBUG ("prepended log function %p (user data %p) to log functions",
1315         func, user_data);
1316 }
1317
1318 static gint
1319 gst_debug_compare_log_function_by_func (gconstpointer entry, gconstpointer func)
1320 {
1321   gpointer entryfunc = (gpointer) (((LogFuncEntry *) entry)->func);
1322
1323   return (entryfunc < func) ? -1 : (entryfunc > func) ? 1 : 0;
1324 }
1325
1326 static gint
1327 gst_debug_compare_log_function_by_data (gconstpointer entry, gconstpointer data)
1328 {
1329   gpointer entrydata = ((LogFuncEntry *) entry)->user_data;
1330
1331   return (entrydata < data) ? -1 : (entrydata > data) ? 1 : 0;
1332 }
1333
1334 static guint
1335 gst_debug_remove_with_compare_func (GCompareFunc func, gpointer data)
1336 {
1337   GSList *found;
1338   GSList *new, *cleanup = NULL;
1339   guint removals = 0;
1340
1341   g_mutex_lock (&__log_func_mutex);
1342   new = __log_functions;
1343   cleanup = NULL;
1344   while ((found = g_slist_find_custom (new, data, func))) {
1345     if (new == __log_functions) {
1346       /* make a copy when we have the first hit, so that we modify the copy and
1347        * make that the new list later */
1348       new = g_slist_copy (new);
1349       continue;
1350     }
1351     cleanup = g_slist_prepend (cleanup, found->data);
1352     new = g_slist_delete_link (new, found);
1353     removals++;
1354   }
1355   /* FIXME: We leak the old list here. See _add_log_function for why. */
1356   __log_functions = new;
1357   g_mutex_unlock (&__log_func_mutex);
1358
1359   while (cleanup) {
1360     LogFuncEntry *entry = cleanup->data;
1361
1362     if (entry->notify)
1363       entry->notify (entry->user_data);
1364
1365     g_slice_free (LogFuncEntry, entry);
1366     cleanup = g_slist_delete_link (cleanup, cleanup);
1367   }
1368   return removals;
1369 }
1370
1371 /**
1372  * gst_debug_remove_log_function:
1373  * @func: (scope call) (allow-none): the log function to remove, or %NULL to
1374  *     remove the default log function
1375  *
1376  * Removes all registered instances of the given logging functions.
1377  *
1378  * Returns: How many instances of the function were removed
1379  */
1380 guint
1381 gst_debug_remove_log_function (GstLogFunction func)
1382 {
1383   guint removals;
1384
1385   if (func == NULL)
1386     func = gst_debug_log_default;
1387
1388   removals =
1389       gst_debug_remove_with_compare_func
1390       (gst_debug_compare_log_function_by_func, (gpointer) func);
1391
1392   if (gst_is_initialized ()) {
1393     GST_DEBUG ("removed log function %p %d times from log function list", func,
1394         removals);
1395   } else {
1396     /* If the default log function is removed before gst_init() was called,
1397      * set a flag so we don't add it in gst_init() later */
1398     if (func == gst_debug_log_default) {
1399       add_default_log_func = FALSE;
1400       ++removals;
1401     }
1402   }
1403
1404   return removals;
1405 }
1406
1407 /**
1408  * gst_debug_remove_log_function_by_data:
1409  * @data: user data of the log function to remove
1410  *
1411  * Removes all registered instances of log functions with the given user data.
1412  *
1413  * Returns: How many instances of the function were removed
1414  */
1415 guint
1416 gst_debug_remove_log_function_by_data (gpointer data)
1417 {
1418   guint removals;
1419
1420   removals =
1421       gst_debug_remove_with_compare_func
1422       (gst_debug_compare_log_function_by_data, data);
1423
1424   if (gst_is_initialized ())
1425     GST_DEBUG
1426         ("removed %d log functions with user data %p from log function list",
1427         removals, data);
1428
1429   return removals;
1430 }
1431
1432 /**
1433  * gst_debug_set_colored:
1434  * @colored: Whether to use colored output or not
1435  *
1436  * Sets or unsets the use of coloured debugging output.
1437  * Same as gst_debug_set_color_mode () with the argument being
1438  * being GST_DEBUG_COLOR_MODE_ON or GST_DEBUG_COLOR_MODE_OFF.
1439  *
1440  * This function may be called before gst_init().
1441  */
1442 void
1443 gst_debug_set_colored (gboolean colored)
1444 {
1445   GstDebugColorMode new_mode;
1446   new_mode = colored ? GST_DEBUG_COLOR_MODE_ON : GST_DEBUG_COLOR_MODE_OFF;
1447   g_atomic_int_set (&__use_color, (gint) new_mode);
1448 }
1449
1450 /**
1451  * gst_debug_set_color_mode:
1452  * @mode: The coloring mode for debug output. See @GstDebugColorMode.
1453  *
1454  * Changes the coloring mode for debug output.
1455  *
1456  * This function may be called before gst_init().
1457  *
1458  * Since: 1.2
1459  */
1460 void
1461 gst_debug_set_color_mode (GstDebugColorMode mode)
1462 {
1463   g_atomic_int_set (&__use_color, mode);
1464 }
1465
1466 /**
1467  * gst_debug_set_color_mode_from_string:
1468  * @mode: The coloring mode for debug output. One of the following:
1469  * "on", "auto", "off", "disable", "unix".
1470  *
1471  * Changes the coloring mode for debug output.
1472  *
1473  * This function may be called before gst_init().
1474  *
1475  * Since: 1.2
1476  */
1477 void
1478 gst_debug_set_color_mode_from_string (const gchar * mode)
1479 {
1480   if ((strcmp (mode, "on") == 0) || (strcmp (mode, "auto") == 0))
1481     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_ON);
1482   else if ((strcmp (mode, "off") == 0) || (strcmp (mode, "disable") == 0))
1483     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
1484   else if (strcmp (mode, "unix") == 0)
1485     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_UNIX);
1486 }
1487
1488 /**
1489  * gst_debug_is_colored:
1490  *
1491  * Checks if the debugging output should be colored.
1492  *
1493  * Returns: %TRUE, if the debug output should be colored.
1494  */
1495 gboolean
1496 gst_debug_is_colored (void)
1497 {
1498   GstDebugColorMode mode = g_atomic_int_get (&__use_color);
1499   return (mode == GST_DEBUG_COLOR_MODE_UNIX || mode == GST_DEBUG_COLOR_MODE_ON);
1500 }
1501
1502 /**
1503  * gst_debug_get_color_mode:
1504  *
1505  * Changes the coloring mode for debug output.
1506  *
1507  * Returns: see @GstDebugColorMode for possible values.
1508  *
1509  * Since: 1.2
1510  */
1511 GstDebugColorMode
1512 gst_debug_get_color_mode (void)
1513 {
1514   return g_atomic_int_get (&__use_color);
1515 }
1516
1517 /**
1518  * gst_debug_set_active:
1519  * @active: Whether to use debugging output or not
1520  *
1521  * If activated, debugging messages are sent to the debugging
1522  * handlers.
1523  * It makes sense to deactivate it for speed issues.
1524  * <note><para>This function is not threadsafe. It makes sense to only call it
1525  * during initialization.</para></note>
1526  */
1527 void
1528 gst_debug_set_active (gboolean active)
1529 {
1530   _gst_debug_enabled = active;
1531   if (active)
1532     _gst_debug_min = GST_LEVEL_COUNT;
1533   else
1534     _gst_debug_min = GST_LEVEL_NONE;
1535 }
1536
1537 /**
1538  * gst_debug_is_active:
1539  *
1540  * Checks if debugging output is activated.
1541  *
1542  * Returns: %TRUE, if debugging is activated
1543  */
1544 gboolean
1545 gst_debug_is_active (void)
1546 {
1547   return _gst_debug_enabled;
1548 }
1549
1550 /**
1551  * gst_debug_set_default_threshold:
1552  * @level: level to set
1553  *
1554  * Sets the default threshold to the given level and updates all categories to
1555  * use this threshold.
1556  *
1557  * This function may be called before gst_init().
1558  */
1559 void
1560 gst_debug_set_default_threshold (GstDebugLevel level)
1561 {
1562   g_atomic_int_set (&__default_level, level);
1563   gst_debug_reset_all_thresholds ();
1564 }
1565
1566 /**
1567  * gst_debug_get_default_threshold:
1568  *
1569  * Returns the default threshold that is used for new categories.
1570  *
1571  * Returns: the default threshold level
1572  */
1573 GstDebugLevel
1574 gst_debug_get_default_threshold (void)
1575 {
1576   return (GstDebugLevel) g_atomic_int_get (&__default_level);
1577 }
1578
1579 static void
1580 gst_debug_reset_threshold (gpointer category, gpointer unused)
1581 {
1582   GstDebugCategory *cat = (GstDebugCategory *) category;
1583   GSList *walk;
1584
1585   g_mutex_lock (&__level_name_mutex);
1586   walk = __level_name;
1587   while (walk) {
1588     LevelNameEntry *entry = walk->data;
1589
1590     walk = g_slist_next (walk);
1591     if (g_pattern_match_string (entry->pat, cat->name)) {
1592       if (gst_is_initialized ())
1593         GST_LOG ("category %s matches pattern %p - gets set to level %d",
1594             cat->name, entry->pat, entry->level);
1595       gst_debug_category_set_threshold (cat, entry->level);
1596       goto exit;
1597     }
1598   }
1599   gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
1600
1601 exit:
1602   g_mutex_unlock (&__level_name_mutex);
1603 }
1604
1605 static void
1606 gst_debug_reset_all_thresholds (void)
1607 {
1608   g_mutex_lock (&__cat_mutex);
1609   g_slist_foreach (__categories, gst_debug_reset_threshold, NULL);
1610   g_mutex_unlock (&__cat_mutex);
1611 }
1612
1613 static void
1614 for_each_threshold_by_entry (gpointer data, gpointer user_data)
1615 {
1616   GstDebugCategory *cat = (GstDebugCategory *) data;
1617   LevelNameEntry *entry = (LevelNameEntry *) user_data;
1618
1619   if (g_pattern_match_string (entry->pat, cat->name)) {
1620     if (gst_is_initialized ())
1621       GST_LOG ("category %s matches pattern %p - gets set to level %d",
1622           cat->name, entry->pat, entry->level);
1623     gst_debug_category_set_threshold (cat, entry->level);
1624   }
1625 }
1626
1627 /**
1628  * gst_debug_set_threshold_for_name:
1629  * @name: name of the categories to set
1630  * @level: level to set them to
1631  *
1632  * Sets all categories which match the given glob style pattern to the given
1633  * level.
1634  */
1635 void
1636 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
1637 {
1638   GPatternSpec *pat;
1639   LevelNameEntry *entry;
1640
1641   g_return_if_fail (name != NULL);
1642
1643   pat = g_pattern_spec_new (name);
1644   entry = g_slice_new (LevelNameEntry);
1645   entry->pat = pat;
1646   entry->level = level;
1647   g_mutex_lock (&__level_name_mutex);
1648   __level_name = g_slist_prepend (__level_name, entry);
1649   g_mutex_unlock (&__level_name_mutex);
1650   g_mutex_lock (&__cat_mutex);
1651   g_slist_foreach (__categories, for_each_threshold_by_entry, entry);
1652   g_mutex_unlock (&__cat_mutex);
1653 }
1654
1655 /**
1656  * gst_debug_unset_threshold_for_name:
1657  * @name: name of the categories to set
1658  *
1659  * Resets all categories with the given name back to the default level.
1660  */
1661 void
1662 gst_debug_unset_threshold_for_name (const gchar * name)
1663 {
1664   GSList *walk;
1665   GPatternSpec *pat;
1666
1667   g_return_if_fail (name != NULL);
1668
1669   pat = g_pattern_spec_new (name);
1670   g_mutex_lock (&__level_name_mutex);
1671   walk = __level_name;
1672   /* improve this if you want, it's mighty slow */
1673   while (walk) {
1674     LevelNameEntry *entry = walk->data;
1675
1676     if (g_pattern_spec_equal (entry->pat, pat)) {
1677       __level_name = g_slist_remove_link (__level_name, walk);
1678       g_pattern_spec_free (entry->pat);
1679       g_slice_free (LevelNameEntry, entry);
1680       g_slist_free_1 (walk);
1681       walk = __level_name;
1682     } else {
1683       walk = g_slist_next (walk);
1684     }
1685   }
1686   g_mutex_unlock (&__level_name_mutex);
1687   g_pattern_spec_free (pat);
1688   gst_debug_reset_all_thresholds ();
1689 }
1690
1691 GstDebugCategory *
1692 _gst_debug_category_new (const gchar * name, guint color,
1693     const gchar * description)
1694 {
1695   GstDebugCategory *cat, *catfound;
1696
1697   g_return_val_if_fail (name != NULL, NULL);
1698
1699   cat = g_slice_new (GstDebugCategory);
1700   cat->name = g_strdup (name);
1701   cat->color = color;
1702   if (description != NULL) {
1703     cat->description = g_strdup (description);
1704   } else {
1705     cat->description = g_strdup ("no description");
1706   }
1707   g_atomic_int_set (&cat->threshold, 0);
1708   gst_debug_reset_threshold (cat, NULL);
1709
1710   /* add to category list */
1711   g_mutex_lock (&__cat_mutex);
1712   catfound = _gst_debug_get_category_locked (name);
1713   if (catfound) {
1714     g_free ((gpointer) cat->name);
1715     g_free ((gpointer) cat->description);
1716     g_slice_free (GstDebugCategory, cat);
1717     cat = catfound;
1718   } else {
1719     __categories = g_slist_prepend (__categories, cat);
1720   }
1721   g_mutex_unlock (&__cat_mutex);
1722
1723   return cat;
1724 }
1725
1726 /**
1727  * gst_debug_category_free:
1728  * @category: #GstDebugCategory to free.
1729  *
1730  * Removes and frees the category and all associated resources.
1731  */
1732 void
1733 gst_debug_category_free (GstDebugCategory * category)
1734 {
1735   if (category == NULL)
1736     return;
1737
1738   /* remove from category list */
1739   g_mutex_lock (&__cat_mutex);
1740   __categories = g_slist_remove (__categories, category);
1741   g_mutex_unlock (&__cat_mutex);
1742
1743   g_free ((gpointer) category->name);
1744   g_free ((gpointer) category->description);
1745   g_slice_free (GstDebugCategory, category);
1746 }
1747
1748 /**
1749  * gst_debug_category_set_threshold:
1750  * @category: a #GstDebugCategory to set threshold of.
1751  * @level: the #GstDebugLevel threshold to set.
1752  *
1753  * Sets the threshold of the category to the given level. Debug information will
1754  * only be output if the threshold is lower or equal to the level of the
1755  * debugging message.
1756  * <note><para>
1757  * Do not use this function in production code, because other functions may
1758  * change the threshold of categories as side effect. It is however a nice
1759  * function to use when debugging (even from gdb).
1760  * </para></note>
1761  */
1762 void
1763 gst_debug_category_set_threshold (GstDebugCategory * category,
1764     GstDebugLevel level)
1765 {
1766   g_return_if_fail (category != NULL);
1767
1768   if (level > _gst_debug_min) {
1769     _gst_debug_enabled = TRUE;
1770     _gst_debug_min = level;
1771   }
1772
1773   g_atomic_int_set (&category->threshold, level);
1774 }
1775
1776 /**
1777  * gst_debug_category_reset_threshold:
1778  * @category: a #GstDebugCategory to reset threshold of.
1779  *
1780  * Resets the threshold of the category to the default level. Debug information
1781  * will only be output if the threshold is lower or equal to the level of the
1782  * debugging message.
1783  * Use this function to set the threshold back to where it was after using
1784  * gst_debug_category_set_threshold().
1785  */
1786 void
1787 gst_debug_category_reset_threshold (GstDebugCategory * category)
1788 {
1789   gst_debug_reset_threshold (category, NULL);
1790 }
1791
1792 /**
1793  * gst_debug_category_get_threshold:
1794  * @category: a #GstDebugCategory to get threshold of.
1795  *
1796  * Returns the threshold of a #GstDebugCategory.
1797  *
1798  * Returns: the #GstDebugLevel that is used as threshold.
1799  */
1800 GstDebugLevel
1801 gst_debug_category_get_threshold (GstDebugCategory * category)
1802 {
1803   return (GstDebugLevel) g_atomic_int_get (&category->threshold);
1804 }
1805
1806 /**
1807  * gst_debug_category_get_name:
1808  * @category: a #GstDebugCategory to get name of.
1809  *
1810  * Returns the name of a debug category.
1811  *
1812  * Returns: the name of the category.
1813  */
1814 const gchar *
1815 gst_debug_category_get_name (GstDebugCategory * category)
1816 {
1817   return category->name;
1818 }
1819
1820 /**
1821  * gst_debug_category_get_color:
1822  * @category: a #GstDebugCategory to get the color of.
1823  *
1824  * Returns the color of a debug category used when printing output in this
1825  * category.
1826  *
1827  * Returns: the color of the category.
1828  */
1829 guint
1830 gst_debug_category_get_color (GstDebugCategory * category)
1831 {
1832   return category->color;
1833 }
1834
1835 /**
1836  * gst_debug_category_get_description:
1837  * @category: a #GstDebugCategory to get the description of.
1838  *
1839  * Returns the description of a debug category.
1840  *
1841  * Returns: the description of the category.
1842  */
1843 const gchar *
1844 gst_debug_category_get_description (GstDebugCategory * category)
1845 {
1846   return category->description;
1847 }
1848
1849 /**
1850  * gst_debug_get_all_categories:
1851  *
1852  * Returns a snapshot of a all categories that are currently in use . This list
1853  * may change anytime.
1854  * The caller has to free the list after use.
1855  *
1856  * Returns: (transfer container) (element-type Gst.DebugCategory): the list of
1857  *     debug categories
1858  */
1859 GSList *
1860 gst_debug_get_all_categories (void)
1861 {
1862   GSList *ret;
1863
1864   g_mutex_lock (&__cat_mutex);
1865   ret = g_slist_copy (__categories);
1866   g_mutex_unlock (&__cat_mutex);
1867
1868   return ret;
1869 }
1870
1871 static GstDebugCategory *
1872 _gst_debug_get_category_locked (const gchar * name)
1873 {
1874   GstDebugCategory *ret = NULL;
1875   GSList *node;
1876
1877   for (node = __categories; node; node = g_slist_next (node)) {
1878     ret = (GstDebugCategory *) node->data;
1879     if (!strcmp (name, ret->name)) {
1880       return ret;
1881     }
1882   }
1883   return NULL;
1884 }
1885
1886 GstDebugCategory *
1887 _gst_debug_get_category (const gchar * name)
1888 {
1889   GstDebugCategory *ret;
1890
1891   g_mutex_lock (&__cat_mutex);
1892   ret = _gst_debug_get_category_locked (name);
1893   g_mutex_unlock (&__cat_mutex);
1894
1895   return ret;
1896 }
1897
1898 static gboolean
1899 parse_debug_category (gchar * str, const gchar ** category)
1900 {
1901   if (!str)
1902     return FALSE;
1903
1904   /* works in place */
1905   g_strstrip (str);
1906
1907   if (str[0] != '\0') {
1908     *category = str;
1909     return TRUE;
1910   }
1911
1912   return FALSE;
1913 }
1914
1915 static gboolean
1916 parse_debug_level (gchar * str, GstDebugLevel * level)
1917 {
1918   if (!str)
1919     return FALSE;
1920
1921   /* works in place */
1922   g_strstrip (str);
1923
1924   if (g_ascii_isdigit (str[0])) {
1925     unsigned long l;
1926     char *endptr;
1927     l = strtoul (str, &endptr, 10);
1928     if (endptr > str && endptr[0] == 0) {
1929       *level = (GstDebugLevel) l;
1930     } else {
1931       return FALSE;
1932     }
1933   } else if (strcmp (str, "ERROR") == 0) {
1934     *level = GST_LEVEL_ERROR;
1935   } else if (strncmp (str, "WARN", 4) == 0) {
1936     *level = GST_LEVEL_WARNING;
1937   } else if (strcmp (str, "FIXME") == 0) {
1938     *level = GST_LEVEL_FIXME;
1939   } else if (strcmp (str, "INFO") == 0) {
1940     *level = GST_LEVEL_INFO;
1941   } else if (strcmp (str, "DEBUG") == 0) {
1942     *level = GST_LEVEL_DEBUG;
1943   } else if (strcmp (str, "LOG") == 0) {
1944     *level = GST_LEVEL_LOG;
1945   } else if (strcmp (str, "TRACE") == 0) {
1946     *level = GST_LEVEL_TRACE;
1947   } else if (strcmp (str, "MEMDUMP") == 0) {
1948     *level = GST_LEVEL_MEMDUMP;
1949   } else
1950     return FALSE;
1951
1952   return TRUE;
1953 }
1954
1955 /**
1956  * gst_debug_set_threshold_from_string:
1957  * @list: comma-separated list of "category:level" pairs to be used
1958  *     as debug logging levels
1959  * @reset: %TRUE to clear all previously-set debug levels before setting
1960  *     new thresholds
1961  * %FALSE if adding the threshold described by @list to the one already set.
1962  *
1963  * Sets the debug logging wanted in the same form as with the GST_DEBUG
1964  * environment variable. You can use wildcards such as '*', but note that
1965  * the order matters when you use wild cards, e.g. "foosrc:6,*src:3,*:2" sets
1966  * everything to log level 2.
1967  *
1968  * Since: 1.2
1969  */
1970 void
1971 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
1972 {
1973   gchar **split;
1974   gchar **walk;
1975
1976   g_assert (list);
1977
1978   if (reset)
1979     gst_debug_set_default_threshold (0);
1980
1981   split = g_strsplit (list, ",", 0);
1982
1983   for (walk = split; *walk; walk++) {
1984     if (strchr (*walk, ':')) {
1985       gchar **values = g_strsplit (*walk, ":", 2);
1986
1987       if (values[0] && values[1]) {
1988         GstDebugLevel level;
1989         const gchar *category;
1990
1991         if (parse_debug_category (values[0], &category)
1992             && parse_debug_level (values[1], &level))
1993           gst_debug_set_threshold_for_name (category, level);
1994       }
1995
1996       g_strfreev (values);
1997     } else {
1998       GstDebugLevel level;
1999
2000       if (parse_debug_level (*walk, &level))
2001         gst_debug_set_default_threshold (level);
2002     }
2003   }
2004
2005   g_strfreev (split);
2006 }
2007
2008 /*** FUNCTION POINTERS ********************************************************/
2009
2010 static GHashTable *__gst_function_pointers;     /* NULL */
2011 static GMutex __dbg_functions_mutex;
2012
2013 /* This function MUST NOT return NULL */
2014 const gchar *
2015 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2016 {
2017   gchar *ptrname;
2018
2019 #ifdef HAVE_DLADDR
2020   Dl_info dl_info;
2021 #endif
2022
2023   if (G_UNLIKELY (func == NULL))
2024     return "(NULL)";
2025
2026   g_mutex_lock (&__dbg_functions_mutex);
2027   if (G_LIKELY (__gst_function_pointers)) {
2028     ptrname = g_hash_table_lookup (__gst_function_pointers, (gpointer) func);
2029     g_mutex_unlock (&__dbg_functions_mutex);
2030     if (G_LIKELY (ptrname))
2031       return ptrname;
2032   } else {
2033     g_mutex_unlock (&__dbg_functions_mutex);
2034   }
2035   /* we need to create an entry in the hash table for this one so we don't leak
2036    * the name */
2037 #ifdef HAVE_DLADDR
2038   if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
2039     gchar *name = g_strdup (dl_info.dli_sname);
2040
2041     _gst_debug_register_funcptr (func, name);
2042     return name;
2043   } else
2044 #endif
2045   {
2046     gchar *name = g_strdup_printf ("%p", (gpointer) func);
2047
2048     _gst_debug_register_funcptr (func, name);
2049     return name;
2050   }
2051 }
2052
2053 void
2054 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2055 {
2056   gpointer ptr = (gpointer) func;
2057
2058   g_mutex_lock (&__dbg_functions_mutex);
2059
2060   if (!__gst_function_pointers)
2061     __gst_function_pointers = g_hash_table_new (g_direct_hash, g_direct_equal);
2062   if (!g_hash_table_lookup (__gst_function_pointers, ptr))
2063     g_hash_table_insert (__gst_function_pointers, ptr, (gpointer) ptrname);
2064
2065   g_mutex_unlock (&__dbg_functions_mutex);
2066 }
2067
2068 static void
2069 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2070     const guint8 * mem, gsize mem_offset, gsize mem_size)
2071 {
2072   gchar hexstr[50], ascstr[18], digitstr[4];
2073
2074   if (mem_size > 16)
2075     mem_size = 16;
2076
2077   hexstr[0] = '\0';
2078   ascstr[0] = '\0';
2079
2080   if (mem != NULL) {
2081     guint i = 0;
2082
2083     mem += mem_offset;
2084     while (i < mem_size) {
2085       ascstr[i] = (g_ascii_isprint (mem[i])) ? mem[i] : '.';
2086       g_snprintf (digitstr, sizeof (digitstr), "%02x ", mem[i]);
2087       g_strlcat (hexstr, digitstr, sizeof (hexstr));
2088       ++i;
2089     }
2090     ascstr[i] = '\0';
2091   }
2092
2093   g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2094       (guint) mem_offset, hexstr, ascstr);
2095 }
2096
2097 void
2098 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2099     const gchar * func, gint line, GObject * obj, const gchar * msg,
2100     const guint8 * data, guint length)
2101 {
2102   guint off = 0;
2103
2104   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2105       "-------------------------------------------------------------------");
2106
2107   if (msg != NULL && *msg != '\0') {
2108     gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", msg);
2109   }
2110
2111   while (off < length) {
2112     gchar buf[128];
2113
2114     /* gst_info_dump_mem_line will process 16 bytes at most */
2115     gst_info_dump_mem_line (buf, sizeof (buf), data, off, length - off);
2116     gst_debug_log (cat, GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", buf);
2117     off += 16;
2118   }
2119
2120   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2121       "-------------------------------------------------------------------");
2122 }
2123
2124 #else /* !GST_DISABLE_GST_DEBUG */
2125 #ifndef GST_REMOVE_DISABLED
2126
2127 GstDebugCategory *
2128 _gst_debug_category_new (const gchar * name, guint color,
2129     const gchar * description)
2130 {
2131   return NULL;
2132 }
2133
2134 void
2135 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2136 {
2137 }
2138
2139 /* This function MUST NOT return NULL */
2140 const gchar *
2141 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2142 {
2143   return "(NULL)";
2144 }
2145
2146 void
2147 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2148     const gchar * file, const gchar * function, gint line,
2149     GObject * object, const gchar * format, ...)
2150 {
2151 }
2152
2153 void
2154 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
2155     const gchar * file, const gchar * function, gint line,
2156     GObject * object, const gchar * format, va_list args)
2157 {
2158 }
2159
2160 const gchar *
2161 gst_debug_message_get (GstDebugMessage * message)
2162 {
2163   return "";
2164 }
2165
2166 void
2167 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
2168     const gchar * file, const gchar * function, gint line,
2169     GObject * object, GstDebugMessage * message, gpointer unused)
2170 {
2171 }
2172
2173 const gchar *
2174 gst_debug_level_get_name (GstDebugLevel level)
2175 {
2176   return "NONE";
2177 }
2178
2179 void
2180 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2181     GDestroyNotify notify)
2182 {
2183 }
2184
2185 guint
2186 gst_debug_remove_log_function (GstLogFunction func)
2187 {
2188   return 0;
2189 }
2190
2191 guint
2192 gst_debug_remove_log_function_by_data (gpointer data)
2193 {
2194   return 0;
2195 }
2196
2197 void
2198 gst_debug_set_active (gboolean active)
2199 {
2200 }
2201
2202 gboolean
2203 gst_debug_is_active (void)
2204 {
2205   return FALSE;
2206 }
2207
2208 void
2209 gst_debug_set_colored (gboolean colored)
2210 {
2211 }
2212
2213 void
2214 gst_debug_set_color_mode (GstDebugColorMode mode)
2215 {
2216 }
2217
2218 void
2219 gst_debug_set_color_mode_from_string (const gchar * str)
2220 {
2221 }
2222
2223 gboolean
2224 gst_debug_is_colored (void)
2225 {
2226   return FALSE;
2227 }
2228
2229 GstDebugColorMode
2230 gst_debug_get_color_mode (void)
2231 {
2232   return GST_DEBUG_COLOR_MODE_OFF;
2233 }
2234
2235 void
2236 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2237 {
2238 }
2239
2240 void
2241 gst_debug_set_default_threshold (GstDebugLevel level)
2242 {
2243 }
2244
2245 GstDebugLevel
2246 gst_debug_get_default_threshold (void)
2247 {
2248   return GST_LEVEL_NONE;
2249 }
2250
2251 void
2252 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2253 {
2254 }
2255
2256 void
2257 gst_debug_unset_threshold_for_name (const gchar * name)
2258 {
2259 }
2260
2261 void
2262 gst_debug_category_free (GstDebugCategory * category)
2263 {
2264 }
2265
2266 void
2267 gst_debug_category_set_threshold (GstDebugCategory * category,
2268     GstDebugLevel level)
2269 {
2270 }
2271
2272 void
2273 gst_debug_category_reset_threshold (GstDebugCategory * category)
2274 {
2275 }
2276
2277 GstDebugLevel
2278 gst_debug_category_get_threshold (GstDebugCategory * category)
2279 {
2280   return GST_LEVEL_NONE;
2281 }
2282
2283 const gchar *
2284 gst_debug_category_get_name (GstDebugCategory * category)
2285 {
2286   return "";
2287 }
2288
2289 guint
2290 gst_debug_category_get_color (GstDebugCategory * category)
2291 {
2292   return 0;
2293 }
2294
2295 const gchar *
2296 gst_debug_category_get_description (GstDebugCategory * category)
2297 {
2298   return "";
2299 }
2300
2301 GSList *
2302 gst_debug_get_all_categories (void)
2303 {
2304   return NULL;
2305 }
2306
2307 GstDebugCategory *
2308 _gst_debug_get_category (const gchar * name)
2309 {
2310   return NULL;
2311 }
2312
2313 gchar *
2314 gst_debug_construct_term_color (guint colorinfo)
2315 {
2316   return g_strdup ("00");
2317 }
2318
2319 gint
2320 gst_debug_construct_win_color (guint colorinfo)
2321 {
2322   return 0;
2323 }
2324
2325 gboolean
2326 _priv_gst_in_valgrind (void)
2327 {
2328   return FALSE;
2329 }
2330
2331 void
2332 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2333     const gchar * func, gint line, GObject * obj, const gchar * msg,
2334     const guint8 * data, guint length)
2335 {
2336 }
2337 #endif /* GST_REMOVE_DISABLED */
2338 #endif /* GST_DISABLE_GST_DEBUG */
2339
2340 /* Need this for _gst_element_error_printf even if GST_REMOVE_DISABLED is set:
2341  * fallback function that cleans up the format string and replaces all pointer
2342  * extension formats with plain %p. */
2343 #ifdef GST_DISABLE_GST_DEBUG
2344 int
2345 __gst_info_fallback_vasprintf (char **result, char const *format, va_list args)
2346 {
2347   gchar *clean_format, *c;
2348   gsize len;
2349
2350   if (format == NULL)
2351     return -1;
2352
2353   clean_format = g_strdup (format);
2354   c = clean_format;
2355   while ((c = strstr (c, "%p\a"))) {
2356     if (c[3] < 'A' || c[3] > 'Z') {
2357       c += 3;
2358       continue;
2359     }
2360     len = strlen (c + 4);
2361     memmove (c + 2, c + 4, len + 1);
2362     c += 2;
2363   }
2364   while ((c = strstr (clean_format, "%P")))     /* old GST_PTR_FORMAT */
2365     c[1] = 'p';
2366   while ((c = strstr (clean_format, "%Q")))     /* old GST_SEGMENT_FORMAT */
2367     c[1] = 'p';
2368
2369   len = g_vasprintf (result, clean_format, args);
2370
2371   g_free (clean_format);
2372
2373   if (*result == NULL)
2374     return -1;
2375
2376   return len;
2377 }
2378 #endif
2379
2380 /**
2381  * gst_info_vasprintf:
2382  * @result: (out): the resulting string
2383  * @format: a printf style format string
2384  * @args: the va_list of printf arguments for @format
2385  *
2386  * Allocates and fills a string large enough (including the terminating null
2387  * byte) to hold the specified printf style @format and @args.
2388  *
2389  * This function deals with the GStreamer specific printf specifiers
2390  * #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.  If you do not have these specifiers
2391  * in your @format string, you do not need to use this function and can use
2392  * alternatives such as g_vasprintf().
2393  *
2394  * Free @result with g_free().
2395  *
2396  * Returns: the length of the string allocated into @result or -1 on any error
2397  *
2398  * Since: 1.8
2399  */
2400 gint
2401 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2402 {
2403   /* This will fallback to __gst_info_fallback_vasprintf() via a #define in
2404    * gst_private.h if the debug system is disabled which will remove the gst
2405    * specific printf format specifiers */
2406   return __gst_vasprintf (result, format, args);
2407 }
2408
2409 /**
2410  * gst_info_strdup_vprintf:
2411  * @format: a printf style format string
2412  * @args: the va_list of printf arguments for @format
2413  *
2414  * Allocates, fills and returns a null terminated string from the printf style
2415  * @format string and @args.
2416  *
2417  * See gst_info_vasprintf() for when this function is required.
2418  *
2419  * Free with g_free().
2420  *
2421  * Returns: a newly allocated null terminated string or %NULL on any error
2422  *
2423  * Since: 1.8
2424  */
2425 gchar *
2426 gst_info_strdup_vprintf (const gchar * format, va_list args)
2427 {
2428   gchar *ret;
2429
2430   if (gst_info_vasprintf (&ret, format, args) < 0)
2431     ret = NULL;
2432
2433   return ret;
2434 }
2435
2436 /**
2437  * gst_info_strdup_printf:
2438  * @format: a printf style format string
2439  * @...: the printf arguments for @format
2440  *
2441  * Allocates, fills and returns a 0-terminated string from the printf style
2442  * @format string and corresponding arguments.
2443  *
2444  * See gst_info_vasprintf() for when this function is required.
2445  *
2446  * Free with g_free().
2447  *
2448  * Returns: a newly allocated null terminated string or %NULL on any error
2449  *
2450  * Since: 1.8
2451  */
2452 gchar *
2453 gst_info_strdup_printf (const gchar * format, ...)
2454 {
2455   gchar *ret;
2456   va_list args;
2457
2458   va_start (args, format);
2459   ret = gst_info_strdup_vprintf (format, args);
2460   va_end (args);
2461
2462   return ret;
2463 }
2464
2465 /**
2466  * gst_print:
2467  * @format: a printf style format string
2468  * @...: the printf arguments for @format
2469  *
2470  * Outputs a formatted message via the GLib print handler. The default print
2471  * handler simply outputs the message to stdout.
2472  *
2473  * This function will not append a new-line character at the end, unlike
2474  * gst_println() which will.
2475  *
2476  * All strings must be in ASCII or UTF-8 encoding.
2477  *
2478  * This function differs from g_print() in that it supports all the additional
2479  * printf specifiers that are supported by GStreamer's debug logging system,
2480  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2481  *
2482  * This function is primarily for printing debug output.
2483  *
2484  * Since: 1.12
2485  */
2486 void
2487 gst_print (const gchar * format, ...)
2488 {
2489   va_list args;
2490   gchar *str;
2491
2492   va_start (args, format);
2493   str = gst_info_strdup_vprintf (format, args);
2494   va_end (args);
2495
2496   g_print ("%s", str);
2497   g_free (str);
2498 }
2499
2500 /**
2501  * gst_println:
2502  * @format: a printf style format string
2503  * @...: the printf arguments for @format
2504  *
2505  * Outputs a formatted message via the GLib print handler. The default print
2506  * handler simply outputs the message to stdout.
2507  *
2508  * This function will append a new-line character at the end, unlike
2509  * gst_print() which will not.
2510  *
2511  * All strings must be in ASCII or UTF-8 encoding.
2512  *
2513  * This function differs from g_print() in that it supports all the additional
2514  * printf specifiers that are supported by GStreamer's debug logging system,
2515  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2516  *
2517  * This function is primarily for printing debug output.
2518  *
2519  * Since: 1.12
2520  */
2521 void
2522 gst_println (const gchar * format, ...)
2523 {
2524   va_list args;
2525   gchar *str;
2526
2527   va_start (args, format);
2528   str = gst_info_strdup_vprintf (format, args);
2529   va_end (args);
2530
2531   g_print ("%s\n", str);
2532   g_free (str);
2533 }
2534
2535 /**
2536  * gst_printerr:
2537  * @format: a printf style format string
2538  * @...: the printf arguments for @format
2539  *
2540  * Outputs a formatted message via the GLib error message handler. The default
2541  * handler simply outputs the message to stderr.
2542  *
2543  * This function will not append a new-line character at the end, unlike
2544  * gst_printerrln() which will.
2545  *
2546  * All strings must be in ASCII or UTF-8 encoding.
2547  *
2548  * This function differs from g_printerr() in that it supports the additional
2549  * printf specifiers that are supported by GStreamer's debug logging system,
2550  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2551  *
2552  * This function is primarily for printing debug output.
2553  *
2554  * Since: 1.12
2555  */
2556 void
2557 gst_printerr (const gchar * format, ...)
2558 {
2559   va_list args;
2560   gchar *str;
2561
2562   va_start (args, format);
2563   str = gst_info_strdup_vprintf (format, args);
2564   va_end (args);
2565
2566   g_printerr ("%s", str);
2567   g_free (str);
2568 }
2569
2570 /**
2571  * gst_printerrln:
2572  * @format: a printf style format string
2573  * @...: the printf arguments for @format
2574  *
2575  * Outputs a formatted message via the GLib error message handler. The default
2576  * handler simply outputs the message to stderr.
2577  *
2578  * This function will append a new-line character at the end, unlike
2579  * gst_printerr() which will not.
2580  *
2581  * All strings must be in ASCII or UTF-8 encoding.
2582  *
2583  * This function differs from g_printerr() in that it supports the additional
2584  * printf specifiers that are supported by GStreamer's debug logging system,
2585  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2586  *
2587  * This function is primarily for printing debug output.
2588  *
2589  * Since: 1.12
2590  */
2591 void
2592 gst_printerrln (const gchar * format, ...)
2593 {
2594   va_list args;
2595   gchar *str;
2596
2597   va_start (args, format);
2598   str = gst_info_strdup_vprintf (format, args);
2599   va_end (args);
2600
2601   g_printerr ("%s\n", str);
2602   g_free (str);
2603 }
2604
2605 #ifdef HAVE_UNWIND
2606 #ifdef HAVE_DW
2607 static gboolean
2608 append_debug_info (GString * trace, const void *ip)
2609 {
2610   Dwfl *dwfl;
2611   Dwfl_Line *line;
2612   Dwarf_Addr addr;
2613   Dwfl_Module *module;
2614   const gchar *function_name;
2615   gchar *debuginfo_path = NULL;
2616   Dwfl_Callbacks callbacks = {
2617     .find_elf = dwfl_linux_proc_find_elf,
2618     .find_debuginfo = dwfl_standard_find_debuginfo,
2619     .debuginfo_path = &debuginfo_path,
2620   };
2621
2622   dwfl = dwfl_begin (&callbacks);
2623   if (!dwfl)
2624     return FALSE;
2625
2626   if (dwfl_linux_proc_report (dwfl, getpid ()) != 0)
2627     return FALSE;
2628
2629   if (dwfl_report_end (dwfl, NULL, NULL))
2630     return FALSE;
2631
2632   addr = (uintptr_t) ip;
2633   module = dwfl_addrmodule (dwfl, addr);
2634   function_name = dwfl_module_addrname (module, addr);
2635
2636   g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
2637
2638   line = dwfl_getsrc (dwfl, addr);
2639   if (line != NULL) {
2640     gint nline;
2641     Dwarf_Addr addr;
2642     const gchar *filename = dwfl_lineinfo (line, &addr,
2643         &nline, NULL, NULL, NULL);
2644
2645     g_string_append_printf (trace, "%s:%d", strrchr (filename,
2646             G_DIR_SEPARATOR) + 1, nline);
2647   } else {
2648     const gchar *eflfile = NULL;
2649
2650     dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
2651     g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
2652   }
2653
2654   return TRUE;
2655 }
2656 #endif /* HAVE_DW */
2657
2658 static gchar *
2659 generate_unwind_trace (void)
2660 {
2661   unw_context_t uc;
2662   unw_cursor_t cursor;
2663   gboolean use_libunwind = TRUE;
2664   GString *trace = g_string_new (NULL);
2665
2666   unw_getcontext (&uc);
2667   unw_init_local (&cursor, &uc);
2668
2669   while (unw_step (&cursor) > 0) {
2670 #ifdef HAVE_DW
2671     unw_word_t ip;
2672
2673     unw_get_reg (&cursor, UNW_REG_IP, &ip);
2674     if (append_debug_info (trace, (void *) (ip - 4))) {
2675       use_libunwind = FALSE;
2676       g_string_append (trace, ")\n");
2677     }
2678 #endif /* HAVE_DW */
2679
2680     if (use_libunwind) {
2681       char name[32];
2682
2683       unw_word_t offset = 0;
2684       unw_get_proc_name (&cursor, name, sizeof (name), &offset);
2685       g_string_append_printf (trace, "%s (0x%" G_GSIZE_FORMAT ")\n", name,
2686           (gsize) offset);
2687     }
2688   }
2689
2690   return g_string_free (trace, FALSE);
2691 }
2692
2693 #endif /* HAVE_UNWIND */
2694
2695 #ifdef HAVE_BACKTRACE
2696 static gchar *
2697 generate_backtrace_trace (void)
2698 {
2699   int j, nptrs;
2700   void *buffer[BT_BUF_SIZE];
2701   char **strings;
2702   GString *trace;
2703
2704   trace = g_string_new (NULL);
2705   nptrs = backtrace (buffer, BT_BUF_SIZE);
2706
2707   strings = backtrace_symbols (buffer, nptrs);
2708
2709   if (!strings)
2710     return NULL;
2711
2712   for (j = 0; j < nptrs; j++)
2713     g_string_append_printf (trace, "%s\n", strings[j]);
2714
2715   return g_string_free (trace, FALSE);
2716 }
2717 #endif /* HAVE_BACKTRACE */
2718
2719 /**
2720  * gst_debug_get_stack_trace:
2721  *
2722  * If libunwind or glibc backtrace are present, a stack trace
2723  * is returned.
2724  */
2725 gchar *
2726 gst_debug_get_stack_trace (void)
2727 {
2728   gchar *trace = NULL;
2729
2730 #ifdef HAVE_UNWIND
2731   trace = generate_unwind_trace ();
2732   if (trace)
2733     return trace;
2734 #endif /* HAVE_UNWIND */
2735
2736 #ifdef HAVE_BACKTRACE
2737   trace = generate_backtrace_trace ();
2738 #endif /* HAVE_BACKTRACE */
2739
2740   return trace;
2741 }
2742
2743 /**
2744  * gst_debug_print_stack_trace:
2745  *
2746  * If libunwind or glibc backtrace are present
2747  * a stack trace is printed.
2748  */
2749 void
2750 gst_debug_print_stack_trace (void)
2751 {
2752   gchar *trace = gst_debug_get_stack_trace ();
2753
2754   if (trace)
2755     g_print ("%s\n", trace);
2756
2757   g_free (trace);
2758 }