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