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