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