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