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