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