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