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