tee: Check for the removed pad flag also in the slow pushing path
[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  * @title: GstInfo
28  * @short_description: Debugging and logging facilities
29  * @see_also: #gst-running for command line parameters
30  * and environment variables that affect the debugging output.
31  *
32  * GStreamer's debugging subsystem is an easy way to get information about what
33  * the application is doing.  It is not meant for programming errors. Use GLib
34  * methods (g_warning and friends) for that.
35  *
36  * The debugging subsystem works only after GStreamer has been initialized
37  * - for example by calling gst_init().
38  *
39  * The debugging subsystem is used to log informational messages while the
40  * application runs.  Each messages has some properties attached to it. Among
41  * these properties are the debugging category, the severity (called "level"
42  * here) and an optional #GObject it belongs to. Each of these messages is sent
43  * to all registered debugging handlers, which then handle the messages.
44  * GStreamer attaches a default handler on startup, which outputs requested
45  * messages to stderr.
46  *
47  * Messages are output by using shortcut macros like #GST_DEBUG,
48  * #GST_CAT_ERROR_OBJECT or similar. These all expand to calling gst_debug_log()
49  * with the right parameters.
50  * The only thing a developer will probably want to do is define his own
51  * categories. This is easily done with 3 lines. At the top of your code,
52  * declare
53  * the variables and set the default category.
54  * |[<!-- language="C" -->
55  *   GST_DEBUG_CATEGORY_STATIC (my_category);  // define category (statically)
56  *   #define GST_CAT_DEFAULT my_category       // set as default
57  * ]|
58  * After that you only need to initialize the category.
59  * |[<!-- language="C" -->
60  *   GST_DEBUG_CATEGORY_INIT (my_category, "my category",
61  *                            0, "This is my very own");
62  * ]|
63  * Initialization must be done before the category is used first.
64  * Plugins do this
65  * in their plugin_init function, libraries and applications should do that
66  * during their initialization.
67  *
68  * The whole debugging subsystem can be disabled at build time with passing the
69  * --disable-gst-debug switch to configure. If this is done, every function,
70  * macro and even structs described in this file evaluate to default values or
71  * nothing at all.
72  * So don't take addresses of these functions or use other tricks.
73  * If you must do that for some reason, there is still an option.
74  * If the debugging
75  * subsystem was compiled out, #GST_DISABLE_GST_DEBUG is defined in
76  * &lt;gst/gst.h&gt;,
77  * so you can check that before doing your trick.
78  * Disabling the debugging subsystem will give you a slight (read: unnoticeable)
79  * speed increase and will reduce the size of your compiled code. The GStreamer
80  * library itself becomes around 10% smaller.
81  *
82  * Please note that there are naming conventions for the names of debugging
83  * categories. These are explained at GST_DEBUG_CATEGORY_INIT().
84  */
85
86 #define GST_INFO_C
87 #include "gst_private.h"
88 #include "gstinfo.h"
89
90 #undef gst_debug_remove_log_function
91 #undef gst_debug_add_log_function
92
93 #ifndef GST_DISABLE_GST_DEBUG
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 #else /* GST_DISABLE_GST_DEBUG */
131
132 #include <glib/gprintf.h>
133 #endif /* !GST_DISABLE_GST_DEBUG */
134
135 #ifdef HAVE_UNWIND
136 /* No need for remote debugging so turn on the 'local only' optimizations in
137  * libunwind */
138 #define UNW_LOCAL_ONLY
139
140 #include <libunwind.h>
141 #include <stdio.h>
142 #include <stdlib.h>
143 #include <string.h>
144 #include <stdarg.h>
145 #include <unistd.h>
146 #include <errno.h>
147
148 #ifdef HAVE_DW
149 #include <elfutils/libdwfl.h>
150 #endif /* HAVE_DW */
151 #endif /* HAVE_UNWIND */
152
153 #ifdef HAVE_BACKTRACE
154 #include <execinfo.h>
155 #define BT_BUF_SIZE 100
156 #endif /* HAVE_BACKTRACE */
157
158 #ifdef HAVE_DBGHELP
159 #include <Windows.h>
160 #include <dbghelp.h>
161 #include <tlhelp32.h>
162 #endif /* HAVE_DBGHELP */
163
164 #ifdef G_OS_WIN32
165 /* We take a lock in order to
166  * 1) keep colors and content together for a single line
167  * 2) serialise gst_print*() and gst_printerr*() with each other and the debug
168  *    log to keep the debug log colouring from interfering with those and
169  *    to prevent broken output on the windows terminal.
170  * Maybe there is a better way but for now this will do the right
171  * thing. */
172 G_LOCK_DEFINE_STATIC (win_print_mutex);
173 #endif
174
175 extern gboolean gst_is_initialized (void);
176
177 /* we want these symbols exported even if debug is disabled, to maintain
178  * ABI compatibility. Unless GST_REMOVE_DISABLED is defined. */
179 #if !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED)
180
181 /* disabled by default, as soon as some threshold is set > NONE,
182  * it becomes enabled. */
183 gboolean _gst_debug_enabled = FALSE;
184 GstDebugLevel _gst_debug_min = GST_LEVEL_NONE;
185
186 GstDebugCategory *GST_CAT_DEFAULT = NULL;
187
188 GstDebugCategory *GST_CAT_GST_INIT = NULL;
189 GstDebugCategory *GST_CAT_MEMORY = NULL;
190 GstDebugCategory *GST_CAT_PARENTAGE = NULL;
191 GstDebugCategory *GST_CAT_STATES = NULL;
192 GstDebugCategory *GST_CAT_SCHEDULING = NULL;
193
194 GstDebugCategory *GST_CAT_BUFFER = NULL;
195 GstDebugCategory *GST_CAT_BUFFER_LIST = NULL;
196 GstDebugCategory *GST_CAT_BUS = NULL;
197 GstDebugCategory *GST_CAT_CAPS = NULL;
198 GstDebugCategory *GST_CAT_CLOCK = NULL;
199 GstDebugCategory *GST_CAT_ELEMENT_PADS = NULL;
200 GstDebugCategory *GST_CAT_PADS = NULL;
201 GstDebugCategory *GST_CAT_PERFORMANCE = NULL;
202 GstDebugCategory *GST_CAT_PIPELINE = NULL;
203 GstDebugCategory *GST_CAT_PLUGIN_LOADING = NULL;
204 GstDebugCategory *GST_CAT_PLUGIN_INFO = NULL;
205 GstDebugCategory *GST_CAT_PROPERTIES = NULL;
206 GstDebugCategory *GST_CAT_NEGOTIATION = NULL;
207 GstDebugCategory *GST_CAT_REFCOUNTING = NULL;
208 GstDebugCategory *GST_CAT_ERROR_SYSTEM = NULL;
209 GstDebugCategory *GST_CAT_EVENT = NULL;
210 GstDebugCategory *GST_CAT_MESSAGE = NULL;
211 GstDebugCategory *GST_CAT_PARAMS = NULL;
212 GstDebugCategory *GST_CAT_CALL_TRACE = NULL;
213 GstDebugCategory *GST_CAT_SIGNAL = NULL;
214 GstDebugCategory *GST_CAT_PROBE = NULL;
215 GstDebugCategory *GST_CAT_REGISTRY = NULL;
216 GstDebugCategory *GST_CAT_QOS = NULL;
217 GstDebugCategory *_priv_GST_CAT_POLL = NULL;
218 GstDebugCategory *GST_CAT_META = NULL;
219 GstDebugCategory *GST_CAT_LOCKING = NULL;
220 GstDebugCategory *GST_CAT_CONTEXT = NULL;
221 GstDebugCategory *_priv_GST_CAT_PROTECTION = NULL;
222
223
224 #endif /* !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED) */
225
226 #ifndef GST_DISABLE_GST_DEBUG
227
228 /* underscore is to prevent conflict with GST_CAT_DEBUG define */
229 GST_DEBUG_CATEGORY_STATIC (_GST_CAT_DEBUG);
230
231 #if 0
232 #if defined __sgi__
233 #include <rld_interface.h>
234 typedef struct DL_INFO
235 {
236   const char *dli_fname;
237   void *dli_fbase;
238   const char *dli_sname;
239   void *dli_saddr;
240   int dli_version;
241   int dli_reserved1;
242   long dli_reserved[4];
243 }
244 Dl_info;
245
246 #define _RLD_DLADDR             14
247 int dladdr (void *address, Dl_info * dl);
248
249 int
250 dladdr (void *address, Dl_info * dl)
251 {
252   void *v;
253
254   v = _rld_new_interface (_RLD_DLADDR, address, dl);
255   return (int) v;
256 }
257 #endif /* __sgi__ */
258 #endif
259
260 static void gst_debug_reset_threshold (gpointer category, gpointer unused);
261 static void gst_debug_reset_all_thresholds (void);
262
263 struct _GstDebugMessage
264 {
265   gchar *message;
266   const gchar *format;
267   va_list arguments;
268 };
269
270 /* list of all name/level pairs from --gst-debug and GST_DEBUG */
271 static GMutex __level_name_mutex;
272 static GSList *__level_name = NULL;
273 typedef struct
274 {
275   GPatternSpec *pat;
276   GstDebugLevel level;
277 }
278 LevelNameEntry;
279
280 /* list of all categories */
281 static GMutex __cat_mutex;
282 static GSList *__categories = NULL;
283
284 static GstDebugCategory *_gst_debug_get_category_locked (const gchar * name);
285
286
287 /* all registered debug handlers */
288 typedef struct
289 {
290   GstLogFunction func;
291   gpointer user_data;
292   GDestroyNotify notify;
293 }
294 LogFuncEntry;
295 static GMutex __log_func_mutex;
296 static GSList *__log_functions = NULL;
297
298 /* whether to add the default log function in gst_init() */
299 static gboolean add_default_log_func = TRUE;
300
301 #define PRETTY_TAGS_DEFAULT  TRUE
302 static gboolean pretty_tags = PRETTY_TAGS_DEFAULT;
303
304 static volatile gint G_GNUC_MAY_ALIAS __default_level = GST_LEVEL_DEFAULT;
305 static volatile gint G_GNUC_MAY_ALIAS __use_color = GST_DEBUG_COLOR_MODE_ON;
306
307 /* FIXME: export this? */
308 gboolean
309 _priv_gst_in_valgrind (void)
310 {
311   static enum
312   {
313     GST_VG_UNCHECKED,
314     GST_VG_NO_VALGRIND,
315     GST_VG_INSIDE
316   }
317   in_valgrind = GST_VG_UNCHECKED;
318
319   if (in_valgrind == GST_VG_UNCHECKED) {
320 #ifdef HAVE_VALGRIND_VALGRIND_H
321     if (RUNNING_ON_VALGRIND) {
322       GST_CAT_INFO (GST_CAT_GST_INIT, "we're running inside valgrind");
323       in_valgrind = GST_VG_INSIDE;
324     } else {
325       GST_CAT_LOG (GST_CAT_GST_INIT, "not doing extra valgrind stuff");
326       in_valgrind = GST_VG_NO_VALGRIND;
327     }
328 #else
329     in_valgrind = GST_VG_NO_VALGRIND;
330 #endif
331     g_assert (in_valgrind == GST_VG_NO_VALGRIND ||
332         in_valgrind == GST_VG_INSIDE);
333   }
334   return (in_valgrind == GST_VG_INSIDE);
335 }
336
337 static gchar *
338 _replace_pattern_in_gst_debug_file_name (gchar * name, const char *token,
339     guint val)
340 {
341   gchar *token_start;
342   if ((token_start = strstr (name, token))) {
343     gsize token_len = strlen (token);
344     gchar *name_prefix = name;
345     gchar *name_suffix = token_start + token_len;
346     token_start[0] = '\0';
347     name = g_strdup_printf ("%s%u%s", name_prefix, val, name_suffix);
348     g_free (name_prefix);
349   }
350   return name;
351 }
352
353 static gchar *
354 _priv_gst_debug_file_name (const gchar * env)
355 {
356   gchar *name;
357
358   name = g_strdup (env);
359   name = _replace_pattern_in_gst_debug_file_name (name, "%p", getpid ());
360   name = _replace_pattern_in_gst_debug_file_name (name, "%r", g_random_int ());
361
362   return name;
363 }
364
365 /* Initialize the debugging system */
366 void
367 _priv_gst_debug_init (void)
368 {
369   const gchar *env;
370   FILE *log_file;
371
372   if (add_default_log_func) {
373     env = g_getenv ("GST_DEBUG_FILE");
374     if (env != NULL && *env != '\0') {
375       if (strcmp (env, "-") == 0) {
376         log_file = stdout;
377       } else {
378         gchar *name = _priv_gst_debug_file_name (env);
379         log_file = g_fopen (name, "w");
380         g_free (name);
381         if (log_file == NULL) {
382           g_printerr ("Could not open log file '%s' for writing: %s\n", env,
383               g_strerror (errno));
384           log_file = stderr;
385         }
386       }
387     } else {
388       log_file = stderr;
389     }
390
391     gst_debug_add_log_function (gst_debug_log_default, log_file, NULL);
392   }
393
394   __gst_printf_pointer_extension_set_func
395       (gst_info_printf_pointer_extension_func);
396
397   /* do NOT use a single debug function before this line has been run */
398   GST_CAT_DEFAULT = _gst_debug_category_new ("default",
399       GST_DEBUG_UNDERLINE, NULL);
400   _GST_CAT_DEBUG = _gst_debug_category_new ("GST_DEBUG",
401       GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, "debugging subsystem");
402
403   /* FIXME: add descriptions here */
404   GST_CAT_GST_INIT = _gst_debug_category_new ("GST_INIT",
405       GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
406   GST_CAT_MEMORY = _gst_debug_category_new ("GST_MEMORY",
407       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, "memory");
408   GST_CAT_PARENTAGE = _gst_debug_category_new ("GST_PARENTAGE",
409       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
410   GST_CAT_STATES = _gst_debug_category_new ("GST_STATES",
411       GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
412   GST_CAT_SCHEDULING = _gst_debug_category_new ("GST_SCHEDULING",
413       GST_DEBUG_BOLD | GST_DEBUG_FG_MAGENTA, NULL);
414   GST_CAT_BUFFER = _gst_debug_category_new ("GST_BUFFER",
415       GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
416   GST_CAT_BUFFER_LIST = _gst_debug_category_new ("GST_BUFFER_LIST",
417       GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
418   GST_CAT_BUS = _gst_debug_category_new ("GST_BUS", GST_DEBUG_BG_YELLOW, NULL);
419   GST_CAT_CAPS = _gst_debug_category_new ("GST_CAPS",
420       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
421   GST_CAT_CLOCK = _gst_debug_category_new ("GST_CLOCK",
422       GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, NULL);
423   GST_CAT_ELEMENT_PADS = _gst_debug_category_new ("GST_ELEMENT_PADS",
424       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
425   GST_CAT_PADS = _gst_debug_category_new ("GST_PADS",
426       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
427   GST_CAT_PERFORMANCE = _gst_debug_category_new ("GST_PERFORMANCE",
428       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
429   GST_CAT_PIPELINE = _gst_debug_category_new ("GST_PIPELINE",
430       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
431   GST_CAT_PLUGIN_LOADING = _gst_debug_category_new ("GST_PLUGIN_LOADING",
432       GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
433   GST_CAT_PLUGIN_INFO = _gst_debug_category_new ("GST_PLUGIN_INFO",
434       GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
435   GST_CAT_PROPERTIES = _gst_debug_category_new ("GST_PROPERTIES",
436       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_BLUE, NULL);
437   GST_CAT_NEGOTIATION = _gst_debug_category_new ("GST_NEGOTIATION",
438       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
439   GST_CAT_REFCOUNTING = _gst_debug_category_new ("GST_REFCOUNTING",
440       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
441   GST_CAT_ERROR_SYSTEM = _gst_debug_category_new ("GST_ERROR_SYSTEM",
442       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_WHITE, NULL);
443
444   GST_CAT_EVENT = _gst_debug_category_new ("GST_EVENT",
445       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
446   GST_CAT_MESSAGE = _gst_debug_category_new ("GST_MESSAGE",
447       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
448   GST_CAT_PARAMS = _gst_debug_category_new ("GST_PARAMS",
449       GST_DEBUG_BOLD | GST_DEBUG_FG_BLACK | GST_DEBUG_BG_YELLOW, NULL);
450   GST_CAT_CALL_TRACE = _gst_debug_category_new ("GST_CALL_TRACE",
451       GST_DEBUG_BOLD, NULL);
452   GST_CAT_SIGNAL = _gst_debug_category_new ("GST_SIGNAL",
453       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
454   GST_CAT_PROBE = _gst_debug_category_new ("GST_PROBE",
455       GST_DEBUG_BOLD | GST_DEBUG_FG_GREEN, "pad probes");
456   GST_CAT_REGISTRY = _gst_debug_category_new ("GST_REGISTRY", 0, "registry");
457   GST_CAT_QOS = _gst_debug_category_new ("GST_QOS", 0, "QoS");
458   _priv_GST_CAT_POLL = _gst_debug_category_new ("GST_POLL", 0, "poll");
459   GST_CAT_META = _gst_debug_category_new ("GST_META", 0, "meta");
460   GST_CAT_LOCKING = _gst_debug_category_new ("GST_LOCKING", 0, "locking");
461   GST_CAT_CONTEXT = _gst_debug_category_new ("GST_CONTEXT", 0, NULL);
462   _priv_GST_CAT_PROTECTION =
463       _gst_debug_category_new ("GST_PROTECTION", 0, "protection");
464
465   /* print out the valgrind message if we're in valgrind */
466   _priv_gst_in_valgrind ();
467
468   env = g_getenv ("GST_DEBUG_OPTIONS");
469   if (env != NULL) {
470     if (strstr (env, "full_tags") || strstr (env, "full-tags"))
471       pretty_tags = FALSE;
472     else if (strstr (env, "pretty_tags") || strstr (env, "pretty-tags"))
473       pretty_tags = TRUE;
474   }
475
476   if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
477     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
478   env = g_getenv ("GST_DEBUG_COLOR_MODE");
479   if (env)
480     gst_debug_set_color_mode_from_string (env);
481
482   env = g_getenv ("GST_DEBUG");
483   if (env)
484     gst_debug_set_threshold_from_string (env, FALSE);
485 }
486
487 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
488 #define GST_CAT_DEFAULT _GST_CAT_DEBUG
489
490 /**
491  * gst_debug_log:
492  * @category: category to log
493  * @level: level of the message is in
494  * @file: the file that emitted the message, usually the __FILE__ identifier
495  * @function: the function that emitted the message
496  * @line: the line from that the message was emitted, usually __LINE__
497  * @object: (transfer none) (allow-none): the object this message relates to,
498  *     or %NULL if none
499  * @format: a printf style format string
500  * @...: optional arguments for the format
501  *
502  * Logs the given message using the currently registered debugging handlers.
503  */
504 void
505 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
506     const gchar * file, const gchar * function, gint line,
507     GObject * object, const gchar * format, ...)
508 {
509   va_list var_args;
510
511   va_start (var_args, format);
512   gst_debug_log_valist (category, level, file, function, line, object, format,
513       var_args);
514   va_end (var_args);
515 }
516
517 /* based on g_basename(), which we can't use because it was deprecated */
518 static inline const gchar *
519 gst_path_basename (const gchar * file_name)
520 {
521   register const gchar *base;
522
523   base = strrchr (file_name, G_DIR_SEPARATOR);
524
525   {
526     const gchar *q = strrchr (file_name, '/');
527     if (base == NULL || (q != NULL && q > base))
528       base = q;
529   }
530
531   if (base)
532     return base + 1;
533
534   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
535     return file_name + 2;
536
537   return file_name;
538 }
539
540 /**
541  * gst_debug_log_valist:
542  * @category: category to log
543  * @level: level of the message is in
544  * @file: the file that emitted the message, usually the __FILE__ identifier
545  * @function: the function that emitted the message
546  * @line: the line from that the message was emitted, usually __LINE__
547  * @object: (transfer none) (allow-none): the object this message relates to,
548  *     or %NULL if none
549  * @format: a printf style format string
550  * @args: optional arguments for the format
551  *
552  * Logs the given message using the currently registered debugging handlers.
553  */
554 void
555 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
556     const gchar * file, const gchar * function, gint line,
557     GObject * object, const gchar * format, va_list args)
558 {
559   GstDebugMessage message;
560   LogFuncEntry *entry;
561   GSList *handler;
562
563   g_return_if_fail (category != NULL);
564
565   if (level > gst_debug_category_get_threshold (category))
566     return;
567
568   g_return_if_fail (file != NULL);
569   g_return_if_fail (function != NULL);
570   g_return_if_fail (format != NULL);
571
572   message.message = NULL;
573   message.format = format;
574   G_VA_COPY (message.arguments, args);
575
576   handler = __log_functions;
577   while (handler) {
578     entry = handler->data;
579     handler = g_slist_next (handler);
580     entry->func (category, level, file, function, line, object, &message,
581         entry->user_data);
582   }
583   g_free (message.message);
584   va_end (message.arguments);
585 }
586
587 /**
588  * gst_debug_message_get:
589  * @message: a debug message
590  *
591  * Gets the string representation of a #GstDebugMessage. This function is used
592  * in debug handlers to extract the message.
593  *
594  * Returns: (nullable): the string representation of a #GstDebugMessage.
595  */
596 const gchar *
597 gst_debug_message_get (GstDebugMessage * message)
598 {
599   if (message->message == NULL) {
600     int len;
601
602     len = __gst_vasprintf (&message->message, message->format,
603         message->arguments);
604
605     if (len < 0)
606       message->message = NULL;
607   }
608   return message->message;
609 }
610
611 #define MAX_BUFFER_DUMP_STRING_LEN  100
612
613 /* structure_to_pretty_string:
614  * @str: a serialized #GstStructure
615  *
616  * If the serialized structure contains large buffers such as images the hex
617  * representation of those buffers will be shortened so that the string remains
618  * readable.
619  *
620  * Returns: the filtered string
621  */
622 static gchar *
623 prettify_structure_string (gchar * str)
624 {
625   gchar *pos = str, *end;
626
627   while ((pos = strstr (pos, "(buffer)"))) {
628     guint count = 0;
629
630     pos += strlen ("(buffer)");
631     for (end = pos; *end != '\0' && *end != ';' && *end != ' '; ++end)
632       ++count;
633     if (count > MAX_BUFFER_DUMP_STRING_LEN) {
634       memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 6, "..", 2);
635       memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 4, pos + count - 4, 4);
636       memmove (pos + MAX_BUFFER_DUMP_STRING_LEN, pos + count,
637           strlen (pos + count) + 1);
638       pos += MAX_BUFFER_DUMP_STRING_LEN;
639     }
640   }
641
642   return str;
643 }
644
645 static inline gchar *
646 gst_info_structure_to_string (const GstStructure * s)
647 {
648   if (G_LIKELY (s)) {
649     gchar *str = gst_structure_to_string (s);
650     if (G_UNLIKELY (pretty_tags && s->name == GST_QUARK (TAGLIST)))
651       return prettify_structure_string (str);
652     else
653       return str;
654   }
655   return NULL;
656 }
657
658 static inline gchar *
659 gst_info_describe_buffer (GstBuffer * buffer)
660 {
661   const gchar *offset_str = "none";
662   const gchar *offset_end_str = "none";
663   gchar offset_buf[32], offset_end_buf[32];
664
665   if (GST_BUFFER_OFFSET_IS_VALID (buffer)) {
666     g_snprintf (offset_buf, sizeof (offset_buf), "%" G_GUINT64_FORMAT,
667         GST_BUFFER_OFFSET (buffer));
668     offset_str = offset_buf;
669   }
670   if (GST_BUFFER_OFFSET_END_IS_VALID (buffer)) {
671     g_snprintf (offset_end_buf, sizeof (offset_end_buf), "%" G_GUINT64_FORMAT,
672         GST_BUFFER_OFFSET_END (buffer));
673     offset_end_str = offset_end_buf;
674   }
675
676   return g_strdup_printf ("buffer: %p, pts %" GST_TIME_FORMAT ", dts %"
677       GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT
678       ", offset %s, offset_end %s, flags 0x%x", buffer,
679       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
680       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
681       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
682       gst_buffer_get_size (buffer), offset_str, offset_end_str,
683       GST_BUFFER_FLAGS (buffer));
684 }
685
686 static inline gchar *
687 gst_info_describe_buffer_list (GstBufferList * list)
688 {
689   GstClockTime pts = GST_CLOCK_TIME_NONE;
690   GstClockTime dts = GST_CLOCK_TIME_NONE;
691   gsize total_size = 0;
692   guint n, i;
693
694   n = gst_buffer_list_length (list);
695   for (i = 0; i < n; ++i) {
696     GstBuffer *buf = gst_buffer_list_get (list, i);
697
698     if (i == 0) {
699       pts = GST_BUFFER_PTS (buf);
700       dts = GST_BUFFER_DTS (buf);
701     }
702
703     total_size += gst_buffer_get_size (buf);
704   }
705
706   return g_strdup_printf ("bufferlist: %p, %u buffers, pts %" GST_TIME_FORMAT
707       ", dts %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT, list, n,
708       GST_TIME_ARGS (pts), GST_TIME_ARGS (dts), total_size);
709 }
710
711 static inline gchar *
712 gst_info_describe_event (GstEvent * event)
713 {
714   gchar *s, *ret;
715
716   s = gst_info_structure_to_string (gst_event_get_structure (event));
717   ret = g_strdup_printf ("%s event: %p, time %" GST_TIME_FORMAT
718       ", seq-num %d, %s", GST_EVENT_TYPE_NAME (event), event,
719       GST_TIME_ARGS (GST_EVENT_TIMESTAMP (event)), GST_EVENT_SEQNUM (event),
720       (s ? s : "(NULL)"));
721   g_free (s);
722   return ret;
723 }
724
725 static inline gchar *
726 gst_info_describe_message (GstMessage * message)
727 {
728   gchar *s, *ret;
729
730   s = gst_info_structure_to_string (gst_message_get_structure (message));
731   ret = g_strdup_printf ("%s message: %p, time %" GST_TIME_FORMAT
732       ", seq-num %d, element '%s', %s", GST_MESSAGE_TYPE_NAME (message),
733       message, GST_TIME_ARGS (GST_MESSAGE_TIMESTAMP (message)),
734       GST_MESSAGE_SEQNUM (message),
735       ((message->src) ? GST_ELEMENT_NAME (message->src) : "(NULL)"),
736       (s ? s : "(NULL)"));
737   g_free (s);
738   return ret;
739 }
740
741 static inline gchar *
742 gst_info_describe_query (GstQuery * query)
743 {
744   gchar *s, *ret;
745
746   s = gst_info_structure_to_string (gst_query_get_structure (query));
747   ret = g_strdup_printf ("%s query: %p, %s", GST_QUERY_TYPE_NAME (query),
748       query, (s ? s : "(NULL)"));
749   g_free (s);
750   return ret;
751 }
752
753 static inline gchar *
754 gst_info_describe_stream (GstStream * stream)
755 {
756   gchar *ret, *caps_str = NULL, *tags_str = NULL;
757   GstCaps *caps;
758   GstTagList *tags;
759
760   caps = gst_stream_get_caps (stream);
761   if (caps) {
762     caps_str = gst_caps_to_string (caps);
763     gst_caps_unref (caps);
764   }
765
766   tags = gst_stream_get_tags (stream);
767   if (tags) {
768     tags_str = gst_tag_list_to_string (tags);
769     gst_tag_list_unref (tags);
770   }
771
772   ret =
773       g_strdup_printf ("stream %s %p, ID %s, flags 0x%x, caps [%s], tags [%s]",
774       gst_stream_type_get_name (gst_stream_get_stream_type (stream)), stream,
775       gst_stream_get_stream_id (stream), gst_stream_get_stream_flags (stream),
776       caps_str ? caps_str : "", tags_str ? tags_str : "");
777
778   g_free (caps_str);
779   g_free (tags_str);
780
781   return ret;
782 }
783
784 static inline gchar *
785 gst_info_describe_stream_collection (GstStreamCollection * collection)
786 {
787   gchar *ret;
788   GString *streams_str;
789   guint i;
790
791   streams_str = g_string_new ("<");
792   for (i = 0; i < gst_stream_collection_get_size (collection); i++) {
793     GstStream *stream = gst_stream_collection_get_stream (collection, i);
794     gchar *s;
795
796     s = gst_info_describe_stream (stream);
797     g_string_append_printf (streams_str, " %s,", s);
798     g_free (s);
799   }
800   g_string_append (streams_str, " >");
801
802   ret = g_strdup_printf ("collection %p (%d streams) %s", collection,
803       gst_stream_collection_get_size (collection), streams_str->str);
804
805   g_string_free (streams_str, TRUE);
806   return ret;
807 }
808
809 static gchar *
810 gst_debug_print_object (gpointer ptr)
811 {
812   GObject *object = (GObject *) ptr;
813
814 #ifdef unused
815   /* This is a cute trick to detect unmapped memory, but is unportable,
816    * slow, screws around with madvise, and not actually that useful. */
817   {
818     int ret;
819
820     ret = madvise ((void *) ((unsigned long) ptr & (~0xfff)), 4096, 0);
821     if (ret == -1 && errno == ENOMEM) {
822       buffer = g_strdup_printf ("%p (unmapped memory)", ptr);
823     }
824   }
825 #endif
826
827   /* nicely printed object */
828   if (object == NULL) {
829     return g_strdup ("(NULL)");
830   }
831   if (GST_IS_CAPS (ptr)) {
832     return gst_caps_to_string ((const GstCaps *) ptr);
833   }
834   if (GST_IS_STRUCTURE (ptr)) {
835     return gst_info_structure_to_string ((const GstStructure *) ptr);
836   }
837   if (*(GType *) ptr == GST_TYPE_CAPS_FEATURES) {
838     return gst_caps_features_to_string ((const GstCapsFeatures *) ptr);
839   }
840   if (GST_IS_TAG_LIST (ptr)) {
841     gchar *str = gst_tag_list_to_string ((GstTagList *) ptr);
842     if (G_UNLIKELY (pretty_tags))
843       return prettify_structure_string (str);
844     else
845       return str;
846   }
847   if (*(GType *) ptr == GST_TYPE_DATE_TIME) {
848     return __gst_date_time_serialize ((GstDateTime *) ptr, TRUE);
849   }
850   if (GST_IS_BUFFER (ptr)) {
851     return gst_info_describe_buffer (GST_BUFFER_CAST (ptr));
852   }
853   if (GST_IS_BUFFER_LIST (ptr)) {
854     return gst_info_describe_buffer_list (GST_BUFFER_LIST_CAST (ptr));
855   }
856 #ifdef USE_POISONING
857   if (*(guint32 *) ptr == 0xffffffff) {
858     return g_strdup_printf ("<poisoned@%p>", ptr);
859   }
860 #endif
861   if (GST_IS_MESSAGE (object)) {
862     return gst_info_describe_message (GST_MESSAGE_CAST (object));
863   }
864   if (GST_IS_QUERY (object)) {
865     return gst_info_describe_query (GST_QUERY_CAST (object));
866   }
867   if (GST_IS_EVENT (object)) {
868     return gst_info_describe_event (GST_EVENT_CAST (object));
869   }
870   if (GST_IS_CONTEXT (object)) {
871     GstContext *context = GST_CONTEXT_CAST (object);
872     gchar *s, *ret;
873     const gchar *type;
874     const GstStructure *structure;
875
876     type = gst_context_get_context_type (context);
877     structure = gst_context_get_structure (context);
878
879     s = gst_info_structure_to_string (structure);
880
881     ret = g_strdup_printf ("context '%s'='%s'", type, s);
882     g_free (s);
883     return ret;
884   }
885   if (GST_IS_STREAM (object)) {
886     return gst_info_describe_stream (GST_STREAM_CAST (object));
887   }
888   if (GST_IS_STREAM_COLLECTION (object)) {
889     return
890         gst_info_describe_stream_collection (GST_STREAM_COLLECTION_CAST
891         (object));
892   }
893   if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
894     return g_strdup_printf ("<%s:%s>", GST_DEBUG_PAD_NAME (object));
895   }
896   if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object)) {
897     return g_strdup_printf ("<%s>", GST_OBJECT_NAME (object));
898   }
899   if (G_IS_OBJECT (object)) {
900     return g_strdup_printf ("<%s@%p>", G_OBJECT_TYPE_NAME (object), object);
901   }
902
903   return g_strdup_printf ("%p", ptr);
904 }
905
906 static gchar *
907 gst_debug_print_segment (gpointer ptr)
908 {
909   GstSegment *segment = (GstSegment *) ptr;
910
911   /* nicely printed segment */
912   if (segment == NULL) {
913     return g_strdup ("(NULL)");
914   }
915
916   switch (segment->format) {
917     case GST_FORMAT_UNDEFINED:{
918       return g_strdup_printf ("UNDEFINED segment");
919     }
920     case GST_FORMAT_TIME:{
921       return g_strdup_printf ("time segment start=%" GST_TIME_FORMAT
922           ", offset=%" GST_TIME_FORMAT ", stop=%" GST_TIME_FORMAT
923           ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" GST_TIME_FORMAT
924           ", base=%" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT
925           ", duration %" GST_TIME_FORMAT, GST_TIME_ARGS (segment->start),
926           GST_TIME_ARGS (segment->offset), GST_TIME_ARGS (segment->stop),
927           segment->rate, segment->applied_rate, (guint) segment->flags,
928           GST_TIME_ARGS (segment->time), GST_TIME_ARGS (segment->base),
929           GST_TIME_ARGS (segment->position), GST_TIME_ARGS (segment->duration));
930     }
931     default:{
932       const gchar *format_name;
933
934       format_name = gst_format_get_name (segment->format);
935       if (G_UNLIKELY (format_name == NULL))
936         format_name = "(UNKNOWN FORMAT)";
937       return g_strdup_printf ("%s segment start=%" G_GINT64_FORMAT
938           ", offset=%" G_GINT64_FORMAT ", stop=%" G_GINT64_FORMAT
939           ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" G_GINT64_FORMAT
940           ", base=%" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT
941           ", duration %" G_GINT64_FORMAT, format_name, segment->start,
942           segment->offset, segment->stop, segment->rate, segment->applied_rate,
943           (guint) segment->flags, segment->time, segment->base,
944           segment->position, segment->duration);
945     }
946   }
947 }
948
949 static char *
950 gst_info_printf_pointer_extension_func (const char *format, void *ptr)
951 {
952   char *s = NULL;
953
954   if (format[0] == 'p' && format[1] == '\a') {
955     switch (format[2]) {
956       case 'A':                /* GST_PTR_FORMAT     */
957         s = gst_debug_print_object (ptr);
958         break;
959       case 'B':                /* GST_SEGMENT_FORMAT */
960         s = gst_debug_print_segment (ptr);
961         break;
962       case 'a':                /* GST_WRAPPED_PTR_FORMAT */
963         s = priv_gst_string_take_and_wrap (gst_debug_print_object (ptr));
964         break;
965       default:
966         /* must have been compiled against a newer version with an extension
967          * we don't known about yet - just ignore and fallback to %p below */
968         break;
969     }
970   }
971   if (s == NULL)
972     s = g_strdup_printf ("%p", ptr);
973
974   return s;
975 }
976
977 /**
978  * gst_debug_construct_term_color:
979  * @colorinfo: the color info
980  *
981  * Constructs a string that can be used for getting the desired color in color
982  * terminals.
983  * You need to free the string after use.
984  *
985  * Returns: (transfer full) (type gchar*): a string containing the color
986  *     definition
987  */
988 gchar *
989 gst_debug_construct_term_color (guint colorinfo)
990 {
991   GString *color;
992
993   color = g_string_new ("\033[00");
994
995   if (colorinfo & GST_DEBUG_BOLD) {
996     g_string_append_len (color, ";01", 3);
997   }
998   if (colorinfo & GST_DEBUG_UNDERLINE) {
999     g_string_append_len (color, ";04", 3);
1000   }
1001   if (colorinfo & GST_DEBUG_FG_MASK) {
1002     g_string_append_printf (color, ";3%1d", colorinfo & GST_DEBUG_FG_MASK);
1003   }
1004   if (colorinfo & GST_DEBUG_BG_MASK) {
1005     g_string_append_printf (color, ";4%1d",
1006         (colorinfo & GST_DEBUG_BG_MASK) >> 4);
1007   }
1008   g_string_append_c (color, 'm');
1009
1010   return g_string_free (color, FALSE);
1011 }
1012
1013 /**
1014  * gst_debug_construct_win_color:
1015  * @colorinfo: the color info
1016  *
1017  * Constructs an integer that can be used for getting the desired color in
1018  * windows' terminals (cmd.exe). As there is no mean to underline, we simply
1019  * ignore this attribute.
1020  *
1021  * This function returns 0 on non-windows machines.
1022  *
1023  * Returns: an integer containing the color definition
1024  */
1025 gint
1026 gst_debug_construct_win_color (guint colorinfo)
1027 {
1028   gint color = 0;
1029 #ifdef G_OS_WIN32
1030   static const guchar ansi_to_win_fg[8] = {
1031     0,                          /* black   */
1032     FOREGROUND_RED,             /* red     */
1033     FOREGROUND_GREEN,           /* green   */
1034     FOREGROUND_RED | FOREGROUND_GREEN,  /* yellow  */
1035     FOREGROUND_BLUE,            /* blue    */
1036     FOREGROUND_RED | FOREGROUND_BLUE,   /* magenta */
1037     FOREGROUND_GREEN | FOREGROUND_BLUE, /* cyan    */
1038     FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE /* white   */
1039   };
1040   static const guchar ansi_to_win_bg[8] = {
1041     0,
1042     BACKGROUND_RED,
1043     BACKGROUND_GREEN,
1044     BACKGROUND_RED | BACKGROUND_GREEN,
1045     BACKGROUND_BLUE,
1046     BACKGROUND_RED | BACKGROUND_BLUE,
1047     BACKGROUND_GREEN | FOREGROUND_BLUE,
1048     BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
1049   };
1050
1051   /* we draw black as white, as cmd.exe can only have black bg */
1052   if ((colorinfo & (GST_DEBUG_FG_MASK | GST_DEBUG_BG_MASK)) == 0) {
1053     color = ansi_to_win_fg[7];
1054   }
1055   if (colorinfo & GST_DEBUG_UNDERLINE) {
1056     color |= BACKGROUND_INTENSITY;
1057   }
1058   if (colorinfo & GST_DEBUG_BOLD) {
1059     color |= FOREGROUND_INTENSITY;
1060   }
1061   if (colorinfo & GST_DEBUG_FG_MASK) {
1062     color |= ansi_to_win_fg[colorinfo & GST_DEBUG_FG_MASK];
1063   }
1064   if (colorinfo & GST_DEBUG_BG_MASK) {
1065     color |= ansi_to_win_bg[(colorinfo & GST_DEBUG_BG_MASK) >> 4];
1066   }
1067 #endif
1068   return color;
1069 }
1070
1071 /* width of %p varies depending on actual value of pointer, which can make
1072  * output unevenly aligned if multiple threads are involved, hence the %14p
1073  * (should really be %18p, but %14p seems a good compromise between too many
1074  * white spaces and likely unalignment on my system) */
1075 #if defined (GLIB_SIZEOF_VOID_P) && GLIB_SIZEOF_VOID_P == 8
1076 #define PTR_FMT "%14p"
1077 #else
1078 #define PTR_FMT "%10p"
1079 #endif
1080 #define PID_FMT "%5d"
1081 #define CAT_FMT "%20s %s:%d:%s:%s"
1082
1083 #ifdef G_OS_WIN32
1084 static const guchar levelcolormap_w32[GST_LEVEL_COUNT] = {
1085   /* GST_LEVEL_NONE */
1086   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1087   /* GST_LEVEL_ERROR */
1088   FOREGROUND_RED | FOREGROUND_INTENSITY,
1089   /* GST_LEVEL_WARNING */
1090   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1091   /* GST_LEVEL_INFO */
1092   FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1093   /* GST_LEVEL_DEBUG */
1094   FOREGROUND_GREEN | FOREGROUND_BLUE,
1095   /* GST_LEVEL_LOG */
1096   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1097   /* GST_LEVEL_FIXME */
1098   FOREGROUND_RED | FOREGROUND_GREEN,
1099   /* GST_LEVEL_TRACE */
1100   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1101   /* placeholder for log level 8 */
1102   0,
1103   /* GST_LEVEL_MEMDUMP */
1104   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
1105 };
1106
1107 static const guchar available_colors[] = {
1108   FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_RED | FOREGROUND_GREEN,
1109   FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_BLUE,
1110   FOREGROUND_GREEN | FOREGROUND_BLUE,
1111 };
1112 #endif /* G_OS_WIN32 */
1113 static const gchar *levelcolormap[GST_LEVEL_COUNT] = {
1114   "\033[37m",                   /* GST_LEVEL_NONE */
1115   "\033[31;01m",                /* GST_LEVEL_ERROR */
1116   "\033[33;01m",                /* GST_LEVEL_WARNING */
1117   "\033[32;01m",                /* GST_LEVEL_INFO */
1118   "\033[36m",                   /* GST_LEVEL_DEBUG */
1119   "\033[37m",                   /* GST_LEVEL_LOG */
1120   "\033[33;01m",                /* GST_LEVEL_FIXME */
1121   "\033[37m",                   /* GST_LEVEL_TRACE */
1122   "\033[37m",                   /* placeholder for log level 8 */
1123   "\033[37m"                    /* GST_LEVEL_MEMDUMP */
1124 };
1125
1126 /**
1127  * gst_debug_log_default:
1128  * @category: category to log
1129  * @level: level of the message
1130  * @file: the file that emitted the message, usually the __FILE__ identifier
1131  * @function: the function that emitted the message
1132  * @line: the line from that the message was emitted, usually __LINE__
1133  * @message: the actual message
1134  * @object: (transfer none) (allow-none): the object this message relates to,
1135  *     or %NULL if none
1136  * @user_data: the FILE* to log to
1137  *
1138  * The default logging handler used by GStreamer. Logging functions get called
1139  * whenever a macro like GST_DEBUG or similar is used. By default this function
1140  * is setup to output the message and additional info to stderr (or the log file
1141  * specified via the GST_DEBUG_FILE environment variable) as received via
1142  * @user_data.
1143  *
1144  * You can add other handlers by using gst_debug_add_log_function().
1145  * And you can remove this handler by calling
1146  * gst_debug_remove_log_function(gst_debug_log_default);
1147  */
1148 void
1149 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
1150     const gchar * file, const gchar * function, gint line,
1151     GObject * object, GstDebugMessage * message, gpointer user_data)
1152 {
1153   gint pid;
1154   GstClockTime elapsed;
1155   gchar *obj = NULL;
1156   GstDebugColorMode color_mode;
1157   const gchar *message_str;
1158   FILE *log_file = user_data ? user_data : stderr;
1159   gchar c;
1160
1161   /* Get message string first because printing it might call into our custom
1162    * printf format extension mechanism which in turn might log something, e.g.
1163    * from inside gst_structure_to_string() when something can't be serialised.
1164    * This means we either need to do this outside of any critical section or
1165    * use a recursive lock instead. As we always need the message string in all
1166    * code paths, we might just as well get it here first thing and outside of
1167    * the win_print_mutex critical section. */
1168   message_str = gst_debug_message_get (message);
1169
1170   /* __FILE__ might be a file name or an absolute path or a
1171    * relative path, irrespective of the exact compiler used,
1172    * in which case we want to shorten it to the filename for
1173    * readability. */
1174   c = file[0];
1175   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
1176     file = gst_path_basename (file);
1177   }
1178
1179   pid = getpid ();
1180   color_mode = gst_debug_get_color_mode ();
1181
1182   if (object) {
1183     obj = gst_debug_print_object (object);
1184   } else {
1185     obj = (gchar *) "";
1186   }
1187
1188   elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
1189
1190   if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
1191 #ifdef G_OS_WIN32
1192     G_LOCK (win_print_mutex);
1193     if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
1194 #endif
1195       /* colors, non-windows */
1196       gchar *color = NULL;
1197       const gchar *clear;
1198       gchar pidcolor[10];
1199       const gchar *levelcolor;
1200
1201       color = gst_debug_construct_term_color (gst_debug_category_get_color
1202           (category));
1203       clear = "\033[00m";
1204       g_sprintf (pidcolor, "\033[3%1dm", pid % 6 + 31);
1205       levelcolor = levelcolormap[level];
1206
1207 #define PRINT_FMT " %s"PID_FMT"%s "PTR_FMT" %s%s%s %s"CAT_FMT"%s %s\n"
1208       fprintf (log_file, "%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
1209           pidcolor, pid, clear, g_thread_self (), levelcolor,
1210           gst_debug_level_get_name (level), clear, color,
1211           gst_debug_category_get_name (category), file, line, function, obj,
1212           clear, message_str);
1213       fflush (log_file);
1214 #undef PRINT_FMT
1215       g_free (color);
1216 #ifdef G_OS_WIN32
1217     } else {
1218       /* colors, windows. */
1219       const gint clear = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
1220 #define SET_COLOR(c) G_STMT_START { \
1221   if (log_file == stderr) \
1222     SetConsoleTextAttribute (GetStdHandle (STD_ERROR_HANDLE), (c)); \
1223   } G_STMT_END
1224       /* timestamp */
1225       fprintf (log_file, "%" GST_TIME_FORMAT " ", GST_TIME_ARGS (elapsed));
1226       fflush (log_file);
1227       /* pid */
1228       SET_COLOR (available_colors[pid % G_N_ELEMENTS (available_colors)]);
1229       fprintf (log_file, PID_FMT, pid);
1230       fflush (log_file);
1231       /* thread */
1232       SET_COLOR (clear);
1233       fprintf (log_file, " " PTR_FMT " ", g_thread_self ());
1234       fflush (log_file);
1235       /* level */
1236       SET_COLOR (levelcolormap_w32[level]);
1237       fprintf (log_file, "%s ", gst_debug_level_get_name (level));
1238       fflush (log_file);
1239       /* category */
1240       SET_COLOR (gst_debug_construct_win_color (gst_debug_category_get_color
1241               (category)));
1242       fprintf (log_file, CAT_FMT, gst_debug_category_get_name (category),
1243           file, line, function, obj);
1244       fflush (log_file);
1245       /* message */
1246       SET_COLOR (clear);
1247       fprintf (log_file, " %s\n", message_str);
1248       fflush (log_file);
1249     }
1250     G_UNLOCK (win_print_mutex);
1251 #endif
1252   } else {
1253     /* no color, all platforms */
1254 #define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
1255     fprintf (log_file, "%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
1256         pid, g_thread_self (), gst_debug_level_get_name (level),
1257         gst_debug_category_get_name (category), file, line, function, obj,
1258         message_str);
1259     fflush (log_file);
1260 #undef PRINT_FMT
1261   }
1262
1263   if (object != NULL)
1264     g_free (obj);
1265 }
1266
1267 /**
1268  * gst_debug_level_get_name:
1269  * @level: the level to get the name for
1270  *
1271  * Get the string representation of a debugging level
1272  *
1273  * Returns: the name
1274  */
1275 const gchar *
1276 gst_debug_level_get_name (GstDebugLevel level)
1277 {
1278   switch (level) {
1279     case GST_LEVEL_NONE:
1280       return "";
1281     case GST_LEVEL_ERROR:
1282       return "ERROR  ";
1283     case GST_LEVEL_WARNING:
1284       return "WARN   ";
1285     case GST_LEVEL_INFO:
1286       return "INFO   ";
1287     case GST_LEVEL_DEBUG:
1288       return "DEBUG  ";
1289     case GST_LEVEL_LOG:
1290       return "LOG    ";
1291     case GST_LEVEL_FIXME:
1292       return "FIXME  ";
1293     case GST_LEVEL_TRACE:
1294       return "TRACE  ";
1295     case GST_LEVEL_MEMDUMP:
1296       return "MEMDUMP";
1297     default:
1298       g_warning ("invalid level specified for gst_debug_level_get_name");
1299       return "";
1300   }
1301 }
1302
1303 /**
1304  * gst_debug_add_log_function:
1305  * @func: the function to use
1306  * @user_data: user data
1307  * @notify: called when @user_data is not used anymore
1308  *
1309  * Adds the logging function to the list of logging functions.
1310  * Be sure to use #G_GNUC_NO_INSTRUMENT on that function, it is needed.
1311  */
1312 void
1313 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
1314     GDestroyNotify notify)
1315 {
1316   LogFuncEntry *entry;
1317   GSList *list;
1318
1319   if (func == NULL)
1320     func = gst_debug_log_default;
1321
1322   entry = g_slice_new (LogFuncEntry);
1323   entry->func = func;
1324   entry->user_data = user_data;
1325   entry->notify = notify;
1326   /* FIXME: we leak the old list here - other threads might access it right now
1327    * in gst_debug_logv. Another solution is to lock the mutex in gst_debug_logv,
1328    * but that is waaay costly.
1329    * It'd probably be clever to use some kind of RCU here, but I don't know
1330    * anything about that.
1331    */
1332   g_mutex_lock (&__log_func_mutex);
1333   list = g_slist_copy (__log_functions);
1334   __log_functions = g_slist_prepend (list, entry);
1335   g_mutex_unlock (&__log_func_mutex);
1336
1337   if (gst_is_initialized ())
1338     GST_DEBUG ("prepended log function %p (user data %p) to log functions",
1339         func, user_data);
1340 }
1341
1342 static gint
1343 gst_debug_compare_log_function_by_func (gconstpointer entry, gconstpointer func)
1344 {
1345   gpointer entryfunc = (gpointer) (((LogFuncEntry *) entry)->func);
1346
1347   return (entryfunc < func) ? -1 : (entryfunc > func) ? 1 : 0;
1348 }
1349
1350 static gint
1351 gst_debug_compare_log_function_by_data (gconstpointer entry, gconstpointer data)
1352 {
1353   gpointer entrydata = ((LogFuncEntry *) entry)->user_data;
1354
1355   return (entrydata < data) ? -1 : (entrydata > data) ? 1 : 0;
1356 }
1357
1358 static guint
1359 gst_debug_remove_with_compare_func (GCompareFunc func, gpointer data)
1360 {
1361   GSList *found;
1362   GSList *new, *cleanup = NULL;
1363   guint removals = 0;
1364
1365   g_mutex_lock (&__log_func_mutex);
1366   new = __log_functions;
1367   cleanup = NULL;
1368   while ((found = g_slist_find_custom (new, data, func))) {
1369     if (new == __log_functions) {
1370       /* make a copy when we have the first hit, so that we modify the copy and
1371        * make that the new list later */
1372       new = g_slist_copy (new);
1373       continue;
1374     }
1375     cleanup = g_slist_prepend (cleanup, found->data);
1376     new = g_slist_delete_link (new, found);
1377     removals++;
1378   }
1379   /* FIXME: We leak the old list here. See _add_log_function for why. */
1380   __log_functions = new;
1381   g_mutex_unlock (&__log_func_mutex);
1382
1383   while (cleanup) {
1384     LogFuncEntry *entry = cleanup->data;
1385
1386     if (entry->notify)
1387       entry->notify (entry->user_data);
1388
1389     g_slice_free (LogFuncEntry, entry);
1390     cleanup = g_slist_delete_link (cleanup, cleanup);
1391   }
1392   return removals;
1393 }
1394
1395 /**
1396  * gst_debug_remove_log_function:
1397  * @func: (scope call) (allow-none): the log function to remove, or %NULL to
1398  *     remove the default log function
1399  *
1400  * Removes all registered instances of the given logging functions.
1401  *
1402  * Returns: How many instances of the function were removed
1403  */
1404 guint
1405 gst_debug_remove_log_function (GstLogFunction func)
1406 {
1407   guint removals;
1408
1409   if (func == NULL)
1410     func = gst_debug_log_default;
1411
1412   removals =
1413       gst_debug_remove_with_compare_func
1414       (gst_debug_compare_log_function_by_func, (gpointer) func);
1415
1416   if (gst_is_initialized ()) {
1417     GST_DEBUG ("removed log function %p %d times from log function list", func,
1418         removals);
1419   } else {
1420     /* If the default log function is removed before gst_init() was called,
1421      * set a flag so we don't add it in gst_init() later */
1422     if (func == gst_debug_log_default) {
1423       add_default_log_func = FALSE;
1424       ++removals;
1425     }
1426   }
1427
1428   return removals;
1429 }
1430
1431 /**
1432  * gst_debug_remove_log_function_by_data:
1433  * @data: user data of the log function to remove
1434  *
1435  * Removes all registered instances of log functions with the given user data.
1436  *
1437  * Returns: How many instances of the function were removed
1438  */
1439 guint
1440 gst_debug_remove_log_function_by_data (gpointer data)
1441 {
1442   guint removals;
1443
1444   removals =
1445       gst_debug_remove_with_compare_func
1446       (gst_debug_compare_log_function_by_data, data);
1447
1448   if (gst_is_initialized ())
1449     GST_DEBUG
1450         ("removed %d log functions with user data %p from log function list",
1451         removals, data);
1452
1453   return removals;
1454 }
1455
1456 /**
1457  * gst_debug_set_colored:
1458  * @colored: Whether to use colored output or not
1459  *
1460  * Sets or unsets the use of coloured debugging output.
1461  * Same as gst_debug_set_color_mode () with the argument being
1462  * being GST_DEBUG_COLOR_MODE_ON or GST_DEBUG_COLOR_MODE_OFF.
1463  *
1464  * This function may be called before gst_init().
1465  */
1466 void
1467 gst_debug_set_colored (gboolean colored)
1468 {
1469   GstDebugColorMode new_mode;
1470   new_mode = colored ? GST_DEBUG_COLOR_MODE_ON : GST_DEBUG_COLOR_MODE_OFF;
1471   g_atomic_int_set (&__use_color, (gint) new_mode);
1472 }
1473
1474 /**
1475  * gst_debug_set_color_mode:
1476  * @mode: The coloring mode for debug output. See @GstDebugColorMode.
1477  *
1478  * Changes the coloring mode for debug output.
1479  *
1480  * This function may be called before gst_init().
1481  *
1482  * Since: 1.2
1483  */
1484 void
1485 gst_debug_set_color_mode (GstDebugColorMode mode)
1486 {
1487   g_atomic_int_set (&__use_color, mode);
1488 }
1489
1490 /**
1491  * gst_debug_set_color_mode_from_string:
1492  * @mode: The coloring mode for debug output. One of the following:
1493  * "on", "auto", "off", "disable", "unix".
1494  *
1495  * Changes the coloring mode for debug output.
1496  *
1497  * This function may be called before gst_init().
1498  *
1499  * Since: 1.2
1500  */
1501 void
1502 gst_debug_set_color_mode_from_string (const gchar * mode)
1503 {
1504   if ((strcmp (mode, "on") == 0) || (strcmp (mode, "auto") == 0))
1505     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_ON);
1506   else if ((strcmp (mode, "off") == 0) || (strcmp (mode, "disable") == 0))
1507     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
1508   else if (strcmp (mode, "unix") == 0)
1509     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_UNIX);
1510 }
1511
1512 /**
1513  * gst_debug_is_colored:
1514  *
1515  * Checks if the debugging output should be colored.
1516  *
1517  * Returns: %TRUE, if the debug output should be colored.
1518  */
1519 gboolean
1520 gst_debug_is_colored (void)
1521 {
1522   GstDebugColorMode mode = g_atomic_int_get (&__use_color);
1523   return (mode == GST_DEBUG_COLOR_MODE_UNIX || mode == GST_DEBUG_COLOR_MODE_ON);
1524 }
1525
1526 /**
1527  * gst_debug_get_color_mode:
1528  *
1529  * Changes the coloring mode for debug output.
1530  *
1531  * Returns: see @GstDebugColorMode for possible values.
1532  *
1533  * Since: 1.2
1534  */
1535 GstDebugColorMode
1536 gst_debug_get_color_mode (void)
1537 {
1538   return g_atomic_int_get (&__use_color);
1539 }
1540
1541 /**
1542  * gst_debug_set_active:
1543  * @active: Whether to use debugging output or not
1544  *
1545  * If activated, debugging messages are sent to the debugging
1546  * handlers.
1547  * It makes sense to deactivate it for speed issues.
1548  * > This function is not threadsafe. It makes sense to only call it
1549  * during initialization.
1550  */
1551 void
1552 gst_debug_set_active (gboolean active)
1553 {
1554   _gst_debug_enabled = active;
1555   if (active)
1556     _gst_debug_min = GST_LEVEL_COUNT;
1557   else
1558     _gst_debug_min = GST_LEVEL_NONE;
1559 }
1560
1561 /**
1562  * gst_debug_is_active:
1563  *
1564  * Checks if debugging output is activated.
1565  *
1566  * Returns: %TRUE, if debugging is activated
1567  */
1568 gboolean
1569 gst_debug_is_active (void)
1570 {
1571   return _gst_debug_enabled;
1572 }
1573
1574 /**
1575  * gst_debug_set_default_threshold:
1576  * @level: level to set
1577  *
1578  * Sets the default threshold to the given level and updates all categories to
1579  * use this threshold.
1580  *
1581  * This function may be called before gst_init().
1582  */
1583 void
1584 gst_debug_set_default_threshold (GstDebugLevel level)
1585 {
1586   g_atomic_int_set (&__default_level, level);
1587   gst_debug_reset_all_thresholds ();
1588 }
1589
1590 /**
1591  * gst_debug_get_default_threshold:
1592  *
1593  * Returns the default threshold that is used for new categories.
1594  *
1595  * Returns: the default threshold level
1596  */
1597 GstDebugLevel
1598 gst_debug_get_default_threshold (void)
1599 {
1600   return (GstDebugLevel) g_atomic_int_get (&__default_level);
1601 }
1602
1603 static gboolean
1604 gst_debug_apply_entry (GstDebugCategory * cat, LevelNameEntry * entry)
1605 {
1606   if (!g_pattern_match_string (entry->pat, cat->name))
1607     return FALSE;
1608
1609   if (gst_is_initialized ())
1610     GST_LOG ("category %s matches pattern %p - gets set to level %d",
1611         cat->name, entry->pat, entry->level);
1612
1613   gst_debug_category_set_threshold (cat, entry->level);
1614   return TRUE;
1615 }
1616
1617 static void
1618 gst_debug_reset_threshold (gpointer category, gpointer unused)
1619 {
1620   GstDebugCategory *cat = (GstDebugCategory *) category;
1621   GSList *walk;
1622
1623   g_mutex_lock (&__level_name_mutex);
1624
1625   for (walk = __level_name; walk != NULL; walk = walk->next) {
1626     if (gst_debug_apply_entry (cat, walk->data))
1627       break;
1628   }
1629
1630   g_mutex_unlock (&__level_name_mutex);
1631
1632   if (walk == NULL)
1633     gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
1634 }
1635
1636 static void
1637 gst_debug_reset_all_thresholds (void)
1638 {
1639   g_mutex_lock (&__cat_mutex);
1640   g_slist_foreach (__categories, gst_debug_reset_threshold, NULL);
1641   g_mutex_unlock (&__cat_mutex);
1642 }
1643
1644 static void
1645 for_each_threshold_by_entry (gpointer data, gpointer user_data)
1646 {
1647   GstDebugCategory *cat = (GstDebugCategory *) data;
1648   LevelNameEntry *entry = (LevelNameEntry *) user_data;
1649
1650   gst_debug_apply_entry (cat, entry);
1651 }
1652
1653 /**
1654  * gst_debug_set_threshold_for_name:
1655  * @name: name of the categories to set
1656  * @level: level to set them to
1657  *
1658  * Sets all categories which match the given glob style pattern to the given
1659  * level.
1660  */
1661 void
1662 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
1663 {
1664   GPatternSpec *pat;
1665   LevelNameEntry *entry;
1666
1667   g_return_if_fail (name != NULL);
1668
1669   pat = g_pattern_spec_new (name);
1670   entry = g_slice_new (LevelNameEntry);
1671   entry->pat = pat;
1672   entry->level = level;
1673   g_mutex_lock (&__level_name_mutex);
1674   __level_name = g_slist_prepend (__level_name, entry);
1675   g_mutex_unlock (&__level_name_mutex);
1676   g_mutex_lock (&__cat_mutex);
1677   g_slist_foreach (__categories, for_each_threshold_by_entry, entry);
1678   g_mutex_unlock (&__cat_mutex);
1679 }
1680
1681 /**
1682  * gst_debug_unset_threshold_for_name:
1683  * @name: name of the categories to set
1684  *
1685  * Resets all categories with the given name back to the default level.
1686  */
1687 void
1688 gst_debug_unset_threshold_for_name (const gchar * name)
1689 {
1690   GSList *walk;
1691   GPatternSpec *pat;
1692
1693   g_return_if_fail (name != NULL);
1694
1695   pat = g_pattern_spec_new (name);
1696   g_mutex_lock (&__level_name_mutex);
1697   walk = __level_name;
1698   /* improve this if you want, it's mighty slow */
1699   while (walk) {
1700     LevelNameEntry *entry = walk->data;
1701
1702     if (g_pattern_spec_equal (entry->pat, pat)) {
1703       __level_name = g_slist_remove_link (__level_name, walk);
1704       g_pattern_spec_free (entry->pat);
1705       g_slice_free (LevelNameEntry, entry);
1706       g_slist_free_1 (walk);
1707       walk = __level_name;
1708     } else {
1709       walk = g_slist_next (walk);
1710     }
1711   }
1712   g_mutex_unlock (&__level_name_mutex);
1713   g_pattern_spec_free (pat);
1714   gst_debug_reset_all_thresholds ();
1715 }
1716
1717 GstDebugCategory *
1718 _gst_debug_category_new (const gchar * name, guint color,
1719     const gchar * description)
1720 {
1721   GstDebugCategory *cat, *catfound;
1722
1723   g_return_val_if_fail (name != NULL, NULL);
1724
1725   cat = g_slice_new (GstDebugCategory);
1726   cat->name = g_strdup (name);
1727   cat->color = color;
1728   if (description != NULL) {
1729     cat->description = g_strdup (description);
1730   } else {
1731     cat->description = g_strdup ("no description");
1732   }
1733   g_atomic_int_set (&cat->threshold, 0);
1734   gst_debug_reset_threshold (cat, NULL);
1735
1736   /* add to category list */
1737   g_mutex_lock (&__cat_mutex);
1738   catfound = _gst_debug_get_category_locked (name);
1739   if (catfound) {
1740     g_free ((gpointer) cat->name);
1741     g_free ((gpointer) cat->description);
1742     g_slice_free (GstDebugCategory, cat);
1743     cat = catfound;
1744   } else {
1745     __categories = g_slist_prepend (__categories, cat);
1746   }
1747   g_mutex_unlock (&__cat_mutex);
1748
1749   return cat;
1750 }
1751
1752 /**
1753  * gst_debug_category_free:
1754  * @category: #GstDebugCategory to free.
1755  *
1756  * Removes and frees the category and all associated resources.
1757  */
1758 void
1759 gst_debug_category_free (GstDebugCategory * category)
1760 {
1761   if (category == NULL)
1762     return;
1763
1764   /* remove from category list */
1765   g_mutex_lock (&__cat_mutex);
1766   __categories = g_slist_remove (__categories, category);
1767   g_mutex_unlock (&__cat_mutex);
1768
1769   g_free ((gpointer) category->name);
1770   g_free ((gpointer) category->description);
1771   g_slice_free (GstDebugCategory, category);
1772 }
1773
1774 /**
1775  * gst_debug_category_set_threshold:
1776  * @category: a #GstDebugCategory to set threshold of.
1777  * @level: the #GstDebugLevel threshold to set.
1778  *
1779  * Sets the threshold of the category to the given level. Debug information will
1780  * only be output if the threshold is lower or equal to the level of the
1781  * debugging message.
1782  * > Do not use this function in production code, because other functions may
1783  * > change the threshold of categories as side effect. It is however a nice
1784  * > function to use when debugging (even from gdb).
1785  */
1786 void
1787 gst_debug_category_set_threshold (GstDebugCategory * category,
1788     GstDebugLevel level)
1789 {
1790   g_return_if_fail (category != NULL);
1791
1792   if (level > _gst_debug_min) {
1793     _gst_debug_enabled = TRUE;
1794     _gst_debug_min = level;
1795   }
1796
1797   g_atomic_int_set (&category->threshold, level);
1798 }
1799
1800 /**
1801  * gst_debug_category_reset_threshold:
1802  * @category: a #GstDebugCategory to reset threshold of.
1803  *
1804  * Resets the threshold of the category to the default level. Debug information
1805  * will only be output if the threshold is lower or equal to the level of the
1806  * debugging message.
1807  * Use this function to set the threshold back to where it was after using
1808  * gst_debug_category_set_threshold().
1809  */
1810 void
1811 gst_debug_category_reset_threshold (GstDebugCategory * category)
1812 {
1813   gst_debug_reset_threshold (category, NULL);
1814 }
1815
1816 /**
1817  * gst_debug_category_get_threshold:
1818  * @category: a #GstDebugCategory to get threshold of.
1819  *
1820  * Returns the threshold of a #GstDebugCategory.
1821  *
1822  * Returns: the #GstDebugLevel that is used as threshold.
1823  */
1824 GstDebugLevel
1825 gst_debug_category_get_threshold (GstDebugCategory * category)
1826 {
1827   return (GstDebugLevel) g_atomic_int_get (&category->threshold);
1828 }
1829
1830 /**
1831  * gst_debug_category_get_name:
1832  * @category: a #GstDebugCategory to get name of.
1833  *
1834  * Returns the name of a debug category.
1835  *
1836  * Returns: the name of the category.
1837  */
1838 const gchar *
1839 gst_debug_category_get_name (GstDebugCategory * category)
1840 {
1841   return category->name;
1842 }
1843
1844 /**
1845  * gst_debug_category_get_color:
1846  * @category: a #GstDebugCategory to get the color of.
1847  *
1848  * Returns the color of a debug category used when printing output in this
1849  * category.
1850  *
1851  * Returns: the color of the category.
1852  */
1853 guint
1854 gst_debug_category_get_color (GstDebugCategory * category)
1855 {
1856   return category->color;
1857 }
1858
1859 /**
1860  * gst_debug_category_get_description:
1861  * @category: a #GstDebugCategory to get the description of.
1862  *
1863  * Returns the description of a debug category.
1864  *
1865  * Returns: the description of the category.
1866  */
1867 const gchar *
1868 gst_debug_category_get_description (GstDebugCategory * category)
1869 {
1870   return category->description;
1871 }
1872
1873 /**
1874  * gst_debug_get_all_categories:
1875  *
1876  * Returns a snapshot of a all categories that are currently in use . This list
1877  * may change anytime.
1878  * The caller has to free the list after use.
1879  *
1880  * Returns: (transfer container) (element-type Gst.DebugCategory): the list of
1881  *     debug categories
1882  */
1883 GSList *
1884 gst_debug_get_all_categories (void)
1885 {
1886   GSList *ret;
1887
1888   g_mutex_lock (&__cat_mutex);
1889   ret = g_slist_copy (__categories);
1890   g_mutex_unlock (&__cat_mutex);
1891
1892   return ret;
1893 }
1894
1895 static GstDebugCategory *
1896 _gst_debug_get_category_locked (const gchar * name)
1897 {
1898   GstDebugCategory *ret = NULL;
1899   GSList *node;
1900
1901   for (node = __categories; node; node = g_slist_next (node)) {
1902     ret = (GstDebugCategory *) node->data;
1903     if (!strcmp (name, ret->name)) {
1904       return ret;
1905     }
1906   }
1907   return NULL;
1908 }
1909
1910 GstDebugCategory *
1911 _gst_debug_get_category (const gchar * name)
1912 {
1913   GstDebugCategory *ret;
1914
1915   g_mutex_lock (&__cat_mutex);
1916   ret = _gst_debug_get_category_locked (name);
1917   g_mutex_unlock (&__cat_mutex);
1918
1919   return ret;
1920 }
1921
1922 static gboolean
1923 parse_debug_category (gchar * str, const gchar ** category)
1924 {
1925   if (!str)
1926     return FALSE;
1927
1928   /* works in place */
1929   g_strstrip (str);
1930
1931   if (str[0] != '\0') {
1932     *category = str;
1933     return TRUE;
1934   }
1935
1936   return FALSE;
1937 }
1938
1939 static gboolean
1940 parse_debug_level (gchar * str, GstDebugLevel * level)
1941 {
1942   if (!str)
1943     return FALSE;
1944
1945   /* works in place */
1946   g_strstrip (str);
1947
1948   if (g_ascii_isdigit (str[0])) {
1949     unsigned long l;
1950     char *endptr;
1951     l = strtoul (str, &endptr, 10);
1952     if (endptr > str && endptr[0] == 0) {
1953       *level = (GstDebugLevel) l;
1954     } else {
1955       return FALSE;
1956     }
1957   } else if (strcmp (str, "ERROR") == 0) {
1958     *level = GST_LEVEL_ERROR;
1959   } else if (strncmp (str, "WARN", 4) == 0) {
1960     *level = GST_LEVEL_WARNING;
1961   } else if (strcmp (str, "FIXME") == 0) {
1962     *level = GST_LEVEL_FIXME;
1963   } else if (strcmp (str, "INFO") == 0) {
1964     *level = GST_LEVEL_INFO;
1965   } else if (strcmp (str, "DEBUG") == 0) {
1966     *level = GST_LEVEL_DEBUG;
1967   } else if (strcmp (str, "LOG") == 0) {
1968     *level = GST_LEVEL_LOG;
1969   } else if (strcmp (str, "TRACE") == 0) {
1970     *level = GST_LEVEL_TRACE;
1971   } else if (strcmp (str, "MEMDUMP") == 0) {
1972     *level = GST_LEVEL_MEMDUMP;
1973   } else
1974     return FALSE;
1975
1976   return TRUE;
1977 }
1978
1979 /**
1980  * gst_debug_set_threshold_from_string:
1981  * @list: comma-separated list of "category:level" pairs to be used
1982  *     as debug logging levels
1983  * @reset: %TRUE to clear all previously-set debug levels before setting
1984  *     new thresholds
1985  * %FALSE if adding the threshold described by @list to the one already set.
1986  *
1987  * Sets the debug logging wanted in the same form as with the GST_DEBUG
1988  * environment variable. You can use wildcards such as '*', but note that
1989  * the order matters when you use wild cards, e.g. "foosrc:6,*src:3,*:2" sets
1990  * everything to log level 2.
1991  *
1992  * Since: 1.2
1993  */
1994 void
1995 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
1996 {
1997   gchar **split;
1998   gchar **walk;
1999
2000   g_assert (list);
2001
2002   if (reset)
2003     gst_debug_set_default_threshold (GST_LEVEL_DEFAULT);
2004
2005   split = g_strsplit (list, ",", 0);
2006
2007   for (walk = split; *walk; walk++) {
2008     if (strchr (*walk, ':')) {
2009       gchar **values = g_strsplit (*walk, ":", 2);
2010
2011       if (values[0] && values[1]) {
2012         GstDebugLevel level;
2013         const gchar *category;
2014
2015         if (parse_debug_category (values[0], &category)
2016             && parse_debug_level (values[1], &level)) {
2017           gst_debug_set_threshold_for_name (category, level);
2018
2019           /* bump min-level anyway to allow the category to be registered in the
2020            * future still */
2021           if (level > _gst_debug_min) {
2022             _gst_debug_min = level;
2023           }
2024         }
2025       }
2026
2027       g_strfreev (values);
2028     } else {
2029       GstDebugLevel level;
2030
2031       if (parse_debug_level (*walk, &level))
2032         gst_debug_set_default_threshold (level);
2033     }
2034   }
2035
2036   g_strfreev (split);
2037 }
2038
2039 /*** FUNCTION POINTERS ********************************************************/
2040
2041 static GHashTable *__gst_function_pointers;     /* NULL */
2042 static GMutex __dbg_functions_mutex;
2043
2044 /* This function MUST NOT return NULL */
2045 const gchar *
2046 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2047 {
2048   gchar *ptrname;
2049
2050 #ifdef HAVE_DLADDR
2051   Dl_info dl_info;
2052 #endif
2053
2054   if (G_UNLIKELY (func == NULL))
2055     return "(NULL)";
2056
2057   g_mutex_lock (&__dbg_functions_mutex);
2058   if (G_LIKELY (__gst_function_pointers)) {
2059     ptrname = g_hash_table_lookup (__gst_function_pointers, (gpointer) func);
2060     g_mutex_unlock (&__dbg_functions_mutex);
2061     if (G_LIKELY (ptrname))
2062       return ptrname;
2063   } else {
2064     g_mutex_unlock (&__dbg_functions_mutex);
2065   }
2066   /* we need to create an entry in the hash table for this one so we don't leak
2067    * the name */
2068 #ifdef HAVE_DLADDR
2069   if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
2070     const gchar *name = g_intern_string (dl_info.dli_sname);
2071
2072     _gst_debug_register_funcptr (func, name);
2073     return name;
2074   } else
2075 #endif
2076   {
2077     gchar *name = g_strdup_printf ("%p", (gpointer) func);
2078     const gchar *iname = g_intern_string (name);
2079
2080     g_free (name);
2081
2082     _gst_debug_register_funcptr (func, iname);
2083     return iname;
2084   }
2085 }
2086
2087 void
2088 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2089 {
2090   gpointer ptr = (gpointer) func;
2091
2092   g_mutex_lock (&__dbg_functions_mutex);
2093
2094   if (!__gst_function_pointers)
2095     __gst_function_pointers = g_hash_table_new (g_direct_hash, g_direct_equal);
2096   if (!g_hash_table_lookup (__gst_function_pointers, ptr)) {
2097     g_hash_table_insert (__gst_function_pointers, ptr, (gpointer) ptrname);
2098   }
2099
2100   g_mutex_unlock (&__dbg_functions_mutex);
2101 }
2102
2103 void
2104 _priv_gst_debug_cleanup (void)
2105 {
2106   g_mutex_lock (&__dbg_functions_mutex);
2107
2108   if (__gst_function_pointers) {
2109     g_hash_table_unref (__gst_function_pointers);
2110     __gst_function_pointers = NULL;
2111   }
2112
2113   g_mutex_unlock (&__dbg_functions_mutex);
2114 }
2115
2116 static void
2117 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2118     const guint8 * mem, gsize mem_offset, gsize mem_size)
2119 {
2120   gchar hexstr[50], ascstr[18], digitstr[4];
2121
2122   if (mem_size > 16)
2123     mem_size = 16;
2124
2125   hexstr[0] = '\0';
2126   ascstr[0] = '\0';
2127
2128   if (mem != NULL) {
2129     guint i = 0;
2130
2131     mem += mem_offset;
2132     while (i < mem_size) {
2133       ascstr[i] = (g_ascii_isprint (mem[i])) ? mem[i] : '.';
2134       g_snprintf (digitstr, sizeof (digitstr), "%02x ", mem[i]);
2135       g_strlcat (hexstr, digitstr, sizeof (hexstr));
2136       ++i;
2137     }
2138     ascstr[i] = '\0';
2139   }
2140
2141   g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2142       (guint) mem_offset, hexstr, ascstr);
2143 }
2144
2145 void
2146 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2147     const gchar * func, gint line, GObject * obj, const gchar * msg,
2148     const guint8 * data, guint length)
2149 {
2150   guint off = 0;
2151
2152   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2153       "-------------------------------------------------------------------");
2154
2155   if (msg != NULL && *msg != '\0') {
2156     gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", msg);
2157   }
2158
2159   while (off < length) {
2160     gchar buf[128];
2161
2162     /* gst_info_dump_mem_line will process 16 bytes at most */
2163     gst_info_dump_mem_line (buf, sizeof (buf), data, off, length - off);
2164     gst_debug_log (cat, GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", buf);
2165     off += 16;
2166   }
2167
2168   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2169       "-------------------------------------------------------------------");
2170 }
2171
2172 #else /* !GST_DISABLE_GST_DEBUG */
2173 #ifndef GST_REMOVE_DISABLED
2174
2175 GstDebugCategory *
2176 _gst_debug_category_new (const gchar * name, guint color,
2177     const gchar * description)
2178 {
2179   return NULL;
2180 }
2181
2182 void
2183 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2184 {
2185 }
2186
2187 /* This function MUST NOT return NULL */
2188 const gchar *
2189 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2190 {
2191   return "(NULL)";
2192 }
2193
2194 void
2195 _priv_gst_debug_cleanup (void)
2196 {
2197 }
2198
2199 void
2200 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2201     const gchar * file, const gchar * function, gint line,
2202     GObject * object, const gchar * format, ...)
2203 {
2204 }
2205
2206 void
2207 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
2208     const gchar * file, const gchar * function, gint line,
2209     GObject * object, const gchar * format, va_list args)
2210 {
2211 }
2212
2213 const gchar *
2214 gst_debug_message_get (GstDebugMessage * message)
2215 {
2216   return "";
2217 }
2218
2219 void
2220 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
2221     const gchar * file, const gchar * function, gint line,
2222     GObject * object, GstDebugMessage * message, gpointer unused)
2223 {
2224 }
2225
2226 const gchar *
2227 gst_debug_level_get_name (GstDebugLevel level)
2228 {
2229   return "NONE";
2230 }
2231
2232 void
2233 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2234     GDestroyNotify notify)
2235 {
2236 }
2237
2238 guint
2239 gst_debug_remove_log_function (GstLogFunction func)
2240 {
2241   return 0;
2242 }
2243
2244 guint
2245 gst_debug_remove_log_function_by_data (gpointer data)
2246 {
2247   return 0;
2248 }
2249
2250 void
2251 gst_debug_set_active (gboolean active)
2252 {
2253 }
2254
2255 gboolean
2256 gst_debug_is_active (void)
2257 {
2258   return FALSE;
2259 }
2260
2261 void
2262 gst_debug_set_colored (gboolean colored)
2263 {
2264 }
2265
2266 void
2267 gst_debug_set_color_mode (GstDebugColorMode mode)
2268 {
2269 }
2270
2271 void
2272 gst_debug_set_color_mode_from_string (const gchar * str)
2273 {
2274 }
2275
2276 gboolean
2277 gst_debug_is_colored (void)
2278 {
2279   return FALSE;
2280 }
2281
2282 GstDebugColorMode
2283 gst_debug_get_color_mode (void)
2284 {
2285   return GST_DEBUG_COLOR_MODE_OFF;
2286 }
2287
2288 void
2289 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2290 {
2291 }
2292
2293 void
2294 gst_debug_set_default_threshold (GstDebugLevel level)
2295 {
2296 }
2297
2298 GstDebugLevel
2299 gst_debug_get_default_threshold (void)
2300 {
2301   return GST_LEVEL_NONE;
2302 }
2303
2304 void
2305 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2306 {
2307 }
2308
2309 void
2310 gst_debug_unset_threshold_for_name (const gchar * name)
2311 {
2312 }
2313
2314 void
2315 gst_debug_category_free (GstDebugCategory * category)
2316 {
2317 }
2318
2319 void
2320 gst_debug_category_set_threshold (GstDebugCategory * category,
2321     GstDebugLevel level)
2322 {
2323 }
2324
2325 void
2326 gst_debug_category_reset_threshold (GstDebugCategory * category)
2327 {
2328 }
2329
2330 GstDebugLevel
2331 gst_debug_category_get_threshold (GstDebugCategory * category)
2332 {
2333   return GST_LEVEL_NONE;
2334 }
2335
2336 const gchar *
2337 gst_debug_category_get_name (GstDebugCategory * category)
2338 {
2339   return "";
2340 }
2341
2342 guint
2343 gst_debug_category_get_color (GstDebugCategory * category)
2344 {
2345   return 0;
2346 }
2347
2348 const gchar *
2349 gst_debug_category_get_description (GstDebugCategory * category)
2350 {
2351   return "";
2352 }
2353
2354 GSList *
2355 gst_debug_get_all_categories (void)
2356 {
2357   return NULL;
2358 }
2359
2360 GstDebugCategory *
2361 _gst_debug_get_category (const gchar * name)
2362 {
2363   return NULL;
2364 }
2365
2366 gchar *
2367 gst_debug_construct_term_color (guint colorinfo)
2368 {
2369   return g_strdup ("00");
2370 }
2371
2372 gint
2373 gst_debug_construct_win_color (guint colorinfo)
2374 {
2375   return 0;
2376 }
2377
2378 gboolean
2379 _priv_gst_in_valgrind (void)
2380 {
2381   return FALSE;
2382 }
2383
2384 void
2385 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2386     const gchar * func, gint line, GObject * obj, const gchar * msg,
2387     const guint8 * data, guint length)
2388 {
2389 }
2390 #endif /* GST_REMOVE_DISABLED */
2391 #endif /* GST_DISABLE_GST_DEBUG */
2392
2393 /* Need this for _gst_element_error_printf even if GST_REMOVE_DISABLED is set:
2394  * fallback function that cleans up the format string and replaces all pointer
2395  * extension formats with plain %p. */
2396 #ifdef GST_DISABLE_GST_DEBUG
2397 int
2398 __gst_info_fallback_vasprintf (char **result, char const *format, va_list args)
2399 {
2400   gchar *clean_format, *c;
2401   gsize len;
2402
2403   if (format == NULL)
2404     return -1;
2405
2406   clean_format = g_strdup (format);
2407   c = clean_format;
2408   while ((c = strstr (c, "%p\a"))) {
2409     if (c[3] < 'A' || c[3] > 'Z') {
2410       c += 3;
2411       continue;
2412     }
2413     len = strlen (c + 4);
2414     memmove (c + 2, c + 4, len + 1);
2415     c += 2;
2416   }
2417   while ((c = strstr (clean_format, "%P")))     /* old GST_PTR_FORMAT */
2418     c[1] = 'p';
2419   while ((c = strstr (clean_format, "%Q")))     /* old GST_SEGMENT_FORMAT */
2420     c[1] = 'p';
2421
2422   len = g_vasprintf (result, clean_format, args);
2423
2424   g_free (clean_format);
2425
2426   if (*result == NULL)
2427     return -1;
2428
2429   return len;
2430 }
2431 #endif
2432
2433 /**
2434  * gst_info_vasprintf:
2435  * @result: (out): the resulting string
2436  * @format: a printf style format string
2437  * @args: the va_list of printf arguments for @format
2438  *
2439  * Allocates and fills a string large enough (including the terminating null
2440  * byte) to hold the specified printf style @format and @args.
2441  *
2442  * This function deals with the GStreamer specific printf specifiers
2443  * #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.  If you do not have these specifiers
2444  * in your @format string, you do not need to use this function and can use
2445  * alternatives such as g_vasprintf().
2446  *
2447  * Free @result with g_free().
2448  *
2449  * Returns: the length of the string allocated into @result or -1 on any error
2450  *
2451  * Since: 1.8
2452  */
2453 gint
2454 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2455 {
2456   /* This will fallback to __gst_info_fallback_vasprintf() via a #define in
2457    * gst_private.h if the debug system is disabled which will remove the gst
2458    * specific printf format specifiers */
2459   return __gst_vasprintf (result, format, args);
2460 }
2461
2462 /**
2463  * gst_info_strdup_vprintf:
2464  * @format: a printf style format string
2465  * @args: the va_list of printf arguments for @format
2466  *
2467  * Allocates, fills and returns a null terminated string from the printf style
2468  * @format string and @args.
2469  *
2470  * See gst_info_vasprintf() for when this function is required.
2471  *
2472  * Free with g_free().
2473  *
2474  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2475  *
2476  * Since: 1.8
2477  */
2478 gchar *
2479 gst_info_strdup_vprintf (const gchar * format, va_list args)
2480 {
2481   gchar *ret;
2482
2483   if (gst_info_vasprintf (&ret, format, args) < 0)
2484     ret = NULL;
2485
2486   return ret;
2487 }
2488
2489 /**
2490  * gst_info_strdup_printf:
2491  * @format: a printf style format string
2492  * @...: the printf arguments for @format
2493  *
2494  * Allocates, fills and returns a 0-terminated string from the printf style
2495  * @format string and corresponding arguments.
2496  *
2497  * See gst_info_vasprintf() for when this function is required.
2498  *
2499  * Free with g_free().
2500  *
2501  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2502  *
2503  * Since: 1.8
2504  */
2505 gchar *
2506 gst_info_strdup_printf (const gchar * format, ...)
2507 {
2508   gchar *ret;
2509   va_list args;
2510
2511   va_start (args, format);
2512   ret = gst_info_strdup_vprintf (format, args);
2513   va_end (args);
2514
2515   return ret;
2516 }
2517
2518 /**
2519  * gst_print:
2520  * @format: a printf style format string
2521  * @...: the printf arguments for @format
2522  *
2523  * Outputs a formatted message via the GLib print handler. The default print
2524  * handler simply outputs the message to stdout.
2525  *
2526  * This function will not append a new-line character at the end, unlike
2527  * gst_println() which will.
2528  *
2529  * All strings must be in ASCII or UTF-8 encoding.
2530  *
2531  * This function differs from g_print() in that it supports all the additional
2532  * printf specifiers that are supported by GStreamer's debug logging system,
2533  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2534  *
2535  * This function is primarily for printing debug output.
2536  *
2537  * Since: 1.12
2538  */
2539 void
2540 gst_print (const gchar * format, ...)
2541 {
2542   va_list args;
2543   gchar *str;
2544
2545   va_start (args, format);
2546   str = gst_info_strdup_vprintf (format, args);
2547   va_end (args);
2548
2549 #ifdef G_OS_WIN32
2550   G_LOCK (win_print_mutex);
2551 #endif
2552
2553   g_print ("%s", str);
2554
2555 #ifdef G_OS_WIN32
2556   G_UNLOCK (win_print_mutex);
2557 #endif
2558   g_free (str);
2559 }
2560
2561 /**
2562  * gst_println:
2563  * @format: a printf style format string
2564  * @...: the printf arguments for @format
2565  *
2566  * Outputs a formatted message via the GLib print handler. The default print
2567  * handler simply outputs the message to stdout.
2568  *
2569  * This function will append a new-line character at the end, unlike
2570  * gst_print() which will not.
2571  *
2572  * All strings must be in ASCII or UTF-8 encoding.
2573  *
2574  * This function differs from g_print() in that it supports all the additional
2575  * printf specifiers that are supported by GStreamer's debug logging system,
2576  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2577  *
2578  * This function is primarily for printing debug output.
2579  *
2580  * Since: 1.12
2581  */
2582 void
2583 gst_println (const gchar * format, ...)
2584 {
2585   va_list args;
2586   gchar *str;
2587
2588   va_start (args, format);
2589   str = gst_info_strdup_vprintf (format, args);
2590   va_end (args);
2591
2592 #ifdef G_OS_WIN32
2593   G_LOCK (win_print_mutex);
2594 #endif
2595
2596   g_print ("%s\n", str);
2597
2598 #ifdef G_OS_WIN32
2599   G_UNLOCK (win_print_mutex);
2600 #endif
2601   g_free (str);
2602 }
2603
2604 /**
2605  * gst_printerr:
2606  * @format: a printf style format string
2607  * @...: the printf arguments for @format
2608  *
2609  * Outputs a formatted message via the GLib error message handler. The default
2610  * handler simply outputs the message to stderr.
2611  *
2612  * This function will not append a new-line character at the end, unlike
2613  * gst_printerrln() which will.
2614  *
2615  * All strings must be in ASCII or UTF-8 encoding.
2616  *
2617  * This function differs from g_printerr() in that it supports the additional
2618  * printf specifiers that are supported by GStreamer's debug logging system,
2619  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2620  *
2621  * This function is primarily for printing debug output.
2622  *
2623  * Since: 1.12
2624  */
2625 void
2626 gst_printerr (const gchar * format, ...)
2627 {
2628   va_list args;
2629   gchar *str;
2630
2631   va_start (args, format);
2632   str = gst_info_strdup_vprintf (format, args);
2633   va_end (args);
2634
2635 #ifdef G_OS_WIN32
2636   G_LOCK (win_print_mutex);
2637 #endif
2638
2639   g_printerr ("%s", str);
2640
2641 #ifdef G_OS_WIN32
2642   G_UNLOCK (win_print_mutex);
2643 #endif
2644   g_free (str);
2645 }
2646
2647 /**
2648  * gst_printerrln:
2649  * @format: a printf style format string
2650  * @...: the printf arguments for @format
2651  *
2652  * Outputs a formatted message via the GLib error message handler. The default
2653  * handler simply outputs the message to stderr.
2654  *
2655  * This function will append a new-line character at the end, unlike
2656  * gst_printerr() which will not.
2657  *
2658  * All strings must be in ASCII or UTF-8 encoding.
2659  *
2660  * This function differs from g_printerr() in that it supports the additional
2661  * printf specifiers that are supported by GStreamer's debug logging system,
2662  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2663  *
2664  * This function is primarily for printing debug output.
2665  *
2666  * Since: 1.12
2667  */
2668 void
2669 gst_printerrln (const gchar * format, ...)
2670 {
2671   va_list args;
2672   gchar *str;
2673
2674   va_start (args, format);
2675   str = gst_info_strdup_vprintf (format, args);
2676   va_end (args);
2677
2678 #ifdef G_OS_WIN32
2679   G_LOCK (win_print_mutex);
2680 #endif
2681
2682   g_printerr ("%s\n", str);
2683
2684 #ifdef G_OS_WIN32
2685   G_UNLOCK (win_print_mutex);
2686 #endif
2687   g_free (str);
2688 }
2689
2690 #ifdef HAVE_UNWIND
2691 #ifdef HAVE_DW
2692 static gboolean
2693 append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
2694 {
2695   Dwfl_Line *line;
2696   Dwarf_Addr addr;
2697   Dwfl_Module *module;
2698   const gchar *function_name;
2699
2700   if (dwfl_linux_proc_report (dwfl, getpid ()) != 0)
2701     return FALSE;
2702
2703   if (dwfl_report_end (dwfl, NULL, NULL))
2704     return FALSE;
2705
2706   addr = (uintptr_t) ip;
2707   module = dwfl_addrmodule (dwfl, addr);
2708   function_name = dwfl_module_addrname (module, addr);
2709
2710   g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
2711
2712   line = dwfl_getsrc (dwfl, addr);
2713   if (line != NULL) {
2714     gint nline;
2715     Dwarf_Addr addr;
2716     const gchar *filename = dwfl_lineinfo (line, &addr,
2717         &nline, NULL, NULL, NULL);
2718
2719     g_string_append_printf (trace, "%s:%d", strrchr (filename,
2720             G_DIR_SEPARATOR) + 1, nline);
2721   } else {
2722     const gchar *eflfile = NULL;
2723
2724     dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
2725     g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
2726   }
2727
2728   return TRUE;
2729 }
2730 #endif /* HAVE_DW */
2731
2732 static gchar *
2733 generate_unwind_trace (GstStackTraceFlags flags)
2734 {
2735   gint unret;
2736   unw_context_t uc;
2737   unw_cursor_t cursor;
2738   gboolean use_libunwind = TRUE;
2739   GString *trace = g_string_new (NULL);
2740
2741 #ifdef HAVE_DW
2742   Dwfl *dwfl = NULL;
2743   Dwfl_Callbacks callbacks = {
2744     .find_elf = dwfl_linux_proc_find_elf,
2745     .find_debuginfo = dwfl_standard_find_debuginfo,
2746   };
2747
2748   if ((flags & GST_STACK_TRACE_SHOW_FULL))
2749     dwfl = dwfl_begin (&callbacks);
2750 #endif /* HAVE_DW */
2751
2752   unret = unw_getcontext (&uc);
2753   if (unret) {
2754     GST_DEBUG ("Could not get libunwind context (%d)", unret);
2755
2756     goto done;
2757   }
2758   unret = unw_init_local (&cursor, &uc);
2759   if (unret) {
2760     GST_DEBUG ("Could not init libunwind context (%d)", unret);
2761
2762     goto done;
2763   }
2764
2765   while (unw_step (&cursor) > 0) {
2766 #ifdef HAVE_DW
2767     if (dwfl) {
2768       unw_word_t ip;
2769
2770       unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
2771       if (unret) {
2772         GST_DEBUG ("libunwind could read frame info (%d)", unret);
2773
2774         goto done;
2775       }
2776
2777       if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
2778         use_libunwind = FALSE;
2779         g_string_append (trace, ")\n");
2780       }
2781     }
2782 #endif /* HAVE_DW */
2783
2784     if (use_libunwind) {
2785       char name[32];
2786
2787       unw_word_t offset = 0;
2788       unw_get_proc_name (&cursor, name, sizeof (name), &offset);
2789       g_string_append_printf (trace, "%s (0x%" G_GSIZE_FORMAT ")\n", name,
2790           (gsize) offset);
2791     }
2792   }
2793
2794 done:
2795 #ifdef HAVE_DW
2796   if (dwfl)
2797     dwfl_end (dwfl);
2798 #endif
2799
2800   return g_string_free (trace, FALSE);
2801 }
2802
2803 #endif /* HAVE_UNWIND */
2804
2805 #ifdef HAVE_BACKTRACE
2806 static gchar *
2807 generate_backtrace_trace (void)
2808 {
2809   int j, nptrs;
2810   void *buffer[BT_BUF_SIZE];
2811   char **strings;
2812   GString *trace;
2813
2814   trace = g_string_new (NULL);
2815   nptrs = backtrace (buffer, BT_BUF_SIZE);
2816
2817   strings = backtrace_symbols (buffer, nptrs);
2818
2819   if (!strings)
2820     return NULL;
2821
2822   for (j = 0; j < nptrs; j++)
2823     g_string_append_printf (trace, "%s\n", strings[j]);
2824
2825   free (strings);
2826
2827   return g_string_free (trace, FALSE);
2828 }
2829 #else
2830 #define generate_backtrace_trace() NULL
2831 #endif /* HAVE_BACKTRACE */
2832
2833 #ifdef HAVE_DBGHELP
2834 static void
2835 dbghelp_initialize_symbols (HANDLE process)
2836 {
2837   static gsize initialization_value = 0;
2838
2839   if (g_once_init_enter (&initialization_value)) {
2840     GST_INFO ("Initializing Windows symbol handler");
2841     SymSetOptions (SYMOPT_LOAD_LINES);
2842     SymInitialize (process, NULL, TRUE);
2843     GST_INFO ("Initialized Windows symbol handler");
2844
2845     g_once_init_leave (&initialization_value, 1);
2846   }
2847 }
2848
2849 static gchar *
2850 generate_dbghelp_trace (void)
2851 {
2852   HANDLE process = GetCurrentProcess ();
2853   HANDLE thread = GetCurrentThread ();
2854   IMAGEHLP_MODULE64 module_info;
2855   DWORD machine;
2856   CONTEXT context;
2857   STACKFRAME64 frame = { 0 };
2858   PVOID save_context;
2859   GString *trace = g_string_new (NULL);
2860
2861   dbghelp_initialize_symbols (process);
2862
2863   memset (&context, 0, sizeof (CONTEXT));
2864   context.ContextFlags = CONTEXT_FULL;
2865
2866   RtlCaptureContext (&context);
2867
2868   frame.AddrPC.Mode = AddrModeFlat;
2869   frame.AddrStack.Mode = AddrModeFlat;
2870   frame.AddrFrame.Mode = AddrModeFlat;
2871
2872 #if (defined _M_IX86)
2873   machine = IMAGE_FILE_MACHINE_I386;
2874   frame.AddrFrame.Offset = context.Ebp;
2875   frame.AddrPC.Offset = context.Eip;
2876   frame.AddrStack.Offset = context.Esp;
2877 #elif (defined _M_X64)
2878   machine = IMAGE_FILE_MACHINE_AMD64;
2879   frame.AddrFrame.Offset = context.Rbp;
2880   frame.AddrPC.Offset = context.Rip;
2881   frame.AddrStack.Offset = context.Rsp;
2882 #else
2883   goto done;
2884 #endif
2885
2886   module_info.SizeOfStruct = sizeof (module_info);
2887   save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
2888
2889   while (TRUE) {
2890     char buffer[sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR)];
2891     PSYMBOL_INFO symbol = (PSYMBOL_INFO) buffer;
2892     IMAGEHLP_LINE64 line;
2893     DWORD displacement = 0;
2894
2895     symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
2896     symbol->MaxNameLen = MAX_SYM_NAME;
2897
2898     line.SizeOfStruct = sizeof (line);
2899
2900     if (!StackWalk64 (machine, process, thread, &frame, save_context, 0,
2901             SymFunctionTableAccess64, SymGetModuleBase64, 0))
2902       break;
2903
2904     if (SymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
2905       g_string_append_printf (trace, "%s ", symbol->Name);
2906     else
2907       g_string_append (trace, "?? ");
2908
2909     if (SymGetLineFromAddr64 (process, frame.AddrPC.Offset, &displacement,
2910             &line))
2911       g_string_append_printf (trace, "(%s:%u)", line.FileName, line.LineNumber);
2912     else if (SymGetModuleInfo64 (process, frame.AddrPC.Offset, &module_info))
2913       g_string_append_printf (trace, "(%s)", module_info.ImageName);
2914     else
2915       g_string_append_printf (trace, "(%s)", "??");
2916
2917     g_string_append (trace, "\n");
2918   }
2919
2920 done:
2921   return g_string_free (trace, FALSE);
2922 }
2923 #endif /* HAVE_DBGHELP */
2924
2925 /**
2926  * gst_debug_get_stack_trace:
2927  * @flags: A set of #GstStackTraceFlags to determine how the stack
2928  * trace should look like. Pass 0 to retrieve a minimal backtrace.
2929  *
2930  * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
2931  * present, else %NULL.
2932  *
2933  * Since: 1.12
2934  */
2935 gchar *
2936 gst_debug_get_stack_trace (GstStackTraceFlags flags)
2937 {
2938   gchar *trace = NULL;
2939 #ifdef HAVE_BACKTRACE
2940   gboolean have_backtrace = TRUE;
2941 #else
2942   gboolean have_backtrace = FALSE;
2943 #endif
2944
2945 #ifdef HAVE_UNWIND
2946   if ((flags & GST_STACK_TRACE_SHOW_FULL) || !have_backtrace)
2947     trace = generate_unwind_trace (flags);
2948 #endif /* HAVE_UNWIND */
2949
2950 #ifdef HAVE_DBGHELP
2951   trace = generate_dbghelp_trace ();
2952 #endif
2953
2954   if (trace)
2955     return trace;
2956   else if (have_backtrace)
2957     return generate_backtrace_trace ();
2958
2959   return NULL;
2960 }
2961
2962 /**
2963  * gst_debug_print_stack_trace:
2964  *
2965  * If libunwind, glibc backtrace or DbgHelp are present
2966  * a stack trace is printed.
2967  */
2968 void
2969 gst_debug_print_stack_trace (void)
2970 {
2971   gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
2972
2973   if (trace) {
2974 #ifdef G_OS_WIN32
2975     G_LOCK (win_print_mutex);
2976 #endif
2977
2978     g_print ("%s\n", trace);
2979
2980 #ifdef G_OS_WIN32
2981     G_UNLOCK (win_print_mutex);
2982 #endif
2983   }
2984
2985   g_free (trace);
2986 }
2987
2988 #ifndef GST_DISABLE_GST_DEBUG
2989 typedef struct
2990 {
2991   guint max_size_per_thread;
2992   guint thread_timeout;
2993   GQueue threads;
2994   GHashTable *thread_index;
2995 } GstRingBufferLogger;
2996
2997 typedef struct
2998 {
2999   GList *link;
3000   gint64 last_use;
3001   GThread *thread;
3002
3003   GQueue log;
3004   gsize log_size;
3005 } GstRingBufferLog;
3006
3007 G_LOCK_DEFINE_STATIC (ring_buffer_logger);
3008 static GstRingBufferLogger *ring_buffer_logger = NULL;
3009
3010 static void
3011 gst_ring_buffer_logger_log (GstDebugCategory * category,
3012     GstDebugLevel level,
3013     const gchar * file,
3014     const gchar * function,
3015     gint line, GObject * object, GstDebugMessage * message, gpointer user_data)
3016 {
3017   GstRingBufferLogger *logger = user_data;
3018   gint pid;
3019   GThread *thread;
3020   GstClockTime elapsed;
3021   gchar *obj = NULL;
3022   gchar c;
3023   gchar *output;
3024   gsize output_len;
3025   GstRingBufferLog *log;
3026   gint64 now = g_get_monotonic_time ();
3027   const gchar *message_str = gst_debug_message_get (message);
3028
3029   /* __FILE__ might be a file name or an absolute path or a
3030    * relative path, irrespective of the exact compiler used,
3031    * in which case we want to shorten it to the filename for
3032    * readability. */
3033   c = file[0];
3034   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
3035     file = gst_path_basename (file);
3036   }
3037
3038   if (object) {
3039     obj = gst_debug_print_object (object);
3040   } else {
3041     obj = (gchar *) "";
3042   }
3043
3044   elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
3045   pid = getpid ();
3046   thread = g_thread_self ();
3047
3048   /* no color, all platforms */
3049 #define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
3050   output =
3051       g_strdup_printf ("%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
3052       pid, thread, gst_debug_level_get_name (level),
3053       gst_debug_category_get_name (category), file, line, function, obj,
3054       message_str);
3055 #undef PRINT_FMT
3056
3057   output_len = strlen (output);
3058
3059   if (object != NULL)
3060     g_free (obj);
3061
3062   G_LOCK (ring_buffer_logger);
3063
3064   if (logger->thread_timeout > 0) {
3065     gchar *buf;
3066
3067     /* Remove all threads that saw no output since thread_timeout seconds.
3068      * By construction these are all at the tail of the queue, and the queue
3069      * is ordered by last use, so we just need to look at the tail.
3070      */
3071     while (logger->threads.tail) {
3072       log = logger->threads.tail->data;
3073       if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
3074         break;
3075
3076       g_hash_table_remove (logger->thread_index, log->thread);
3077       while ((buf = g_queue_pop_head (&log->log)))
3078         g_free (buf);
3079       g_free (log);
3080       g_queue_pop_tail (&logger->threads);
3081     }
3082   }
3083
3084   /* Get logger for this thread, and put it back at the
3085    * head of the threads queue */
3086   log = g_hash_table_lookup (logger->thread_index, thread);
3087   if (!log) {
3088     log = g_new0 (GstRingBufferLog, 1);
3089     g_queue_init (&log->log);
3090     log->log_size = 0;
3091     g_queue_push_head (&logger->threads, log);
3092     log->link = logger->threads.head;
3093     log->thread = thread;
3094     g_hash_table_insert (logger->thread_index, thread, log);
3095   } else {
3096     g_queue_unlink (&logger->threads, log->link);
3097     g_queue_push_head_link (&logger->threads, log->link);
3098   }
3099   log->last_use = now;
3100
3101   if (output_len < logger->max_size_per_thread) {
3102     gchar *buf;
3103
3104     /* While using a GQueue here is not the most efficient thing to do, we
3105      * have to allocate a string for every output anyway and could just store
3106      * that instead of copying it to an actual ringbuffer.
3107      * Better than GQueue would be GstQueueArray, but that one is in
3108      * libgstbase and we can't use it here. That one allocation will not make
3109      * much of a difference anymore, considering the number of allocations
3110      * needed to get to this point...
3111      */
3112     while (log->log_size + output_len > logger->max_size_per_thread) {
3113       buf = g_queue_pop_head (&log->log);
3114       log->log_size -= strlen (buf);
3115       g_free (buf);
3116     }
3117     g_queue_push_tail (&log->log, output);
3118     log->log_size += output_len;
3119   } else {
3120     gchar *buf;
3121
3122     /* Can't really write anything as the line is bigger than the maximum
3123      * allowed log size already, so just remove everything */
3124
3125     while ((buf = g_queue_pop_head (&log->log)))
3126       g_free (buf);
3127     g_free (output);
3128     log->log_size = 0;
3129   }
3130
3131   G_UNLOCK (ring_buffer_logger);
3132 }
3133
3134 /**
3135  * gst_debug_ring_buffer_logger_get_logs:
3136  *
3137  * Fetches the current logs per thread from the ring buffer logger. See
3138  * gst_debug_add_ring_buffer_logger() for details.
3139  *
3140  * Returns: (transfer full) (array zero-terminated): NULL-terminated array of
3141  * strings with the debug output per thread
3142  *
3143  * Since: 1.14
3144  */
3145 gchar **
3146 gst_debug_ring_buffer_logger_get_logs (void)
3147 {
3148   gchar **logs, **tmp;
3149   GList *l;
3150
3151   g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
3152
3153   G_LOCK (ring_buffer_logger);
3154
3155   tmp = logs = g_new0 (gchar *, ring_buffer_logger->threads.length + 1);
3156   for (l = ring_buffer_logger->threads.head; l; l = l->next) {
3157     GstRingBufferLog *log = l->data;
3158     GList *l;
3159     gchar *p;
3160     gsize len;
3161
3162     *tmp = p = g_new0 (gchar, log->log_size + 1);
3163
3164     for (l = log->log.head; l; l = l->next) {
3165       len = strlen (l->data);
3166       memcpy (p, l->data, len);
3167       p += len;
3168     }
3169
3170     tmp++;
3171   }
3172
3173   G_UNLOCK (ring_buffer_logger);
3174
3175   return logs;
3176 }
3177
3178 static void
3179 gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
3180 {
3181   G_LOCK (ring_buffer_logger);
3182   if (ring_buffer_logger == logger) {
3183     GstRingBufferLog *log;
3184
3185     while ((log = g_queue_pop_head (&logger->threads))) {
3186       gchar *buf;
3187       while ((buf = g_queue_pop_head (&log->log)))
3188         g_free (buf);
3189       g_free (log);
3190     }
3191
3192     g_hash_table_unref (logger->thread_index);
3193
3194     g_free (logger);
3195     ring_buffer_logger = NULL;
3196   }
3197   G_UNLOCK (ring_buffer_logger);
3198 }
3199
3200 /**
3201  * gst_debug_add_ring_buffer_logger:
3202  * @max_size_per_thread: Maximum size of log per thread in bytes
3203  * @thread_timeout: Timeout for threads in seconds
3204  *
3205  * Adds a memory ringbuffer based debug logger that stores up to
3206  * @max_size_per_thread bytes of logs per thread and times out threads after
3207  * @thread_timeout seconds of inactivity.
3208  *
3209  * Logs can be fetched with gst_debug_ring_buffer_logger_get_logs() and the
3210  * logger can be removed again with gst_debug_remove_ring_buffer_logger().
3211  * Only one logger at a time is possible.
3212  *
3213  * Since: 1.14
3214  */
3215 void
3216 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3217     guint thread_timeout)
3218 {
3219   GstRingBufferLogger *logger;
3220
3221   G_LOCK (ring_buffer_logger);
3222
3223   if (ring_buffer_logger) {
3224     g_warn_if_reached ();
3225     G_UNLOCK (ring_buffer_logger);
3226     return;
3227   }
3228
3229   logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
3230
3231   logger->max_size_per_thread = max_size_per_thread;
3232   logger->thread_timeout = thread_timeout;
3233   logger->thread_index = g_hash_table_new (g_direct_hash, g_direct_equal);
3234   g_queue_init (&logger->threads);
3235
3236   gst_debug_add_log_function (gst_ring_buffer_logger_log, logger,
3237       (GDestroyNotify) gst_ring_buffer_logger_free);
3238   G_UNLOCK (ring_buffer_logger);
3239 }
3240
3241 /**
3242  * gst_debug_remove_ring_buffer_logger:
3243  *
3244  * Removes any previously added ring buffer logger with
3245  * gst_debug_add_ring_buffer_logger().
3246  *
3247  * Since: 1.14
3248  */
3249 void
3250 gst_debug_remove_ring_buffer_logger (void)
3251 {
3252   gst_debug_remove_log_function (gst_ring_buffer_logger_log);
3253 }
3254
3255 #else /* GST_DISABLE_GST_DEBUG */
3256 #ifndef GST_REMOVE_DISABLED
3257
3258 gchar **
3259 gst_debug_ring_buffer_logger_get_logs (void)
3260 {
3261   return NULL;
3262 }
3263
3264 void
3265 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3266     guint thread_timeout)
3267 {
3268 }
3269
3270 void
3271 gst_debug_remove_ring_buffer_logger (void)
3272 {
3273 }
3274
3275 #endif /* GST_REMOVE_DISABLED */
3276 #endif /* GST_DISABLE_GST_DEBUG */