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