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>
7 * gstinfo.c: debugging functions
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.
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.
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.
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.
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.
36 * The debugging subsystem works only after GStreamer has been initialized
37 * - for example by calling gst_init().
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
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,
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
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");
63 * Initialization must be done before the category is used first.
65 * in their plugin_init function, libraries and applications should do that
66 * during their initialization.
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
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.
75 * subsystem was compiled out, GST_DISABLE_GST_DEBUG is defined in
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.
82 * Please note that there are naming conventions for the names of debugging
83 * categories. These are explained at GST_DEBUG_CATEGORY_INIT().
87 #include "gst_private.h"
90 #undef gst_debug_remove_log_function
91 #undef gst_debug_add_log_function
93 #ifndef GST_DISABLE_GST_DEBUG
97 #include <stdio.h> /* fprintf */
98 #include <glib/gstdio.h>
100 #include <string.h> /* G_VA_COPY */
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"
109 #ifdef HAVE_VALGRIND_VALGRIND_H
110 # include <valgrind/valgrind.h>
112 #include <glib/gprintf.h> /* g_sprintf */
114 /* our own printf implementation with custom extensions to %p for caps etc. */
115 #include "printf/printf.h"
116 #include "printf/printf-extension.h"
118 static char *gst_info_printf_pointer_extension_func (const char *format,
120 #else /* GST_DISABLE_GST_DEBUG */
122 #include <glib/gprintf.h>
123 #endif /* !GST_DISABLE_GST_DEBUG */
126 # include <unistd.h> /* getpid on UNIX */
130 # define WIN32_LEAN_AND_MEAN /* prevents from including too many things */
131 # include <windows.h> /* GetStdHandle, windows console */
132 # include <processthreadsapi.h> /* GetCurrentProcessId */
133 /* getpid() is not allowed in case of UWP, use GetCurrentProcessId() instead
134 * which can be used on both desktop and UWP */
137 /* use glib's abstraction once it's landed
138 * https://gitlab.gnome.org/GNOME/glib/-/merge_requests/2475 */
143 return GetCurrentProcessId ();
154 /* No need for remote debugging so turn on the 'local only' optimizations in
156 #define UNW_LOCAL_ONLY
158 #include <libunwind.h>
167 #include <elfutils/libdwfl.h>
168 static Dwfl *_global_dwfl = NULL;
169 static GMutex _dwfl_mutex;
171 #define GST_DWFL_LOCK() g_mutex_lock(&_dwfl_mutex);
172 #define GST_DWFL_UNLOCK() g_mutex_unlock(&_dwfl_mutex);
175 get_global_dwfl (void)
177 if (g_once_init_enter (&_global_dwfl)) {
178 static Dwfl_Callbacks callbacks = {
179 .find_elf = dwfl_linux_proc_find_elf,
180 .find_debuginfo = dwfl_standard_find_debuginfo,
182 Dwfl *_dwfl = dwfl_begin (&callbacks);
183 g_mutex_init (&_dwfl_mutex);
184 g_once_init_leave (&_global_dwfl, _dwfl);
191 #endif /* HAVE_UNWIND */
193 #ifdef HAVE_BACKTRACE
194 #include <execinfo.h>
195 #define BT_BUF_SIZE 100
196 #endif /* HAVE_BACKTRACE */
201 #include <tlhelp32.h>
203 #endif /* HAVE_DBGHELP */
206 /* We take a lock in order to
207 * 1) keep colors and content together for a single line
208 * 2) serialise gst_print*() and gst_printerr*() with each other and the debug
209 * log to keep the debug log colouring from interfering with those and
210 * to prevent broken output on the windows terminal.
211 * Maybe there is a better way but for now this will do the right
213 G_LOCK_DEFINE_STATIC (win_print_mutex);
216 extern gboolean gst_is_initialized (void);
218 /* we want these symbols exported even if debug is disabled, to maintain
219 * ABI compatibility. Unless GST_REMOVE_DISABLED is defined. */
220 #if !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED)
222 /* disabled by default, as soon as some threshold is set > NONE,
223 * it becomes enabled. */
224 gboolean _gst_debug_enabled = FALSE;
225 GstDebugLevel _gst_debug_min = GST_LEVEL_NONE;
227 GstDebugCategory *GST_CAT_DEFAULT = NULL;
229 GstDebugCategory *GST_CAT_GST_INIT = NULL;
230 GstDebugCategory *GST_CAT_MEMORY = NULL;
231 GstDebugCategory *GST_CAT_PARENTAGE = NULL;
232 GstDebugCategory *GST_CAT_STATES = NULL;
233 GstDebugCategory *GST_CAT_SCHEDULING = NULL;
235 GstDebugCategory *GST_CAT_BUFFER = NULL;
236 GstDebugCategory *GST_CAT_BUFFER_LIST = NULL;
237 GstDebugCategory *GST_CAT_BUS = NULL;
238 GstDebugCategory *GST_CAT_CAPS = NULL;
239 GstDebugCategory *GST_CAT_CLOCK = NULL;
240 GstDebugCategory *GST_CAT_ELEMENT_PADS = NULL;
241 GstDebugCategory *GST_CAT_PADS = NULL;
242 GstDebugCategory *GST_CAT_PERFORMANCE = NULL;
243 GstDebugCategory *GST_CAT_PIPELINE = NULL;
244 GstDebugCategory *GST_CAT_PLUGIN_LOADING = NULL;
245 GstDebugCategory *GST_CAT_PLUGIN_INFO = NULL;
246 GstDebugCategory *GST_CAT_PROPERTIES = NULL;
247 GstDebugCategory *GST_CAT_NEGOTIATION = NULL;
248 GstDebugCategory *GST_CAT_REFCOUNTING = NULL;
249 GstDebugCategory *GST_CAT_ERROR_SYSTEM = NULL;
250 GstDebugCategory *GST_CAT_EVENT = NULL;
251 GstDebugCategory *GST_CAT_MESSAGE = NULL;
252 GstDebugCategory *GST_CAT_PARAMS = NULL;
253 GstDebugCategory *GST_CAT_CALL_TRACE = NULL;
254 GstDebugCategory *GST_CAT_SIGNAL = NULL;
255 GstDebugCategory *GST_CAT_PROBE = NULL;
256 GstDebugCategory *GST_CAT_REGISTRY = NULL;
257 GstDebugCategory *GST_CAT_QOS = NULL;
258 GstDebugCategory *_priv_GST_CAT_POLL = NULL;
259 GstDebugCategory *GST_CAT_META = NULL;
260 GstDebugCategory *GST_CAT_LOCKING = NULL;
261 GstDebugCategory *GST_CAT_CONTEXT = NULL;
262 GstDebugCategory *_priv_GST_CAT_PROTECTION = NULL;
265 #endif /* !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED) */
267 #ifndef GST_DISABLE_GST_DEBUG
269 /* underscore is to prevent conflict with GST_CAT_DEBUG define */
270 GST_DEBUG_CATEGORY_STATIC (_GST_CAT_DEBUG);
274 #include <rld_interface.h>
275 typedef struct DL_INFO
277 const char *dli_fname;
279 const char *dli_sname;
283 long dli_reserved[4];
287 #define _RLD_DLADDR 14
288 int dladdr (void *address, Dl_info * dl);
291 dladdr (void *address, Dl_info * dl)
295 v = _rld_new_interface (_RLD_DLADDR, address, dl);
301 static void gst_debug_reset_threshold (gpointer category, gpointer unused);
302 static void gst_debug_reset_all_thresholds (void);
304 struct _GstDebugMessage
311 /* list of all name/level pairs from --gst-debug and GST_DEBUG */
312 static GMutex __level_name_mutex;
313 static GSList *__level_name = NULL;
321 /* list of all categories */
322 static GMutex __cat_mutex;
323 static GSList *__categories = NULL;
325 static GstDebugCategory *_gst_debug_get_category_locked (const gchar * name);
328 /* all registered debug handlers */
333 GDestroyNotify notify;
336 static GMutex __log_func_mutex;
337 static GSList *__log_functions = NULL;
339 /* whether to add the default log function in gst_init() */
340 static gboolean add_default_log_func = TRUE;
342 #define PRETTY_TAGS_DEFAULT TRUE
343 static gboolean pretty_tags = PRETTY_TAGS_DEFAULT;
345 static gint G_GNUC_MAY_ALIAS __default_level = GST_LEVEL_DEFAULT;
346 static gint G_GNUC_MAY_ALIAS __use_color = GST_DEBUG_COLOR_MODE_ON;
349 _replace_pattern_in_gst_debug_file_name (gchar * name, const char *token,
353 if ((token_start = strstr (name, token))) {
354 gsize token_len = strlen (token);
355 gchar *name_prefix = name;
356 gchar *name_suffix = token_start + token_len;
357 token_start[0] = '\0';
358 name = g_strdup_printf ("%s%u%s", name_prefix, val, name_suffix);
359 g_free (name_prefix);
365 _priv_gst_debug_file_name (const gchar * env)
369 name = g_strdup (env);
370 name = _replace_pattern_in_gst_debug_file_name (name, "%p", _gst_getpid ());
371 name = _replace_pattern_in_gst_debug_file_name (name, "%r", g_random_int ());
376 /* Initialize the debugging system */
378 _priv_gst_debug_init (void)
383 if (add_default_log_func) {
384 env = g_getenv ("GST_DEBUG_FILE");
385 if (env != NULL && *env != '\0') {
386 if (strcmp (env, "-") == 0) {
389 gchar *name = _priv_gst_debug_file_name (env);
390 log_file = g_fopen (name, "w");
392 if (log_file == NULL) {
393 g_printerr ("Could not open log file '%s' for writing: %s\n", env,
402 gst_debug_add_log_function (gst_debug_log_default, log_file, NULL);
405 __gst_printf_pointer_extension_set_func
406 (gst_info_printf_pointer_extension_func);
408 /* do NOT use a single debug function before this line has been run */
409 GST_CAT_DEFAULT = _gst_debug_category_new ("default",
410 GST_DEBUG_UNDERLINE, NULL);
411 _GST_CAT_DEBUG = _gst_debug_category_new ("GST_DEBUG",
412 GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, "debugging subsystem");
414 /* FIXME: add descriptions here */
415 GST_CAT_GST_INIT = _gst_debug_category_new ("GST_INIT",
416 GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
417 GST_CAT_MEMORY = _gst_debug_category_new ("GST_MEMORY",
418 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, "memory");
419 GST_CAT_PARENTAGE = _gst_debug_category_new ("GST_PARENTAGE",
420 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
421 GST_CAT_STATES = _gst_debug_category_new ("GST_STATES",
422 GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
423 GST_CAT_SCHEDULING = _gst_debug_category_new ("GST_SCHEDULING",
424 GST_DEBUG_BOLD | GST_DEBUG_FG_MAGENTA, NULL);
425 GST_CAT_BUFFER = _gst_debug_category_new ("GST_BUFFER",
426 GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
427 GST_CAT_BUFFER_LIST = _gst_debug_category_new ("GST_BUFFER_LIST",
428 GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
429 GST_CAT_BUS = _gst_debug_category_new ("GST_BUS", GST_DEBUG_BG_YELLOW, NULL);
430 GST_CAT_CAPS = _gst_debug_category_new ("GST_CAPS",
431 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
432 GST_CAT_CLOCK = _gst_debug_category_new ("GST_CLOCK",
433 GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, NULL);
434 GST_CAT_ELEMENT_PADS = _gst_debug_category_new ("GST_ELEMENT_PADS",
435 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
436 GST_CAT_PADS = _gst_debug_category_new ("GST_PADS",
437 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
438 GST_CAT_PERFORMANCE = _gst_debug_category_new ("GST_PERFORMANCE",
439 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
440 GST_CAT_PIPELINE = _gst_debug_category_new ("GST_PIPELINE",
441 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
442 GST_CAT_PLUGIN_LOADING = _gst_debug_category_new ("GST_PLUGIN_LOADING",
443 GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
444 GST_CAT_PLUGIN_INFO = _gst_debug_category_new ("GST_PLUGIN_INFO",
445 GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
446 GST_CAT_PROPERTIES = _gst_debug_category_new ("GST_PROPERTIES",
447 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_BLUE, NULL);
448 GST_CAT_NEGOTIATION = _gst_debug_category_new ("GST_NEGOTIATION",
449 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
450 GST_CAT_REFCOUNTING = _gst_debug_category_new ("GST_REFCOUNTING",
451 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
452 GST_CAT_ERROR_SYSTEM = _gst_debug_category_new ("GST_ERROR_SYSTEM",
453 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_WHITE, NULL);
455 GST_CAT_EVENT = _gst_debug_category_new ("GST_EVENT",
456 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
457 GST_CAT_MESSAGE = _gst_debug_category_new ("GST_MESSAGE",
458 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
459 GST_CAT_PARAMS = _gst_debug_category_new ("GST_PARAMS",
460 GST_DEBUG_BOLD | GST_DEBUG_FG_BLACK | GST_DEBUG_BG_YELLOW, NULL);
461 GST_CAT_CALL_TRACE = _gst_debug_category_new ("GST_CALL_TRACE",
462 GST_DEBUG_BOLD, NULL);
463 GST_CAT_SIGNAL = _gst_debug_category_new ("GST_SIGNAL",
464 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
465 GST_CAT_PROBE = _gst_debug_category_new ("GST_PROBE",
466 GST_DEBUG_BOLD | GST_DEBUG_FG_GREEN, "pad probes");
467 GST_CAT_REGISTRY = _gst_debug_category_new ("GST_REGISTRY", 0, "registry");
468 GST_CAT_QOS = _gst_debug_category_new ("GST_QOS", 0, "QoS");
469 _priv_GST_CAT_POLL = _gst_debug_category_new ("GST_POLL", 0, "poll");
470 GST_CAT_META = _gst_debug_category_new ("GST_META", 0, "meta");
471 GST_CAT_LOCKING = _gst_debug_category_new ("GST_LOCKING", 0, "locking");
472 GST_CAT_CONTEXT = _gst_debug_category_new ("GST_CONTEXT", 0, NULL);
473 _priv_GST_CAT_PROTECTION =
474 _gst_debug_category_new ("GST_PROTECTION", 0, "protection");
476 env = g_getenv ("GST_DEBUG_OPTIONS");
478 if (strstr (env, "full_tags") || strstr (env, "full-tags"))
480 else if (strstr (env, "pretty_tags") || strstr (env, "pretty-tags"))
484 if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
485 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
486 env = g_getenv ("GST_DEBUG_COLOR_MODE");
488 gst_debug_set_color_mode_from_string (env);
490 env = g_getenv ("GST_DEBUG");
492 gst_debug_set_threshold_from_string (env, FALSE);
495 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
496 #define GST_CAT_DEFAULT _GST_CAT_DEBUG
500 * @category: category to log
501 * @level: level of the message is in
502 * @file: the file that emitted the message, usually the __FILE__ identifier
503 * @function: the function that emitted the message
504 * @line: the line from that the message was emitted, usually __LINE__
505 * @object: (transfer none) (allow-none): the object this message relates to,
507 * @format: a printf style format string
508 * @...: optional arguments for the format
510 * Logs the given message using the currently registered debugging handlers.
513 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
514 const gchar * file, const gchar * function, gint line,
515 GObject * object, const gchar * format, ...)
519 va_start (var_args, format);
520 gst_debug_log_valist (category, level, file, function, line, object, format,
525 /* based on g_basename(), which we can't use because it was deprecated */
526 static inline const gchar *
527 gst_path_basename (const gchar * file_name)
529 register const gchar *base;
531 base = strrchr (file_name, G_DIR_SEPARATOR);
534 const gchar *q = strrchr (file_name, '/');
535 if (base == NULL || (q != NULL && q > base))
542 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
543 return file_name + 2;
549 * gst_debug_log_valist:
550 * @category: category to log
551 * @level: level of the message is in
552 * @file: the file that emitted the message, usually the __FILE__ identifier
553 * @function: the function that emitted the message
554 * @line: the line from that the message was emitted, usually __LINE__
555 * @object: (transfer none) (allow-none): the object this message relates to,
557 * @format: a printf style format string
558 * @args: optional arguments for the format
560 * Logs the given message using the currently registered debugging handlers.
563 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
564 const gchar * file, const gchar * function, gint line,
565 GObject * object, const gchar * format, va_list args)
567 GstDebugMessage message;
571 g_return_if_fail (category != NULL);
573 #ifdef GST_ENABLE_EXTRA_CHECKS
574 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
577 if (level > gst_debug_category_get_threshold (category))
580 g_return_if_fail (file != NULL);
581 g_return_if_fail (function != NULL);
582 g_return_if_fail (format != NULL);
584 message.message = NULL;
585 message.format = format;
586 G_VA_COPY (message.arguments, args);
588 handler = __log_functions;
590 entry = handler->data;
591 handler = g_slist_next (handler);
592 entry->func (category, level, file, function, line, object, &message,
595 g_free (message.message);
596 va_end (message.arguments);
600 * gst_debug_log_literal:
601 * @category: category to log
602 * @level: level of the message is in
603 * @file: the file that emitted the message, usually the __FILE__ identifier
604 * @function: the function that emitted the message
605 * @line: the line from that the message was emitted, usually __LINE__
606 * @object: (transfer none) (allow-none): the object this message relates to,
608 * @message_string: a message string
610 * Logs the given message using the currently registered debugging handlers.
615 gst_debug_log_literal (GstDebugCategory * category, GstDebugLevel level,
616 const gchar * file, const gchar * function, gint line,
617 GObject * object, const gchar * message_string)
619 GstDebugMessage message;
623 g_return_if_fail (category != NULL);
625 #ifdef GST_ENABLE_EXTRA_CHECKS
626 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
629 if (level > gst_debug_category_get_threshold (category))
632 g_return_if_fail (file != NULL);
633 g_return_if_fail (function != NULL);
634 g_return_if_fail (message_string != NULL);
636 message.message = (gchar *) message_string;
638 handler = __log_functions;
640 entry = handler->data;
641 handler = g_slist_next (handler);
642 entry->func (category, level, file, function, line, object, &message,
648 * gst_debug_message_get:
649 * @message: a debug message
651 * Gets the string representation of a #GstDebugMessage. This function is used
652 * in debug handlers to extract the message.
654 * Returns: (nullable): the string representation of a #GstDebugMessage.
657 gst_debug_message_get (GstDebugMessage * message)
659 if (message->message == NULL) {
662 len = __gst_vasprintf (&message->message, message->format,
666 message->message = NULL;
668 return message->message;
671 #define MAX_BUFFER_DUMP_STRING_LEN 100
673 /* structure_to_pretty_string:
674 * @str: a serialized #GstStructure
676 * If the serialized structure contains large buffers such as images the hex
677 * representation of those buffers will be shortened so that the string remains
680 * Returns: the filtered string
683 prettify_structure_string (gchar * str)
685 gchar *pos = str, *end;
687 while ((pos = strstr (pos, "(buffer)"))) {
690 pos += strlen ("(buffer)");
691 for (end = pos; *end != '\0' && *end != ';' && *end != ' '; ++end)
693 if (count > MAX_BUFFER_DUMP_STRING_LEN) {
694 memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 6, "..", 2);
695 memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 4, pos + count - 4, 4);
696 memmove (pos + MAX_BUFFER_DUMP_STRING_LEN, pos + count,
697 strlen (pos + count) + 1);
698 pos += MAX_BUFFER_DUMP_STRING_LEN;
705 static inline gchar *
706 gst_info_structure_to_string (const GstStructure * s)
709 gchar *str = gst_structure_to_string (s);
710 if (G_UNLIKELY (pretty_tags && s->name == GST_QUARK (TAGLIST)))
711 return prettify_structure_string (str);
718 static inline gchar *
719 gst_info_describe_buffer (GstBuffer * buffer)
721 const gchar *offset_str = "none";
722 const gchar *offset_end_str = "none";
723 gchar offset_buf[32], offset_end_buf[32];
725 if (GST_BUFFER_OFFSET_IS_VALID (buffer)) {
726 g_snprintf (offset_buf, sizeof (offset_buf), "%" G_GUINT64_FORMAT,
727 GST_BUFFER_OFFSET (buffer));
728 offset_str = offset_buf;
730 if (GST_BUFFER_OFFSET_END_IS_VALID (buffer)) {
731 g_snprintf (offset_end_buf, sizeof (offset_end_buf), "%" G_GUINT64_FORMAT,
732 GST_BUFFER_OFFSET_END (buffer));
733 offset_end_str = offset_end_buf;
736 return g_strdup_printf ("buffer: %p, pts %" GST_TIME_FORMAT ", dts %"
737 GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT
738 ", offset %s, offset_end %s, flags 0x%x", buffer,
739 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
740 GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
741 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
742 gst_buffer_get_size (buffer), offset_str, offset_end_str,
743 GST_BUFFER_FLAGS (buffer));
746 static inline gchar *
747 gst_info_describe_buffer_list (GstBufferList * list)
749 GstClockTime pts = GST_CLOCK_TIME_NONE;
750 GstClockTime dts = GST_CLOCK_TIME_NONE;
751 gsize total_size = 0;
754 n = gst_buffer_list_length (list);
755 for (i = 0; i < n; ++i) {
756 GstBuffer *buf = gst_buffer_list_get (list, i);
759 pts = GST_BUFFER_PTS (buf);
760 dts = GST_BUFFER_DTS (buf);
763 total_size += gst_buffer_get_size (buf);
766 return g_strdup_printf ("bufferlist: %p, %u buffers, pts %" GST_TIME_FORMAT
767 ", dts %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT, list, n,
768 GST_TIME_ARGS (pts), GST_TIME_ARGS (dts), total_size);
771 static inline gchar *
772 gst_info_describe_event (GstEvent * event)
776 s = gst_info_structure_to_string (gst_event_get_structure (event));
777 ret = g_strdup_printf ("%s event: %p, time %" GST_TIME_FORMAT
778 ", seq-num %d, %s", GST_EVENT_TYPE_NAME (event), event,
779 GST_TIME_ARGS (GST_EVENT_TIMESTAMP (event)), GST_EVENT_SEQNUM (event),
785 static inline gchar *
786 gst_info_describe_message (GstMessage * message)
790 s = gst_info_structure_to_string (gst_message_get_structure (message));
791 ret = g_strdup_printf ("%s message: %p, time %" GST_TIME_FORMAT
792 ", seq-num %d, element '%s', %s", GST_MESSAGE_TYPE_NAME (message),
793 message, GST_TIME_ARGS (GST_MESSAGE_TIMESTAMP (message)),
794 GST_MESSAGE_SEQNUM (message),
795 ((message->src) ? GST_ELEMENT_NAME (message->src) : "(NULL)"),
801 static inline gchar *
802 gst_info_describe_query (GstQuery * query)
806 s = gst_info_structure_to_string (gst_query_get_structure (query));
807 ret = g_strdup_printf ("%s query: %p, %s", GST_QUERY_TYPE_NAME (query),
808 query, (s ? s : "(NULL)"));
813 static inline gchar *
814 gst_info_describe_stream (GstStream * stream)
816 gchar *ret, *caps_str = NULL, *tags_str = NULL;
820 caps = gst_stream_get_caps (stream);
822 caps_str = gst_caps_to_string (caps);
823 gst_caps_unref (caps);
826 tags = gst_stream_get_tags (stream);
828 tags_str = gst_tag_list_to_string (tags);
829 gst_tag_list_unref (tags);
833 g_strdup_printf ("stream %s %p, ID %s, flags 0x%x, caps [%s], tags [%s]",
834 gst_stream_type_get_name (gst_stream_get_stream_type (stream)), stream,
835 gst_stream_get_stream_id (stream), gst_stream_get_stream_flags (stream),
836 caps_str ? caps_str : "", tags_str ? tags_str : "");
844 static inline gchar *
845 gst_info_describe_stream_collection (GstStreamCollection * collection)
848 GString *streams_str;
851 streams_str = g_string_new ("<");
852 for (i = 0; i < gst_stream_collection_get_size (collection); i++) {
853 GstStream *stream = gst_stream_collection_get_stream (collection, i);
856 s = gst_info_describe_stream (stream);
857 g_string_append_printf (streams_str, " %s,", s);
860 g_string_append (streams_str, " >");
862 ret = g_strdup_printf ("collection %p (%d streams) %s", collection,
863 gst_stream_collection_get_size (collection), streams_str->str);
865 g_string_free (streams_str, TRUE);
870 gst_debug_print_object (gpointer ptr)
872 GObject *object = (GObject *) ptr;
875 /* This is a cute trick to detect unmapped memory, but is unportable,
876 * slow, screws around with madvise, and not actually that useful. */
880 ret = madvise ((void *) ((unsigned long) ptr & (~0xfff)), 4096, 0);
881 if (ret == -1 && errno == ENOMEM) {
882 buffer = g_strdup_printf ("%p (unmapped memory)", ptr);
887 /* nicely printed object */
888 if (object == NULL) {
889 return g_strdup ("(NULL)");
891 if (GST_IS_CAPS (ptr)) {
892 return gst_caps_to_string ((const GstCaps *) ptr);
894 if (GST_IS_STRUCTURE (ptr)) {
895 return gst_info_structure_to_string ((const GstStructure *) ptr);
897 if (*(GType *) ptr == GST_TYPE_CAPS_FEATURES) {
898 return gst_caps_features_to_string ((const GstCapsFeatures *) ptr);
900 if (GST_IS_TAG_LIST (ptr)) {
901 gchar *str = gst_tag_list_to_string ((GstTagList *) ptr);
902 if (G_UNLIKELY (pretty_tags))
903 return prettify_structure_string (str);
907 if (*(GType *) ptr == GST_TYPE_DATE_TIME) {
908 return __gst_date_time_serialize ((GstDateTime *) ptr, TRUE);
910 if (GST_IS_BUFFER (ptr)) {
911 return gst_info_describe_buffer (GST_BUFFER_CAST (ptr));
913 if (GST_IS_BUFFER_LIST (ptr)) {
914 return gst_info_describe_buffer_list (GST_BUFFER_LIST_CAST (ptr));
917 if (*(guint32 *) ptr == 0xffffffff) {
918 return g_strdup_printf ("<poisoned@%p>", ptr);
921 if (GST_IS_MESSAGE (object)) {
922 return gst_info_describe_message (GST_MESSAGE_CAST (object));
924 if (GST_IS_QUERY (object)) {
925 return gst_info_describe_query (GST_QUERY_CAST (object));
927 if (GST_IS_EVENT (object)) {
928 return gst_info_describe_event (GST_EVENT_CAST (object));
930 if (GST_IS_CONTEXT (object)) {
931 GstContext *context = GST_CONTEXT_CAST (object);
934 const GstStructure *structure;
936 type = gst_context_get_context_type (context);
937 structure = gst_context_get_structure (context);
939 s = gst_info_structure_to_string (structure);
941 ret = g_strdup_printf ("context '%s'='%s'", type, s);
945 if (GST_IS_STREAM (object)) {
946 return gst_info_describe_stream (GST_STREAM_CAST (object));
948 if (GST_IS_STREAM_COLLECTION (object)) {
950 gst_info_describe_stream_collection (GST_STREAM_COLLECTION_CAST
953 if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
954 return g_strdup_printf ("<%s:%s>", GST_DEBUG_PAD_NAME (object));
956 if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object)) {
957 return g_strdup_printf ("<%s>", GST_OBJECT_NAME (object));
959 if (G_IS_OBJECT (object)) {
960 return g_strdup_printf ("<%s@%p>", G_OBJECT_TYPE_NAME (object), object);
963 return g_strdup_printf ("%p", ptr);
967 gst_debug_print_segment (gpointer ptr)
969 GstSegment *segment = (GstSegment *) ptr;
971 /* nicely printed segment */
972 if (segment == NULL) {
973 return g_strdup ("(NULL)");
976 switch (segment->format) {
977 case GST_FORMAT_UNDEFINED:{
978 return g_strdup_printf ("UNDEFINED segment");
980 case GST_FORMAT_TIME:{
981 return g_strdup_printf ("time segment start=%" GST_TIME_FORMAT
982 ", offset=%" GST_TIME_FORMAT ", stop=%" GST_TIME_FORMAT
983 ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" GST_TIME_FORMAT
984 ", base=%" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT
985 ", duration %" GST_TIME_FORMAT, GST_TIME_ARGS (segment->start),
986 GST_TIME_ARGS (segment->offset), GST_TIME_ARGS (segment->stop),
987 segment->rate, segment->applied_rate, (guint) segment->flags,
988 GST_TIME_ARGS (segment->time), GST_TIME_ARGS (segment->base),
989 GST_TIME_ARGS (segment->position), GST_TIME_ARGS (segment->duration));
992 const gchar *format_name;
994 format_name = gst_format_get_name (segment->format);
995 if (G_UNLIKELY (format_name == NULL))
996 format_name = "(UNKNOWN FORMAT)";
997 return g_strdup_printf ("%s segment start=%" G_GINT64_FORMAT
998 ", offset=%" G_GINT64_FORMAT ", stop=%" G_GINT64_FORMAT
999 ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" G_GINT64_FORMAT
1000 ", base=%" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT
1001 ", duration %" G_GINT64_FORMAT, format_name, segment->start,
1002 segment->offset, segment->stop, segment->rate, segment->applied_rate,
1003 (guint) segment->flags, segment->time, segment->base,
1004 segment->position, segment->duration);
1010 gst_info_printf_pointer_extension_func (const char *format, void *ptr)
1014 if (format[0] == 'p' && format[1] == '\a') {
1015 switch (format[2]) {
1016 case 'A': /* GST_PTR_FORMAT */
1017 s = gst_debug_print_object (ptr);
1019 case 'B': /* GST_SEGMENT_FORMAT */
1020 s = gst_debug_print_segment (ptr);
1022 case 'T': /* GST_TIMEP_FORMAT */
1024 s = g_strdup_printf ("%" GST_TIME_FORMAT,
1025 GST_TIME_ARGS (*(GstClockTime *) ptr));
1027 case 'S': /* GST_STIMEP_FORMAT */
1029 s = g_strdup_printf ("%" GST_STIME_FORMAT,
1030 GST_STIME_ARGS (*(gint64 *) ptr));
1032 case 'a': /* GST_WRAPPED_PTR_FORMAT */
1033 s = priv_gst_string_take_and_wrap (gst_debug_print_object (ptr));
1036 /* must have been compiled against a newer version with an extension
1037 * we don't known about yet - just ignore and fallback to %p below */
1042 s = g_strdup_printf ("%p", ptr);
1048 * gst_debug_construct_term_color:
1049 * @colorinfo: the color info
1051 * Constructs a string that can be used for getting the desired color in color
1053 * You need to free the string after use.
1055 * Returns: (transfer full) (type gchar*): a string containing the color
1059 gst_debug_construct_term_color (guint colorinfo)
1063 color = g_string_new ("\033[00");
1065 if (colorinfo & GST_DEBUG_BOLD) {
1066 g_string_append_len (color, ";01", 3);
1068 if (colorinfo & GST_DEBUG_UNDERLINE) {
1069 g_string_append_len (color, ";04", 3);
1071 if (colorinfo & GST_DEBUG_FG_MASK) {
1072 g_string_append_printf (color, ";3%1d", colorinfo & GST_DEBUG_FG_MASK);
1074 if (colorinfo & GST_DEBUG_BG_MASK) {
1075 g_string_append_printf (color, ";4%1d",
1076 (colorinfo & GST_DEBUG_BG_MASK) >> 4);
1078 g_string_append_c (color, 'm');
1080 return g_string_free (color, FALSE);
1084 * gst_debug_construct_win_color:
1085 * @colorinfo: the color info
1087 * Constructs an integer that can be used for getting the desired color in
1088 * windows' terminals (cmd.exe). As there is no mean to underline, we simply
1089 * ignore this attribute.
1091 * This function returns 0 on non-windows machines.
1093 * Returns: an integer containing the color definition
1096 gst_debug_construct_win_color (guint colorinfo)
1100 static const guchar ansi_to_win_fg[8] = {
1102 FOREGROUND_RED, /* red */
1103 FOREGROUND_GREEN, /* green */
1104 FOREGROUND_RED | FOREGROUND_GREEN, /* yellow */
1105 FOREGROUND_BLUE, /* blue */
1106 FOREGROUND_RED | FOREGROUND_BLUE, /* magenta */
1107 FOREGROUND_GREEN | FOREGROUND_BLUE, /* cyan */
1108 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE /* white */
1110 static const guchar ansi_to_win_bg[8] = {
1114 BACKGROUND_RED | BACKGROUND_GREEN,
1116 BACKGROUND_RED | BACKGROUND_BLUE,
1117 BACKGROUND_GREEN | FOREGROUND_BLUE,
1118 BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
1121 /* we draw black as white, as cmd.exe can only have black bg */
1122 if ((colorinfo & (GST_DEBUG_FG_MASK | GST_DEBUG_BG_MASK)) == 0) {
1123 color = ansi_to_win_fg[7];
1125 if (colorinfo & GST_DEBUG_UNDERLINE) {
1126 color |= BACKGROUND_INTENSITY;
1128 if (colorinfo & GST_DEBUG_BOLD) {
1129 color |= FOREGROUND_INTENSITY;
1131 if (colorinfo & GST_DEBUG_FG_MASK) {
1132 color |= ansi_to_win_fg[colorinfo & GST_DEBUG_FG_MASK];
1134 if (colorinfo & GST_DEBUG_BG_MASK) {
1135 color |= ansi_to_win_bg[(colorinfo & GST_DEBUG_BG_MASK) >> 4];
1141 /* width of %p varies depending on actual value of pointer, which can make
1142 * output unevenly aligned if multiple threads are involved, hence the %14p
1143 * (should really be %18p, but %14p seems a good compromise between too many
1144 * white spaces and likely unalignment on my system) */
1145 #if defined (GLIB_SIZEOF_VOID_P) && GLIB_SIZEOF_VOID_P == 8
1146 #define PTR_FMT "%14p"
1148 #define PTR_FMT "%10p"
1151 #define PID_FMT "%5lu"
1153 #define PID_FMT "%5d"
1155 #define CAT_FMT "%20s %s:%d:%s:%s"
1156 #define NOCOLOR_PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
1159 static const guchar levelcolormap_w32[GST_LEVEL_COUNT] = {
1160 /* GST_LEVEL_NONE */
1161 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1162 /* GST_LEVEL_ERROR */
1163 FOREGROUND_RED | FOREGROUND_INTENSITY,
1164 /* GST_LEVEL_WARNING */
1165 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1166 /* GST_LEVEL_INFO */
1167 FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1168 /* GST_LEVEL_DEBUG */
1169 FOREGROUND_GREEN | FOREGROUND_BLUE,
1171 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1172 /* GST_LEVEL_FIXME */
1173 FOREGROUND_RED | FOREGROUND_GREEN,
1174 /* GST_LEVEL_TRACE */
1175 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1176 /* placeholder for log level 8 */
1178 /* GST_LEVEL_MEMDUMP */
1179 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
1182 static const guchar available_colors[] = {
1183 FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_RED | FOREGROUND_GREEN,
1184 FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_BLUE,
1185 FOREGROUND_GREEN | FOREGROUND_BLUE,
1187 #endif /* G_OS_WIN32 */
1188 static const gchar *levelcolormap[GST_LEVEL_COUNT] = {
1189 "\033[37m", /* GST_LEVEL_NONE */
1190 "\033[31;01m", /* GST_LEVEL_ERROR */
1191 "\033[33;01m", /* GST_LEVEL_WARNING */
1192 "\033[32;01m", /* GST_LEVEL_INFO */
1193 "\033[36m", /* GST_LEVEL_DEBUG */
1194 "\033[37m", /* GST_LEVEL_LOG */
1195 "\033[33;01m", /* GST_LEVEL_FIXME */
1196 "\033[37m", /* GST_LEVEL_TRACE */
1197 "\033[37m", /* placeholder for log level 8 */
1198 "\033[37m" /* GST_LEVEL_MEMDUMP */
1202 _gst_debug_log_preamble (GstDebugMessage * message, GObject * object,
1203 const gchar ** file, const gchar ** message_str, gchar ** obj_str,
1204 GstClockTime * elapsed)
1208 /* Get message string first because printing it might call into our custom
1209 * printf format extension mechanism which in turn might log something, e.g.
1210 * from inside gst_structure_to_string() when something can't be serialised.
1211 * This means we either need to do this outside of any critical section or
1212 * use a recursive lock instead. As we always need the message string in all
1213 * code paths, we might just as well get it here first thing and outside of
1214 * the win_print_mutex critical section. */
1215 *message_str = gst_debug_message_get (message);
1217 /* __FILE__ might be a file name or an absolute path or a
1218 * relative path, irrespective of the exact compiler used,
1219 * in which case we want to shorten it to the filename for
1222 if (c == '.' || c == '/' || c == '\\' || (c != '\0' && (*file)[1] == ':')) {
1223 *file = gst_path_basename (*file);
1227 *obj_str = gst_debug_print_object (object);
1229 *obj_str = (gchar *) "";
1232 *elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
1236 * gst_debug_log_get_line:
1237 * @category: category to log
1238 * @level: level of the message
1239 * @file: the file that emitted the message, usually the __FILE__ identifier
1240 * @function: the function that emitted the message
1241 * @line: the line from that the message was emitted, usually __LINE__
1242 * @object: (transfer none) (allow-none): the object this message relates to,
1244 * @message: the actual message
1246 * Returns the string representation for the specified debug log message
1247 * formatted in the same way as gst_debug_log_default() (the default handler),
1248 * without color. The purpose is to make it easy for custom log output
1249 * handlers to get a log output that is identical to what the default handler
1255 gst_debug_log_get_line (GstDebugCategory * category, GstDebugLevel level,
1256 const gchar * file, const gchar * function, gint line,
1257 GObject * object, GstDebugMessage * message)
1259 GstClockTime elapsed;
1260 gchar *ret, *obj_str = NULL;
1261 const gchar *message_str;
1263 #ifdef GST_ENABLE_EXTRA_CHECKS
1264 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1267 _gst_debug_log_preamble (message, object, &file, &message_str, &obj_str,
1270 ret = g_strdup_printf ("%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1271 GST_TIME_ARGS (elapsed), _gst_getpid (), g_thread_self (),
1272 gst_debug_level_get_name (level), gst_debug_category_get_name
1273 (category), file, line, function, obj_str, message_str);
1282 _gst_debug_fprintf (FILE * file, const gchar * format, ...)
1288 va_start (args, format);
1289 length = gst_info_vasprintf (&str, format, args);
1292 if (length == 0 || !str)
1295 /* Even if it's valid UTF-8 string, console might print broken string
1296 * depending on codepage and the content of the given string.
1297 * Fortunately, g_print* family will take care of the Windows' codepage
1298 * specific behavior.
1300 if (file == stderr) {
1301 g_printerr ("%s", str);
1302 } else if (file == stdout) {
1303 g_print ("%s", str);
1305 /* We are writing to file. Text editors/viewers should be able to
1306 * decode valid UTF-8 string regardless of codepage setting */
1307 fwrite (str, 1, length, file);
1309 /* FIXME: fflush here might be redundant if setvbuf works as expected */
1318 * gst_debug_log_default:
1319 * @category: category to log
1320 * @level: level of the message
1321 * @file: the file that emitted the message, usually the __FILE__ identifier
1322 * @function: the function that emitted the message
1323 * @line: the line from that the message was emitted, usually __LINE__
1324 * @message: the actual message
1325 * @object: (transfer none) (allow-none): the object this message relates to,
1327 * @user_data: the FILE* to log to
1329 * The default logging handler used by GStreamer. Logging functions get called
1330 * whenever a macro like GST_DEBUG or similar is used. By default this function
1331 * is setup to output the message and additional info to stderr (or the log file
1332 * specified via the GST_DEBUG_FILE environment variable) as received via
1335 * You can add other handlers by using gst_debug_add_log_function().
1336 * And you can remove this handler by calling
1337 * gst_debug_remove_log_function(gst_debug_log_default);
1340 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
1341 const gchar * file, const gchar * function, gint line,
1342 GObject * object, GstDebugMessage * message, gpointer user_data)
1345 GstClockTime elapsed;
1347 GstDebugColorMode color_mode;
1348 const gchar *message_str;
1349 FILE *log_file = user_data ? user_data : stderr;
1351 #define FPRINTF_DEBUG _gst_debug_fprintf
1352 /* _gst_debug_fprintf will do fflush if it's required */
1353 #define FFLUSH_DEBUG(f) ((void)(f))
1355 #define FPRINTF_DEBUG fprintf
1356 #define FFLUSH_DEBUG(f) G_STMT_START { \
1361 #ifdef GST_ENABLE_EXTRA_CHECKS
1362 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1365 _gst_debug_log_preamble (message, object, &file, &message_str, &obj,
1368 pid = _gst_getpid ();
1369 color_mode = gst_debug_get_color_mode ();
1371 if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
1373 G_LOCK (win_print_mutex);
1374 if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
1376 /* colors, non-windows */
1377 gchar *color = NULL;
1380 const gchar *levelcolor;
1382 color = gst_debug_construct_term_color (gst_debug_category_get_color
1385 g_sprintf (pidcolor, "\033[%02dm", pid % 6 + 31);
1386 levelcolor = levelcolormap[level];
1388 #define PRINT_FMT " %s"PID_FMT"%s "PTR_FMT" %s%s%s %s"CAT_FMT"%s %s\n"
1389 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT PRINT_FMT,
1390 GST_TIME_ARGS (elapsed), pidcolor, pid, clear, g_thread_self (),
1391 levelcolor, gst_debug_level_get_name (level), clear, color,
1392 gst_debug_category_get_name (category), file, line, function, obj,
1393 clear, message_str);
1394 FFLUSH_DEBUG (log_file);
1399 /* colors, windows. */
1400 const gint clear = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
1401 #define SET_COLOR(c) G_STMT_START { \
1402 if (log_file == stderr) \
1403 SetConsoleTextAttribute (GetStdHandle (STD_ERROR_HANDLE), (c)); \
1406 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT " ",
1407 GST_TIME_ARGS (elapsed));
1409 SET_COLOR (available_colors[pid % G_N_ELEMENTS (available_colors)]);
1410 FPRINTF_DEBUG (log_file, PID_FMT, pid);
1413 FPRINTF_DEBUG (log_file, " " PTR_FMT " ", g_thread_self ());
1415 SET_COLOR (levelcolormap_w32[level]);
1416 FPRINTF_DEBUG (log_file, "%s ", gst_debug_level_get_name (level));
1418 SET_COLOR (gst_debug_construct_win_color (gst_debug_category_get_color
1420 FPRINTF_DEBUG (log_file, CAT_FMT, gst_debug_category_get_name (category),
1421 file, line, function, obj);
1424 FPRINTF_DEBUG (log_file, " %s\n", message_str);
1426 G_UNLOCK (win_print_mutex);
1429 /* no color, all platforms */
1430 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1431 GST_TIME_ARGS (elapsed), pid, g_thread_self (),
1432 gst_debug_level_get_name (level),
1433 gst_debug_category_get_name (category), file, line, function, obj,
1435 FFLUSH_DEBUG (log_file);
1443 * gst_debug_level_get_name:
1444 * @level: the level to get the name for
1446 * Get the string representation of a debugging level
1451 gst_debug_level_get_name (GstDebugLevel level)
1454 case GST_LEVEL_NONE:
1456 case GST_LEVEL_ERROR:
1458 case GST_LEVEL_WARNING:
1460 case GST_LEVEL_INFO:
1462 case GST_LEVEL_DEBUG:
1466 case GST_LEVEL_FIXME:
1468 case GST_LEVEL_TRACE:
1470 case GST_LEVEL_MEMDUMP:
1473 g_warning ("invalid level specified for gst_debug_level_get_name");
1479 * gst_debug_add_log_function:
1480 * @func: the function to use
1481 * @user_data: user data
1482 * @notify: called when @user_data is not used anymore
1484 * Adds the logging function to the list of logging functions.
1485 * Be sure to use #G_GNUC_NO_INSTRUMENT on that function, it is needed.
1488 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
1489 GDestroyNotify notify)
1491 LogFuncEntry *entry;
1495 func = gst_debug_log_default;
1497 entry = g_slice_new (LogFuncEntry);
1499 entry->user_data = user_data;
1500 entry->notify = notify;
1501 /* FIXME: we leak the old list here - other threads might access it right now
1502 * in gst_debug_logv. Another solution is to lock the mutex in gst_debug_logv,
1503 * but that is waaay costly.
1504 * It'd probably be clever to use some kind of RCU here, but I don't know
1505 * anything about that.
1507 g_mutex_lock (&__log_func_mutex);
1508 list = g_slist_copy (__log_functions);
1509 __log_functions = g_slist_prepend (list, entry);
1510 g_mutex_unlock (&__log_func_mutex);
1512 if (gst_is_initialized ())
1513 GST_DEBUG ("prepended log function %p (user data %p) to log functions",
1518 gst_debug_compare_log_function_by_func (gconstpointer entry, gconstpointer func)
1520 gpointer entryfunc = (gpointer) (((LogFuncEntry *) entry)->func);
1522 return (entryfunc < func) ? -1 : (entryfunc > func) ? 1 : 0;
1526 gst_debug_compare_log_function_by_data (gconstpointer entry, gconstpointer data)
1528 gpointer entrydata = ((LogFuncEntry *) entry)->user_data;
1530 return (entrydata < data) ? -1 : (entrydata > data) ? 1 : 0;
1534 gst_debug_remove_with_compare_func (GCompareFunc func, gpointer data)
1537 GSList *new, *cleanup = NULL;
1540 g_mutex_lock (&__log_func_mutex);
1541 new = __log_functions;
1543 while ((found = g_slist_find_custom (new, data, func))) {
1544 if (new == __log_functions) {
1545 /* make a copy when we have the first hit, so that we modify the copy and
1546 * make that the new list later */
1547 new = g_slist_copy (new);
1550 cleanup = g_slist_prepend (cleanup, found->data);
1551 new = g_slist_delete_link (new, found);
1554 /* FIXME: We leak the old list here. See _add_log_function for why. */
1555 __log_functions = new;
1556 g_mutex_unlock (&__log_func_mutex);
1559 LogFuncEntry *entry = cleanup->data;
1562 entry->notify (entry->user_data);
1564 g_slice_free (LogFuncEntry, entry);
1565 cleanup = g_slist_delete_link (cleanup, cleanup);
1571 * gst_debug_remove_log_function:
1572 * @func: (scope call) (allow-none): the log function to remove, or %NULL to
1573 * remove the default log function
1575 * Removes all registered instances of the given logging functions.
1577 * Returns: How many instances of the function were removed
1580 gst_debug_remove_log_function (GstLogFunction func)
1585 func = gst_debug_log_default;
1588 gst_debug_remove_with_compare_func
1589 (gst_debug_compare_log_function_by_func, (gpointer) func);
1591 if (gst_is_initialized ()) {
1592 GST_DEBUG ("removed log function %p %d times from log function list", func,
1595 /* If the default log function is removed before gst_init() was called,
1596 * set a flag so we don't add it in gst_init() later */
1597 if (func == gst_debug_log_default) {
1598 add_default_log_func = FALSE;
1607 * gst_debug_remove_log_function_by_data:
1608 * @data: user data of the log function to remove
1610 * Removes all registered instances of log functions with the given user data.
1612 * Returns: How many instances of the function were removed
1615 gst_debug_remove_log_function_by_data (gpointer data)
1620 gst_debug_remove_with_compare_func
1621 (gst_debug_compare_log_function_by_data, data);
1623 if (gst_is_initialized ())
1625 ("removed %d log functions with user data %p from log function list",
1632 * gst_debug_set_colored:
1633 * @colored: Whether to use colored output or not
1635 * Sets or unsets the use of coloured debugging output.
1636 * Same as gst_debug_set_color_mode () with the argument being
1637 * being GST_DEBUG_COLOR_MODE_ON or GST_DEBUG_COLOR_MODE_OFF.
1639 * This function may be called before gst_init().
1642 gst_debug_set_colored (gboolean colored)
1644 GstDebugColorMode new_mode;
1645 new_mode = colored ? GST_DEBUG_COLOR_MODE_ON : GST_DEBUG_COLOR_MODE_OFF;
1646 g_atomic_int_set (&__use_color, (gint) new_mode);
1650 * gst_debug_set_color_mode:
1651 * @mode: The coloring mode for debug output. See @GstDebugColorMode.
1653 * Changes the coloring mode for debug output.
1655 * This function may be called before gst_init().
1660 gst_debug_set_color_mode (GstDebugColorMode mode)
1662 g_atomic_int_set (&__use_color, mode);
1666 * gst_debug_set_color_mode_from_string:
1667 * @mode: The coloring mode for debug output. One of the following:
1668 * "on", "auto", "off", "disable", "unix".
1670 * Changes the coloring mode for debug output.
1672 * This function may be called before gst_init().
1677 gst_debug_set_color_mode_from_string (const gchar * mode)
1679 if ((strcmp (mode, "on") == 0) || (strcmp (mode, "auto") == 0))
1680 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_ON);
1681 else if ((strcmp (mode, "off") == 0) || (strcmp (mode, "disable") == 0))
1682 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
1683 else if (strcmp (mode, "unix") == 0)
1684 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_UNIX);
1688 * gst_debug_is_colored:
1690 * Checks if the debugging output should be colored.
1692 * Returns: %TRUE, if the debug output should be colored.
1695 gst_debug_is_colored (void)
1697 GstDebugColorMode mode = g_atomic_int_get (&__use_color);
1698 return (mode == GST_DEBUG_COLOR_MODE_UNIX || mode == GST_DEBUG_COLOR_MODE_ON);
1702 * gst_debug_get_color_mode:
1704 * Changes the coloring mode for debug output.
1706 * Returns: see @GstDebugColorMode for possible values.
1711 gst_debug_get_color_mode (void)
1713 return g_atomic_int_get (&__use_color);
1717 * gst_debug_set_active:
1718 * @active: Whether to use debugging output or not
1720 * If activated, debugging messages are sent to the debugging
1722 * It makes sense to deactivate it for speed issues.
1723 * > This function is not threadsafe. It makes sense to only call it
1724 * during initialization.
1727 gst_debug_set_active (gboolean active)
1729 _gst_debug_enabled = active;
1731 _gst_debug_min = GST_LEVEL_COUNT;
1733 _gst_debug_min = GST_LEVEL_NONE;
1737 * gst_debug_is_active:
1739 * Checks if debugging output is activated.
1741 * Returns: %TRUE, if debugging is activated
1744 gst_debug_is_active (void)
1746 return _gst_debug_enabled;
1750 * gst_debug_set_default_threshold:
1751 * @level: level to set
1753 * Sets the default threshold to the given level and updates all categories to
1754 * use this threshold.
1756 * This function may be called before gst_init().
1759 gst_debug_set_default_threshold (GstDebugLevel level)
1761 g_atomic_int_set (&__default_level, level);
1762 gst_debug_reset_all_thresholds ();
1766 * gst_debug_get_default_threshold:
1768 * Returns the default threshold that is used for new categories.
1770 * Returns: the default threshold level
1773 gst_debug_get_default_threshold (void)
1775 return (GstDebugLevel) g_atomic_int_get (&__default_level);
1778 #if !GLIB_CHECK_VERSION(2,70,0)
1779 #define g_pattern_spec_match_string g_pattern_match_string
1783 gst_debug_apply_entry (GstDebugCategory * cat, LevelNameEntry * entry)
1785 if (!g_pattern_spec_match_string (entry->pat, cat->name))
1788 if (gst_is_initialized ())
1789 GST_LOG ("category %s matches pattern %p - gets set to level %d",
1790 cat->name, entry->pat, entry->level);
1792 gst_debug_category_set_threshold (cat, entry->level);
1797 gst_debug_reset_threshold (gpointer category, gpointer unused)
1799 GstDebugCategory *cat = (GstDebugCategory *) category;
1802 g_mutex_lock (&__level_name_mutex);
1804 for (walk = __level_name; walk != NULL; walk = walk->next) {
1805 if (gst_debug_apply_entry (cat, walk->data))
1809 g_mutex_unlock (&__level_name_mutex);
1812 gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
1816 gst_debug_reset_all_thresholds (void)
1818 g_mutex_lock (&__cat_mutex);
1819 g_slist_foreach (__categories, gst_debug_reset_threshold, NULL);
1820 g_mutex_unlock (&__cat_mutex);
1824 for_each_threshold_by_entry (gpointer data, gpointer user_data)
1826 GstDebugCategory *cat = (GstDebugCategory *) data;
1827 LevelNameEntry *entry = (LevelNameEntry *) user_data;
1829 gst_debug_apply_entry (cat, entry);
1833 * gst_debug_set_threshold_for_name:
1834 * @name: name of the categories to set
1835 * @level: level to set them to
1837 * Sets all categories which match the given glob style pattern to the given
1841 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
1844 LevelNameEntry *entry;
1846 g_return_if_fail (name != NULL);
1848 pat = g_pattern_spec_new (name);
1849 entry = g_slice_new (LevelNameEntry);
1851 entry->level = level;
1852 g_mutex_lock (&__level_name_mutex);
1853 __level_name = g_slist_prepend (__level_name, entry);
1854 g_mutex_unlock (&__level_name_mutex);
1855 g_mutex_lock (&__cat_mutex);
1856 g_slist_foreach (__categories, for_each_threshold_by_entry, entry);
1857 g_mutex_unlock (&__cat_mutex);
1861 * gst_debug_unset_threshold_for_name:
1862 * @name: name of the categories to set
1864 * Resets all categories with the given name back to the default level.
1867 gst_debug_unset_threshold_for_name (const gchar * name)
1872 g_return_if_fail (name != NULL);
1874 pat = g_pattern_spec_new (name);
1875 g_mutex_lock (&__level_name_mutex);
1876 walk = __level_name;
1877 /* improve this if you want, it's mighty slow */
1879 LevelNameEntry *entry = walk->data;
1881 if (g_pattern_spec_equal (entry->pat, pat)) {
1882 __level_name = g_slist_remove_link (__level_name, walk);
1883 g_pattern_spec_free (entry->pat);
1884 g_slice_free (LevelNameEntry, entry);
1885 g_slist_free_1 (walk);
1886 walk = __level_name;
1888 walk = g_slist_next (walk);
1891 g_mutex_unlock (&__level_name_mutex);
1892 g_pattern_spec_free (pat);
1893 gst_debug_reset_all_thresholds ();
1897 _gst_debug_category_new (const gchar * name, guint color,
1898 const gchar * description)
1900 GstDebugCategory *cat, *catfound;
1902 g_return_val_if_fail (name != NULL, NULL);
1904 cat = g_slice_new (GstDebugCategory);
1905 cat->name = g_strdup (name);
1907 if (description != NULL) {
1908 cat->description = g_strdup (description);
1910 cat->description = g_strdup ("no description");
1912 g_atomic_int_set (&cat->threshold, 0);
1913 gst_debug_reset_threshold (cat, NULL);
1915 /* add to category list */
1916 g_mutex_lock (&__cat_mutex);
1917 catfound = _gst_debug_get_category_locked (name);
1919 g_free ((gpointer) cat->name);
1920 g_free ((gpointer) cat->description);
1921 g_slice_free (GstDebugCategory, cat);
1924 __categories = g_slist_prepend (__categories, cat);
1926 g_mutex_unlock (&__cat_mutex);
1931 #ifndef GST_REMOVE_DEPRECATED
1933 * gst_debug_category_free:
1934 * @category: #GstDebugCategory to free.
1936 * Removes and frees the category and all associated resources.
1938 * Deprecated: This function can easily cause memory corruption, don't use it.
1941 gst_debug_category_free (GstDebugCategory * category)
1947 * gst_debug_category_set_threshold:
1948 * @category: a #GstDebugCategory to set threshold of.
1949 * @level: the #GstDebugLevel threshold to set.
1951 * Sets the threshold of the category to the given level. Debug information will
1952 * only be output if the threshold is lower or equal to the level of the
1953 * debugging message.
1954 * > Do not use this function in production code, because other functions may
1955 * > change the threshold of categories as side effect. It is however a nice
1956 * > function to use when debugging (even from gdb).
1959 gst_debug_category_set_threshold (GstDebugCategory * category,
1960 GstDebugLevel level)
1962 g_return_if_fail (category != NULL);
1964 if (level > _gst_debug_min) {
1965 _gst_debug_enabled = TRUE;
1966 _gst_debug_min = level;
1969 g_atomic_int_set (&category->threshold, level);
1973 * gst_debug_category_reset_threshold:
1974 * @category: a #GstDebugCategory to reset threshold of.
1976 * Resets the threshold of the category to the default level. Debug information
1977 * will only be output if the threshold is lower or equal to the level of the
1978 * debugging message.
1979 * Use this function to set the threshold back to where it was after using
1980 * gst_debug_category_set_threshold().
1983 gst_debug_category_reset_threshold (GstDebugCategory * category)
1985 gst_debug_reset_threshold (category, NULL);
1989 * gst_debug_category_get_threshold:
1990 * @category: a #GstDebugCategory to get threshold of.
1992 * Returns the threshold of a #GstDebugCategory.
1994 * Returns: the #GstDebugLevel that is used as threshold.
1997 gst_debug_category_get_threshold (GstDebugCategory * category)
1999 return (GstDebugLevel) g_atomic_int_get (&category->threshold);
2003 * gst_debug_category_get_name:
2004 * @category: a #GstDebugCategory to get name of.
2006 * Returns the name of a debug category.
2008 * Returns: the name of the category.
2011 gst_debug_category_get_name (GstDebugCategory * category)
2013 return category->name;
2017 * gst_debug_category_get_color:
2018 * @category: a #GstDebugCategory to get the color of.
2020 * Returns the color of a debug category used when printing output in this
2023 * Returns: the color of the category.
2026 gst_debug_category_get_color (GstDebugCategory * category)
2028 return category->color;
2032 * gst_debug_category_get_description:
2033 * @category: a #GstDebugCategory to get the description of.
2035 * Returns the description of a debug category.
2037 * Returns: the description of the category.
2040 gst_debug_category_get_description (GstDebugCategory * category)
2042 return category->description;
2046 * gst_debug_get_all_categories:
2048 * Returns a snapshot of a all categories that are currently in use . This list
2049 * may change anytime.
2050 * The caller has to free the list after use.
2052 * Returns: (transfer container) (element-type Gst.DebugCategory): the list of
2056 gst_debug_get_all_categories (void)
2060 g_mutex_lock (&__cat_mutex);
2061 ret = g_slist_copy (__categories);
2062 g_mutex_unlock (&__cat_mutex);
2067 static GstDebugCategory *
2068 _gst_debug_get_category_locked (const gchar * name)
2070 GstDebugCategory *ret = NULL;
2073 for (node = __categories; node; node = g_slist_next (node)) {
2074 ret = (GstDebugCategory *) node->data;
2075 if (!strcmp (name, ret->name)) {
2083 _gst_debug_get_category (const gchar * name)
2085 GstDebugCategory *ret;
2087 g_mutex_lock (&__cat_mutex);
2088 ret = _gst_debug_get_category_locked (name);
2089 g_mutex_unlock (&__cat_mutex);
2095 parse_debug_category (gchar * str, const gchar ** category)
2100 /* works in place */
2103 if (str[0] != '\0') {
2112 parse_debug_level (gchar * str, GstDebugLevel * level)
2117 /* works in place */
2120 if (g_ascii_isdigit (str[0])) {
2123 l = strtoul (str, &endptr, 10);
2124 if (endptr > str && endptr[0] == 0) {
2125 *level = (GstDebugLevel) l;
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;
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
2157 * %FALSE if adding the threshold described by @list to the one already set.
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.
2167 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2175 gst_debug_set_default_threshold (GST_LEVEL_DEFAULT);
2177 split = g_strsplit (list, ",", 0);
2179 for (walk = split; *walk; walk++) {
2180 if (strchr (*walk, ':')) {
2181 gchar **values = g_strsplit (*walk, ":", 2);
2183 if (values[0] && values[1]) {
2184 GstDebugLevel level;
2185 const gchar *category;
2187 if (parse_debug_category (values[0], &category)
2188 && parse_debug_level (values[1], &level)) {
2189 gst_debug_set_threshold_for_name (category, level);
2191 /* bump min-level anyway to allow the category to be registered in the
2193 if (level > _gst_debug_min) {
2194 _gst_debug_min = level;
2199 g_strfreev (values);
2201 GstDebugLevel level;
2203 if (parse_debug_level (*walk, &level))
2204 gst_debug_set_default_threshold (level);
2211 /*** FUNCTION POINTERS ********************************************************/
2213 static GHashTable *__gst_function_pointers; /* NULL */
2214 static GMutex __dbg_functions_mutex;
2216 /* This function MUST NOT return NULL */
2218 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2226 if (G_UNLIKELY (func == NULL))
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))
2236 g_mutex_unlock (&__dbg_functions_mutex);
2238 /* we need to create an entry in the hash table for this one so we don't leak
2241 if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
2242 const gchar *name = g_intern_string (dl_info.dli_sname);
2244 _gst_debug_register_funcptr (func, name);
2249 gchar *name = g_strdup_printf ("%p", (gpointer) func);
2250 const gchar *iname = g_intern_string (name);
2254 _gst_debug_register_funcptr (func, iname);
2260 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2262 gpointer ptr = (gpointer) func;
2264 g_mutex_lock (&__dbg_functions_mutex);
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);
2272 g_mutex_unlock (&__dbg_functions_mutex);
2276 _priv_gst_debug_cleanup (void)
2278 g_mutex_lock (&__dbg_functions_mutex);
2280 if (__gst_function_pointers) {
2281 g_hash_table_unref (__gst_function_pointers);
2282 __gst_function_pointers = NULL;
2285 g_mutex_unlock (&__dbg_functions_mutex);
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);
2295 g_mutex_unlock (&__cat_mutex);
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);
2304 g_mutex_unlock (&__level_name_mutex);
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);
2314 g_mutex_unlock (&__log_func_mutex);
2318 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2319 const guint8 * mem, gsize mem_offset, gsize mem_size)
2321 gchar hexstr[50], ascstr[18], digitstr[4];
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));
2342 g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2343 (guint) mem_offset, hexstr, ascstr);
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)
2353 gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2354 "-------------------------------------------------------------------");
2356 if (msg != NULL && *msg != '\0') {
2357 gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", msg);
2360 while (off < length) {
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);
2369 gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2370 "-------------------------------------------------------------------");
2373 #else /* !GST_DISABLE_GST_DEBUG */
2374 #ifndef GST_REMOVE_DISABLED
2377 _gst_debug_category_new (const gchar * name, guint color,
2378 const gchar * description)
2384 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2388 /* This function MUST NOT return NULL */
2390 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2396 _priv_gst_debug_cleanup (void)
2401 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2402 const gchar * file, const gchar * function, gint line,
2403 GObject * object, const gchar * format, ...)
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)
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)
2422 gst_debug_message_get (GstDebugMessage * message)
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)
2435 gst_debug_level_get_name (GstDebugLevel level)
2441 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2442 GDestroyNotify notify)
2449 gst_debug_remove_log_function (GstLogFunction func)
2455 gst_debug_remove_log_function_by_data (gpointer data)
2461 gst_debug_set_active (gboolean active)
2466 gst_debug_is_active (void)
2472 gst_debug_set_colored (gboolean colored)
2477 gst_debug_set_color_mode (GstDebugColorMode mode)
2482 gst_debug_set_color_mode_from_string (const gchar * str)
2487 gst_debug_is_colored (void)
2493 gst_debug_get_color_mode (void)
2495 return GST_DEBUG_COLOR_MODE_OFF;
2499 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2504 gst_debug_set_default_threshold (GstDebugLevel level)
2509 gst_debug_get_default_threshold (void)
2511 return GST_LEVEL_NONE;
2515 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2520 gst_debug_unset_threshold_for_name (const gchar * name)
2524 #ifndef GST_REMOVE_DEPRECATED
2526 gst_debug_category_free (GstDebugCategory * category)
2532 gst_debug_category_set_threshold (GstDebugCategory * category,
2533 GstDebugLevel level)
2538 gst_debug_category_reset_threshold (GstDebugCategory * category)
2543 gst_debug_category_get_threshold (GstDebugCategory * category)
2545 return GST_LEVEL_NONE;
2549 gst_debug_category_get_name (GstDebugCategory * category)
2555 gst_debug_category_get_color (GstDebugCategory * category)
2561 gst_debug_category_get_description (GstDebugCategory * category)
2567 gst_debug_get_all_categories (void)
2573 _gst_debug_get_category (const gchar * name)
2579 gst_debug_construct_term_color (guint colorinfo)
2581 return g_strdup ("00");
2585 gst_debug_construct_win_color (guint colorinfo)
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)
2596 #endif /* GST_REMOVE_DISABLED */
2597 #endif /* GST_DISABLE_GST_DEBUG */
2599 /* Need this for _gst_element_error_printf even if GST_REMOVE_DISABLED is set:
2600 * fallback function that cleans up the format string and replaces all pointer
2601 * extension formats with plain %p. */
2602 #ifdef GST_DISABLE_GST_DEBUG
2604 __gst_info_fallback_vasprintf (char **result, char const *format, va_list args)
2606 gchar *clean_format, *c;
2612 clean_format = g_strdup (format);
2614 while ((c = strstr (c, "%p\a"))) {
2615 if (c[3] < 'A' || c[3] > 'Z') {
2619 len = strlen (c + 4);
2620 memmove (c + 2, c + 4, len + 1);
2623 while ((c = strstr (clean_format, "%P"))) /* old GST_PTR_FORMAT */
2625 while ((c = strstr (clean_format, "%Q"))) /* old GST_SEGMENT_FORMAT */
2628 len = g_vasprintf (result, clean_format, args);
2630 g_free (clean_format);
2632 if (*result == NULL)
2640 * gst_info_vasprintf:
2641 * @result: (out): the resulting string
2642 * @format: a printf style format string
2643 * @args: the va_list of printf arguments for @format
2645 * Allocates and fills a string large enough (including the terminating null
2646 * byte) to hold the specified printf style @format and @args.
2648 * This function deals with the GStreamer specific printf specifiers
2649 * #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT. If you do not have these specifiers
2650 * in your @format string, you do not need to use this function and can use
2651 * alternatives such as g_vasprintf().
2653 * Free @result with g_free().
2655 * Returns: the length of the string allocated into @result or -1 on any error
2660 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2662 /* This will fallback to __gst_info_fallback_vasprintf() via a #define in
2663 * gst_private.h if the debug system is disabled which will remove the gst
2664 * specific printf format specifiers */
2665 return __gst_vasprintf (result, format, args);
2669 * gst_info_strdup_vprintf:
2670 * @format: a printf style format string
2671 * @args: the va_list of printf arguments for @format
2673 * Allocates, fills and returns a null terminated string from the printf style
2674 * @format string and @args.
2676 * See gst_info_vasprintf() for when this function is required.
2678 * Free with g_free().
2680 * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2685 gst_info_strdup_vprintf (const gchar * format, va_list args)
2689 if (gst_info_vasprintf (&ret, format, args) < 0)
2696 * gst_info_strdup_printf:
2697 * @format: a printf style format string
2698 * @...: the printf arguments for @format
2700 * Allocates, fills and returns a 0-terminated string from the printf style
2701 * @format string and corresponding arguments.
2703 * See gst_info_vasprintf() for when this function is required.
2705 * Free with g_free().
2707 * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2712 gst_info_strdup_printf (const gchar * format, ...)
2717 va_start (args, format);
2718 ret = gst_info_strdup_vprintf (format, args);
2726 * @format: a printf style format string
2727 * @...: the printf arguments for @format
2729 * Outputs a formatted message via the GLib print handler. The default print
2730 * handler simply outputs the message to stdout.
2732 * This function will not append a new-line character at the end, unlike
2733 * gst_println() which will.
2735 * All strings must be in ASCII or UTF-8 encoding.
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.
2741 * This function is primarily for printing debug output.
2746 gst_print (const gchar * format, ...)
2751 va_start (args, format);
2752 str = gst_info_strdup_vprintf (format, args);
2756 G_LOCK (win_print_mutex);
2759 g_print ("%s", str);
2762 G_UNLOCK (win_print_mutex);
2769 * @format: a printf style format string
2770 * @...: the printf arguments for @format
2772 * Outputs a formatted message via the GLib print handler. The default print
2773 * handler simply outputs the message to stdout.
2775 * This function will append a new-line character at the end, unlike
2776 * gst_print() which will not.
2778 * All strings must be in ASCII or UTF-8 encoding.
2780 * This function differs from g_print() in that it supports all the additional
2781 * printf specifiers that are supported by GStreamer's debug logging system,
2782 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2784 * This function is primarily for printing debug output.
2789 gst_println (const gchar * format, ...)
2794 va_start (args, format);
2795 str = gst_info_strdup_vprintf (format, args);
2799 G_LOCK (win_print_mutex);
2802 g_print ("%s\n", str);
2805 G_UNLOCK (win_print_mutex);
2812 * @format: a printf style format string
2813 * @...: the printf arguments for @format
2815 * Outputs a formatted message via the GLib error message handler. The default
2816 * handler simply outputs the message to stderr.
2818 * This function will not append a new-line character at the end, unlike
2819 * gst_printerrln() which will.
2821 * All strings must be in ASCII or UTF-8 encoding.
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.
2827 * This function is primarily for printing debug output.
2832 gst_printerr (const gchar * format, ...)
2837 va_start (args, format);
2838 str = gst_info_strdup_vprintf (format, args);
2842 G_LOCK (win_print_mutex);
2845 g_printerr ("%s", str);
2848 G_UNLOCK (win_print_mutex);
2855 * @format: a printf style format string
2856 * @...: the printf arguments for @format
2858 * Outputs a formatted message via the GLib error message handler. The default
2859 * handler simply outputs the message to stderr.
2861 * This function will append a new-line character at the end, unlike
2862 * gst_printerr() which will not.
2864 * All strings must be in ASCII or UTF-8 encoding.
2866 * This function differs from g_printerr() in that it supports the additional
2867 * printf specifiers that are supported by GStreamer's debug logging system,
2868 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2870 * This function is primarily for printing debug output.
2875 gst_printerrln (const gchar * format, ...)
2880 va_start (args, format);
2881 str = gst_info_strdup_vprintf (format, args);
2885 G_LOCK (win_print_mutex);
2888 g_printerr ("%s\n", str);
2891 G_UNLOCK (win_print_mutex);
2899 append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
2903 Dwfl_Module *module;
2904 const gchar *function_name;
2906 addr = (uintptr_t) ip;
2907 module = dwfl_addrmodule (dwfl, addr);
2908 function_name = dwfl_module_addrname (module, addr);
2910 g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
2912 line = dwfl_getsrc (dwfl, addr);
2916 const gchar *filename = dwfl_lineinfo (line, &addr,
2917 &nline, NULL, NULL, NULL);
2919 g_string_append_printf (trace, "%s:%d", strrchr (filename,
2920 G_DIR_SEPARATOR) + 1, nline);
2922 const gchar *eflfile = NULL;
2924 dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
2925 g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
2930 #endif /* HAVE_DW */
2933 generate_unwind_trace (GstStackTraceFlags flags)
2937 unw_cursor_t cursor;
2938 gboolean use_libunwind = TRUE;
2939 GString *trace = g_string_new (NULL);
2944 if ((flags & GST_STACK_TRACE_SHOW_FULL)) {
2945 dwfl = get_global_dwfl ();
2946 if (G_UNLIKELY (dwfl == NULL)) {
2947 GST_WARNING ("Failed to initialize dwlf");
2952 #endif /* HAVE_DW */
2954 unret = unw_getcontext (&uc);
2956 GST_DEBUG ("Could not get libunwind context (%d)", unret);
2960 unret = unw_init_local (&cursor, &uc);
2962 GST_DEBUG ("Could not init libunwind context (%d)", unret);
2967 /* Due to plugins being loaded, mapping of process might have changed,
2968 * so always scan it. */
2969 if (dwfl_linux_proc_report (dwfl, _gst_getpid ()) != 0)
2973 while (unw_step (&cursor) > 0) {
2978 unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
2980 GST_DEBUG ("libunwind could not read frame info (%d)", unret);
2985 if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
2986 use_libunwind = FALSE;
2987 g_string_append (trace, ")\n");
2990 #endif /* HAVE_DW */
2992 if (use_libunwind) {
2995 unw_word_t offset = 0;
2996 unw_get_proc_name (&cursor, name, sizeof (name), &offset);
2997 g_string_append_printf (trace, "%s (0x%" G_GSIZE_FORMAT ")\n", name,
3008 return g_string_free (trace, FALSE);
3011 #endif /* HAVE_UNWIND */
3013 #ifdef HAVE_BACKTRACE
3015 generate_backtrace_trace (void)
3018 void *buffer[BT_BUF_SIZE];
3022 nptrs = backtrace (buffer, BT_BUF_SIZE);
3024 strings = backtrace_symbols (buffer, nptrs);
3029 trace = g_string_new (NULL);
3031 for (j = 0; j < nptrs; j++)
3032 g_string_append_printf (trace, "%s\n", strings[j]);
3036 return g_string_free (trace, FALSE);
3039 #define generate_backtrace_trace() NULL
3040 #endif /* HAVE_BACKTRACE */
3046 DWORD (WINAPI * pSymSetOptions) (DWORD SymOptions);
3047 BOOL (WINAPI * pSymInitialize) (HANDLE hProcess,
3048 PCSTR UserSearchPath,
3049 BOOL fInvadeProcess);
3050 BOOL (WINAPI * pStackWalk64) (DWORD MachineType,
3053 LPSTACKFRAME64 StackFrame,
3054 PVOID ContextRecord,
3055 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
3056 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
3057 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
3058 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
3059 PVOID (WINAPI * pSymFunctionTableAccess64) (HANDLE hProcess,
3061 DWORD64 (WINAPI * pSymGetModuleBase64) (HANDLE hProcess,
3063 BOOL (WINAPI * pSymFromAddr) (HANDLE hProcess,
3065 PDWORD64 Displacement,
3066 PSYMBOL_INFO Symbol);
3067 BOOL (WINAPI * pSymGetModuleInfo64) (HANDLE hProcess,
3069 PIMAGEHLP_MODULE64 ModuleInfo);
3070 BOOL (WINAPI * pSymGetLineFromAddr64) (HANDLE hProcess,
3072 PDWORD pdwDisplacement,
3073 PIMAGEHLP_LINE64 Line64);
3074 } dbg_help_vtable = { NULL,};
3077 static GModule *dbg_help_module = NULL;
3080 dbghelp_load_symbol (const gchar * symbol_name, gpointer * symbol)
3082 if (dbg_help_module &&
3083 !g_module_symbol (dbg_help_module, symbol_name, symbol)) {
3084 GST_WARNING ("Cannot load %s symbol", symbol_name);
3085 g_module_close (dbg_help_module);
3086 dbg_help_module = NULL;
3089 return ! !dbg_help_module;
3093 dbghelp_initialize_symbols (HANDLE process)
3095 static gsize initialization_value = 0;
3097 if (g_once_init_enter (&initialization_value)) {
3098 GST_INFO ("Initializing Windows symbol handler");
3100 dbg_help_module = g_module_open ("dbghelp.dll", G_MODULE_BIND_LAZY);
3101 dbghelp_load_symbol ("SymSetOptions",
3102 (gpointer *) & dbg_help_vtable.pSymSetOptions);
3103 dbghelp_load_symbol ("SymInitialize",
3104 (gpointer *) & dbg_help_vtable.pSymInitialize);
3105 dbghelp_load_symbol ("StackWalk64",
3106 (gpointer *) & dbg_help_vtable.pStackWalk64);
3107 dbghelp_load_symbol ("SymFunctionTableAccess64",
3108 (gpointer *) & dbg_help_vtable.pSymFunctionTableAccess64);
3109 dbghelp_load_symbol ("SymGetModuleBase64",
3110 (gpointer *) & dbg_help_vtable.pSymGetModuleBase64);
3111 dbghelp_load_symbol ("SymFromAddr",
3112 (gpointer *) & dbg_help_vtable.pSymFromAddr);
3113 dbghelp_load_symbol ("SymGetModuleInfo64",
3114 (gpointer *) & dbg_help_vtable.pSymGetModuleInfo64);
3115 dbghelp_load_symbol ("SymGetLineFromAddr64",
3116 (gpointer *) & dbg_help_vtable.pSymGetLineFromAddr64);
3118 if (dbg_help_module) {
3119 dbg_help_vtable.pSymSetOptions (SYMOPT_LOAD_LINES);
3120 dbg_help_vtable.pSymInitialize (process, NULL, TRUE);
3121 GST_INFO ("Initialized Windows symbol handler");
3124 g_once_init_leave (&initialization_value, 1);
3127 return ! !dbg_help_module;
3131 generate_dbghelp_trace (void)
3133 HANDLE process = GetCurrentProcess ();
3134 HANDLE thread = GetCurrentThread ();
3135 IMAGEHLP_MODULE64 module_info;
3138 STACKFRAME64 frame = { 0 };
3140 GString *trace = NULL;
3142 if (!dbghelp_initialize_symbols (process))
3145 memset (&context, 0, sizeof (CONTEXT));
3146 context.ContextFlags = CONTEXT_FULL;
3148 RtlCaptureContext (&context);
3150 frame.AddrPC.Mode = AddrModeFlat;
3151 frame.AddrStack.Mode = AddrModeFlat;
3152 frame.AddrFrame.Mode = AddrModeFlat;
3154 #if (defined _M_IX86)
3155 machine = IMAGE_FILE_MACHINE_I386;
3156 frame.AddrFrame.Offset = context.Ebp;
3157 frame.AddrPC.Offset = context.Eip;
3158 frame.AddrStack.Offset = context.Esp;
3159 #elif (defined _M_X64)
3160 machine = IMAGE_FILE_MACHINE_AMD64;
3161 frame.AddrFrame.Offset = context.Rbp;
3162 frame.AddrPC.Offset = context.Rip;
3163 frame.AddrStack.Offset = context.Rsp;
3168 trace = g_string_new (NULL);
3170 module_info.SizeOfStruct = sizeof (module_info);
3171 save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
3174 char buffer[sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR)];
3175 PSYMBOL_INFO symbol = (PSYMBOL_INFO) buffer;
3176 IMAGEHLP_LINE64 line;
3177 DWORD displacement = 0;
3179 symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
3180 symbol->MaxNameLen = MAX_SYM_NAME;
3182 line.SizeOfStruct = sizeof (line);
3184 if (!dbg_help_vtable.pStackWalk64 (machine, process, thread, &frame,
3185 save_context, 0, dbg_help_vtable.pSymFunctionTableAccess64,
3186 dbg_help_vtable.pSymGetModuleBase64, 0)) {
3190 if (dbg_help_vtable.pSymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
3191 g_string_append_printf (trace, "%s ", symbol->Name);
3193 g_string_append (trace, "?? ");
3195 if (dbg_help_vtable.pSymGetLineFromAddr64 (process, frame.AddrPC.Offset,
3196 &displacement, &line))
3197 g_string_append_printf (trace, "(%s:%lu)", line.FileName,
3199 else if (dbg_help_vtable.pSymGetModuleInfo64 (process, frame.AddrPC.Offset,
3201 g_string_append_printf (trace, "(%s)", module_info.ImageName);
3203 g_string_append_printf (trace, "(%s)", "??");
3205 g_string_append (trace, "\n");
3208 return g_string_free (trace, FALSE);
3210 #endif /* HAVE_DBGHELP */
3213 * gst_debug_get_stack_trace:
3214 * @flags: A set of #GstStackTraceFlags to determine how the stack trace should
3215 * look like. Pass #GST_STACK_TRACE_SHOW_NONE to retrieve a minimal backtrace.
3217 * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
3218 * present, else %NULL.
3223 gst_debug_get_stack_trace (GstStackTraceFlags flags)
3225 gchar *trace = NULL;
3226 #ifdef HAVE_BACKTRACE
3227 gboolean have_backtrace = TRUE;
3229 gboolean have_backtrace = FALSE;
3233 if ((flags & GST_STACK_TRACE_SHOW_FULL) || !have_backtrace)
3234 trace = generate_unwind_trace (flags);
3235 #elif defined(HAVE_DBGHELP)
3236 trace = generate_dbghelp_trace ();
3241 else if (have_backtrace)
3242 return generate_backtrace_trace ();
3248 * gst_debug_print_stack_trace:
3250 * If libunwind, glibc backtrace or DbgHelp are present
3251 * a stack trace is printed.
3254 gst_debug_print_stack_trace (void)
3256 gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
3260 G_LOCK (win_print_mutex);
3263 g_print ("%s\n", trace);
3266 G_UNLOCK (win_print_mutex);
3273 #ifndef GST_DISABLE_GST_DEBUG
3276 guint max_size_per_thread;
3277 guint thread_timeout;
3279 GHashTable *thread_index;
3280 } GstRingBufferLogger;
3292 G_LOCK_DEFINE_STATIC (ring_buffer_logger);
3293 static GstRingBufferLogger *ring_buffer_logger = NULL;
3296 gst_ring_buffer_logger_log (GstDebugCategory * category,
3297 GstDebugLevel level,
3299 const gchar * function,
3300 gint line, GObject * object, GstDebugMessage * message, gpointer user_data)
3302 GstRingBufferLogger *logger = user_data;
3304 GstClockTime elapsed;
3309 GstRingBufferLog *log;
3310 gint64 now = g_get_monotonic_time ();
3311 const gchar *message_str = gst_debug_message_get (message);
3313 /* __FILE__ might be a file name or an absolute path or a
3314 * relative path, irrespective of the exact compiler used,
3315 * in which case we want to shorten it to the filename for
3318 if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
3319 file = gst_path_basename (file);
3323 obj = gst_debug_print_object (object);
3328 elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
3329 thread = g_thread_self ();
3331 /* no color, all platforms */
3332 #define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
3334 g_strdup_printf ("%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
3335 _gst_getpid (), thread, gst_debug_level_get_name (level),
3336 gst_debug_category_get_name (category), file, line, function, obj,
3340 output_len = strlen (output);
3345 G_LOCK (ring_buffer_logger);
3347 if (logger->thread_timeout > 0) {
3350 /* Remove all threads that saw no output since thread_timeout seconds.
3351 * By construction these are all at the tail of the queue, and the queue
3352 * is ordered by last use, so we just need to look at the tail.
3354 while (logger->threads.tail) {
3355 log = logger->threads.tail->data;
3356 if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
3359 g_hash_table_remove (logger->thread_index, log->thread);
3360 while ((buf = g_queue_pop_head (&log->log)))
3363 g_queue_pop_tail (&logger->threads);
3367 /* Get logger for this thread, and put it back at the
3368 * head of the threads queue */
3369 log = g_hash_table_lookup (logger->thread_index, thread);
3371 log = g_new0 (GstRingBufferLog, 1);
3372 g_queue_init (&log->log);
3374 g_queue_push_head (&logger->threads, log);
3375 log->link = logger->threads.head;
3376 log->thread = thread;
3377 g_hash_table_insert (logger->thread_index, thread, log);
3379 g_queue_unlink (&logger->threads, log->link);
3380 g_queue_push_head_link (&logger->threads, log->link);
3382 log->last_use = now;
3384 if (output_len < logger->max_size_per_thread) {
3387 /* While using a GQueue here is not the most efficient thing to do, we
3388 * have to allocate a string for every output anyway and could just store
3389 * that instead of copying it to an actual ringbuffer.
3390 * Better than GQueue would be GstQueueArray, but that one is in
3391 * libgstbase and we can't use it here. That one allocation will not make
3392 * much of a difference anymore, considering the number of allocations
3393 * needed to get to this point...
3395 while (log->log_size + output_len > logger->max_size_per_thread) {
3396 buf = g_queue_pop_head (&log->log);
3397 log->log_size -= strlen (buf);
3400 g_queue_push_tail (&log->log, output);
3401 log->log_size += output_len;
3405 /* Can't really write anything as the line is bigger than the maximum
3406 * allowed log size already, so just remove everything */
3408 while ((buf = g_queue_pop_head (&log->log)))
3414 G_UNLOCK (ring_buffer_logger);
3418 * gst_debug_ring_buffer_logger_get_logs:
3420 * Fetches the current logs per thread from the ring buffer logger. See
3421 * gst_debug_add_ring_buffer_logger() for details.
3423 * Returns: (transfer full) (array zero-terminated): NULL-terminated array of
3424 * strings with the debug output per thread
3429 gst_debug_ring_buffer_logger_get_logs (void)
3431 gchar **logs, **tmp;
3434 g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
3436 G_LOCK (ring_buffer_logger);
3438 tmp = logs = g_new0 (gchar *, ring_buffer_logger->threads.length + 1);
3439 for (l = ring_buffer_logger->threads.head; l; l = l->next) {
3440 GstRingBufferLog *log = l->data;
3445 *tmp = p = g_new0 (gchar, log->log_size + 1);
3447 for (l = log->log.head; l; l = l->next) {
3448 len = strlen (l->data);
3449 memcpy (p, l->data, len);
3456 G_UNLOCK (ring_buffer_logger);
3462 gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
3464 G_LOCK (ring_buffer_logger);
3465 if (ring_buffer_logger == logger) {
3466 GstRingBufferLog *log;
3468 while ((log = g_queue_pop_head (&logger->threads))) {
3470 while ((buf = g_queue_pop_head (&log->log)))
3475 g_hash_table_unref (logger->thread_index);
3478 ring_buffer_logger = NULL;
3480 G_UNLOCK (ring_buffer_logger);
3484 * gst_debug_add_ring_buffer_logger:
3485 * @max_size_per_thread: Maximum size of log per thread in bytes
3486 * @thread_timeout: Timeout for threads in seconds
3488 * Adds a memory ringbuffer based debug logger that stores up to
3489 * @max_size_per_thread bytes of logs per thread and times out threads after
3490 * @thread_timeout seconds of inactivity.
3492 * Logs can be fetched with gst_debug_ring_buffer_logger_get_logs() and the
3493 * logger can be removed again with gst_debug_remove_ring_buffer_logger().
3494 * Only one logger at a time is possible.
3499 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3500 guint thread_timeout)
3502 GstRingBufferLogger *logger;
3504 G_LOCK (ring_buffer_logger);
3506 if (ring_buffer_logger) {
3507 g_warn_if_reached ();
3508 G_UNLOCK (ring_buffer_logger);
3512 logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
3514 logger->max_size_per_thread = max_size_per_thread;
3515 logger->thread_timeout = thread_timeout;
3516 logger->thread_index = g_hash_table_new (g_direct_hash, g_direct_equal);
3517 g_queue_init (&logger->threads);
3519 gst_debug_add_log_function (gst_ring_buffer_logger_log, logger,
3520 (GDestroyNotify) gst_ring_buffer_logger_free);
3521 G_UNLOCK (ring_buffer_logger);
3525 * gst_debug_remove_ring_buffer_logger:
3527 * Removes any previously added ring buffer logger with
3528 * gst_debug_add_ring_buffer_logger().
3533 gst_debug_remove_ring_buffer_logger (void)
3535 gst_debug_remove_log_function (gst_ring_buffer_logger_log);
3538 #else /* GST_DISABLE_GST_DEBUG */
3539 #ifndef GST_REMOVE_DISABLED
3542 gst_debug_ring_buffer_logger_get_logs (void)
3548 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3549 guint thread_timeout)
3554 gst_debug_remove_ring_buffer_logger (void)
3558 #endif /* GST_REMOVE_DISABLED */
3559 #endif /* GST_DISABLE_GST_DEBUG */