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