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