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