gstinfo: clean up function pointer names hashtable
[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     const gchar *name = g_intern_string (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     const gchar *iname = g_intern_string (name);
2072
2073     g_free (name);
2074
2075     _gst_debug_register_funcptr (func, iname);
2076     return iname;
2077   }
2078 }
2079
2080 void
2081 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2082 {
2083   gpointer ptr = (gpointer) func;
2084
2085   g_mutex_lock (&__dbg_functions_mutex);
2086
2087   if (!__gst_function_pointers)
2088     __gst_function_pointers = g_hash_table_new (g_direct_hash, g_direct_equal);
2089   if (!g_hash_table_lookup (__gst_function_pointers, ptr)) {
2090     g_hash_table_insert (__gst_function_pointers, ptr, (gpointer) ptrname);
2091   }
2092
2093   g_mutex_unlock (&__dbg_functions_mutex);
2094 }
2095
2096 void
2097 _priv_gst_debug_cleanup (void)
2098 {
2099   g_mutex_lock (&__dbg_functions_mutex);
2100
2101   if (__gst_function_pointers) {
2102     g_hash_table_unref (__gst_function_pointers);
2103     __gst_function_pointers = NULL;
2104   }
2105
2106   g_mutex_unlock (&__dbg_functions_mutex);
2107 }
2108
2109 static void
2110 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2111     const guint8 * mem, gsize mem_offset, gsize mem_size)
2112 {
2113   gchar hexstr[50], ascstr[18], digitstr[4];
2114
2115   if (mem_size > 16)
2116     mem_size = 16;
2117
2118   hexstr[0] = '\0';
2119   ascstr[0] = '\0';
2120
2121   if (mem != NULL) {
2122     guint i = 0;
2123
2124     mem += mem_offset;
2125     while (i < mem_size) {
2126       ascstr[i] = (g_ascii_isprint (mem[i])) ? mem[i] : '.';
2127       g_snprintf (digitstr, sizeof (digitstr), "%02x ", mem[i]);
2128       g_strlcat (hexstr, digitstr, sizeof (hexstr));
2129       ++i;
2130     }
2131     ascstr[i] = '\0';
2132   }
2133
2134   g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2135       (guint) mem_offset, hexstr, ascstr);
2136 }
2137
2138 void
2139 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2140     const gchar * func, gint line, GObject * obj, const gchar * msg,
2141     const guint8 * data, guint length)
2142 {
2143   guint off = 0;
2144
2145   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2146       "-------------------------------------------------------------------");
2147
2148   if (msg != NULL && *msg != '\0') {
2149     gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", msg);
2150   }
2151
2152   while (off < length) {
2153     gchar buf[128];
2154
2155     /* gst_info_dump_mem_line will process 16 bytes at most */
2156     gst_info_dump_mem_line (buf, sizeof (buf), data, off, length - off);
2157     gst_debug_log (cat, GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", buf);
2158     off += 16;
2159   }
2160
2161   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2162       "-------------------------------------------------------------------");
2163 }
2164
2165 #else /* !GST_DISABLE_GST_DEBUG */
2166 #ifndef GST_REMOVE_DISABLED
2167
2168 GstDebugCategory *
2169 _gst_debug_category_new (const gchar * name, guint color,
2170     const gchar * description)
2171 {
2172   return NULL;
2173 }
2174
2175 void
2176 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2177 {
2178 }
2179
2180 /* This function MUST NOT return NULL */
2181 const gchar *
2182 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2183 {
2184   return "(NULL)";
2185 }
2186
2187 void
2188 _priv_gst_debug_cleanup (void)
2189 {
2190 }
2191
2192 void
2193 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2194     const gchar * file, const gchar * function, gint line,
2195     GObject * object, const gchar * format, ...)
2196 {
2197 }
2198
2199 void
2200 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
2201     const gchar * file, const gchar * function, gint line,
2202     GObject * object, const gchar * format, va_list args)
2203 {
2204 }
2205
2206 const gchar *
2207 gst_debug_message_get (GstDebugMessage * message)
2208 {
2209   return "";
2210 }
2211
2212 void
2213 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
2214     const gchar * file, const gchar * function, gint line,
2215     GObject * object, GstDebugMessage * message, gpointer unused)
2216 {
2217 }
2218
2219 const gchar *
2220 gst_debug_level_get_name (GstDebugLevel level)
2221 {
2222   return "NONE";
2223 }
2224
2225 void
2226 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2227     GDestroyNotify notify)
2228 {
2229 }
2230
2231 guint
2232 gst_debug_remove_log_function (GstLogFunction func)
2233 {
2234   return 0;
2235 }
2236
2237 guint
2238 gst_debug_remove_log_function_by_data (gpointer data)
2239 {
2240   return 0;
2241 }
2242
2243 void
2244 gst_debug_set_active (gboolean active)
2245 {
2246 }
2247
2248 gboolean
2249 gst_debug_is_active (void)
2250 {
2251   return FALSE;
2252 }
2253
2254 void
2255 gst_debug_set_colored (gboolean colored)
2256 {
2257 }
2258
2259 void
2260 gst_debug_set_color_mode (GstDebugColorMode mode)
2261 {
2262 }
2263
2264 void
2265 gst_debug_set_color_mode_from_string (const gchar * str)
2266 {
2267 }
2268
2269 gboolean
2270 gst_debug_is_colored (void)
2271 {
2272   return FALSE;
2273 }
2274
2275 GstDebugColorMode
2276 gst_debug_get_color_mode (void)
2277 {
2278   return GST_DEBUG_COLOR_MODE_OFF;
2279 }
2280
2281 void
2282 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2283 {
2284 }
2285
2286 void
2287 gst_debug_set_default_threshold (GstDebugLevel level)
2288 {
2289 }
2290
2291 GstDebugLevel
2292 gst_debug_get_default_threshold (void)
2293 {
2294   return GST_LEVEL_NONE;
2295 }
2296
2297 void
2298 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2299 {
2300 }
2301
2302 void
2303 gst_debug_unset_threshold_for_name (const gchar * name)
2304 {
2305 }
2306
2307 void
2308 gst_debug_category_free (GstDebugCategory * category)
2309 {
2310 }
2311
2312 void
2313 gst_debug_category_set_threshold (GstDebugCategory * category,
2314     GstDebugLevel level)
2315 {
2316 }
2317
2318 void
2319 gst_debug_category_reset_threshold (GstDebugCategory * category)
2320 {
2321 }
2322
2323 GstDebugLevel
2324 gst_debug_category_get_threshold (GstDebugCategory * category)
2325 {
2326   return GST_LEVEL_NONE;
2327 }
2328
2329 const gchar *
2330 gst_debug_category_get_name (GstDebugCategory * category)
2331 {
2332   return "";
2333 }
2334
2335 guint
2336 gst_debug_category_get_color (GstDebugCategory * category)
2337 {
2338   return 0;
2339 }
2340
2341 const gchar *
2342 gst_debug_category_get_description (GstDebugCategory * category)
2343 {
2344   return "";
2345 }
2346
2347 GSList *
2348 gst_debug_get_all_categories (void)
2349 {
2350   return NULL;
2351 }
2352
2353 GstDebugCategory *
2354 _gst_debug_get_category (const gchar * name)
2355 {
2356   return NULL;
2357 }
2358
2359 gchar *
2360 gst_debug_construct_term_color (guint colorinfo)
2361 {
2362   return g_strdup ("00");
2363 }
2364
2365 gint
2366 gst_debug_construct_win_color (guint colorinfo)
2367 {
2368   return 0;
2369 }
2370
2371 gboolean
2372 _priv_gst_in_valgrind (void)
2373 {
2374   return FALSE;
2375 }
2376
2377 void
2378 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2379     const gchar * func, gint line, GObject * obj, const gchar * msg,
2380     const guint8 * data, guint length)
2381 {
2382 }
2383 #endif /* GST_REMOVE_DISABLED */
2384 #endif /* GST_DISABLE_GST_DEBUG */
2385
2386 /* Need this for _gst_element_error_printf even if GST_REMOVE_DISABLED is set:
2387  * fallback function that cleans up the format string and replaces all pointer
2388  * extension formats with plain %p. */
2389 #ifdef GST_DISABLE_GST_DEBUG
2390 int
2391 __gst_info_fallback_vasprintf (char **result, char const *format, va_list args)
2392 {
2393   gchar *clean_format, *c;
2394   gsize len;
2395
2396   if (format == NULL)
2397     return -1;
2398
2399   clean_format = g_strdup (format);
2400   c = clean_format;
2401   while ((c = strstr (c, "%p\a"))) {
2402     if (c[3] < 'A' || c[3] > 'Z') {
2403       c += 3;
2404       continue;
2405     }
2406     len = strlen (c + 4);
2407     memmove (c + 2, c + 4, len + 1);
2408     c += 2;
2409   }
2410   while ((c = strstr (clean_format, "%P")))     /* old GST_PTR_FORMAT */
2411     c[1] = 'p';
2412   while ((c = strstr (clean_format, "%Q")))     /* old GST_SEGMENT_FORMAT */
2413     c[1] = 'p';
2414
2415   len = g_vasprintf (result, clean_format, args);
2416
2417   g_free (clean_format);
2418
2419   if (*result == NULL)
2420     return -1;
2421
2422   return len;
2423 }
2424 #endif
2425
2426 /**
2427  * gst_info_vasprintf:
2428  * @result: (out): the resulting string
2429  * @format: a printf style format string
2430  * @args: the va_list of printf arguments for @format
2431  *
2432  * Allocates and fills a string large enough (including the terminating null
2433  * byte) to hold the specified printf style @format and @args.
2434  *
2435  * This function deals with the GStreamer specific printf specifiers
2436  * #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.  If you do not have these specifiers
2437  * in your @format string, you do not need to use this function and can use
2438  * alternatives such as g_vasprintf().
2439  *
2440  * Free @result with g_free().
2441  *
2442  * Returns: the length of the string allocated into @result or -1 on any error
2443  *
2444  * Since: 1.8
2445  */
2446 gint
2447 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2448 {
2449   /* This will fallback to __gst_info_fallback_vasprintf() via a #define in
2450    * gst_private.h if the debug system is disabled which will remove the gst
2451    * specific printf format specifiers */
2452   return __gst_vasprintf (result, format, args);
2453 }
2454
2455 /**
2456  * gst_info_strdup_vprintf:
2457  * @format: a printf style format string
2458  * @args: the va_list of printf arguments for @format
2459  *
2460  * Allocates, fills and returns a null terminated string from the printf style
2461  * @format string and @args.
2462  *
2463  * See gst_info_vasprintf() for when this function is required.
2464  *
2465  * Free with g_free().
2466  *
2467  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2468  *
2469  * Since: 1.8
2470  */
2471 gchar *
2472 gst_info_strdup_vprintf (const gchar * format, va_list args)
2473 {
2474   gchar *ret;
2475
2476   if (gst_info_vasprintf (&ret, format, args) < 0)
2477     ret = NULL;
2478
2479   return ret;
2480 }
2481
2482 /**
2483  * gst_info_strdup_printf:
2484  * @format: a printf style format string
2485  * @...: the printf arguments for @format
2486  *
2487  * Allocates, fills and returns a 0-terminated string from the printf style
2488  * @format string and corresponding arguments.
2489  *
2490  * See gst_info_vasprintf() for when this function is required.
2491  *
2492  * Free with g_free().
2493  *
2494  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2495  *
2496  * Since: 1.8
2497  */
2498 gchar *
2499 gst_info_strdup_printf (const gchar * format, ...)
2500 {
2501   gchar *ret;
2502   va_list args;
2503
2504   va_start (args, format);
2505   ret = gst_info_strdup_vprintf (format, args);
2506   va_end (args);
2507
2508   return ret;
2509 }
2510
2511 /**
2512  * gst_print:
2513  * @format: a printf style format string
2514  * @...: the printf arguments for @format
2515  *
2516  * Outputs a formatted message via the GLib print handler. The default print
2517  * handler simply outputs the message to stdout.
2518  *
2519  * This function will not append a new-line character at the end, unlike
2520  * gst_println() which will.
2521  *
2522  * All strings must be in ASCII or UTF-8 encoding.
2523  *
2524  * This function differs from g_print() in that it supports all the additional
2525  * printf specifiers that are supported by GStreamer's debug logging system,
2526  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2527  *
2528  * This function is primarily for printing debug output.
2529  *
2530  * Since: 1.12
2531  */
2532 void
2533 gst_print (const gchar * format, ...)
2534 {
2535   va_list args;
2536   gchar *str;
2537
2538   va_start (args, format);
2539   str = gst_info_strdup_vprintf (format, args);
2540   va_end (args);
2541
2542   g_print ("%s", str);
2543   g_free (str);
2544 }
2545
2546 /**
2547  * gst_println:
2548  * @format: a printf style format string
2549  * @...: the printf arguments for @format
2550  *
2551  * Outputs a formatted message via the GLib print handler. The default print
2552  * handler simply outputs the message to stdout.
2553  *
2554  * This function will append a new-line character at the end, unlike
2555  * gst_print() which will not.
2556  *
2557  * All strings must be in ASCII or UTF-8 encoding.
2558  *
2559  * This function differs from g_print() in that it supports all the additional
2560  * printf specifiers that are supported by GStreamer's debug logging system,
2561  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2562  *
2563  * This function is primarily for printing debug output.
2564  *
2565  * Since: 1.12
2566  */
2567 void
2568 gst_println (const gchar * format, ...)
2569 {
2570   va_list args;
2571   gchar *str;
2572
2573   va_start (args, format);
2574   str = gst_info_strdup_vprintf (format, args);
2575   va_end (args);
2576
2577   g_print ("%s\n", str);
2578   g_free (str);
2579 }
2580
2581 /**
2582  * gst_printerr:
2583  * @format: a printf style format string
2584  * @...: the printf arguments for @format
2585  *
2586  * Outputs a formatted message via the GLib error message handler. The default
2587  * handler simply outputs the message to stderr.
2588  *
2589  * This function will not append a new-line character at the end, unlike
2590  * gst_printerrln() which will.
2591  *
2592  * All strings must be in ASCII or UTF-8 encoding.
2593  *
2594  * This function differs from g_printerr() in that it supports the additional
2595  * printf specifiers that are supported by GStreamer's debug logging system,
2596  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2597  *
2598  * This function is primarily for printing debug output.
2599  *
2600  * Since: 1.12
2601  */
2602 void
2603 gst_printerr (const gchar * format, ...)
2604 {
2605   va_list args;
2606   gchar *str;
2607
2608   va_start (args, format);
2609   str = gst_info_strdup_vprintf (format, args);
2610   va_end (args);
2611
2612   g_printerr ("%s", str);
2613   g_free (str);
2614 }
2615
2616 /**
2617  * gst_printerrln:
2618  * @format: a printf style format string
2619  * @...: the printf arguments for @format
2620  *
2621  * Outputs a formatted message via the GLib error message handler. The default
2622  * handler simply outputs the message to stderr.
2623  *
2624  * This function will append a new-line character at the end, unlike
2625  * gst_printerr() which will not.
2626  *
2627  * All strings must be in ASCII or UTF-8 encoding.
2628  *
2629  * This function differs from g_printerr() in that it supports the additional
2630  * printf specifiers that are supported by GStreamer's debug logging system,
2631  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2632  *
2633  * This function is primarily for printing debug output.
2634  *
2635  * Since: 1.12
2636  */
2637 void
2638 gst_printerrln (const gchar * format, ...)
2639 {
2640   va_list args;
2641   gchar *str;
2642
2643   va_start (args, format);
2644   str = gst_info_strdup_vprintf (format, args);
2645   va_end (args);
2646
2647   g_printerr ("%s\n", str);
2648   g_free (str);
2649 }
2650
2651 #ifdef HAVE_UNWIND
2652 #ifdef HAVE_DW
2653 static gboolean
2654 append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
2655 {
2656   Dwfl_Line *line;
2657   Dwarf_Addr addr;
2658   Dwfl_Module *module;
2659   const gchar *function_name;
2660
2661   if (dwfl_linux_proc_report (dwfl, getpid ()) != 0)
2662     return FALSE;
2663
2664   if (dwfl_report_end (dwfl, NULL, NULL))
2665     return FALSE;
2666
2667   addr = (uintptr_t) ip;
2668   module = dwfl_addrmodule (dwfl, addr);
2669   function_name = dwfl_module_addrname (module, addr);
2670
2671   g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
2672
2673   line = dwfl_getsrc (dwfl, addr);
2674   if (line != NULL) {
2675     gint nline;
2676     Dwarf_Addr addr;
2677     const gchar *filename = dwfl_lineinfo (line, &addr,
2678         &nline, NULL, NULL, NULL);
2679
2680     g_string_append_printf (trace, "%s:%d", strrchr (filename,
2681             G_DIR_SEPARATOR) + 1, nline);
2682   } else {
2683     const gchar *eflfile = NULL;
2684
2685     dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
2686     g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
2687   }
2688
2689   return TRUE;
2690 }
2691 #endif /* HAVE_DW */
2692
2693 static gchar *
2694 generate_unwind_trace (GstStackTraceFlags flags)
2695 {
2696   gint unret;
2697   unw_context_t uc;
2698   unw_cursor_t cursor;
2699   gboolean use_libunwind = TRUE;
2700   GString *trace = g_string_new (NULL);
2701
2702 #ifdef HAVE_DW
2703   Dwfl *dwfl = NULL;
2704   Dwfl_Callbacks callbacks = {
2705     .find_elf = dwfl_linux_proc_find_elf,
2706     .find_debuginfo = dwfl_standard_find_debuginfo,
2707   };
2708
2709   if ((flags & GST_STACK_TRACE_SHOW_FULL))
2710     dwfl = dwfl_begin (&callbacks);
2711 #endif /* HAVE_DW */
2712
2713   unret = unw_getcontext (&uc);
2714   if (unret) {
2715     GST_DEBUG ("Could not get libunwind context (%d)", unret);
2716
2717     goto done;
2718   }
2719   unret = unw_init_local (&cursor, &uc);
2720   if (unret) {
2721     GST_DEBUG ("Could not init libunwind context (%d)", unret);
2722
2723     goto done;
2724   }
2725
2726   while (unw_step (&cursor) > 0) {
2727 #ifdef HAVE_DW
2728     if (dwfl) {
2729       unw_word_t ip;
2730
2731       unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
2732       if (unret) {
2733         GST_DEBUG ("libunwind could read frame info (%d)", unret);
2734
2735         goto done;
2736       }
2737
2738       if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
2739         use_libunwind = FALSE;
2740         g_string_append (trace, ")\n");
2741       }
2742     }
2743 #endif /* HAVE_DW */
2744
2745     if (use_libunwind) {
2746       char name[32];
2747
2748       unw_word_t offset = 0;
2749       unw_get_proc_name (&cursor, name, sizeof (name), &offset);
2750       g_string_append_printf (trace, "%s (0x%" G_GSIZE_FORMAT ")\n", name,
2751           (gsize) offset);
2752     }
2753   }
2754
2755 done:
2756 #ifdef HAVE_DW
2757   if (dwfl)
2758     dwfl_end (dwfl);
2759 #endif
2760
2761   return g_string_free (trace, FALSE);
2762 }
2763
2764 #endif /* HAVE_UNWIND */
2765
2766 #ifdef HAVE_BACKTRACE
2767 static gchar *
2768 generate_backtrace_trace (void)
2769 {
2770   int j, nptrs;
2771   void *buffer[BT_BUF_SIZE];
2772   char **strings;
2773   GString *trace;
2774
2775   trace = g_string_new (NULL);
2776   nptrs = backtrace (buffer, BT_BUF_SIZE);
2777
2778   strings = backtrace_symbols (buffer, nptrs);
2779
2780   if (!strings)
2781     return NULL;
2782
2783   for (j = 0; j < nptrs; j++)
2784     g_string_append_printf (trace, "%s\n", strings[j]);
2785
2786   free (strings);
2787
2788   return g_string_free (trace, FALSE);
2789 }
2790 #else
2791 #define generate_backtrace_trace() NULL
2792 #endif /* HAVE_BACKTRACE */
2793
2794 #ifdef HAVE_DBGHELP
2795 static void
2796 dbghelp_initialize_symbols (HANDLE process)
2797 {
2798   static gsize initialization_value = 0;
2799
2800   if (g_once_init_enter (&initialization_value)) {
2801     GST_INFO ("Initializing Windows symbol handler");
2802     SymSetOptions (SYMOPT_LOAD_LINES);
2803     SymInitialize (process, NULL, TRUE);
2804     GST_INFO ("Initialized Windows symbol handler");
2805
2806     g_once_init_leave (&initialization_value, 1);
2807   }
2808 }
2809
2810 static gchar *
2811 generate_dbghelp_trace (void)
2812 {
2813   HANDLE process = GetCurrentProcess ();
2814   HANDLE thread = GetCurrentThread ();
2815   IMAGEHLP_MODULE64 module_info;
2816   DWORD machine;
2817   CONTEXT context;
2818   STACKFRAME64 frame = { 0 };
2819   PVOID save_context;
2820   GString *trace = g_string_new (NULL);
2821
2822   dbghelp_initialize_symbols (process);
2823
2824   memset (&context, 0, sizeof (CONTEXT));
2825   context.ContextFlags = CONTEXT_FULL;
2826
2827   RtlCaptureContext (&context);
2828
2829   frame.AddrPC.Mode = AddrModeFlat;
2830   frame.AddrStack.Mode = AddrModeFlat;
2831   frame.AddrFrame.Mode = AddrModeFlat;
2832
2833 #if (defined _M_IX86)
2834   machine = IMAGE_FILE_MACHINE_I386;
2835   frame.AddrFrame.Offset = context.Ebp;
2836   frame.AddrPC.Offset = context.Eip;
2837   frame.AddrStack.Offset = context.Esp;
2838 #elif (defined _M_X64)
2839   machine = IMAGE_FILE_MACHINE_AMD64;
2840   frame.AddrFrame.Offset = context.Rbp;
2841   frame.AddrPC.Offset = context.Rip;
2842   frame.AddrStack.Offset = context.Rsp;
2843 #else
2844   goto done;
2845 #endif
2846
2847   module_info.SizeOfStruct = sizeof (module_info);
2848   save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
2849
2850   while (TRUE) {
2851     char buffer[sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR)];
2852     PSYMBOL_INFO symbol = (PSYMBOL_INFO) buffer;
2853     IMAGEHLP_LINE64 line;
2854     DWORD displacement = 0;
2855
2856     symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
2857     symbol->MaxNameLen = MAX_SYM_NAME;
2858
2859     line.SizeOfStruct = sizeof (line);
2860
2861     if (!StackWalk64 (machine, process, thread, &frame, save_context, 0,
2862             SymFunctionTableAccess64, SymGetModuleBase64, 0))
2863       break;
2864
2865     if (SymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
2866       g_string_append_printf (trace, "%s ", symbol->Name);
2867     else
2868       g_string_append (trace, "?? ");
2869
2870     if (SymGetLineFromAddr64 (process, frame.AddrPC.Offset, &displacement,
2871             &line))
2872       g_string_append_printf (trace, "(%s:%u)", line.FileName, line.LineNumber);
2873     else if (SymGetModuleInfo64 (process, frame.AddrPC.Offset, &module_info))
2874       g_string_append_printf (trace, "(%s)", module_info.ImageName);
2875     else
2876       g_string_append_printf (trace, "(%s)", "??");
2877
2878     g_string_append (trace, "\n");
2879   }
2880
2881 done:
2882   return g_string_free (trace, FALSE);
2883 }
2884 #endif /* HAVE_DBGHELP */
2885
2886 /**
2887  * gst_debug_get_stack_trace:
2888  * @flags: A set of #GstStackTraceFlags to determine how the stack
2889  * trace should look like. Pass 0 to retrieve a minimal backtrace.
2890  *
2891  * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
2892  * present, else %NULL.
2893  *
2894  * Since: 1.12
2895  */
2896 gchar *
2897 gst_debug_get_stack_trace (GstStackTraceFlags flags)
2898 {
2899   gchar *trace = NULL;
2900 #ifdef HAVE_BACKTRACE
2901   gboolean have_backtrace = TRUE;
2902 #else
2903   gboolean have_backtrace = FALSE;
2904 #endif
2905
2906 #ifdef HAVE_UNWIND
2907   if ((flags & GST_STACK_TRACE_SHOW_FULL) || !have_backtrace)
2908     trace = generate_unwind_trace (flags);
2909 #endif /* HAVE_UNWIND */
2910
2911 #ifdef HAVE_DBGHELP
2912   trace = generate_dbghelp_trace ();
2913 #endif
2914
2915   if (trace)
2916     return trace;
2917   else if (have_backtrace)
2918     return generate_backtrace_trace ();
2919
2920   return NULL;
2921 }
2922
2923 /**
2924  * gst_debug_print_stack_trace:
2925  *
2926  * If libunwind, glibc backtrace or DbgHelp are present
2927  * a stack trace is printed.
2928  */
2929 void
2930 gst_debug_print_stack_trace (void)
2931 {
2932   gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
2933
2934   if (trace)
2935     g_print ("%s\n", trace);
2936
2937   g_free (trace);
2938 }
2939
2940 #ifndef GST_DISABLE_GST_DEBUG
2941 typedef struct
2942 {
2943   guint max_size_per_thread;
2944   guint thread_timeout;
2945   GQueue threads;
2946   GHashTable *thread_index;
2947 } GstRingBufferLogger;
2948
2949 typedef struct
2950 {
2951   GList *link;
2952   gint64 last_use;
2953   GThread *thread;
2954
2955   GQueue log;
2956   gsize log_size;
2957 } GstRingBufferLog;
2958
2959 G_LOCK_DEFINE_STATIC (ring_buffer_logger);
2960 static GstRingBufferLogger *ring_buffer_logger = NULL;
2961
2962 static void
2963 gst_ring_buffer_logger_log (GstDebugCategory * category,
2964     GstDebugLevel level,
2965     const gchar * file,
2966     const gchar * function,
2967     gint line, GObject * object, GstDebugMessage * message, gpointer user_data)
2968 {
2969   GstRingBufferLogger *logger = user_data;
2970   gint pid;
2971   GThread *thread;
2972   GstClockTime elapsed;
2973   gchar *obj = NULL;
2974   gchar c;
2975   gchar *output;
2976   gsize output_len;
2977   GstRingBufferLog *log;
2978   gint64 now = g_get_monotonic_time ();
2979   const gchar *message_str = gst_debug_message_get (message);
2980
2981   G_LOCK (ring_buffer_logger);
2982
2983   if (logger->thread_timeout > 0) {
2984     /* Remove all threads that saw no output since thread_timeout seconds.
2985      * By construction these are all at the tail of the queue, and the queue
2986      * is ordered by last use, so we just need to look at the tail.
2987      */
2988     while (logger->threads.tail) {
2989       log = logger->threads.tail->data;
2990       if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
2991         break;
2992
2993       g_hash_table_remove (logger->thread_index, log->thread);
2994       while ((output = g_queue_pop_head (&log->log)))
2995         g_free (output);
2996       g_free (log);
2997       g_queue_pop_tail (&logger->threads);
2998     }
2999   }
3000
3001   /* Get logger for this thread, and put it back at the
3002    * head of the threads queue */
3003   thread = g_thread_self ();
3004   log = g_hash_table_lookup (logger->thread_index, thread);
3005   if (!log) {
3006     log = g_new0 (GstRingBufferLog, 1);
3007     g_queue_init (&log->log);
3008     log->log_size = 0;
3009     g_queue_push_head (&logger->threads, log);
3010     log->link = logger->threads.head;
3011     log->thread = thread;
3012     g_hash_table_insert (logger->thread_index, thread, log);
3013   } else {
3014     g_queue_unlink (&logger->threads, log->link);
3015     g_queue_push_head_link (&logger->threads, log->link);
3016   }
3017   log->last_use = now;
3018
3019   /* __FILE__ might be a file name or an absolute path or a
3020    * relative path, irrespective of the exact compiler used,
3021    * in which case we want to shorten it to the filename for
3022    * readability. */
3023   c = file[0];
3024   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
3025     file = gst_path_basename (file);
3026   }
3027
3028   pid = getpid ();
3029
3030   if (object) {
3031     obj = gst_debug_print_object (object);
3032   } else {
3033     obj = (gchar *) "";
3034   }
3035
3036   elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
3037
3038   /* no color, all platforms */
3039 #define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
3040   output =
3041       g_strdup_printf ("%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
3042       pid, thread, gst_debug_level_get_name (level),
3043       gst_debug_category_get_name (category), file, line, function, obj,
3044       message_str);
3045 #undef PRINT_FMT
3046
3047   output_len = strlen (output);
3048
3049   if (output_len < logger->max_size_per_thread) {
3050     gchar *buf;
3051
3052     /* While using a GQueue here is not the most efficient thing to do, we
3053      * have to allocate a string for every output anyway and could just store
3054      * that instead of copying it to an actual ringbuffer.
3055      * Better than GQueue would be GstQueueArray, but that one is in
3056      * libgstbase and we can't use it here. That one allocation will not make
3057      * much of a difference anymore, considering the number of allocations
3058      * needed to get to this point...
3059      */
3060     while (log->log_size + output_len > logger->max_size_per_thread) {
3061       buf = g_queue_pop_head (&log->log);
3062       log->log_size -= strlen (buf);
3063       g_free (buf);
3064     }
3065     g_queue_push_tail (&log->log, output);
3066     log->log_size += output_len;
3067   } else {
3068     gchar *buf;
3069
3070     /* Can't really write anything as the line is bigger than the maximum
3071      * allowed log size already, so just remove everything */
3072
3073     while ((buf = g_queue_pop_head (&log->log)))
3074       g_free (buf);
3075     g_free (output);
3076     log->log_size = 0;
3077   }
3078
3079   if (object != NULL)
3080     g_free (obj);
3081
3082   G_UNLOCK (ring_buffer_logger);
3083 }
3084
3085 /**
3086  * gst_debug_ring_buffer_logger_get_logs:
3087  *
3088  * Fetches the current logs per thread from the ring buffer logger. See
3089  * gst_debug_add_ring_buffer_logger() for details.
3090  *
3091  * Returns: (transfer full) (array zero-terminated): NULL-terminated array of
3092  * strings with the debug output per thread
3093  *
3094  * Since: 1.14
3095  */
3096 gchar **
3097 gst_debug_ring_buffer_logger_get_logs (void)
3098 {
3099   gchar **logs, **tmp;
3100   GList *l;
3101
3102   g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
3103
3104   G_LOCK (ring_buffer_logger);
3105
3106   tmp = logs = g_new0 (gchar *, ring_buffer_logger->threads.length + 1);
3107   for (l = ring_buffer_logger->threads.head; l; l = l->next) {
3108     GstRingBufferLog *log = l->data;
3109     GList *l;
3110     gchar *p;
3111     gsize len;
3112
3113     *tmp = p = g_new0 (gchar, log->log_size + 1);
3114
3115     for (l = log->log.head; l; l = l->next) {
3116       len = strlen (l->data);
3117       memcpy (p, l->data, len);
3118       p += len;
3119     }
3120
3121     tmp++;
3122   }
3123
3124   G_UNLOCK (ring_buffer_logger);
3125
3126   return logs;
3127 }
3128
3129 static void
3130 gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
3131 {
3132   G_LOCK (ring_buffer_logger);
3133   if (ring_buffer_logger == logger) {
3134     GstRingBufferLog *log;
3135
3136     while ((log = g_queue_pop_head (&logger->threads))) {
3137       gchar *buf;
3138       while ((buf = g_queue_pop_head (&log->log)))
3139         g_free (buf);
3140       g_free (log);
3141     }
3142
3143     g_hash_table_unref (logger->thread_index);
3144
3145     g_free (logger);
3146     ring_buffer_logger = NULL;
3147   }
3148   G_UNLOCK (ring_buffer_logger);
3149 }
3150
3151 /**
3152  * gst_debug_add_ring_buffer_logger:
3153  * @max_size_per_thread: Maximum size of log per thread in bytes
3154  * @thread_timeout: Timeout for threads in seconds
3155  *
3156  * Adds a memory ringbuffer based debug logger that stores up to
3157  * @max_size_per_thread bytes of logs per thread and times out threads after
3158  * @thread_timeout seconds of inactivity.
3159  *
3160  * Logs can be fetched with gst_debug_ring_buffer_logger_get_logs() and the
3161  * logger can be removed again with gst_debug_remove_ring_buffer_logger().
3162  * Only one logger at a time is possible.
3163  *
3164  * Since: 1.14
3165  */
3166 void
3167 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3168     guint thread_timeout)
3169 {
3170   GstRingBufferLogger *logger;
3171
3172   G_LOCK (ring_buffer_logger);
3173
3174   if (ring_buffer_logger) {
3175     g_warn_if_reached ();
3176     G_UNLOCK (ring_buffer_logger);
3177     return;
3178   }
3179
3180   logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
3181
3182   logger->max_size_per_thread = max_size_per_thread;
3183   logger->thread_timeout = thread_timeout;
3184   logger->thread_index = g_hash_table_new (g_direct_hash, g_direct_equal);
3185   g_queue_init (&logger->threads);
3186
3187   gst_debug_add_log_function (gst_ring_buffer_logger_log, logger,
3188       (GDestroyNotify) gst_ring_buffer_logger_free);
3189   G_UNLOCK (ring_buffer_logger);
3190 }
3191
3192 /**
3193  * gst_debug_remove_ring_buffer_logger:
3194  *
3195  * Removes any previously added ring buffer logger with
3196  * gst_debug_add_ring_buffer_logger().
3197  *
3198  * Since: 1.14
3199  */
3200 void
3201 gst_debug_remove_ring_buffer_logger (void)
3202 {
3203   gst_debug_remove_log_function (gst_ring_buffer_logger_log);
3204 }
3205
3206 #else /* GST_DISABLE_GST_DEBUG */
3207 #ifndef GST_REMOVE_DISABLED
3208
3209 gchar **
3210 gst_debug_ring_buffer_logger_get_logs (void)
3211 {
3212   return NULL;
3213 }
3214
3215 void
3216 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3217     guint thread_timeout)
3218 {
3219 }
3220
3221 void
3222 gst_debug_remove_ring_buffer_logger (void)
3223 {
3224 }
3225
3226 #endif /* GST_REMOVE_DISABLED */
3227 #endif /* GST_DISABLE_GST_DEBUG */