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 #endif /* GST_DISABLE_GST_DEBUG */
114 #include <glib/gprintf.h> /* g_sprintf */
116 /* our own printf implementation with custom extensions to %p for caps etc. */
117 #include "printf/printf.h"
118 #include "printf/printf-extension.h"
120 static char *gst_info_printf_pointer_extension_func (const char *format,
124 # include <unistd.h> /* getpid on UNIX */
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 */
135 /* use glib's abstraction once it's landed
136 * https://gitlab.gnome.org/GNOME/glib/-/merge_requests/2475 */
141 return GetCurrentProcessId ();
152 /* No need for remote debugging so turn on the 'local only' optimizations in
154 #define UNW_LOCAL_ONLY
156 #include <libunwind.h>
165 #include <elfutils/libdwfl.h>
166 static Dwfl *_global_dwfl = NULL;
167 static GMutex _dwfl_mutex;
169 #define GST_DWFL_LOCK() g_mutex_lock(&_dwfl_mutex);
170 #define GST_DWFL_UNLOCK() g_mutex_unlock(&_dwfl_mutex);
173 get_global_dwfl (void)
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,
180 Dwfl *_dwfl = dwfl_begin (&callbacks);
181 g_mutex_init (&_dwfl_mutex);
182 g_once_init_leave (&_global_dwfl, _dwfl);
189 #endif /* HAVE_UNWIND */
191 #ifdef HAVE_BACKTRACE
192 #include <execinfo.h>
193 #define BT_BUF_SIZE 100
194 #endif /* HAVE_BACKTRACE */
199 #include <tlhelp32.h>
201 #endif /* HAVE_DBGHELP */
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
211 G_LOCK_DEFINE_STATIC (win_print_mutex);
214 extern gboolean gst_is_initialized (void);
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)
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;
225 GstDebugCategory *GST_CAT_DEFAULT = NULL;
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;
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;
263 #endif /* !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED) */
265 #ifndef GST_DISABLE_GST_DEBUG
267 /* underscore is to prevent conflict with GST_CAT_DEBUG define */
268 GST_DEBUG_CATEGORY_STATIC (_GST_CAT_DEBUG);
272 #include <rld_interface.h>
273 typedef struct DL_INFO
275 const char *dli_fname;
277 const char *dli_sname;
281 long dli_reserved[4];
285 #define _RLD_DLADDR 14
286 int dladdr (void *address, Dl_info * dl);
289 dladdr (void *address, Dl_info * dl)
293 v = _rld_new_interface (_RLD_DLADDR, address, dl);
299 static void gst_debug_reset_threshold (gpointer category, gpointer unused);
300 static void gst_debug_reset_all_thresholds (void);
302 struct _GstDebugMessage
308 /* The emitter of the message (can be NULL) */
311 /* Provider of the message. Can be user-provided, or generated dynamically
315 /* Whether object_id was dynamically allocated and should be freed */
316 gboolean free_object_id;
318 /* heap-allocated write area for short names */
322 /* list of all name/level pairs from --gst-debug and GST_DEBUG */
323 static GMutex __level_name_mutex;
324 static GSList *__level_name = NULL;
332 static void clear_level_names (void);
334 /* list of all categories */
335 static GMutex __cat_mutex;
336 static GSList *__categories = NULL;
338 static GstDebugCategory *_gst_debug_get_category_locked (const gchar * name);
341 /* all registered debug handlers */
346 GDestroyNotify notify;
349 static GMutex __log_func_mutex;
350 static GSList *__log_functions = NULL;
352 /* whether to add the default log function in gst_init() */
353 static gboolean add_default_log_func = TRUE;
355 #define PRETTY_TAGS_DEFAULT TRUE
356 static gboolean pretty_tags = PRETTY_TAGS_DEFAULT;
358 static gint G_GNUC_MAY_ALIAS __default_level = GST_LEVEL_DEFAULT;
359 static gint G_GNUC_MAY_ALIAS __use_color = GST_DEBUG_COLOR_MODE_ON;
362 _replace_pattern_in_gst_debug_file_name (gchar * name, const char *token,
366 if ((token_start = strstr (name, token))) {
367 gsize token_len = strlen (token);
368 gchar *name_prefix = name;
369 gchar *name_suffix = token_start + token_len;
370 token_start[0] = '\0';
371 name = g_strdup_printf ("%s%u%s", name_prefix, val, name_suffix);
372 g_free (name_prefix);
378 _priv_gst_debug_file_name (const gchar * env)
382 name = g_strdup (env);
383 name = _replace_pattern_in_gst_debug_file_name (name, "%p", _gst_getpid ());
384 name = _replace_pattern_in_gst_debug_file_name (name, "%r", g_random_int ());
389 /* Initialize the debugging system */
391 _priv_gst_debug_init (void)
396 if (add_default_log_func) {
397 env = g_getenv ("GST_DEBUG_FILE");
398 if (env != NULL && *env != '\0') {
399 if (strcmp (env, "-") == 0) {
402 gchar *name = _priv_gst_debug_file_name (env);
403 log_file = g_fopen (name, "w");
405 if (log_file == NULL) {
406 g_printerr ("Could not open log file '%s' for writing: %s\n", env,
415 gst_debug_add_log_function (gst_debug_log_default, log_file, NULL);
418 __gst_printf_pointer_extension_set_func
419 (gst_info_printf_pointer_extension_func);
421 /* do NOT use a single debug function before this line has been run */
422 GST_CAT_DEFAULT = _gst_debug_category_new ("default",
423 GST_DEBUG_UNDERLINE, NULL);
424 _GST_CAT_DEBUG = _gst_debug_category_new ("GST_DEBUG",
425 GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, "debugging subsystem");
427 /* FIXME: add descriptions here */
428 GST_CAT_GST_INIT = _gst_debug_category_new ("GST_INIT",
429 GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
430 GST_CAT_MEMORY = _gst_debug_category_new ("GST_MEMORY",
431 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, "memory");
432 GST_CAT_PARENTAGE = _gst_debug_category_new ("GST_PARENTAGE",
433 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
434 GST_CAT_STATES = _gst_debug_category_new ("GST_STATES",
435 GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
436 GST_CAT_SCHEDULING = _gst_debug_category_new ("GST_SCHEDULING",
437 GST_DEBUG_BOLD | GST_DEBUG_FG_MAGENTA, NULL);
438 GST_CAT_BUFFER = _gst_debug_category_new ("GST_BUFFER",
439 GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
440 GST_CAT_BUFFER_LIST = _gst_debug_category_new ("GST_BUFFER_LIST",
441 GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
442 GST_CAT_BUS = _gst_debug_category_new ("GST_BUS", GST_DEBUG_BG_YELLOW, NULL);
443 GST_CAT_CAPS = _gst_debug_category_new ("GST_CAPS",
444 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
445 GST_CAT_CLOCK = _gst_debug_category_new ("GST_CLOCK",
446 GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, NULL);
447 GST_CAT_ELEMENT_PADS = _gst_debug_category_new ("GST_ELEMENT_PADS",
448 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
449 GST_CAT_PADS = _gst_debug_category_new ("GST_PADS",
450 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
451 GST_CAT_PERFORMANCE = _gst_debug_category_new ("GST_PERFORMANCE",
452 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
453 GST_CAT_PIPELINE = _gst_debug_category_new ("GST_PIPELINE",
454 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
455 GST_CAT_PLUGIN_LOADING = _gst_debug_category_new ("GST_PLUGIN_LOADING",
456 GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
457 GST_CAT_PLUGIN_INFO = _gst_debug_category_new ("GST_PLUGIN_INFO",
458 GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
459 GST_CAT_PROPERTIES = _gst_debug_category_new ("GST_PROPERTIES",
460 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_BLUE, NULL);
461 GST_CAT_NEGOTIATION = _gst_debug_category_new ("GST_NEGOTIATION",
462 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
463 GST_CAT_REFCOUNTING = _gst_debug_category_new ("GST_REFCOUNTING",
464 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
465 GST_CAT_ERROR_SYSTEM = _gst_debug_category_new ("GST_ERROR_SYSTEM",
466 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_WHITE, NULL);
468 GST_CAT_EVENT = _gst_debug_category_new ("GST_EVENT",
469 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
470 GST_CAT_MESSAGE = _gst_debug_category_new ("GST_MESSAGE",
471 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
472 GST_CAT_PARAMS = _gst_debug_category_new ("GST_PARAMS",
473 GST_DEBUG_BOLD | GST_DEBUG_FG_BLACK | GST_DEBUG_BG_YELLOW, NULL);
474 GST_CAT_CALL_TRACE = _gst_debug_category_new ("GST_CALL_TRACE",
475 GST_DEBUG_BOLD, NULL);
476 GST_CAT_SIGNAL = _gst_debug_category_new ("GST_SIGNAL",
477 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
478 GST_CAT_PROBE = _gst_debug_category_new ("GST_PROBE",
479 GST_DEBUG_BOLD | GST_DEBUG_FG_GREEN, "pad probes");
480 GST_CAT_REGISTRY = _gst_debug_category_new ("GST_REGISTRY", 0, "registry");
481 GST_CAT_QOS = _gst_debug_category_new ("GST_QOS", 0, "QoS");
482 _priv_GST_CAT_POLL = _gst_debug_category_new ("GST_POLL", 0, "poll");
483 GST_CAT_META = _gst_debug_category_new ("GST_META", 0, "meta");
484 GST_CAT_LOCKING = _gst_debug_category_new ("GST_LOCKING", 0, "locking");
485 GST_CAT_CONTEXT = _gst_debug_category_new ("GST_CONTEXT", 0, NULL);
486 _priv_GST_CAT_PROTECTION =
487 _gst_debug_category_new ("GST_PROTECTION", 0, "protection");
489 env = g_getenv ("GST_DEBUG_OPTIONS");
491 if (strstr (env, "full_tags") || strstr (env, "full-tags"))
493 else if (strstr (env, "pretty_tags") || strstr (env, "pretty-tags"))
497 if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
498 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
499 env = g_getenv ("GST_DEBUG_COLOR_MODE");
501 gst_debug_set_color_mode_from_string (env);
503 env = g_getenv ("GST_DEBUG");
505 gst_debug_set_threshold_from_string (env, FALSE);
508 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
509 #define GST_CAT_DEFAULT _GST_CAT_DEBUG
513 * @category: category to log
514 * @level: level of the message is in
515 * @file: the file that emitted the message, usually the __FILE__ identifier
516 * @function: the function that emitted the message
517 * @line: the line from that the message was emitted, usually __LINE__
518 * @object: (transfer none) (allow-none): the object this message relates to,
520 * @format: a printf style format string
521 * @...: optional arguments for the format
523 * Logs the given message using the currently registered debugging handlers.
526 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
527 const gchar * file, const gchar * function, gint line,
528 GObject * object, const gchar * format, ...)
532 va_start (var_args, format);
533 gst_debug_log_valist (category, level, file, function, line, object, format,
540 * @category: category to log
541 * @level: level of the message is in
542 * @file: the file that emitted the message, usually the __FILE__ identifier
543 * @function: the function that emitted the message
544 * @line: the line from that the message was emitted, usually __LINE__
545 * @id: (transfer none) (allow-none): the identifier of the object this message
546 * relates to, or %NULL if none.
547 * @format: a printf style format string
548 * @...: optional arguments for the format
550 * Logs the given message using the currently registered debugging handlers.
555 gst_debug_log_id (GstDebugCategory * category, GstDebugLevel level,
556 const gchar * file, const gchar * function, gint line,
557 const gchar * id, const gchar * format, ...)
561 va_start (var_args, format);
562 gst_debug_log_id_valist (category, level, file, function, line, id, format,
567 /* based on g_basename(), which we can't use because it was deprecated */
568 static inline const gchar *
569 gst_path_basename (const gchar * file_name)
571 register const gchar *base;
573 base = strrchr (file_name, G_DIR_SEPARATOR);
576 const gchar *q = strrchr (file_name, '/');
577 if (base == NULL || (q != NULL && q > base))
584 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
585 return file_name + 2;
591 gst_debug_log_full_valist (GstDebugCategory * category, GstDebugLevel level,
592 const gchar * file, const gchar * function, gint line,
593 GObject * object, const gchar * id, const gchar * format, va_list args)
595 GstDebugMessage message;
599 g_return_if_fail (category != NULL);
601 if (level > gst_debug_category_get_threshold (category))
604 g_return_if_fail (file != NULL);
605 g_return_if_fail (function != NULL);
606 g_return_if_fail (format != NULL);
608 #ifdef GST_ENABLE_EXTRA_CHECKS
609 g_return_if_fail (id != NULL || object == NULL || G_IS_OBJECT (object));
612 message.message = NULL;
613 message.format = format;
614 message.object = object;
615 message.object_id = (gchar *) id;
616 message.free_object_id = FALSE;
618 G_VA_COPY (message.arguments, args);
620 handler = __log_functions;
622 entry = handler->data;
623 handler = g_slist_next (handler);
624 entry->func (category, level, file, function, line, object, &message,
627 g_free (message.message);
628 if (message.free_object_id)
629 g_free (message.object_id);
630 va_end (message.arguments);
634 * gst_debug_log_valist:
635 * @category: category to log
636 * @level: level of the message is in
637 * @file: the file that emitted the message, usually the __FILE__ identifier
638 * @function: the function that emitted the message
639 * @line: the line from that the message was emitted, usually __LINE__
640 * @object: (transfer none) (allow-none): the object this message relates to,
642 * @format: a printf style format string
643 * @args: optional arguments for the format
645 * Logs the given message using the currently registered debugging handlers.
648 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
649 const gchar * file, const gchar * function, gint line,
650 GObject * object, const gchar * format, va_list args)
652 #ifdef GST_ENABLE_EXTRA_CHECKS
653 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
656 gst_debug_log_full_valist (category, level, file, function, line, object,
661 * gst_debug_log_id_valist:
662 * @category: category to log
663 * @level: level of the message is in
664 * @file: the file that emitted the message, usually the __FILE__ identifier
665 * @function: the function that emitted the message
666 * @line: the line from that the message was emitted, usually __LINE__
667 * @id: (transfer none) (allow-none): the identifier of the object this message
668 * relates to or %NULL if none.
669 * @format: a printf style format string
670 * @args: optional arguments for the format
672 * Logs the given message using the currently registered debugging handlers.
677 gst_debug_log_id_valist (GstDebugCategory * category, GstDebugLevel level,
678 const gchar * file, const gchar * function, gint line,
679 const gchar * id, const gchar * format, va_list args)
681 gst_debug_log_full_valist (category, level, file, function, line, NULL, id,
686 gst_debug_log_literal_full (GstDebugCategory * category, GstDebugLevel level,
687 const gchar * file, const gchar * function, gint line,
688 GObject * object, const gchar * id, const gchar * message_string)
690 GstDebugMessage message;
694 g_return_if_fail (category != NULL);
696 if (level > gst_debug_category_get_threshold (category))
699 #ifdef GST_ENABLE_EXTRA_CHECKS
700 g_return_if_fail (id != NULL || object == NULL || G_IS_OBJECT (object));
703 g_return_if_fail (file != NULL);
704 g_return_if_fail (function != NULL);
705 g_return_if_fail (message_string != NULL);
707 message.message = (gchar *) message_string;
708 message.object = object;
709 message.object_id = (gchar *) id;
710 message.free_object_id = FALSE;
712 handler = __log_functions;
714 entry = handler->data;
715 handler = g_slist_next (handler);
716 entry->func (category, level, file, function, line, object, &message,
720 if (message.free_object_id)
721 g_free (message.object_id);
725 * gst_debug_log_literal:
726 * @category: category to log
727 * @level: level of the message is in
728 * @file: the file that emitted the message, usually the __FILE__ identifier
729 * @function: the function that emitted the message
730 * @line: the line from that the message was emitted, usually __LINE__
731 * @object: (transfer none) (allow-none): the object this message relates to,
733 * @message_string: a message string
735 * Logs the given message using the currently registered debugging handlers.
740 gst_debug_log_literal (GstDebugCategory * category, GstDebugLevel level,
741 const gchar * file, const gchar * function, gint line,
742 GObject * object, const gchar * message_string)
744 #ifdef GST_ENABLE_EXTRA_CHECKS
745 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
748 gst_debug_log_literal_full (category, level, file, function, line, object,
749 NULL, message_string);
753 * gst_debug_log_id_literal:
754 * @category: category to log
755 * @level: level of the message is in
756 * @file: the file that emitted the message, usually the __FILE__ identifier
757 * @function: the function that emitted the message
758 * @line: the line from that the message was emitted, usually __LINE__
759 * @id: (transfer none) (allow-none): the identifier of the object this message relates to
761 * @message_string: a message string
763 * Logs the given message using the currently registered debugging handlers.
768 gst_debug_log_id_literal (GstDebugCategory * category, GstDebugLevel level,
769 const gchar * file, const gchar * function, gint line,
770 const gchar * id, const gchar * message_string)
772 gst_debug_log_literal_full (category, level, file, function, line, NULL, id,
777 * gst_debug_message_get:
778 * @message: a debug message
780 * Gets the string representation of a #GstDebugMessage. This function is used
781 * in debug handlers to extract the message.
783 * Returns: (nullable): the string representation of a #GstDebugMessage.
786 gst_debug_message_get (GstDebugMessage * message)
788 if (message->message == NULL) {
791 len = __gst_vasprintf (&message->message, message->format,
795 message->message = NULL;
797 return message->message;
800 /* Return the pad name. Will use the provided 32 byte write_area if it fits
802 static inline gchar *
803 _heap_pad_name (GstPad * pad, gchar * write_area, gboolean * allocated)
805 GstObject *parent = GST_OBJECT_PARENT (pad);
806 const gchar *parentname =
807 parent ? GST_STR_NULL (GST_OBJECT_NAME (parent)) : "''";
808 const gchar *padname = GST_STR_NULL (GST_OBJECT_NAME (pad));
810 /* 1 byte for ':' and 1 for terminating '\0' */
811 if (strlen (parentname) + strlen (padname) + 2 <= 32) {
812 g_sprintf (write_area, "%s:%s", parentname, padname);
817 return g_strdup_printf ("%s:%s", parentname, padname);
820 /* Returns the object id. Allocated is set to TRUE if a memory allocation
821 * happened and the returned value should be freed */
823 _get_object_id (GObject * object, gboolean * allocated, gchar * write_area)
827 if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
828 object_id = _heap_pad_name (GST_PAD_CAST (object), write_area, allocated);
829 } else if (GST_IS_OBJECT (object)
830 && GST_OBJECT_NAME (object)) {
831 object_id = GST_OBJECT_NAME (object);
833 } else if (G_IS_OBJECT (object)) {
834 object_id = g_strdup_printf ("%s@%p", G_OBJECT_TYPE_NAME (object), object);
837 object_id = g_strdup_printf ("%p", object);
845 * gst_debug_message_get_id:
846 * @message: a debug message
848 * Get the id of the object that emitted this message. This function is used in
849 * debug handlers. Can be empty.
853 * Returns: (nullable): The emitter of a #GstDebugMessage.
856 gst_debug_message_get_id (GstDebugMessage * message)
858 if (!message->object_id && message->object) {
859 /* Dynamically generate the object id */
860 /* Note : we don't use gst_debug_print_object since we only accept a subset
861 * and can avoid duplicating if needed */
863 _get_object_id (message->object, &message->free_object_id,
864 (gchar *) & message->tmp_id);
866 return message->object_id;
869 #define MAX_BUFFER_DUMP_STRING_LEN 100
871 /* structure_to_pretty_string:
872 * @str: a serialized #GstStructure
874 * If the serialized structure contains large buffers such as images the hex
875 * representation of those buffers will be shortened so that the string remains
878 * Returns: the filtered string
881 prettify_structure_string (gchar * str)
883 gchar *pos = str, *end;
885 while ((pos = strstr (pos, "(buffer)"))) {
888 pos += strlen ("(buffer)");
889 for (end = pos; *end != '\0' && *end != ';' && *end != ' '; ++end)
891 if (count > MAX_BUFFER_DUMP_STRING_LEN) {
892 memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 6, "..", 2);
893 memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 4, pos + count - 4, 4);
894 memmove (pos + MAX_BUFFER_DUMP_STRING_LEN, pos + count,
895 strlen (pos + count) + 1);
896 pos += MAX_BUFFER_DUMP_STRING_LEN;
903 static inline gchar *
904 gst_info_structure_to_string (const GstStructure * s)
907 gchar *str = gst_structure_to_string (s);
908 if (G_UNLIKELY (pretty_tags && s->name == GST_QUARK (TAGLIST)))
909 return prettify_structure_string (str);
916 static inline gchar *
917 gst_info_describe_buffer (GstBuffer * buffer)
919 const gchar *offset_str = "none";
920 const gchar *offset_end_str = "none";
921 gchar offset_buf[32], offset_end_buf[32];
923 if (GST_BUFFER_OFFSET_IS_VALID (buffer)) {
924 g_snprintf (offset_buf, sizeof (offset_buf), "%" G_GUINT64_FORMAT,
925 GST_BUFFER_OFFSET (buffer));
926 offset_str = offset_buf;
928 if (GST_BUFFER_OFFSET_END_IS_VALID (buffer)) {
929 g_snprintf (offset_end_buf, sizeof (offset_end_buf), "%" G_GUINT64_FORMAT,
930 GST_BUFFER_OFFSET_END (buffer));
931 offset_end_str = offset_end_buf;
934 return g_strdup_printf ("buffer: %p, pts %" GST_TIME_FORMAT ", dts %"
935 GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT
936 ", offset %s, offset_end %s, flags 0x%x", buffer,
937 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
938 GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
939 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
940 gst_buffer_get_size (buffer), offset_str, offset_end_str,
941 GST_BUFFER_FLAGS (buffer));
944 static inline gchar *
945 gst_info_describe_buffer_list (GstBufferList * list)
947 GstClockTime pts = GST_CLOCK_TIME_NONE;
948 GstClockTime dts = GST_CLOCK_TIME_NONE;
949 gsize total_size = 0;
952 n = gst_buffer_list_length (list);
953 for (i = 0; i < n; ++i) {
954 GstBuffer *buf = gst_buffer_list_get (list, i);
957 pts = GST_BUFFER_PTS (buf);
958 dts = GST_BUFFER_DTS (buf);
961 total_size += gst_buffer_get_size (buf);
964 return g_strdup_printf ("bufferlist: %p, %u buffers, pts %" GST_TIME_FORMAT
965 ", dts %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT, list, n,
966 GST_TIME_ARGS (pts), GST_TIME_ARGS (dts), total_size);
969 static inline gchar *
970 gst_info_describe_event (GstEvent * event)
974 s = gst_info_structure_to_string (gst_event_get_structure (event));
975 ret = g_strdup_printf ("%s event: %p, time %" GST_TIME_FORMAT
976 ", seq-num %d, %s", GST_EVENT_TYPE_NAME (event), event,
977 GST_TIME_ARGS (GST_EVENT_TIMESTAMP (event)), GST_EVENT_SEQNUM (event),
983 static inline gchar *
984 gst_info_describe_message (GstMessage * message)
988 s = gst_info_structure_to_string (gst_message_get_structure (message));
989 ret = g_strdup_printf ("%s message: %p, time %" GST_TIME_FORMAT
990 ", seq-num %d, element '%s', %s", GST_MESSAGE_TYPE_NAME (message),
991 message, GST_TIME_ARGS (GST_MESSAGE_TIMESTAMP (message)),
992 GST_MESSAGE_SEQNUM (message),
993 ((message->src) ? GST_ELEMENT_NAME (message->src) : "(NULL)"),
999 static inline gchar *
1000 gst_info_describe_query (GstQuery * query)
1004 s = gst_info_structure_to_string (gst_query_get_structure (query));
1005 ret = g_strdup_printf ("%s query: %p, %s", GST_QUERY_TYPE_NAME (query),
1006 query, (s ? s : "(NULL)"));
1011 static inline gchar *
1012 gst_info_describe_stream (GstStream * stream)
1014 gchar *ret, *caps_str = NULL, *tags_str = NULL;
1018 caps = gst_stream_get_caps (stream);
1020 caps_str = gst_caps_to_string (caps);
1021 gst_caps_unref (caps);
1024 tags = gst_stream_get_tags (stream);
1026 tags_str = gst_tag_list_to_string (tags);
1027 gst_tag_list_unref (tags);
1031 g_strdup_printf ("stream %s %p, ID %s, flags 0x%x, caps [%s], tags [%s]",
1032 gst_stream_type_get_name (gst_stream_get_stream_type (stream)), stream,
1033 gst_stream_get_stream_id (stream), gst_stream_get_stream_flags (stream),
1034 caps_str ? caps_str : "", tags_str ? tags_str : "");
1042 static inline gchar *
1043 gst_info_describe_stream_collection (GstStreamCollection * collection)
1046 GString *streams_str;
1049 streams_str = g_string_new ("<");
1050 for (i = 0; i < gst_stream_collection_get_size (collection); i++) {
1051 GstStream *stream = gst_stream_collection_get_stream (collection, i);
1054 s = gst_info_describe_stream (stream);
1055 g_string_append_printf (streams_str, " %s,", s);
1058 g_string_append (streams_str, " >");
1060 ret = g_strdup_printf ("collection %p (%d streams) %s", collection,
1061 gst_stream_collection_get_size (collection), streams_str->str);
1063 g_string_free (streams_str, TRUE);
1068 gst_debug_print_object (gpointer ptr)
1070 GObject *object = (GObject *) ptr;
1073 /* This is a cute trick to detect unmapped memory, but is unportable,
1074 * slow, screws around with madvise, and not actually that useful. */
1078 ret = madvise ((void *) ((unsigned long) ptr & (~0xfff)), 4096, 0);
1079 if (ret == -1 && errno == ENOMEM) {
1080 buffer = g_strdup_printf ("%p (unmapped memory)", ptr);
1085 /* nicely printed object */
1086 if (object == NULL) {
1087 return g_strdup ("(NULL)");
1089 if (GST_IS_CAPS (ptr)) {
1090 return gst_caps_to_string ((const GstCaps *) ptr);
1092 if (GST_IS_STRUCTURE (ptr)) {
1093 return gst_info_structure_to_string ((const GstStructure *) ptr);
1095 if (*(GType *) ptr == GST_TYPE_CAPS_FEATURES) {
1096 return gst_caps_features_to_string ((const GstCapsFeatures *) ptr);
1098 if (GST_IS_TAG_LIST (ptr)) {
1099 gchar *str = gst_tag_list_to_string ((GstTagList *) ptr);
1100 if (G_UNLIKELY (pretty_tags))
1101 return prettify_structure_string (str);
1105 if (*(GType *) ptr == GST_TYPE_DATE_TIME) {
1106 return __gst_date_time_serialize ((GstDateTime *) ptr, TRUE);
1108 if (GST_IS_BUFFER (ptr)) {
1109 return gst_info_describe_buffer (GST_BUFFER_CAST (ptr));
1111 if (GST_IS_BUFFER_LIST (ptr)) {
1112 return gst_info_describe_buffer_list (GST_BUFFER_LIST_CAST (ptr));
1114 #ifdef USE_POISONING
1115 if (*(guint32 *) ptr == 0xffffffff) {
1116 return g_strdup_printf ("<poisoned@%p>", ptr);
1119 if (GST_IS_MESSAGE (object)) {
1120 return gst_info_describe_message (GST_MESSAGE_CAST (object));
1122 if (GST_IS_QUERY (object)) {
1123 return gst_info_describe_query (GST_QUERY_CAST (object));
1125 if (GST_IS_EVENT (object)) {
1126 return gst_info_describe_event (GST_EVENT_CAST (object));
1128 if (GST_IS_CONTEXT (object)) {
1129 GstContext *context = GST_CONTEXT_CAST (object);
1132 const GstStructure *structure;
1134 type = gst_context_get_context_type (context);
1135 structure = gst_context_get_structure (context);
1137 s = gst_info_structure_to_string (structure);
1139 ret = g_strdup_printf ("context '%s'='%s'", type, s);
1143 if (GST_IS_STREAM (object)) {
1144 return gst_info_describe_stream (GST_STREAM_CAST (object));
1146 if (GST_IS_STREAM_COLLECTION (object)) {
1148 gst_info_describe_stream_collection (GST_STREAM_COLLECTION_CAST
1151 if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
1152 return g_strdup_printf ("<%s:%s>", GST_DEBUG_PAD_NAME (object));
1154 if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object)) {
1155 return g_strdup_printf ("<%s>", GST_OBJECT_NAME (object));
1157 if (G_IS_OBJECT (object)) {
1158 return g_strdup_printf ("<%s@%p>", G_OBJECT_TYPE_NAME (object), object);
1161 return g_strdup_printf ("%p", ptr);
1165 gst_debug_print_segment (gpointer ptr)
1167 GstSegment *segment = (GstSegment *) ptr;
1169 /* nicely printed segment */
1170 if (segment == NULL) {
1171 return g_strdup ("(NULL)");
1174 switch (segment->format) {
1175 case GST_FORMAT_UNDEFINED:{
1176 return g_strdup_printf ("UNDEFINED segment");
1178 case GST_FORMAT_TIME:{
1179 return g_strdup_printf ("time segment start=%" GST_TIME_FORMAT
1180 ", offset=%" GST_TIME_FORMAT ", stop=%" GST_TIME_FORMAT
1181 ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" GST_TIME_FORMAT
1182 ", base=%" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT
1183 ", duration %" GST_TIME_FORMAT, GST_TIME_ARGS (segment->start),
1184 GST_TIME_ARGS (segment->offset), GST_TIME_ARGS (segment->stop),
1185 segment->rate, segment->applied_rate, (guint) segment->flags,
1186 GST_TIME_ARGS (segment->time), GST_TIME_ARGS (segment->base),
1187 GST_TIME_ARGS (segment->position), GST_TIME_ARGS (segment->duration));
1190 const gchar *format_name;
1192 format_name = gst_format_get_name (segment->format);
1193 if (G_UNLIKELY (format_name == NULL))
1194 format_name = "(UNKNOWN FORMAT)";
1195 return g_strdup_printf ("%s segment start=%" G_GINT64_FORMAT
1196 ", offset=%" G_GINT64_FORMAT ", stop=%" G_GINT64_FORMAT
1197 ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" G_GINT64_FORMAT
1198 ", base=%" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT
1199 ", duration %" G_GINT64_FORMAT, format_name, segment->start,
1200 segment->offset, segment->stop, segment->rate, segment->applied_rate,
1201 (guint) segment->flags, segment->time, segment->base,
1202 segment->position, segment->duration);
1208 gst_info_printf_pointer_extension_func (const char *format, void *ptr)
1212 if (format[0] == 'p' && format[1] == '\a') {
1213 switch (format[2]) {
1214 case 'A': /* GST_PTR_FORMAT */
1215 s = gst_debug_print_object (ptr);
1217 case 'B': /* GST_SEGMENT_FORMAT */
1218 s = gst_debug_print_segment (ptr);
1220 case 'T': /* GST_TIMEP_FORMAT */
1222 s = g_strdup_printf ("%" GST_TIME_FORMAT,
1223 GST_TIME_ARGS (*(GstClockTime *) ptr));
1225 case 'S': /* GST_STIMEP_FORMAT */
1227 s = g_strdup_printf ("%" GST_STIME_FORMAT,
1228 GST_STIME_ARGS (*(gint64 *) ptr));
1230 case 'a': /* GST_WRAPPED_PTR_FORMAT */
1231 s = priv_gst_string_take_and_wrap (gst_debug_print_object (ptr));
1234 /* must have been compiled against a newer version with an extension
1235 * we don't known about yet - just ignore and fallback to %p below */
1240 s = g_strdup_printf ("%p", ptr);
1245 /* Allocation-less generator of color escape code. Provide a 20 byte write
1248 _construct_term_color (guint colorinfo, gchar write_area[20])
1252 memcpy (write_area, "\033[00", 4);
1255 if (colorinfo & GST_DEBUG_BOLD) {
1256 memcpy (write_area + offset, ";01", 3);
1259 if (colorinfo & GST_DEBUG_UNDERLINE) {
1260 memcpy (write_area + offset, ";04", 3);
1263 if (colorinfo & GST_DEBUG_FG_MASK) {
1264 memcpy (write_area + offset, ";3", 2);
1265 write_area[offset + 2] = '0' + (colorinfo & GST_DEBUG_FG_MASK);
1268 if (colorinfo & GST_DEBUG_BG_MASK) {
1269 memcpy (write_area + offset, ";4", 2);
1270 write_area[offset + 2] = '0' + ((colorinfo & GST_DEBUG_BG_MASK) >> 4);
1273 strncpy (write_area + offset, "m", 2);
1277 * gst_debug_construct_term_color:
1278 * @colorinfo: the color info
1280 * Constructs a string that can be used for getting the desired color in color
1282 * You need to free the string after use.
1284 * Returns: (transfer full) (type gchar*): a string containing the color
1288 gst_debug_construct_term_color (guint colorinfo)
1290 gchar tmp_color[20];
1292 _construct_term_color (colorinfo, tmp_color);
1294 return g_strdup (tmp_color);
1298 * gst_debug_construct_win_color:
1299 * @colorinfo: the color info
1301 * Constructs an integer that can be used for getting the desired color in
1302 * windows' terminals (cmd.exe). As there is no mean to underline, we simply
1303 * ignore this attribute.
1305 * This function returns 0 on non-windows machines.
1307 * Returns: an integer containing the color definition
1310 gst_debug_construct_win_color (guint colorinfo)
1314 static const guchar ansi_to_win_fg[8] = {
1316 FOREGROUND_RED, /* red */
1317 FOREGROUND_GREEN, /* green */
1318 FOREGROUND_RED | FOREGROUND_GREEN, /* yellow */
1319 FOREGROUND_BLUE, /* blue */
1320 FOREGROUND_RED | FOREGROUND_BLUE, /* magenta */
1321 FOREGROUND_GREEN | FOREGROUND_BLUE, /* cyan */
1322 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE /* white */
1324 static const guchar ansi_to_win_bg[8] = {
1328 BACKGROUND_RED | BACKGROUND_GREEN,
1330 BACKGROUND_RED | BACKGROUND_BLUE,
1331 BACKGROUND_GREEN | FOREGROUND_BLUE,
1332 BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
1335 /* we draw black as white, as cmd.exe can only have black bg */
1336 if ((colorinfo & (GST_DEBUG_FG_MASK | GST_DEBUG_BG_MASK)) == 0) {
1337 color = ansi_to_win_fg[7];
1339 if (colorinfo & GST_DEBUG_UNDERLINE) {
1340 color |= BACKGROUND_INTENSITY;
1342 if (colorinfo & GST_DEBUG_BOLD) {
1343 color |= FOREGROUND_INTENSITY;
1345 if (colorinfo & GST_DEBUG_FG_MASK) {
1346 color |= ansi_to_win_fg[colorinfo & GST_DEBUG_FG_MASK];
1348 if (colorinfo & GST_DEBUG_BG_MASK) {
1349 color |= ansi_to_win_bg[(colorinfo & GST_DEBUG_BG_MASK) >> 4];
1355 /* width of %p varies depending on actual value of pointer, which can make
1356 * output unevenly aligned if multiple threads are involved, hence the %14p
1357 * (should really be %18p, but %14p seems a good compromise between too many
1358 * white spaces and likely unalignment on my system) */
1359 #if defined (GLIB_SIZEOF_VOID_P) && GLIB_SIZEOF_VOID_P == 8
1360 #define PTR_FMT "%14p"
1362 #define PTR_FMT "%10p"
1365 #define PID_FMT "%5lu"
1367 #define PID_FMT "%5d"
1369 #define CAT_FMT "%20s %s:%d:%s:%s"
1370 #define NOCOLOR_PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
1371 #define CAT_FMT_ID "%20s %s:%d:%s:<%s>"
1372 #define NOCOLOR_PRINT_FMT_ID " "PID_FMT" "PTR_FMT" %s "CAT_FMT_ID" %s\n"
1375 static const guchar levelcolormap_w32[GST_LEVEL_COUNT] = {
1376 /* GST_LEVEL_NONE */
1377 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1378 /* GST_LEVEL_ERROR */
1379 FOREGROUND_RED | FOREGROUND_INTENSITY,
1380 /* GST_LEVEL_WARNING */
1381 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1382 /* GST_LEVEL_INFO */
1383 FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1384 /* GST_LEVEL_DEBUG */
1385 FOREGROUND_GREEN | FOREGROUND_BLUE,
1387 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1388 /* GST_LEVEL_FIXME */
1389 FOREGROUND_RED | FOREGROUND_GREEN,
1390 /* GST_LEVEL_TRACE */
1391 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1392 /* placeholder for log level 8 */
1394 /* GST_LEVEL_MEMDUMP */
1395 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
1398 static const guchar available_colors[] = {
1399 FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_RED | FOREGROUND_GREEN,
1400 FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_BLUE,
1401 FOREGROUND_GREEN | FOREGROUND_BLUE,
1403 #endif /* G_OS_WIN32 */
1404 static const gchar *levelcolormap[GST_LEVEL_COUNT] = {
1405 "\033[37m", /* GST_LEVEL_NONE */
1406 "\033[31;01m", /* GST_LEVEL_ERROR */
1407 "\033[33;01m", /* GST_LEVEL_WARNING */
1408 "\033[32;01m", /* GST_LEVEL_INFO */
1409 "\033[36m", /* GST_LEVEL_DEBUG */
1410 "\033[37m", /* GST_LEVEL_LOG */
1411 "\033[33;01m", /* GST_LEVEL_FIXME */
1412 "\033[37m", /* GST_LEVEL_TRACE */
1413 "\033[37m", /* placeholder for log level 8 */
1414 "\033[37m" /* GST_LEVEL_MEMDUMP */
1418 _gst_debug_log_preamble (GstDebugMessage * message, const gchar ** file,
1419 const gchar ** message_str, const gchar ** object_id,
1420 GstClockTime * elapsed)
1424 /* Get message string first because printing it might call into our custom
1425 * printf format extension mechanism which in turn might log something, e.g.
1426 * from inside gst_structure_to_string() when something can't be serialised.
1427 * This means we either need to do this outside of any critical section or
1428 * use a recursive lock instead. As we always need the message string in all
1429 * code paths, we might just as well get it here first thing and outside of
1430 * the win_print_mutex critical section. */
1431 *message_str = gst_debug_message_get (message);
1433 /* __FILE__ might be a file name or an absolute path or a
1434 * relative path, irrespective of the exact compiler used,
1435 * in which case we want to shorten it to the filename for
1438 if (c == '.' || c == '/' || c == '\\' || (c != '\0' && (*file)[1] == ':')) {
1439 *file = gst_path_basename (*file);
1442 *object_id = gst_debug_message_get_id (message);
1443 *elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
1447 * gst_debug_log_get_line:
1448 * @category: category to log
1449 * @level: level of the message
1450 * @file: the file that emitted the message, usually the __FILE__ identifier
1451 * @function: the function that emitted the message
1452 * @line: the line from that the message was emitted, usually __LINE__
1453 * @object: (transfer none) (allow-none): the object this message relates to,
1455 * @message: the actual message
1457 * Returns the string representation for the specified debug log message
1458 * formatted in the same way as gst_debug_log_default() (the default handler),
1459 * without color. The purpose is to make it easy for custom log output
1460 * handlers to get a log output that is identical to what the default handler
1466 gst_debug_log_get_line (GstDebugCategory * category, GstDebugLevel level,
1467 const gchar * file, const gchar * function, gint line,
1468 GObject * object, GstDebugMessage * message)
1470 GstClockTime elapsed;
1472 const gchar *message_str, *object_id;
1474 _gst_debug_log_preamble (message, &file, &message_str, &object_id, &elapsed);
1477 ret = g_strdup_printf ("%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT_ID,
1478 GST_TIME_ARGS (elapsed), _gst_getpid (), g_thread_self (),
1479 gst_debug_level_get_name (level), gst_debug_category_get_name
1480 (category), file, line, function, object_id, message_str);
1482 ret = g_strdup_printf ("%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1483 GST_TIME_ARGS (elapsed), _gst_getpid (), g_thread_self (),
1484 gst_debug_level_get_name (level), gst_debug_category_get_name
1485 (category), file, line, function, "", message_str);
1492 _gst_debug_fprintf (FILE * file, const gchar * format, ...)
1498 va_start (args, format);
1499 length = gst_info_vasprintf (&str, format, args);
1502 if (length == 0 || !str)
1505 /* Even if it's valid UTF-8 string, console might print broken string
1506 * depending on codepage and the content of the given string.
1507 * Fortunately, g_print* family will take care of the Windows' codepage
1508 * specific behavior.
1510 if (file == stderr) {
1511 g_printerr ("%s", str);
1512 } else if (file == stdout) {
1513 g_print ("%s", str);
1515 /* We are writing to file. Text editors/viewers should be able to
1516 * decode valid UTF-8 string regardless of codepage setting */
1517 fwrite (str, 1, length, file);
1519 /* FIXME: fflush here might be redundant if setvbuf works as expected */
1528 * gst_debug_log_default:
1529 * @category: category to log
1530 * @level: level of the message
1531 * @file: the file that emitted the message, usually the __FILE__ identifier
1532 * @function: the function that emitted the message
1533 * @line: the line from that the message was emitted, usually __LINE__
1534 * @message: the actual message
1535 * @object: (transfer none) (allow-none): the object this message relates to,
1537 * @user_data: the FILE* to log to
1539 * The default logging handler used by GStreamer. Logging functions get called
1540 * whenever a macro like GST_DEBUG or similar is used. By default this function
1541 * is setup to output the message and additional info to stderr (or the log file
1542 * specified via the GST_DEBUG_FILE environment variable) as received via
1545 * You can add other handlers by using gst_debug_add_log_function().
1546 * And you can remove this handler by calling
1547 * gst_debug_remove_log_function(gst_debug_log_default);
1550 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
1551 const gchar * file, const gchar * function, gint line,
1552 GObject * object, GstDebugMessage * message, gpointer user_data)
1555 GstClockTime elapsed;
1556 const gchar *object_id;
1557 GstDebugColorMode color_mode;
1558 const gchar *message_str;
1559 FILE *log_file = user_data ? user_data : stderr;
1561 #define FPRINTF_DEBUG _gst_debug_fprintf
1562 /* _gst_debug_fprintf will do fflush if it's required */
1563 #define FFLUSH_DEBUG(f) ((void)(f))
1565 #define FPRINTF_DEBUG fprintf
1566 #define FFLUSH_DEBUG(f) G_STMT_START { \
1571 #ifdef GST_ENABLE_EXTRA_CHECKS
1572 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1575 _gst_debug_log_preamble (message, &file, &message_str, &object_id, &elapsed);
1577 pid = _gst_getpid ();
1578 color_mode = gst_debug_get_color_mode ();
1580 if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
1582 G_LOCK (win_print_mutex);
1583 if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
1585 /* colors, non-windows */
1589 const gchar *levelcolor;
1591 _construct_term_color (gst_debug_category_get_color (category), color);
1593 g_sprintf (pidcolor, "\033[%02dm", pid % 6 + 31);
1594 levelcolor = levelcolormap[level];
1597 #define PRINT_FMT_ID " %s"PID_FMT"%s "PTR_FMT" %s%s%s %s"CAT_FMT_ID"%s %s\n"
1598 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT PRINT_FMT_ID,
1599 GST_TIME_ARGS (elapsed), pidcolor, pid, clear, g_thread_self (),
1600 levelcolor, gst_debug_level_get_name (level), clear, color,
1601 gst_debug_category_get_name (category), file, line, function,
1602 object_id, clear, message_str);
1604 #define PRINT_FMT " %s"PID_FMT"%s "PTR_FMT" %s%s%s %s"CAT_FMT"%s %s\n"
1605 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT PRINT_FMT,
1606 GST_TIME_ARGS (elapsed), pidcolor, pid, clear, g_thread_self (),
1607 levelcolor, gst_debug_level_get_name (level), clear, color,
1608 gst_debug_category_get_name (category), file, line, function, "",
1609 clear, message_str);
1611 FFLUSH_DEBUG (log_file);
1616 /* colors, windows. */
1617 const gint clear = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
1618 #define SET_COLOR(c) G_STMT_START { \
1619 if (log_file == stderr) \
1620 SetConsoleTextAttribute (GetStdHandle (STD_ERROR_HANDLE), (c)); \
1623 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT " ",
1624 GST_TIME_ARGS (elapsed));
1626 SET_COLOR (available_colors[pid % G_N_ELEMENTS (available_colors)]);
1627 FPRINTF_DEBUG (log_file, PID_FMT, pid);
1630 FPRINTF_DEBUG (log_file, " " PTR_FMT " ", g_thread_self ());
1632 SET_COLOR (levelcolormap_w32[level]);
1633 FPRINTF_DEBUG (log_file, "%s ", gst_debug_level_get_name (level));
1635 SET_COLOR (gst_debug_construct_win_color (gst_debug_category_get_color
1638 FPRINTF_DEBUG (log_file, CAT_FMT_ID,
1639 gst_debug_category_get_name (category), file, line, function,
1642 FPRINTF_DEBUG (log_file, CAT_FMT,
1643 gst_debug_category_get_name (category), file, line, function, "");
1647 FPRINTF_DEBUG (log_file, " %s\n", message_str);
1649 G_UNLOCK (win_print_mutex);
1652 /* no color, all platforms */
1654 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT_ID,
1655 GST_TIME_ARGS (elapsed), pid, g_thread_self (),
1656 gst_debug_level_get_name (level),
1657 gst_debug_category_get_name (category), file, line, function,
1658 object_id, message_str);
1660 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1661 GST_TIME_ARGS (elapsed), pid, g_thread_self (),
1662 gst_debug_level_get_name (level),
1663 gst_debug_category_get_name (category), file, line, function, "",
1666 FFLUSH_DEBUG (log_file);
1671 * gst_debug_level_get_name:
1672 * @level: the level to get the name for
1674 * Get the string representation of a debugging level
1679 gst_debug_level_get_name (GstDebugLevel level)
1682 case GST_LEVEL_NONE:
1684 case GST_LEVEL_ERROR:
1686 case GST_LEVEL_WARNING:
1688 case GST_LEVEL_INFO:
1690 case GST_LEVEL_DEBUG:
1694 case GST_LEVEL_FIXME:
1696 case GST_LEVEL_TRACE:
1698 case GST_LEVEL_MEMDUMP:
1701 g_warning ("invalid level specified for gst_debug_level_get_name");
1707 * gst_debug_add_log_function:
1708 * @func: the function to use
1709 * @user_data: user data
1710 * @notify: called when @user_data is not used anymore
1712 * Adds the logging function to the list of logging functions.
1713 * Be sure to use #G_GNUC_NO_INSTRUMENT on that function, it is needed.
1716 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
1717 GDestroyNotify notify)
1719 LogFuncEntry *entry;
1723 func = gst_debug_log_default;
1725 entry = g_slice_new (LogFuncEntry);
1727 entry->user_data = user_data;
1728 entry->notify = notify;
1729 /* FIXME: we leak the old list here - other threads might access it right now
1730 * in gst_debug_logv. Another solution is to lock the mutex in gst_debug_logv,
1731 * but that is waaay costly.
1732 * It'd probably be clever to use some kind of RCU here, but I don't know
1733 * anything about that.
1735 g_mutex_lock (&__log_func_mutex);
1736 list = g_slist_copy (__log_functions);
1737 __log_functions = g_slist_prepend (list, entry);
1738 g_mutex_unlock (&__log_func_mutex);
1740 if (gst_is_initialized ())
1741 GST_DEBUG ("prepended log function %p (user data %p) to log functions",
1746 gst_debug_compare_log_function_by_func (gconstpointer entry, gconstpointer func)
1748 gpointer entryfunc = (gpointer) (((LogFuncEntry *) entry)->func);
1750 return (entryfunc < func) ? -1 : (entryfunc > func) ? 1 : 0;
1754 gst_debug_compare_log_function_by_data (gconstpointer entry, gconstpointer data)
1756 gpointer entrydata = ((LogFuncEntry *) entry)->user_data;
1758 return (entrydata < data) ? -1 : (entrydata > data) ? 1 : 0;
1762 gst_debug_remove_with_compare_func (GCompareFunc func, gpointer data)
1765 GSList *new, *cleanup = NULL;
1768 g_mutex_lock (&__log_func_mutex);
1769 new = __log_functions;
1771 while ((found = g_slist_find_custom (new, data, func))) {
1772 if (new == __log_functions) {
1773 /* make a copy when we have the first hit, so that we modify the copy and
1774 * make that the new list later */
1775 new = g_slist_copy (new);
1778 cleanup = g_slist_prepend (cleanup, found->data);
1779 new = g_slist_delete_link (new, found);
1782 /* FIXME: We leak the old list here. See _add_log_function for why. */
1783 __log_functions = new;
1784 g_mutex_unlock (&__log_func_mutex);
1787 LogFuncEntry *entry = cleanup->data;
1790 entry->notify (entry->user_data);
1792 g_slice_free (LogFuncEntry, entry);
1793 cleanup = g_slist_delete_link (cleanup, cleanup);
1799 * gst_debug_remove_log_function:
1800 * @func: (scope call) (allow-none): the log function to remove, or %NULL to
1801 * remove the default log function
1803 * Removes all registered instances of the given logging functions.
1805 * Returns: How many instances of the function were removed
1808 gst_debug_remove_log_function (GstLogFunction func)
1813 func = gst_debug_log_default;
1816 gst_debug_remove_with_compare_func
1817 (gst_debug_compare_log_function_by_func, (gpointer) func);
1819 if (gst_is_initialized ()) {
1820 GST_DEBUG ("removed log function %p %d times from log function list", func,
1823 /* If the default log function is removed before gst_init() was called,
1824 * set a flag so we don't add it in gst_init() later */
1825 if (func == gst_debug_log_default) {
1826 add_default_log_func = FALSE;
1835 * gst_debug_remove_log_function_by_data:
1836 * @data: user data of the log function to remove
1838 * Removes all registered instances of log functions with the given user data.
1840 * Returns: How many instances of the function were removed
1843 gst_debug_remove_log_function_by_data (gpointer data)
1848 gst_debug_remove_with_compare_func
1849 (gst_debug_compare_log_function_by_data, data);
1851 if (gst_is_initialized ())
1853 ("removed %d log functions with user data %p from log function list",
1860 * gst_debug_set_colored:
1861 * @colored: Whether to use colored output or not
1863 * Sets or unsets the use of coloured debugging output.
1864 * Same as gst_debug_set_color_mode () with the argument being
1865 * being GST_DEBUG_COLOR_MODE_ON or GST_DEBUG_COLOR_MODE_OFF.
1867 * This function may be called before gst_init().
1870 gst_debug_set_colored (gboolean colored)
1872 GstDebugColorMode new_mode;
1873 new_mode = colored ? GST_DEBUG_COLOR_MODE_ON : GST_DEBUG_COLOR_MODE_OFF;
1874 g_atomic_int_set (&__use_color, (gint) new_mode);
1878 * gst_debug_set_color_mode:
1879 * @mode: The coloring mode for debug output. See @GstDebugColorMode.
1881 * Changes the coloring mode for debug output.
1883 * This function may be called before gst_init().
1888 gst_debug_set_color_mode (GstDebugColorMode mode)
1890 g_atomic_int_set (&__use_color, mode);
1894 * gst_debug_set_color_mode_from_string:
1895 * @mode: The coloring mode for debug output. One of the following:
1896 * "on", "auto", "off", "disable", "unix".
1898 * Changes the coloring mode for debug output.
1900 * This function may be called before gst_init().
1905 gst_debug_set_color_mode_from_string (const gchar * mode)
1907 if ((strcmp (mode, "on") == 0) || (strcmp (mode, "auto") == 0))
1908 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_ON);
1909 else if ((strcmp (mode, "off") == 0) || (strcmp (mode, "disable") == 0))
1910 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
1911 else if (strcmp (mode, "unix") == 0)
1912 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_UNIX);
1916 * gst_debug_is_colored:
1918 * Checks if the debugging output should be colored.
1920 * Returns: %TRUE, if the debug output should be colored.
1923 gst_debug_is_colored (void)
1925 GstDebugColorMode mode = g_atomic_int_get (&__use_color);
1926 return (mode == GST_DEBUG_COLOR_MODE_UNIX || mode == GST_DEBUG_COLOR_MODE_ON);
1930 * gst_debug_get_color_mode:
1932 * Changes the coloring mode for debug output.
1934 * Returns: see @GstDebugColorMode for possible values.
1939 gst_debug_get_color_mode (void)
1941 return g_atomic_int_get (&__use_color);
1945 * gst_debug_set_active:
1946 * @active: Whether to use debugging output or not
1948 * If activated, debugging messages are sent to the debugging
1950 * It makes sense to deactivate it for speed issues.
1951 * > This function is not threadsafe. It makes sense to only call it
1952 * during initialization.
1955 gst_debug_set_active (gboolean active)
1957 _gst_debug_enabled = active;
1959 _gst_debug_min = GST_LEVEL_COUNT;
1961 _gst_debug_min = GST_LEVEL_NONE;
1965 * gst_debug_is_active:
1967 * Checks if debugging output is activated.
1969 * Returns: %TRUE, if debugging is activated
1972 gst_debug_is_active (void)
1974 return _gst_debug_enabled;
1978 * gst_debug_set_default_threshold:
1979 * @level: level to set
1981 * Sets the default threshold to the given level and updates all categories to
1982 * use this threshold.
1984 * This function may be called before gst_init().
1987 gst_debug_set_default_threshold (GstDebugLevel level)
1989 g_atomic_int_set (&__default_level, level);
1990 gst_debug_reset_all_thresholds ();
1994 * gst_debug_get_default_threshold:
1996 * Returns the default threshold that is used for new categories.
1998 * Returns: the default threshold level
2001 gst_debug_get_default_threshold (void)
2003 return (GstDebugLevel) g_atomic_int_get (&__default_level);
2006 #if !GLIB_CHECK_VERSION(2,70,0)
2007 #define g_pattern_spec_match_string g_pattern_match_string
2011 gst_debug_apply_entry (GstDebugCategory * cat, LevelNameEntry * entry)
2013 if (!g_pattern_spec_match_string (entry->pat, cat->name))
2016 if (gst_is_initialized ())
2017 GST_LOG ("category %s matches pattern %p - gets set to level %d",
2018 cat->name, entry->pat, entry->level);
2020 gst_debug_category_set_threshold (cat, entry->level);
2025 gst_debug_reset_threshold (gpointer category, gpointer unused)
2027 GstDebugCategory *cat = (GstDebugCategory *) category;
2030 g_mutex_lock (&__level_name_mutex);
2032 for (walk = __level_name; walk != NULL; walk = walk->next) {
2033 if (gst_debug_apply_entry (cat, walk->data))
2037 g_mutex_unlock (&__level_name_mutex);
2040 gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
2044 gst_debug_reset_all_thresholds (void)
2046 g_mutex_lock (&__cat_mutex);
2047 g_slist_foreach (__categories, gst_debug_reset_threshold, NULL);
2048 g_mutex_unlock (&__cat_mutex);
2052 for_each_threshold_by_entry (gpointer data, gpointer user_data)
2054 GstDebugCategory *cat = (GstDebugCategory *) data;
2055 LevelNameEntry *entry = (LevelNameEntry *) user_data;
2057 gst_debug_apply_entry (cat, entry);
2061 * gst_debug_set_threshold_for_name:
2062 * @name: name of the categories to set
2063 * @level: level to set them to
2065 * Sets all categories which match the given glob style pattern to the given
2069 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2072 LevelNameEntry *entry;
2074 g_return_if_fail (name != NULL);
2076 pat = g_pattern_spec_new (name);
2077 entry = g_slice_new (LevelNameEntry);
2079 entry->level = level;
2080 g_mutex_lock (&__level_name_mutex);
2081 __level_name = g_slist_prepend (__level_name, entry);
2082 g_mutex_unlock (&__level_name_mutex);
2083 g_mutex_lock (&__cat_mutex);
2084 g_slist_foreach (__categories, for_each_threshold_by_entry, entry);
2085 g_mutex_unlock (&__cat_mutex);
2089 * gst_debug_unset_threshold_for_name:
2090 * @name: name of the categories to set
2092 * Resets all categories with the given name back to the default level.
2095 gst_debug_unset_threshold_for_name (const gchar * name)
2100 g_return_if_fail (name != NULL);
2102 pat = g_pattern_spec_new (name);
2103 g_mutex_lock (&__level_name_mutex);
2104 walk = __level_name;
2105 /* improve this if you want, it's mighty slow */
2107 LevelNameEntry *entry = walk->data;
2109 if (g_pattern_spec_equal (entry->pat, pat)) {
2110 __level_name = g_slist_remove_link (__level_name, walk);
2111 g_pattern_spec_free (entry->pat);
2112 g_slice_free (LevelNameEntry, entry);
2113 g_slist_free_1 (walk);
2114 walk = __level_name;
2116 walk = g_slist_next (walk);
2119 g_mutex_unlock (&__level_name_mutex);
2120 g_pattern_spec_free (pat);
2121 gst_debug_reset_all_thresholds ();
2125 _gst_debug_category_new (const gchar * name, guint color,
2126 const gchar * description)
2128 GstDebugCategory *cat, *catfound;
2130 g_return_val_if_fail (name != NULL, NULL);
2132 cat = g_slice_new (GstDebugCategory);
2133 cat->name = g_strdup (name);
2135 if (description != NULL) {
2136 cat->description = g_strdup (description);
2138 cat->description = g_strdup ("no description");
2140 g_atomic_int_set (&cat->threshold, 0);
2141 gst_debug_reset_threshold (cat, NULL);
2143 /* add to category list */
2144 g_mutex_lock (&__cat_mutex);
2145 catfound = _gst_debug_get_category_locked (name);
2147 g_free ((gpointer) cat->name);
2148 g_free ((gpointer) cat->description);
2149 g_slice_free (GstDebugCategory, cat);
2152 __categories = g_slist_prepend (__categories, cat);
2154 g_mutex_unlock (&__cat_mutex);
2159 #ifndef GST_REMOVE_DEPRECATED
2161 * gst_debug_category_free:
2162 * @category: #GstDebugCategory to free.
2164 * Removes and frees the category and all associated resources.
2166 * Deprecated: This function can easily cause memory corruption, don't use it.
2169 gst_debug_category_free (GstDebugCategory * category)
2175 * gst_debug_category_set_threshold:
2176 * @category: a #GstDebugCategory to set threshold of.
2177 * @level: the #GstDebugLevel threshold to set.
2179 * Sets the threshold of the category to the given level. Debug information will
2180 * only be output if the threshold is lower or equal to the level of the
2181 * debugging message.
2182 * > Do not use this function in production code, because other functions may
2183 * > change the threshold of categories as side effect. It is however a nice
2184 * > function to use when debugging (even from gdb).
2187 gst_debug_category_set_threshold (GstDebugCategory * category,
2188 GstDebugLevel level)
2190 g_return_if_fail (category != NULL);
2192 if (level > _gst_debug_min) {
2193 _gst_debug_enabled = TRUE;
2194 _gst_debug_min = level;
2197 g_atomic_int_set (&category->threshold, level);
2201 * gst_debug_category_reset_threshold:
2202 * @category: a #GstDebugCategory to reset threshold of.
2204 * Resets the threshold of the category to the default level. Debug information
2205 * will only be output if the threshold is lower or equal to the level of the
2206 * debugging message.
2207 * Use this function to set the threshold back to where it was after using
2208 * gst_debug_category_set_threshold().
2211 gst_debug_category_reset_threshold (GstDebugCategory * category)
2213 gst_debug_reset_threshold (category, NULL);
2217 * gst_debug_category_get_threshold:
2218 * @category: a #GstDebugCategory to get threshold of.
2220 * Returns the threshold of a #GstDebugCategory.
2222 * Returns: the #GstDebugLevel that is used as threshold.
2225 gst_debug_category_get_threshold (GstDebugCategory * category)
2227 return (GstDebugLevel) g_atomic_int_get (&category->threshold);
2231 * gst_debug_category_get_name:
2232 * @category: a #GstDebugCategory to get name of.
2234 * Returns the name of a debug category.
2236 * Returns: the name of the category.
2239 gst_debug_category_get_name (GstDebugCategory * category)
2241 return category->name;
2245 * gst_debug_category_get_color:
2246 * @category: a #GstDebugCategory to get the color of.
2248 * Returns the color of a debug category used when printing output in this
2251 * Returns: the color of the category.
2254 gst_debug_category_get_color (GstDebugCategory * category)
2256 return category->color;
2260 * gst_debug_category_get_description:
2261 * @category: a #GstDebugCategory to get the description of.
2263 * Returns the description of a debug category.
2265 * Returns: the description of the category.
2268 gst_debug_category_get_description (GstDebugCategory * category)
2270 return category->description;
2274 * gst_debug_get_all_categories:
2276 * Returns a snapshot of a all categories that are currently in use . This list
2277 * may change anytime.
2278 * The caller has to free the list after use.
2280 * Returns: (transfer container) (element-type Gst.DebugCategory): the list of
2284 gst_debug_get_all_categories (void)
2288 g_mutex_lock (&__cat_mutex);
2289 ret = g_slist_copy (__categories);
2290 g_mutex_unlock (&__cat_mutex);
2295 static GstDebugCategory *
2296 _gst_debug_get_category_locked (const gchar * name)
2298 GstDebugCategory *ret = NULL;
2301 for (node = __categories; node; node = g_slist_next (node)) {
2302 ret = (GstDebugCategory *) node->data;
2303 if (!strcmp (name, ret->name)) {
2311 _gst_debug_get_category (const gchar * name)
2313 GstDebugCategory *ret;
2315 g_mutex_lock (&__cat_mutex);
2316 ret = _gst_debug_get_category_locked (name);
2317 g_mutex_unlock (&__cat_mutex);
2323 parse_debug_category (gchar * str, const gchar ** category)
2328 /* works in place */
2331 if (str[0] != '\0') {
2340 parse_debug_level (gchar * str, GstDebugLevel * level)
2345 /* works in place */
2348 if (g_ascii_isdigit (str[0])) {
2351 l = strtoul (str, &endptr, 10);
2352 if (endptr > str && endptr[0] == 0) {
2353 *level = (GstDebugLevel) l;
2357 } else if (strcmp (str, "NONE") == 0) {
2358 *level = GST_LEVEL_NONE;
2359 } else if (strcmp (str, "ERROR") == 0) {
2360 *level = GST_LEVEL_ERROR;
2361 } else if (strncmp (str, "WARN", 4) == 0) {
2362 *level = GST_LEVEL_WARNING;
2363 } else if (strcmp (str, "FIXME") == 0) {
2364 *level = GST_LEVEL_FIXME;
2365 } else if (strcmp (str, "INFO") == 0) {
2366 *level = GST_LEVEL_INFO;
2367 } else if (strcmp (str, "DEBUG") == 0) {
2368 *level = GST_LEVEL_DEBUG;
2369 } else if (strcmp (str, "LOG") == 0) {
2370 *level = GST_LEVEL_LOG;
2371 } else if (strcmp (str, "TRACE") == 0) {
2372 *level = GST_LEVEL_TRACE;
2373 } else if (strcmp (str, "MEMDUMP") == 0) {
2374 *level = GST_LEVEL_MEMDUMP;
2382 * gst_debug_set_threshold_from_string:
2383 * @list: comma-separated list of "category:level" pairs to be used
2384 * as debug logging levels
2385 * @reset: %TRUE to clear all previously-set debug levels before setting
2387 * %FALSE if adding the threshold described by @list to the one already set.
2389 * Sets the debug logging wanted in the same form as with the GST_DEBUG
2390 * environment variable. You can use wildcards such as '*', but note that
2391 * the order matters when you use wild cards, e.g. "foosrc:6,*src:3,*:2" sets
2392 * everything to log level 2.
2397 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2405 clear_level_names ();
2406 gst_debug_set_default_threshold (GST_LEVEL_DEFAULT);
2409 split = g_strsplit (list, ",", 0);
2411 for (walk = split; *walk; walk++) {
2412 if (strchr (*walk, ':')) {
2413 gchar **values = g_strsplit (*walk, ":", 2);
2415 if (values[0] && values[1]) {
2416 GstDebugLevel level;
2417 const gchar *category;
2419 if (parse_debug_category (values[0], &category)
2420 && parse_debug_level (values[1], &level)) {
2421 gst_debug_set_threshold_for_name (category, level);
2423 /* bump min-level anyway to allow the category to be registered in the
2425 if (level > _gst_debug_min) {
2426 _gst_debug_min = level;
2431 g_strfreev (values);
2433 GstDebugLevel level;
2435 if (parse_debug_level (*walk, &level))
2436 gst_debug_set_default_threshold (level);
2443 /*** FUNCTION POINTERS ********************************************************/
2445 static GHashTable *__gst_function_pointers; /* NULL */
2446 static GMutex __dbg_functions_mutex;
2448 /* This function MUST NOT return NULL */
2450 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2458 if (G_UNLIKELY (func == NULL))
2461 g_mutex_lock (&__dbg_functions_mutex);
2462 if (G_LIKELY (__gst_function_pointers)) {
2463 ptrname = g_hash_table_lookup (__gst_function_pointers, (gpointer) func);
2464 g_mutex_unlock (&__dbg_functions_mutex);
2465 if (G_LIKELY (ptrname))
2468 g_mutex_unlock (&__dbg_functions_mutex);
2470 /* we need to create an entry in the hash table for this one so we don't leak
2473 if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
2474 const gchar *name = g_intern_string (dl_info.dli_sname);
2476 _gst_debug_register_funcptr (func, name);
2481 gchar *name = g_strdup_printf ("%p", (gpointer) func);
2482 const gchar *iname = g_intern_string (name);
2486 _gst_debug_register_funcptr (func, iname);
2492 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2494 gpointer ptr = (gpointer) func;
2496 g_mutex_lock (&__dbg_functions_mutex);
2498 if (!__gst_function_pointers)
2499 __gst_function_pointers = g_hash_table_new (g_direct_hash, g_direct_equal);
2500 if (!g_hash_table_lookup (__gst_function_pointers, ptr)) {
2501 g_hash_table_insert (__gst_function_pointers, ptr, (gpointer) ptrname);
2504 g_mutex_unlock (&__dbg_functions_mutex);
2508 clear_level_names (void)
2510 g_mutex_lock (&__level_name_mutex);
2511 while (__level_name) {
2512 LevelNameEntry *level_name_entry = __level_name->data;
2513 g_pattern_spec_free (level_name_entry->pat);
2514 g_slice_free (LevelNameEntry, level_name_entry);
2515 __level_name = g_slist_delete_link (__level_name, __level_name);
2517 g_mutex_unlock (&__level_name_mutex);
2521 _priv_gst_debug_cleanup (void)
2523 g_mutex_lock (&__dbg_functions_mutex);
2525 if (__gst_function_pointers) {
2526 g_hash_table_unref (__gst_function_pointers);
2527 __gst_function_pointers = NULL;
2530 g_mutex_unlock (&__dbg_functions_mutex);
2532 g_mutex_lock (&__cat_mutex);
2533 while (__categories) {
2534 GstDebugCategory *cat = __categories->data;
2535 g_free ((gpointer) cat->name);
2536 g_free ((gpointer) cat->description);
2537 g_slice_free (GstDebugCategory, cat);
2538 __categories = g_slist_delete_link (__categories, __categories);
2540 g_mutex_unlock (&__cat_mutex);
2542 clear_level_names ();
2544 g_mutex_lock (&__log_func_mutex);
2545 while (__log_functions) {
2546 LogFuncEntry *log_func_entry = __log_functions->data;
2547 if (log_func_entry->notify)
2548 log_func_entry->notify (log_func_entry->user_data);
2549 g_slice_free (LogFuncEntry, log_func_entry);
2550 __log_functions = g_slist_delete_link (__log_functions, __log_functions);
2552 g_mutex_unlock (&__log_func_mutex);
2556 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2557 const guint8 * mem, gsize mem_offset, gsize mem_size)
2559 gchar hexstr[50], ascstr[18], digitstr[4];
2571 while (i < mem_size) {
2572 ascstr[i] = (g_ascii_isprint (mem[i])) ? mem[i] : '.';
2573 g_snprintf (digitstr, sizeof (digitstr), "%02x ", mem[i]);
2574 g_strlcat (hexstr, digitstr, sizeof (hexstr));
2580 g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2581 (guint) mem_offset, hexstr, ascstr);
2585 _gst_debug_dump_mem_full (GstDebugCategory * cat, const gchar * file,
2586 const gchar * func, gint line, GObject * obj, const gchar * object_id,
2587 const gchar * msg, const guint8 * data, guint length)
2590 gboolean free_object_id = FALSE;
2593 if (object_id == NULL && obj)
2594 object_id = _get_object_id (obj, &free_object_id, (gchar *) & tmp_id);
2596 gst_debug_log_id ((cat), GST_LEVEL_MEMDUMP, file, func, line, object_id,
2598 "-------------------------------------------------------------------");
2600 if (msg != NULL && *msg != '\0') {
2601 gst_debug_log_id ((cat), GST_LEVEL_MEMDUMP, file, func, line, object_id,
2605 while (off < length) {
2608 /* gst_info_dump_mem_line will process 16 bytes at most */
2609 gst_info_dump_mem_line (buf, sizeof (buf), data, off, length - off);
2610 gst_debug_log_id (cat, GST_LEVEL_MEMDUMP, file, func, line, object_id, "%s",
2615 gst_debug_log_id ((cat), GST_LEVEL_MEMDUMP, file, func, line, object_id,
2617 "-------------------------------------------------------------------");
2620 g_free ((gchar *) object_id);
2624 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2625 const gchar * func, gint line, GObject * obj, const gchar * msg,
2626 const guint8 * data, guint length)
2628 _gst_debug_dump_mem_full (cat, file, func, line, obj, NULL, msg, data,
2633 _gst_debug_dump_mem_id (GstDebugCategory * cat, const gchar * file,
2634 const gchar * func, gint line, const gchar * object_id, const gchar * msg,
2635 const guint8 * data, guint length)
2637 _gst_debug_dump_mem_full (cat, file, func, line, NULL, object_id, msg, data,
2642 #else /* !GST_DISABLE_GST_DEBUG */
2643 #ifndef GST_REMOVE_DISABLED
2646 _gst_debug_category_new (const gchar * name, guint color,
2647 const gchar * description)
2653 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2657 /* This function MUST NOT return NULL */
2659 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2665 _priv_gst_debug_cleanup (void)
2670 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2671 const gchar * file, const gchar * function, gint line,
2672 GObject * object, const gchar * format, ...)
2677 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
2678 const gchar * file, const gchar * function, gint line,
2679 GObject * object, const gchar * format, va_list args)
2684 gst_debug_log_literal (GstDebugCategory * category, GstDebugLevel level,
2685 const gchar * file, const gchar * function, gint line,
2686 GObject * object, const gchar * message_string)
2691 gst_debug_message_get (GstDebugMessage * message)
2697 gst_debug_message_get_id (GstDebugMessage * message)
2703 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
2704 const gchar * file, const gchar * function, gint line,
2705 GObject * object, GstDebugMessage * message, gpointer unused)
2710 gst_debug_level_get_name (GstDebugLevel level)
2716 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2717 GDestroyNotify notify)
2724 gst_debug_remove_log_function (GstLogFunction func)
2730 gst_debug_remove_log_function_by_data (gpointer data)
2736 gst_debug_set_active (gboolean active)
2741 gst_debug_is_active (void)
2747 gst_debug_set_colored (gboolean colored)
2752 gst_debug_set_color_mode (GstDebugColorMode mode)
2757 gst_debug_set_color_mode_from_string (const gchar * str)
2762 gst_debug_is_colored (void)
2768 gst_debug_get_color_mode (void)
2770 return GST_DEBUG_COLOR_MODE_OFF;
2774 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2779 gst_debug_set_default_threshold (GstDebugLevel level)
2784 gst_debug_get_default_threshold (void)
2786 return GST_LEVEL_NONE;
2790 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2795 gst_debug_unset_threshold_for_name (const gchar * name)
2799 #ifndef GST_REMOVE_DEPRECATED
2801 gst_debug_category_free (GstDebugCategory * category)
2807 gst_debug_category_set_threshold (GstDebugCategory * category,
2808 GstDebugLevel level)
2813 gst_debug_category_reset_threshold (GstDebugCategory * category)
2818 gst_debug_category_get_threshold (GstDebugCategory * category)
2820 return GST_LEVEL_NONE;
2824 gst_debug_category_get_name (GstDebugCategory * category)
2830 gst_debug_category_get_color (GstDebugCategory * category)
2836 gst_debug_category_get_description (GstDebugCategory * category)
2842 gst_debug_get_all_categories (void)
2848 _gst_debug_get_category (const gchar * name)
2854 gst_debug_construct_term_color (guint colorinfo)
2856 return g_strdup ("00");
2860 gst_debug_construct_win_color (guint colorinfo)
2866 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2867 const gchar * func, gint line, GObject * obj, const gchar * msg,
2868 const guint8 * data, guint length)
2871 #endif /* GST_REMOVE_DISABLED */
2872 #endif /* GST_DISABLE_GST_DEBUG */
2875 * gst_info_vasprintf:
2876 * @result: (out): the resulting string
2877 * @format: a printf style format string
2878 * @args: the va_list of printf arguments for @format
2880 * Allocates and fills a string large enough (including the terminating null
2881 * byte) to hold the specified printf style @format and @args.
2883 * This function deals with the GStreamer specific printf specifiers
2884 * #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT. If you do not have these specifiers
2885 * in your @format string, you do not need to use this function and can use
2886 * alternatives such as g_vasprintf().
2888 * Free @result with g_free().
2890 * Returns: the length of the string allocated into @result or -1 on any error
2895 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2897 return __gst_vasprintf (result, format, args);
2901 * gst_info_strdup_vprintf:
2902 * @format: a printf style format string
2903 * @args: the va_list of printf arguments for @format
2905 * Allocates, fills and returns a null terminated string from the printf style
2906 * @format string and @args.
2908 * See gst_info_vasprintf() for when this function is required.
2910 * Free with g_free().
2912 * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2917 gst_info_strdup_vprintf (const gchar * format, va_list args)
2921 if (gst_info_vasprintf (&ret, format, args) < 0)
2928 * gst_info_strdup_printf:
2929 * @format: a printf style format string
2930 * @...: the printf arguments for @format
2932 * Allocates, fills and returns a 0-terminated string from the printf style
2933 * @format string and corresponding arguments.
2935 * See gst_info_vasprintf() for when this function is required.
2937 * Free with g_free().
2939 * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2944 gst_info_strdup_printf (const gchar * format, ...)
2949 va_start (args, format);
2950 ret = gst_info_strdup_vprintf (format, args);
2958 * @format: a printf style format string
2959 * @...: the printf arguments for @format
2961 * Outputs a formatted message via the GLib print handler. The default print
2962 * handler simply outputs the message to stdout.
2964 * This function will not append a new-line character at the end, unlike
2965 * gst_println() which will.
2967 * All strings must be in ASCII or UTF-8 encoding.
2969 * This function differs from g_print() in that it supports all the additional
2970 * printf specifiers that are supported by GStreamer's debug logging system,
2971 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2973 * This function is primarily for printing debug output.
2978 gst_print (const gchar * format, ...)
2983 va_start (args, format);
2984 str = gst_info_strdup_vprintf (format, args);
2988 G_LOCK (win_print_mutex);
2991 g_print ("%s", str);
2994 G_UNLOCK (win_print_mutex);
3001 * @format: a printf style format string
3002 * @...: the printf arguments for @format
3004 * Outputs a formatted message via the GLib print handler. The default print
3005 * handler simply outputs the message to stdout.
3007 * This function will append a new-line character at the end, unlike
3008 * gst_print() which will not.
3010 * All strings must be in ASCII or UTF-8 encoding.
3012 * This function differs from g_print() in that it supports all the additional
3013 * printf specifiers that are supported by GStreamer's debug logging system,
3014 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
3016 * This function is primarily for printing debug output.
3021 gst_println (const gchar * format, ...)
3026 va_start (args, format);
3027 str = gst_info_strdup_vprintf (format, args);
3031 G_LOCK (win_print_mutex);
3034 g_print ("%s\n", str);
3037 G_UNLOCK (win_print_mutex);
3044 * @format: a printf style format string
3045 * @...: the printf arguments for @format
3047 * Outputs a formatted message via the GLib error message handler. The default
3048 * handler simply outputs the message to stderr.
3050 * This function will not append a new-line character at the end, unlike
3051 * gst_printerrln() which will.
3053 * All strings must be in ASCII or UTF-8 encoding.
3055 * This function differs from g_printerr() in that it supports the additional
3056 * printf specifiers that are supported by GStreamer's debug logging system,
3057 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
3059 * This function is primarily for printing debug output.
3064 gst_printerr (const gchar * format, ...)
3069 va_start (args, format);
3070 str = gst_info_strdup_vprintf (format, args);
3074 G_LOCK (win_print_mutex);
3077 g_printerr ("%s", str);
3080 G_UNLOCK (win_print_mutex);
3087 * @format: a printf style format string
3088 * @...: the printf arguments for @format
3090 * Outputs a formatted message via the GLib error message handler. The default
3091 * handler simply outputs the message to stderr.
3093 * This function will append a new-line character at the end, unlike
3094 * gst_printerr() which will not.
3096 * All strings must be in ASCII or UTF-8 encoding.
3098 * This function differs from g_printerr() in that it supports the additional
3099 * printf specifiers that are supported by GStreamer's debug logging system,
3100 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
3102 * This function is primarily for printing debug output.
3107 gst_printerrln (const gchar * format, ...)
3112 va_start (args, format);
3113 str = gst_info_strdup_vprintf (format, args);
3117 G_LOCK (win_print_mutex);
3120 g_printerr ("%s\n", str);
3123 G_UNLOCK (win_print_mutex);
3131 append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
3135 Dwfl_Module *module;
3136 const gchar *function_name;
3138 addr = (uintptr_t) ip;
3139 module = dwfl_addrmodule (dwfl, addr);
3140 function_name = dwfl_module_addrname (module, addr);
3142 g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
3144 line = dwfl_getsrc (dwfl, addr);
3148 const gchar *filename = dwfl_lineinfo (line, &addr,
3149 &nline, NULL, NULL, NULL);
3151 g_string_append_printf (trace, "%s:%d", strrchr (filename,
3152 G_DIR_SEPARATOR) + 1, nline);
3154 const gchar *eflfile = NULL;
3156 dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
3157 g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
3162 #endif /* HAVE_DW */
3165 generate_unwind_trace (GstStackTraceFlags flags)
3169 unw_cursor_t cursor;
3170 gboolean use_libunwind = TRUE;
3171 GString *trace = g_string_new (NULL);
3176 if ((flags & GST_STACK_TRACE_SHOW_FULL)) {
3177 dwfl = get_global_dwfl ();
3178 if (G_UNLIKELY (dwfl == NULL)) {
3179 GST_WARNING ("Failed to initialize dwlf");
3184 #endif /* HAVE_DW */
3186 unret = unw_getcontext (&uc);
3188 GST_DEBUG ("Could not get libunwind context (%d)", unret);
3192 unret = unw_init_local (&cursor, &uc);
3194 GST_DEBUG ("Could not init libunwind context (%d)", unret);
3199 /* Due to plugins being loaded, mapping of process might have changed,
3200 * so always scan it. */
3201 if (dwfl_linux_proc_report (dwfl, _gst_getpid ()) != 0)
3205 while (unw_step (&cursor) > 0) {
3210 unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
3212 GST_DEBUG ("libunwind could not read frame info (%d)", unret);
3217 if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
3218 use_libunwind = FALSE;
3219 g_string_append (trace, ")\n");
3222 #endif /* HAVE_DW */
3224 if (use_libunwind) {
3227 unw_word_t offset = 0;
3228 unw_get_proc_name (&cursor, name, sizeof (name), &offset);
3229 g_string_append_printf (trace, "%s (0x%" G_GSIZE_FORMAT ")\n", name,
3240 return g_string_free (trace, FALSE);
3243 #endif /* HAVE_UNWIND */
3245 #ifdef HAVE_BACKTRACE
3247 generate_backtrace_trace (void)
3250 void *buffer[BT_BUF_SIZE];
3254 nptrs = backtrace (buffer, BT_BUF_SIZE);
3256 strings = backtrace_symbols (buffer, nptrs);
3261 trace = g_string_new (NULL);
3263 for (j = 0; j < nptrs; j++)
3264 g_string_append_printf (trace, "%s\n", strings[j]);
3268 return g_string_free (trace, FALSE);
3271 #define generate_backtrace_trace() NULL
3272 #endif /* HAVE_BACKTRACE */
3278 DWORD (WINAPI * pSymSetOptions) (DWORD SymOptions);
3279 BOOL (WINAPI * pSymInitialize) (HANDLE hProcess,
3280 PCSTR UserSearchPath,
3281 BOOL fInvadeProcess);
3282 BOOL (WINAPI * pStackWalk64) (DWORD MachineType,
3285 LPSTACKFRAME64 StackFrame,
3286 PVOID ContextRecord,
3287 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
3288 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
3289 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
3290 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
3291 PVOID (WINAPI * pSymFunctionTableAccess64) (HANDLE hProcess,
3293 DWORD64 (WINAPI * pSymGetModuleBase64) (HANDLE hProcess,
3295 BOOL (WINAPI * pSymFromAddr) (HANDLE hProcess,
3297 PDWORD64 Displacement,
3298 PSYMBOL_INFO Symbol);
3299 BOOL (WINAPI * pSymGetModuleInfo64) (HANDLE hProcess,
3301 PIMAGEHLP_MODULE64 ModuleInfo);
3302 BOOL (WINAPI * pSymGetLineFromAddr64) (HANDLE hProcess,
3304 PDWORD pdwDisplacement,
3305 PIMAGEHLP_LINE64 Line64);
3306 } dbg_help_vtable = { NULL,};
3309 static GModule *dbg_help_module = NULL;
3312 dbghelp_load_symbol (const gchar * symbol_name, gpointer * symbol)
3314 if (dbg_help_module &&
3315 !g_module_symbol (dbg_help_module, symbol_name, symbol)) {
3316 GST_WARNING ("Cannot load %s symbol", symbol_name);
3317 g_module_close (dbg_help_module);
3318 dbg_help_module = NULL;
3321 return dbg_help_module != NULL;
3325 dbghelp_initialize_symbols (HANDLE process)
3327 static gsize initialization_value = 0;
3329 if (g_once_init_enter (&initialization_value)) {
3330 GST_INFO ("Initializing Windows symbol handler");
3332 dbg_help_module = g_module_open ("dbghelp.dll", G_MODULE_BIND_LAZY);
3333 dbghelp_load_symbol ("SymSetOptions",
3334 (gpointer *) & dbg_help_vtable.pSymSetOptions);
3335 dbghelp_load_symbol ("SymInitialize",
3336 (gpointer *) & dbg_help_vtable.pSymInitialize);
3337 dbghelp_load_symbol ("StackWalk64",
3338 (gpointer *) & dbg_help_vtable.pStackWalk64);
3339 dbghelp_load_symbol ("SymFunctionTableAccess64",
3340 (gpointer *) & dbg_help_vtable.pSymFunctionTableAccess64);
3341 dbghelp_load_symbol ("SymGetModuleBase64",
3342 (gpointer *) & dbg_help_vtable.pSymGetModuleBase64);
3343 dbghelp_load_symbol ("SymFromAddr",
3344 (gpointer *) & dbg_help_vtable.pSymFromAddr);
3345 dbghelp_load_symbol ("SymGetModuleInfo64",
3346 (gpointer *) & dbg_help_vtable.pSymGetModuleInfo64);
3347 dbghelp_load_symbol ("SymGetLineFromAddr64",
3348 (gpointer *) & dbg_help_vtable.pSymGetLineFromAddr64);
3350 if (dbg_help_module) {
3351 dbg_help_vtable.pSymSetOptions (SYMOPT_LOAD_LINES);
3352 dbg_help_vtable.pSymInitialize (process, NULL, TRUE);
3353 GST_INFO ("Initialized Windows symbol handler");
3356 g_once_init_leave (&initialization_value, 1);
3359 return dbg_help_module != NULL;
3363 generate_dbghelp_trace (void)
3365 HANDLE process = GetCurrentProcess ();
3366 HANDLE thread = GetCurrentThread ();
3367 IMAGEHLP_MODULE64 module_info;
3370 STACKFRAME64 frame = { 0 };
3372 GString *trace = NULL;
3374 if (!dbghelp_initialize_symbols (process))
3377 memset (&context, 0, sizeof (CONTEXT));
3378 context.ContextFlags = CONTEXT_FULL;
3380 RtlCaptureContext (&context);
3382 frame.AddrPC.Mode = AddrModeFlat;
3383 frame.AddrStack.Mode = AddrModeFlat;
3384 frame.AddrFrame.Mode = AddrModeFlat;
3386 #if (defined _M_IX86)
3387 machine = IMAGE_FILE_MACHINE_I386;
3388 frame.AddrFrame.Offset = context.Ebp;
3389 frame.AddrPC.Offset = context.Eip;
3390 frame.AddrStack.Offset = context.Esp;
3391 #elif (defined _M_X64)
3392 machine = IMAGE_FILE_MACHINE_AMD64;
3393 frame.AddrFrame.Offset = context.Rbp;
3394 frame.AddrPC.Offset = context.Rip;
3395 frame.AddrStack.Offset = context.Rsp;
3400 trace = g_string_new (NULL);
3402 module_info.SizeOfStruct = sizeof (module_info);
3403 save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
3406 char buffer[sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR)];
3407 PSYMBOL_INFO symbol = (PSYMBOL_INFO) buffer;
3408 IMAGEHLP_LINE64 line;
3409 DWORD displacement = 0;
3411 symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
3412 symbol->MaxNameLen = MAX_SYM_NAME;
3414 line.SizeOfStruct = sizeof (line);
3416 if (!dbg_help_vtable.pStackWalk64 (machine, process, thread, &frame,
3417 save_context, 0, dbg_help_vtable.pSymFunctionTableAccess64,
3418 dbg_help_vtable.pSymGetModuleBase64, 0)) {
3422 if (dbg_help_vtable.pSymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
3423 g_string_append_printf (trace, "%s ", symbol->Name);
3425 g_string_append (trace, "?? ");
3427 if (dbg_help_vtable.pSymGetLineFromAddr64 (process, frame.AddrPC.Offset,
3428 &displacement, &line))
3429 g_string_append_printf (trace, "(%s:%lu)", line.FileName,
3431 else if (dbg_help_vtable.pSymGetModuleInfo64 (process, frame.AddrPC.Offset,
3433 g_string_append_printf (trace, "(%s)", module_info.ImageName);
3435 g_string_append_printf (trace, "(%s)", "??");
3437 g_string_append (trace, "\n");
3440 return g_string_free (trace, FALSE);
3442 #endif /* HAVE_DBGHELP */
3445 * gst_debug_get_stack_trace:
3446 * @flags: A set of #GstStackTraceFlags to determine how the stack trace should
3447 * look like. Pass #GST_STACK_TRACE_SHOW_NONE to retrieve a minimal backtrace.
3449 * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
3450 * present, else %NULL.
3455 gst_debug_get_stack_trace (GstStackTraceFlags flags)
3457 gchar *trace = NULL;
3458 #ifdef HAVE_BACKTRACE
3459 gboolean have_backtrace = TRUE;
3461 gboolean have_backtrace = FALSE;
3465 if ((flags & GST_STACK_TRACE_SHOW_FULL) || !have_backtrace)
3466 trace = generate_unwind_trace (flags);
3467 #elif defined(HAVE_DBGHELP)
3468 trace = generate_dbghelp_trace ();
3473 else if (have_backtrace)
3474 return generate_backtrace_trace ();
3480 * gst_debug_print_stack_trace:
3482 * If libunwind, glibc backtrace or DbgHelp are present
3483 * a stack trace is printed.
3486 gst_debug_print_stack_trace (void)
3488 gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
3492 G_LOCK (win_print_mutex);
3495 g_print ("%s\n", trace);
3498 G_UNLOCK (win_print_mutex);
3505 #ifndef GST_DISABLE_GST_DEBUG
3508 guint max_size_per_thread;
3509 guint thread_timeout;
3511 GHashTable *thread_index;
3512 } GstRingBufferLogger;
3524 G_LOCK_DEFINE_STATIC (ring_buffer_logger);
3525 static GstRingBufferLogger *ring_buffer_logger = NULL;
3528 gst_ring_buffer_logger_log (GstDebugCategory * category,
3529 GstDebugLevel level, const gchar * file, const gchar * function,
3530 gint line, GObject * object, GstDebugMessage * message, gpointer user_data)
3532 GstRingBufferLogger *logger = user_data;
3534 GstClockTime elapsed;
3538 GstRingBufferLog *log;
3539 gint64 now = g_get_monotonic_time ();
3540 const gchar *message_str = gst_debug_message_get (message);
3541 const gchar *object_id = gst_debug_message_get_id (message);
3543 /* __FILE__ might be a file name or an absolute path or a
3544 * relative path, irrespective of the exact compiler used,
3545 * in which case we want to shorten it to the filename for
3548 if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
3549 file = gst_path_basename (file);
3552 elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
3553 thread = g_thread_self ();
3556 /* no color, all platforms */
3558 g_strdup_printf ("%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT_ID,
3559 GST_TIME_ARGS (elapsed), _gst_getpid (), thread,
3560 gst_debug_level_get_name (level),
3561 gst_debug_category_get_name (category), file, line, function,
3562 object_id, message_str);
3564 /* no color, all platforms */
3566 g_strdup_printf ("%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
3567 GST_TIME_ARGS (elapsed), _gst_getpid (), thread,
3568 gst_debug_level_get_name (level),
3569 gst_debug_category_get_name (category), file, line, function, "",
3573 output_len = strlen (output);
3576 G_LOCK (ring_buffer_logger);
3578 if (logger->thread_timeout > 0) {
3581 /* Remove all threads that saw no output since thread_timeout seconds.
3582 * By construction these are all at the tail of the queue, and the queue
3583 * is ordered by last use, so we just need to look at the tail.
3585 while (logger->threads.tail) {
3586 log = logger->threads.tail->data;
3587 if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
3590 g_hash_table_remove (logger->thread_index, log->thread);
3591 while ((buf = g_queue_pop_head (&log->log)))
3594 g_queue_pop_tail (&logger->threads);
3598 /* Get logger for this thread, and put it back at the
3599 * head of the threads queue */
3600 log = g_hash_table_lookup (logger->thread_index, thread);
3602 log = g_new0 (GstRingBufferLog, 1);
3603 g_queue_init (&log->log);
3605 g_queue_push_head (&logger->threads, log);
3606 log->link = logger->threads.head;
3607 log->thread = thread;
3608 g_hash_table_insert (logger->thread_index, thread, log);
3610 g_queue_unlink (&logger->threads, log->link);
3611 g_queue_push_head_link (&logger->threads, log->link);
3613 log->last_use = now;
3615 if (output_len < logger->max_size_per_thread) {
3618 /* While using a GQueue here is not the most efficient thing to do, we
3619 * have to allocate a string for every output anyway and could just store
3620 * that instead of copying it to an actual ringbuffer.
3621 * Better than GQueue would be GstQueueArray, but that one is in
3622 * libgstbase and we can't use it here. That one allocation will not make
3623 * much of a difference anymore, considering the number of allocations
3624 * needed to get to this point...
3626 while (log->log_size + output_len > logger->max_size_per_thread) {
3627 buf = g_queue_pop_head (&log->log);
3628 log->log_size -= strlen (buf);
3631 g_queue_push_tail (&log->log, output);
3632 log->log_size += output_len;
3636 /* Can't really write anything as the line is bigger than the maximum
3637 * allowed log size already, so just remove everything */
3639 while ((buf = g_queue_pop_head (&log->log)))
3645 G_UNLOCK (ring_buffer_logger);
3649 * gst_debug_ring_buffer_logger_get_logs:
3651 * Fetches the current logs per thread from the ring buffer logger. See
3652 * gst_debug_add_ring_buffer_logger() for details.
3654 * Returns: (transfer full) (array zero-terminated=1): NULL-terminated array of
3655 * strings with the debug output per thread
3660 gst_debug_ring_buffer_logger_get_logs (void)
3662 gchar **logs, **tmp;
3665 g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
3667 G_LOCK (ring_buffer_logger);
3669 tmp = logs = g_new0 (gchar *, ring_buffer_logger->threads.length + 1);
3670 for (l = ring_buffer_logger->threads.head; l; l = l->next) {
3671 GstRingBufferLog *log = l->data;
3676 *tmp = p = g_new0 (gchar, log->log_size + 1);
3678 for (l = log->log.head; l; l = l->next) {
3679 len = strlen (l->data);
3680 memcpy (p, l->data, len);
3687 G_UNLOCK (ring_buffer_logger);
3693 gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
3695 G_LOCK (ring_buffer_logger);
3696 if (ring_buffer_logger == logger) {
3697 GstRingBufferLog *log;
3699 while ((log = g_queue_pop_head (&logger->threads))) {
3701 while ((buf = g_queue_pop_head (&log->log)))
3706 g_hash_table_unref (logger->thread_index);
3709 ring_buffer_logger = NULL;
3711 G_UNLOCK (ring_buffer_logger);
3715 * gst_debug_add_ring_buffer_logger:
3716 * @max_size_per_thread: Maximum size of log per thread in bytes
3717 * @thread_timeout: Timeout for threads in seconds
3719 * Adds a memory ringbuffer based debug logger that stores up to
3720 * @max_size_per_thread bytes of logs per thread and times out threads after
3721 * @thread_timeout seconds of inactivity.
3723 * Logs can be fetched with gst_debug_ring_buffer_logger_get_logs() and the
3724 * logger can be removed again with gst_debug_remove_ring_buffer_logger().
3725 * Only one logger at a time is possible.
3730 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3731 guint thread_timeout)
3733 GstRingBufferLogger *logger;
3735 G_LOCK (ring_buffer_logger);
3737 if (ring_buffer_logger) {
3738 g_warn_if_reached ();
3739 G_UNLOCK (ring_buffer_logger);
3743 logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
3745 logger->max_size_per_thread = max_size_per_thread;
3746 logger->thread_timeout = thread_timeout;
3747 logger->thread_index = g_hash_table_new (g_direct_hash, g_direct_equal);
3748 g_queue_init (&logger->threads);
3750 gst_debug_add_log_function (gst_ring_buffer_logger_log, logger,
3751 (GDestroyNotify) gst_ring_buffer_logger_free);
3752 G_UNLOCK (ring_buffer_logger);
3756 * gst_debug_remove_ring_buffer_logger:
3758 * Removes any previously added ring buffer logger with
3759 * gst_debug_add_ring_buffer_logger().
3764 gst_debug_remove_ring_buffer_logger (void)
3766 gst_debug_remove_log_function (gst_ring_buffer_logger_log);
3769 #else /* GST_DISABLE_GST_DEBUG */
3770 #ifndef GST_REMOVE_DISABLED
3773 gst_debug_ring_buffer_logger_get_logs (void)
3779 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3780 guint thread_timeout)
3785 gst_debug_remove_ring_buffer_logger (void)
3789 #endif /* GST_REMOVE_DISABLED */
3790 #endif /* GST_DISABLE_GST_DEBUG */