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