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