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