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
309 /* list of all name/level pairs from --gst-debug and GST_DEBUG */
310 static GMutex __level_name_mutex;
311 static GSList *__level_name = NULL;
319 /* list of all categories */
320 static GMutex __cat_mutex;
321 static GSList *__categories = NULL;
323 static GstDebugCategory *_gst_debug_get_category_locked (const gchar * name);
326 /* all registered debug handlers */
331 GDestroyNotify notify;
334 static GMutex __log_func_mutex;
335 static GSList *__log_functions = NULL;
337 /* whether to add the default log function in gst_init() */
338 static gboolean add_default_log_func = TRUE;
340 #define PRETTY_TAGS_DEFAULT TRUE
341 static gboolean pretty_tags = PRETTY_TAGS_DEFAULT;
343 static gint G_GNUC_MAY_ALIAS __default_level = GST_LEVEL_DEFAULT;
344 static gint G_GNUC_MAY_ALIAS __use_color = GST_DEBUG_COLOR_MODE_ON;
347 _replace_pattern_in_gst_debug_file_name (gchar * name, const char *token,
351 if ((token_start = strstr (name, token))) {
352 gsize token_len = strlen (token);
353 gchar *name_prefix = name;
354 gchar *name_suffix = token_start + token_len;
355 token_start[0] = '\0';
356 name = g_strdup_printf ("%s%u%s", name_prefix, val, name_suffix);
357 g_free (name_prefix);
363 _priv_gst_debug_file_name (const gchar * env)
367 name = g_strdup (env);
368 name = _replace_pattern_in_gst_debug_file_name (name, "%p", _gst_getpid ());
369 name = _replace_pattern_in_gst_debug_file_name (name, "%r", g_random_int ());
374 /* Initialize the debugging system */
376 _priv_gst_debug_init (void)
381 if (add_default_log_func) {
382 env = g_getenv ("GST_DEBUG_FILE");
383 if (env != NULL && *env != '\0') {
384 if (strcmp (env, "-") == 0) {
387 gchar *name = _priv_gst_debug_file_name (env);
388 log_file = g_fopen (name, "w");
390 if (log_file == NULL) {
391 g_printerr ("Could not open log file '%s' for writing: %s\n", env,
400 gst_debug_add_log_function (gst_debug_log_default, log_file, NULL);
403 __gst_printf_pointer_extension_set_func
404 (gst_info_printf_pointer_extension_func);
406 /* do NOT use a single debug function before this line has been run */
407 GST_CAT_DEFAULT = _gst_debug_category_new ("default",
408 GST_DEBUG_UNDERLINE, NULL);
409 _GST_CAT_DEBUG = _gst_debug_category_new ("GST_DEBUG",
410 GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, "debugging subsystem");
412 /* FIXME: add descriptions here */
413 GST_CAT_GST_INIT = _gst_debug_category_new ("GST_INIT",
414 GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
415 GST_CAT_MEMORY = _gst_debug_category_new ("GST_MEMORY",
416 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, "memory");
417 GST_CAT_PARENTAGE = _gst_debug_category_new ("GST_PARENTAGE",
418 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
419 GST_CAT_STATES = _gst_debug_category_new ("GST_STATES",
420 GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
421 GST_CAT_SCHEDULING = _gst_debug_category_new ("GST_SCHEDULING",
422 GST_DEBUG_BOLD | GST_DEBUG_FG_MAGENTA, NULL);
423 GST_CAT_BUFFER = _gst_debug_category_new ("GST_BUFFER",
424 GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
425 GST_CAT_BUFFER_LIST = _gst_debug_category_new ("GST_BUFFER_LIST",
426 GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
427 GST_CAT_BUS = _gst_debug_category_new ("GST_BUS", GST_DEBUG_BG_YELLOW, NULL);
428 GST_CAT_CAPS = _gst_debug_category_new ("GST_CAPS",
429 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
430 GST_CAT_CLOCK = _gst_debug_category_new ("GST_CLOCK",
431 GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, NULL);
432 GST_CAT_ELEMENT_PADS = _gst_debug_category_new ("GST_ELEMENT_PADS",
433 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
434 GST_CAT_PADS = _gst_debug_category_new ("GST_PADS",
435 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
436 GST_CAT_PERFORMANCE = _gst_debug_category_new ("GST_PERFORMANCE",
437 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
438 GST_CAT_PIPELINE = _gst_debug_category_new ("GST_PIPELINE",
439 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
440 GST_CAT_PLUGIN_LOADING = _gst_debug_category_new ("GST_PLUGIN_LOADING",
441 GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
442 GST_CAT_PLUGIN_INFO = _gst_debug_category_new ("GST_PLUGIN_INFO",
443 GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
444 GST_CAT_PROPERTIES = _gst_debug_category_new ("GST_PROPERTIES",
445 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_BLUE, NULL);
446 GST_CAT_NEGOTIATION = _gst_debug_category_new ("GST_NEGOTIATION",
447 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
448 GST_CAT_REFCOUNTING = _gst_debug_category_new ("GST_REFCOUNTING",
449 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
450 GST_CAT_ERROR_SYSTEM = _gst_debug_category_new ("GST_ERROR_SYSTEM",
451 GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_WHITE, NULL);
453 GST_CAT_EVENT = _gst_debug_category_new ("GST_EVENT",
454 GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
455 GST_CAT_MESSAGE = _gst_debug_category_new ("GST_MESSAGE",
456 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
457 GST_CAT_PARAMS = _gst_debug_category_new ("GST_PARAMS",
458 GST_DEBUG_BOLD | GST_DEBUG_FG_BLACK | GST_DEBUG_BG_YELLOW, NULL);
459 GST_CAT_CALL_TRACE = _gst_debug_category_new ("GST_CALL_TRACE",
460 GST_DEBUG_BOLD, NULL);
461 GST_CAT_SIGNAL = _gst_debug_category_new ("GST_SIGNAL",
462 GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
463 GST_CAT_PROBE = _gst_debug_category_new ("GST_PROBE",
464 GST_DEBUG_BOLD | GST_DEBUG_FG_GREEN, "pad probes");
465 GST_CAT_REGISTRY = _gst_debug_category_new ("GST_REGISTRY", 0, "registry");
466 GST_CAT_QOS = _gst_debug_category_new ("GST_QOS", 0, "QoS");
467 _priv_GST_CAT_POLL = _gst_debug_category_new ("GST_POLL", 0, "poll");
468 GST_CAT_META = _gst_debug_category_new ("GST_META", 0, "meta");
469 GST_CAT_LOCKING = _gst_debug_category_new ("GST_LOCKING", 0, "locking");
470 GST_CAT_CONTEXT = _gst_debug_category_new ("GST_CONTEXT", 0, NULL);
471 _priv_GST_CAT_PROTECTION =
472 _gst_debug_category_new ("GST_PROTECTION", 0, "protection");
474 env = g_getenv ("GST_DEBUG_OPTIONS");
476 if (strstr (env, "full_tags") || strstr (env, "full-tags"))
478 else if (strstr (env, "pretty_tags") || strstr (env, "pretty-tags"))
482 if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
483 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
484 env = g_getenv ("GST_DEBUG_COLOR_MODE");
486 gst_debug_set_color_mode_from_string (env);
488 env = g_getenv ("GST_DEBUG");
490 gst_debug_set_threshold_from_string (env, FALSE);
493 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
494 #define GST_CAT_DEFAULT _GST_CAT_DEBUG
498 * @category: category to log
499 * @level: level of the message is in
500 * @file: the file that emitted the message, usually the __FILE__ identifier
501 * @function: the function that emitted the message
502 * @line: the line from that the message was emitted, usually __LINE__
503 * @object: (transfer none) (allow-none): the object this message relates to,
505 * @format: a printf style format string
506 * @...: optional arguments for the format
508 * Logs the given message using the currently registered debugging handlers.
511 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
512 const gchar * file, const gchar * function, gint line,
513 GObject * object, const gchar * format, ...)
517 va_start (var_args, format);
518 gst_debug_log_valist (category, level, file, function, line, object, format,
523 /* based on g_basename(), which we can't use because it was deprecated */
524 static inline const gchar *
525 gst_path_basename (const gchar * file_name)
527 register const gchar *base;
529 base = strrchr (file_name, G_DIR_SEPARATOR);
532 const gchar *q = strrchr (file_name, '/');
533 if (base == NULL || (q != NULL && q > base))
540 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
541 return file_name + 2;
547 * gst_debug_log_valist:
548 * @category: category to log
549 * @level: level of the message is in
550 * @file: the file that emitted the message, usually the __FILE__ identifier
551 * @function: the function that emitted the message
552 * @line: the line from that the message was emitted, usually __LINE__
553 * @object: (transfer none) (allow-none): the object this message relates to,
555 * @format: a printf style format string
556 * @args: optional arguments for the format
558 * Logs the given message using the currently registered debugging handlers.
561 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
562 const gchar * file, const gchar * function, gint line,
563 GObject * object, const gchar * format, va_list args)
565 GstDebugMessage message;
569 g_return_if_fail (category != NULL);
571 #ifdef GST_ENABLE_EXTRA_CHECKS
572 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
575 if (level > gst_debug_category_get_threshold (category))
578 g_return_if_fail (file != NULL);
579 g_return_if_fail (function != NULL);
580 g_return_if_fail (format != NULL);
582 message.message = NULL;
583 message.format = format;
584 G_VA_COPY (message.arguments, args);
586 handler = __log_functions;
588 entry = handler->data;
589 handler = g_slist_next (handler);
590 entry->func (category, level, file, function, line, object, &message,
593 g_free (message.message);
594 va_end (message.arguments);
598 * gst_debug_log_literal:
599 * @category: category to log
600 * @level: level of the message is in
601 * @file: the file that emitted the message, usually the __FILE__ identifier
602 * @function: the function that emitted the message
603 * @line: the line from that the message was emitted, usually __LINE__
604 * @object: (transfer none) (allow-none): the object this message relates to,
606 * @message_string: a message string
608 * Logs the given message using the currently registered debugging handlers.
613 gst_debug_log_literal (GstDebugCategory * category, GstDebugLevel level,
614 const gchar * file, const gchar * function, gint line,
615 GObject * object, const gchar * message_string)
617 GstDebugMessage message;
621 g_return_if_fail (category != NULL);
623 #ifdef GST_ENABLE_EXTRA_CHECKS
624 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
627 if (level > gst_debug_category_get_threshold (category))
630 g_return_if_fail (file != NULL);
631 g_return_if_fail (function != NULL);
632 g_return_if_fail (message_string != NULL);
634 message.message = (gchar *) message_string;
636 handler = __log_functions;
638 entry = handler->data;
639 handler = g_slist_next (handler);
640 entry->func (category, level, file, function, line, object, &message,
646 * gst_debug_message_get:
647 * @message: a debug message
649 * Gets the string representation of a #GstDebugMessage. This function is used
650 * in debug handlers to extract the message.
652 * Returns: (nullable): the string representation of a #GstDebugMessage.
655 gst_debug_message_get (GstDebugMessage * message)
657 if (message->message == NULL) {
660 len = __gst_vasprintf (&message->message, message->format,
664 message->message = NULL;
666 return message->message;
669 #define MAX_BUFFER_DUMP_STRING_LEN 100
671 /* structure_to_pretty_string:
672 * @str: a serialized #GstStructure
674 * If the serialized structure contains large buffers such as images the hex
675 * representation of those buffers will be shortened so that the string remains
678 * Returns: the filtered string
681 prettify_structure_string (gchar * str)
683 gchar *pos = str, *end;
685 while ((pos = strstr (pos, "(buffer)"))) {
688 pos += strlen ("(buffer)");
689 for (end = pos; *end != '\0' && *end != ';' && *end != ' '; ++end)
691 if (count > MAX_BUFFER_DUMP_STRING_LEN) {
692 memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 6, "..", 2);
693 memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 4, pos + count - 4, 4);
694 memmove (pos + MAX_BUFFER_DUMP_STRING_LEN, pos + count,
695 strlen (pos + count) + 1);
696 pos += MAX_BUFFER_DUMP_STRING_LEN;
703 static inline gchar *
704 gst_info_structure_to_string (const GstStructure * s)
707 gchar *str = gst_structure_to_string (s);
708 if (G_UNLIKELY (pretty_tags && s->name == GST_QUARK (TAGLIST)))
709 return prettify_structure_string (str);
716 static inline gchar *
717 gst_info_describe_buffer (GstBuffer * buffer)
719 const gchar *offset_str = "none";
720 const gchar *offset_end_str = "none";
721 gchar offset_buf[32], offset_end_buf[32];
723 if (GST_BUFFER_OFFSET_IS_VALID (buffer)) {
724 g_snprintf (offset_buf, sizeof (offset_buf), "%" G_GUINT64_FORMAT,
725 GST_BUFFER_OFFSET (buffer));
726 offset_str = offset_buf;
728 if (GST_BUFFER_OFFSET_END_IS_VALID (buffer)) {
729 g_snprintf (offset_end_buf, sizeof (offset_end_buf), "%" G_GUINT64_FORMAT,
730 GST_BUFFER_OFFSET_END (buffer));
731 offset_end_str = offset_end_buf;
734 return g_strdup_printf ("buffer: %p, pts %" GST_TIME_FORMAT ", dts %"
735 GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT
736 ", offset %s, offset_end %s, flags 0x%x", buffer,
737 GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
738 GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
739 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
740 gst_buffer_get_size (buffer), offset_str, offset_end_str,
741 GST_BUFFER_FLAGS (buffer));
744 static inline gchar *
745 gst_info_describe_buffer_list (GstBufferList * list)
747 GstClockTime pts = GST_CLOCK_TIME_NONE;
748 GstClockTime dts = GST_CLOCK_TIME_NONE;
749 gsize total_size = 0;
752 n = gst_buffer_list_length (list);
753 for (i = 0; i < n; ++i) {
754 GstBuffer *buf = gst_buffer_list_get (list, i);
757 pts = GST_BUFFER_PTS (buf);
758 dts = GST_BUFFER_DTS (buf);
761 total_size += gst_buffer_get_size (buf);
764 return g_strdup_printf ("bufferlist: %p, %u buffers, pts %" GST_TIME_FORMAT
765 ", dts %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT, list, n,
766 GST_TIME_ARGS (pts), GST_TIME_ARGS (dts), total_size);
769 static inline gchar *
770 gst_info_describe_event (GstEvent * event)
774 s = gst_info_structure_to_string (gst_event_get_structure (event));
775 ret = g_strdup_printf ("%s event: %p, time %" GST_TIME_FORMAT
776 ", seq-num %d, %s", GST_EVENT_TYPE_NAME (event), event,
777 GST_TIME_ARGS (GST_EVENT_TIMESTAMP (event)), GST_EVENT_SEQNUM (event),
783 static inline gchar *
784 gst_info_describe_message (GstMessage * message)
788 s = gst_info_structure_to_string (gst_message_get_structure (message));
789 ret = g_strdup_printf ("%s message: %p, time %" GST_TIME_FORMAT
790 ", seq-num %d, element '%s', %s", GST_MESSAGE_TYPE_NAME (message),
791 message, GST_TIME_ARGS (GST_MESSAGE_TIMESTAMP (message)),
792 GST_MESSAGE_SEQNUM (message),
793 ((message->src) ? GST_ELEMENT_NAME (message->src) : "(NULL)"),
799 static inline gchar *
800 gst_info_describe_query (GstQuery * query)
804 s = gst_info_structure_to_string (gst_query_get_structure (query));
805 ret = g_strdup_printf ("%s query: %p, %s", GST_QUERY_TYPE_NAME (query),
806 query, (s ? s : "(NULL)"));
811 static inline gchar *
812 gst_info_describe_stream (GstStream * stream)
814 gchar *ret, *caps_str = NULL, *tags_str = NULL;
818 caps = gst_stream_get_caps (stream);
820 caps_str = gst_caps_to_string (caps);
821 gst_caps_unref (caps);
824 tags = gst_stream_get_tags (stream);
826 tags_str = gst_tag_list_to_string (tags);
827 gst_tag_list_unref (tags);
831 g_strdup_printf ("stream %s %p, ID %s, flags 0x%x, caps [%s], tags [%s]",
832 gst_stream_type_get_name (gst_stream_get_stream_type (stream)), stream,
833 gst_stream_get_stream_id (stream), gst_stream_get_stream_flags (stream),
834 caps_str ? caps_str : "", tags_str ? tags_str : "");
842 static inline gchar *
843 gst_info_describe_stream_collection (GstStreamCollection * collection)
846 GString *streams_str;
849 streams_str = g_string_new ("<");
850 for (i = 0; i < gst_stream_collection_get_size (collection); i++) {
851 GstStream *stream = gst_stream_collection_get_stream (collection, i);
854 s = gst_info_describe_stream (stream);
855 g_string_append_printf (streams_str, " %s,", s);
858 g_string_append (streams_str, " >");
860 ret = g_strdup_printf ("collection %p (%d streams) %s", collection,
861 gst_stream_collection_get_size (collection), streams_str->str);
863 g_string_free (streams_str, TRUE);
868 gst_debug_print_object (gpointer ptr)
870 GObject *object = (GObject *) ptr;
873 /* This is a cute trick to detect unmapped memory, but is unportable,
874 * slow, screws around with madvise, and not actually that useful. */
878 ret = madvise ((void *) ((unsigned long) ptr & (~0xfff)), 4096, 0);
879 if (ret == -1 && errno == ENOMEM) {
880 buffer = g_strdup_printf ("%p (unmapped memory)", ptr);
885 /* nicely printed object */
886 if (object == NULL) {
887 return g_strdup ("(NULL)");
889 if (GST_IS_CAPS (ptr)) {
890 return gst_caps_to_string ((const GstCaps *) ptr);
892 if (GST_IS_STRUCTURE (ptr)) {
893 return gst_info_structure_to_string ((const GstStructure *) ptr);
895 if (*(GType *) ptr == GST_TYPE_CAPS_FEATURES) {
896 return gst_caps_features_to_string ((const GstCapsFeatures *) ptr);
898 if (GST_IS_TAG_LIST (ptr)) {
899 gchar *str = gst_tag_list_to_string ((GstTagList *) ptr);
900 if (G_UNLIKELY (pretty_tags))
901 return prettify_structure_string (str);
905 if (*(GType *) ptr == GST_TYPE_DATE_TIME) {
906 return __gst_date_time_serialize ((GstDateTime *) ptr, TRUE);
908 if (GST_IS_BUFFER (ptr)) {
909 return gst_info_describe_buffer (GST_BUFFER_CAST (ptr));
911 if (GST_IS_BUFFER_LIST (ptr)) {
912 return gst_info_describe_buffer_list (GST_BUFFER_LIST_CAST (ptr));
915 if (*(guint32 *) ptr == 0xffffffff) {
916 return g_strdup_printf ("<poisoned@%p>", ptr);
919 if (GST_IS_MESSAGE (object)) {
920 return gst_info_describe_message (GST_MESSAGE_CAST (object));
922 if (GST_IS_QUERY (object)) {
923 return gst_info_describe_query (GST_QUERY_CAST (object));
925 if (GST_IS_EVENT (object)) {
926 return gst_info_describe_event (GST_EVENT_CAST (object));
928 if (GST_IS_CONTEXT (object)) {
929 GstContext *context = GST_CONTEXT_CAST (object);
932 const GstStructure *structure;
934 type = gst_context_get_context_type (context);
935 structure = gst_context_get_structure (context);
937 s = gst_info_structure_to_string (structure);
939 ret = g_strdup_printf ("context '%s'='%s'", type, s);
943 if (GST_IS_STREAM (object)) {
944 return gst_info_describe_stream (GST_STREAM_CAST (object));
946 if (GST_IS_STREAM_COLLECTION (object)) {
948 gst_info_describe_stream_collection (GST_STREAM_COLLECTION_CAST
951 if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
952 return g_strdup_printf ("<%s:%s>", GST_DEBUG_PAD_NAME (object));
954 if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object)) {
955 return g_strdup_printf ("<%s>", GST_OBJECT_NAME (object));
957 if (G_IS_OBJECT (object)) {
958 return g_strdup_printf ("<%s@%p>", G_OBJECT_TYPE_NAME (object), object);
961 return g_strdup_printf ("%p", ptr);
965 gst_debug_print_segment (gpointer ptr)
967 GstSegment *segment = (GstSegment *) ptr;
969 /* nicely printed segment */
970 if (segment == NULL) {
971 return g_strdup ("(NULL)");
974 switch (segment->format) {
975 case GST_FORMAT_UNDEFINED:{
976 return g_strdup_printf ("UNDEFINED segment");
978 case GST_FORMAT_TIME:{
979 return g_strdup_printf ("time segment start=%" GST_TIME_FORMAT
980 ", offset=%" GST_TIME_FORMAT ", stop=%" GST_TIME_FORMAT
981 ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" GST_TIME_FORMAT
982 ", base=%" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT
983 ", duration %" GST_TIME_FORMAT, GST_TIME_ARGS (segment->start),
984 GST_TIME_ARGS (segment->offset), GST_TIME_ARGS (segment->stop),
985 segment->rate, segment->applied_rate, (guint) segment->flags,
986 GST_TIME_ARGS (segment->time), GST_TIME_ARGS (segment->base),
987 GST_TIME_ARGS (segment->position), GST_TIME_ARGS (segment->duration));
990 const gchar *format_name;
992 format_name = gst_format_get_name (segment->format);
993 if (G_UNLIKELY (format_name == NULL))
994 format_name = "(UNKNOWN FORMAT)";
995 return g_strdup_printf ("%s segment start=%" G_GINT64_FORMAT
996 ", offset=%" G_GINT64_FORMAT ", stop=%" G_GINT64_FORMAT
997 ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" G_GINT64_FORMAT
998 ", base=%" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT
999 ", duration %" G_GINT64_FORMAT, format_name, segment->start,
1000 segment->offset, segment->stop, segment->rate, segment->applied_rate,
1001 (guint) segment->flags, segment->time, segment->base,
1002 segment->position, segment->duration);
1008 gst_info_printf_pointer_extension_func (const char *format, void *ptr)
1012 if (format[0] == 'p' && format[1] == '\a') {
1013 switch (format[2]) {
1014 case 'A': /* GST_PTR_FORMAT */
1015 s = gst_debug_print_object (ptr);
1017 case 'B': /* GST_SEGMENT_FORMAT */
1018 s = gst_debug_print_segment (ptr);
1020 case 'T': /* GST_TIMEP_FORMAT */
1022 s = g_strdup_printf ("%" GST_TIME_FORMAT,
1023 GST_TIME_ARGS (*(GstClockTime *) ptr));
1025 case 'S': /* GST_STIMEP_FORMAT */
1027 s = g_strdup_printf ("%" GST_STIME_FORMAT,
1028 GST_STIME_ARGS (*(gint64 *) ptr));
1030 case 'a': /* GST_WRAPPED_PTR_FORMAT */
1031 s = priv_gst_string_take_and_wrap (gst_debug_print_object (ptr));
1034 /* must have been compiled against a newer version with an extension
1035 * we don't known about yet - just ignore and fallback to %p below */
1040 s = g_strdup_printf ("%p", ptr);
1046 * gst_debug_construct_term_color:
1047 * @colorinfo: the color info
1049 * Constructs a string that can be used for getting the desired color in color
1051 * You need to free the string after use.
1053 * Returns: (transfer full) (type gchar*): a string containing the color
1057 gst_debug_construct_term_color (guint colorinfo)
1061 color = g_string_new ("\033[00");
1063 if (colorinfo & GST_DEBUG_BOLD) {
1064 g_string_append_len (color, ";01", 3);
1066 if (colorinfo & GST_DEBUG_UNDERLINE) {
1067 g_string_append_len (color, ";04", 3);
1069 if (colorinfo & GST_DEBUG_FG_MASK) {
1070 g_string_append_printf (color, ";3%1d", colorinfo & GST_DEBUG_FG_MASK);
1072 if (colorinfo & GST_DEBUG_BG_MASK) {
1073 g_string_append_printf (color, ";4%1d",
1074 (colorinfo & GST_DEBUG_BG_MASK) >> 4);
1076 g_string_append_c (color, 'm');
1078 return g_string_free (color, FALSE);
1082 * gst_debug_construct_win_color:
1083 * @colorinfo: the color info
1085 * Constructs an integer that can be used for getting the desired color in
1086 * windows' terminals (cmd.exe). As there is no mean to underline, we simply
1087 * ignore this attribute.
1089 * This function returns 0 on non-windows machines.
1091 * Returns: an integer containing the color definition
1094 gst_debug_construct_win_color (guint colorinfo)
1098 static const guchar ansi_to_win_fg[8] = {
1100 FOREGROUND_RED, /* red */
1101 FOREGROUND_GREEN, /* green */
1102 FOREGROUND_RED | FOREGROUND_GREEN, /* yellow */
1103 FOREGROUND_BLUE, /* blue */
1104 FOREGROUND_RED | FOREGROUND_BLUE, /* magenta */
1105 FOREGROUND_GREEN | FOREGROUND_BLUE, /* cyan */
1106 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE /* white */
1108 static const guchar ansi_to_win_bg[8] = {
1112 BACKGROUND_RED | BACKGROUND_GREEN,
1114 BACKGROUND_RED | BACKGROUND_BLUE,
1115 BACKGROUND_GREEN | FOREGROUND_BLUE,
1116 BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
1119 /* we draw black as white, as cmd.exe can only have black bg */
1120 if ((colorinfo & (GST_DEBUG_FG_MASK | GST_DEBUG_BG_MASK)) == 0) {
1121 color = ansi_to_win_fg[7];
1123 if (colorinfo & GST_DEBUG_UNDERLINE) {
1124 color |= BACKGROUND_INTENSITY;
1126 if (colorinfo & GST_DEBUG_BOLD) {
1127 color |= FOREGROUND_INTENSITY;
1129 if (colorinfo & GST_DEBUG_FG_MASK) {
1130 color |= ansi_to_win_fg[colorinfo & GST_DEBUG_FG_MASK];
1132 if (colorinfo & GST_DEBUG_BG_MASK) {
1133 color |= ansi_to_win_bg[(colorinfo & GST_DEBUG_BG_MASK) >> 4];
1139 /* width of %p varies depending on actual value of pointer, which can make
1140 * output unevenly aligned if multiple threads are involved, hence the %14p
1141 * (should really be %18p, but %14p seems a good compromise between too many
1142 * white spaces and likely unalignment on my system) */
1143 #if defined (GLIB_SIZEOF_VOID_P) && GLIB_SIZEOF_VOID_P == 8
1144 #define PTR_FMT "%14p"
1146 #define PTR_FMT "%10p"
1149 #define PID_FMT "%5lu"
1151 #define PID_FMT "%5d"
1153 #define CAT_FMT "%20s %s:%d:%s:%s"
1154 #define NOCOLOR_PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
1157 static const guchar levelcolormap_w32[GST_LEVEL_COUNT] = {
1158 /* GST_LEVEL_NONE */
1159 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1160 /* GST_LEVEL_ERROR */
1161 FOREGROUND_RED | FOREGROUND_INTENSITY,
1162 /* GST_LEVEL_WARNING */
1163 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1164 /* GST_LEVEL_INFO */
1165 FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1166 /* GST_LEVEL_DEBUG */
1167 FOREGROUND_GREEN | FOREGROUND_BLUE,
1169 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1170 /* GST_LEVEL_FIXME */
1171 FOREGROUND_RED | FOREGROUND_GREEN,
1172 /* GST_LEVEL_TRACE */
1173 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1174 /* placeholder for log level 8 */
1176 /* GST_LEVEL_MEMDUMP */
1177 FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
1180 static const guchar available_colors[] = {
1181 FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_RED | FOREGROUND_GREEN,
1182 FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_BLUE,
1183 FOREGROUND_GREEN | FOREGROUND_BLUE,
1185 #endif /* G_OS_WIN32 */
1186 static const gchar *levelcolormap[GST_LEVEL_COUNT] = {
1187 "\033[37m", /* GST_LEVEL_NONE */
1188 "\033[31;01m", /* GST_LEVEL_ERROR */
1189 "\033[33;01m", /* GST_LEVEL_WARNING */
1190 "\033[32;01m", /* GST_LEVEL_INFO */
1191 "\033[36m", /* GST_LEVEL_DEBUG */
1192 "\033[37m", /* GST_LEVEL_LOG */
1193 "\033[33;01m", /* GST_LEVEL_FIXME */
1194 "\033[37m", /* GST_LEVEL_TRACE */
1195 "\033[37m", /* placeholder for log level 8 */
1196 "\033[37m" /* GST_LEVEL_MEMDUMP */
1200 _gst_debug_log_preamble (GstDebugMessage * message, GObject * object,
1201 const gchar ** file, const gchar ** message_str, gchar ** obj_str,
1202 GstClockTime * elapsed)
1206 /* Get message string first because printing it might call into our custom
1207 * printf format extension mechanism which in turn might log something, e.g.
1208 * from inside gst_structure_to_string() when something can't be serialised.
1209 * This means we either need to do this outside of any critical section or
1210 * use a recursive lock instead. As we always need the message string in all
1211 * code paths, we might just as well get it here first thing and outside of
1212 * the win_print_mutex critical section. */
1213 *message_str = gst_debug_message_get (message);
1215 /* __FILE__ might be a file name or an absolute path or a
1216 * relative path, irrespective of the exact compiler used,
1217 * in which case we want to shorten it to the filename for
1220 if (c == '.' || c == '/' || c == '\\' || (c != '\0' && (*file)[1] == ':')) {
1221 *file = gst_path_basename (*file);
1225 *obj_str = gst_debug_print_object (object);
1227 *obj_str = (gchar *) "";
1230 *elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
1234 * gst_debug_log_get_line:
1235 * @category: category to log
1236 * @level: level of the message
1237 * @file: the file that emitted the message, usually the __FILE__ identifier
1238 * @function: the function that emitted the message
1239 * @line: the line from that the message was emitted, usually __LINE__
1240 * @object: (transfer none) (allow-none): the object this message relates to,
1242 * @message: the actual message
1244 * Returns the string representation for the specified debug log message
1245 * formatted in the same way as gst_debug_log_default() (the default handler),
1246 * without color. The purpose is to make it easy for custom log output
1247 * handlers to get a log output that is identical to what the default handler
1253 gst_debug_log_get_line (GstDebugCategory * category, GstDebugLevel level,
1254 const gchar * file, const gchar * function, gint line,
1255 GObject * object, GstDebugMessage * message)
1257 GstClockTime elapsed;
1258 gchar *ret, *obj_str = NULL;
1259 const gchar *message_str;
1261 #ifdef GST_ENABLE_EXTRA_CHECKS
1262 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1265 _gst_debug_log_preamble (message, object, &file, &message_str, &obj_str,
1268 ret = g_strdup_printf ("%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1269 GST_TIME_ARGS (elapsed), _gst_getpid (), g_thread_self (),
1270 gst_debug_level_get_name (level), gst_debug_category_get_name
1271 (category), file, line, function, obj_str, message_str);
1280 _gst_debug_fprintf (FILE * file, const gchar * format, ...)
1286 va_start (args, format);
1287 length = gst_info_vasprintf (&str, format, args);
1290 if (length == 0 || !str)
1293 /* Even if it's valid UTF-8 string, console might print broken string
1294 * depending on codepage and the content of the given string.
1295 * Fortunately, g_print* family will take care of the Windows' codepage
1296 * specific behavior.
1298 if (file == stderr) {
1299 g_printerr ("%s", str);
1300 } else if (file == stdout) {
1301 g_print ("%s", str);
1303 /* We are writing to file. Text editors/viewers should be able to
1304 * decode valid UTF-8 string regardless of codepage setting */
1305 fwrite (str, 1, length, file);
1307 /* FIXME: fflush here might be redundant if setvbuf works as expected */
1316 * gst_debug_log_default:
1317 * @category: category to log
1318 * @level: level of the message
1319 * @file: the file that emitted the message, usually the __FILE__ identifier
1320 * @function: the function that emitted the message
1321 * @line: the line from that the message was emitted, usually __LINE__
1322 * @message: the actual message
1323 * @object: (transfer none) (allow-none): the object this message relates to,
1325 * @user_data: the FILE* to log to
1327 * The default logging handler used by GStreamer. Logging functions get called
1328 * whenever a macro like GST_DEBUG or similar is used. By default this function
1329 * is setup to output the message and additional info to stderr (or the log file
1330 * specified via the GST_DEBUG_FILE environment variable) as received via
1333 * You can add other handlers by using gst_debug_add_log_function().
1334 * And you can remove this handler by calling
1335 * gst_debug_remove_log_function(gst_debug_log_default);
1338 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
1339 const gchar * file, const gchar * function, gint line,
1340 GObject * object, GstDebugMessage * message, gpointer user_data)
1343 GstClockTime elapsed;
1345 GstDebugColorMode color_mode;
1346 const gchar *message_str;
1347 FILE *log_file = user_data ? user_data : stderr;
1349 #define FPRINTF_DEBUG _gst_debug_fprintf
1350 /* _gst_debug_fprintf will do fflush if it's required */
1351 #define FFLUSH_DEBUG(f) ((void)(f))
1353 #define FPRINTF_DEBUG fprintf
1354 #define FFLUSH_DEBUG(f) G_STMT_START { \
1359 #ifdef GST_ENABLE_EXTRA_CHECKS
1360 g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1363 _gst_debug_log_preamble (message, object, &file, &message_str, &obj,
1366 pid = _gst_getpid ();
1367 color_mode = gst_debug_get_color_mode ();
1369 if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
1371 G_LOCK (win_print_mutex);
1372 if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
1374 /* colors, non-windows */
1375 gchar *color = NULL;
1378 const gchar *levelcolor;
1380 color = gst_debug_construct_term_color (gst_debug_category_get_color
1383 g_sprintf (pidcolor, "\033[%02dm", pid % 6 + 31);
1384 levelcolor = levelcolormap[level];
1386 #define PRINT_FMT " %s"PID_FMT"%s "PTR_FMT" %s%s%s %s"CAT_FMT"%s %s\n"
1387 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT PRINT_FMT,
1388 GST_TIME_ARGS (elapsed), pidcolor, pid, clear, g_thread_self (),
1389 levelcolor, gst_debug_level_get_name (level), clear, color,
1390 gst_debug_category_get_name (category), file, line, function, obj,
1391 clear, message_str);
1392 FFLUSH_DEBUG (log_file);
1397 /* colors, windows. */
1398 const gint clear = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
1399 #define SET_COLOR(c) G_STMT_START { \
1400 if (log_file == stderr) \
1401 SetConsoleTextAttribute (GetStdHandle (STD_ERROR_HANDLE), (c)); \
1404 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT " ",
1405 GST_TIME_ARGS (elapsed));
1407 SET_COLOR (available_colors[pid % G_N_ELEMENTS (available_colors)]);
1408 FPRINTF_DEBUG (log_file, PID_FMT, pid);
1411 FPRINTF_DEBUG (log_file, " " PTR_FMT " ", g_thread_self ());
1413 SET_COLOR (levelcolormap_w32[level]);
1414 FPRINTF_DEBUG (log_file, "%s ", gst_debug_level_get_name (level));
1416 SET_COLOR (gst_debug_construct_win_color (gst_debug_category_get_color
1418 FPRINTF_DEBUG (log_file, CAT_FMT, gst_debug_category_get_name (category),
1419 file, line, function, obj);
1422 FPRINTF_DEBUG (log_file, " %s\n", message_str);
1424 G_UNLOCK (win_print_mutex);
1427 /* no color, all platforms */
1428 FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1429 GST_TIME_ARGS (elapsed), pid, g_thread_self (),
1430 gst_debug_level_get_name (level),
1431 gst_debug_category_get_name (category), file, line, function, obj,
1433 FFLUSH_DEBUG (log_file);
1441 * gst_debug_level_get_name:
1442 * @level: the level to get the name for
1444 * Get the string representation of a debugging level
1449 gst_debug_level_get_name (GstDebugLevel level)
1452 case GST_LEVEL_NONE:
1454 case GST_LEVEL_ERROR:
1456 case GST_LEVEL_WARNING:
1458 case GST_LEVEL_INFO:
1460 case GST_LEVEL_DEBUG:
1464 case GST_LEVEL_FIXME:
1466 case GST_LEVEL_TRACE:
1468 case GST_LEVEL_MEMDUMP:
1471 g_warning ("invalid level specified for gst_debug_level_get_name");
1477 * gst_debug_add_log_function:
1478 * @func: the function to use
1479 * @user_data: user data
1480 * @notify: called when @user_data is not used anymore
1482 * Adds the logging function to the list of logging functions.
1483 * Be sure to use #G_GNUC_NO_INSTRUMENT on that function, it is needed.
1486 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
1487 GDestroyNotify notify)
1489 LogFuncEntry *entry;
1493 func = gst_debug_log_default;
1495 entry = g_slice_new (LogFuncEntry);
1497 entry->user_data = user_data;
1498 entry->notify = notify;
1499 /* FIXME: we leak the old list here - other threads might access it right now
1500 * in gst_debug_logv. Another solution is to lock the mutex in gst_debug_logv,
1501 * but that is waaay costly.
1502 * It'd probably be clever to use some kind of RCU here, but I don't know
1503 * anything about that.
1505 g_mutex_lock (&__log_func_mutex);
1506 list = g_slist_copy (__log_functions);
1507 __log_functions = g_slist_prepend (list, entry);
1508 g_mutex_unlock (&__log_func_mutex);
1510 if (gst_is_initialized ())
1511 GST_DEBUG ("prepended log function %p (user data %p) to log functions",
1516 gst_debug_compare_log_function_by_func (gconstpointer entry, gconstpointer func)
1518 gpointer entryfunc = (gpointer) (((LogFuncEntry *) entry)->func);
1520 return (entryfunc < func) ? -1 : (entryfunc > func) ? 1 : 0;
1524 gst_debug_compare_log_function_by_data (gconstpointer entry, gconstpointer data)
1526 gpointer entrydata = ((LogFuncEntry *) entry)->user_data;
1528 return (entrydata < data) ? -1 : (entrydata > data) ? 1 : 0;
1532 gst_debug_remove_with_compare_func (GCompareFunc func, gpointer data)
1535 GSList *new, *cleanup = NULL;
1538 g_mutex_lock (&__log_func_mutex);
1539 new = __log_functions;
1541 while ((found = g_slist_find_custom (new, data, func))) {
1542 if (new == __log_functions) {
1543 /* make a copy when we have the first hit, so that we modify the copy and
1544 * make that the new list later */
1545 new = g_slist_copy (new);
1548 cleanup = g_slist_prepend (cleanup, found->data);
1549 new = g_slist_delete_link (new, found);
1552 /* FIXME: We leak the old list here. See _add_log_function for why. */
1553 __log_functions = new;
1554 g_mutex_unlock (&__log_func_mutex);
1557 LogFuncEntry *entry = cleanup->data;
1560 entry->notify (entry->user_data);
1562 g_slice_free (LogFuncEntry, entry);
1563 cleanup = g_slist_delete_link (cleanup, cleanup);
1569 * gst_debug_remove_log_function:
1570 * @func: (scope call) (allow-none): the log function to remove, or %NULL to
1571 * remove the default log function
1573 * Removes all registered instances of the given logging functions.
1575 * Returns: How many instances of the function were removed
1578 gst_debug_remove_log_function (GstLogFunction func)
1583 func = gst_debug_log_default;
1586 gst_debug_remove_with_compare_func
1587 (gst_debug_compare_log_function_by_func, (gpointer) func);
1589 if (gst_is_initialized ()) {
1590 GST_DEBUG ("removed log function %p %d times from log function list", func,
1593 /* If the default log function is removed before gst_init() was called,
1594 * set a flag so we don't add it in gst_init() later */
1595 if (func == gst_debug_log_default) {
1596 add_default_log_func = FALSE;
1605 * gst_debug_remove_log_function_by_data:
1606 * @data: user data of the log function to remove
1608 * Removes all registered instances of log functions with the given user data.
1610 * Returns: How many instances of the function were removed
1613 gst_debug_remove_log_function_by_data (gpointer data)
1618 gst_debug_remove_with_compare_func
1619 (gst_debug_compare_log_function_by_data, data);
1621 if (gst_is_initialized ())
1623 ("removed %d log functions with user data %p from log function list",
1630 * gst_debug_set_colored:
1631 * @colored: Whether to use colored output or not
1633 * Sets or unsets the use of coloured debugging output.
1634 * Same as gst_debug_set_color_mode () with the argument being
1635 * being GST_DEBUG_COLOR_MODE_ON or GST_DEBUG_COLOR_MODE_OFF.
1637 * This function may be called before gst_init().
1640 gst_debug_set_colored (gboolean colored)
1642 GstDebugColorMode new_mode;
1643 new_mode = colored ? GST_DEBUG_COLOR_MODE_ON : GST_DEBUG_COLOR_MODE_OFF;
1644 g_atomic_int_set (&__use_color, (gint) new_mode);
1648 * gst_debug_set_color_mode:
1649 * @mode: The coloring mode for debug output. See @GstDebugColorMode.
1651 * Changes the coloring mode for debug output.
1653 * This function may be called before gst_init().
1658 gst_debug_set_color_mode (GstDebugColorMode mode)
1660 g_atomic_int_set (&__use_color, mode);
1664 * gst_debug_set_color_mode_from_string:
1665 * @mode: The coloring mode for debug output. One of the following:
1666 * "on", "auto", "off", "disable", "unix".
1668 * Changes the coloring mode for debug output.
1670 * This function may be called before gst_init().
1675 gst_debug_set_color_mode_from_string (const gchar * mode)
1677 if ((strcmp (mode, "on") == 0) || (strcmp (mode, "auto") == 0))
1678 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_ON);
1679 else if ((strcmp (mode, "off") == 0) || (strcmp (mode, "disable") == 0))
1680 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
1681 else if (strcmp (mode, "unix") == 0)
1682 gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_UNIX);
1686 * gst_debug_is_colored:
1688 * Checks if the debugging output should be colored.
1690 * Returns: %TRUE, if the debug output should be colored.
1693 gst_debug_is_colored (void)
1695 GstDebugColorMode mode = g_atomic_int_get (&__use_color);
1696 return (mode == GST_DEBUG_COLOR_MODE_UNIX || mode == GST_DEBUG_COLOR_MODE_ON);
1700 * gst_debug_get_color_mode:
1702 * Changes the coloring mode for debug output.
1704 * Returns: see @GstDebugColorMode for possible values.
1709 gst_debug_get_color_mode (void)
1711 return g_atomic_int_get (&__use_color);
1715 * gst_debug_set_active:
1716 * @active: Whether to use debugging output or not
1718 * If activated, debugging messages are sent to the debugging
1720 * It makes sense to deactivate it for speed issues.
1721 * > This function is not threadsafe. It makes sense to only call it
1722 * during initialization.
1725 gst_debug_set_active (gboolean active)
1727 _gst_debug_enabled = active;
1729 _gst_debug_min = GST_LEVEL_COUNT;
1731 _gst_debug_min = GST_LEVEL_NONE;
1735 * gst_debug_is_active:
1737 * Checks if debugging output is activated.
1739 * Returns: %TRUE, if debugging is activated
1742 gst_debug_is_active (void)
1744 return _gst_debug_enabled;
1748 * gst_debug_set_default_threshold:
1749 * @level: level to set
1751 * Sets the default threshold to the given level and updates all categories to
1752 * use this threshold.
1754 * This function may be called before gst_init().
1757 gst_debug_set_default_threshold (GstDebugLevel level)
1759 g_atomic_int_set (&__default_level, level);
1760 gst_debug_reset_all_thresholds ();
1764 * gst_debug_get_default_threshold:
1766 * Returns the default threshold that is used for new categories.
1768 * Returns: the default threshold level
1771 gst_debug_get_default_threshold (void)
1773 return (GstDebugLevel) g_atomic_int_get (&__default_level);
1776 #if !GLIB_CHECK_VERSION(2,70,0)
1777 #define g_pattern_spec_match_string g_pattern_match_string
1781 gst_debug_apply_entry (GstDebugCategory * cat, LevelNameEntry * entry)
1783 if (!g_pattern_spec_match_string (entry->pat, cat->name))
1786 if (gst_is_initialized ())
1787 GST_LOG ("category %s matches pattern %p - gets set to level %d",
1788 cat->name, entry->pat, entry->level);
1790 gst_debug_category_set_threshold (cat, entry->level);
1795 gst_debug_reset_threshold (gpointer category, gpointer unused)
1797 GstDebugCategory *cat = (GstDebugCategory *) category;
1800 g_mutex_lock (&__level_name_mutex);
1802 for (walk = __level_name; walk != NULL; walk = walk->next) {
1803 if (gst_debug_apply_entry (cat, walk->data))
1807 g_mutex_unlock (&__level_name_mutex);
1810 gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
1814 gst_debug_reset_all_thresholds (void)
1816 g_mutex_lock (&__cat_mutex);
1817 g_slist_foreach (__categories, gst_debug_reset_threshold, NULL);
1818 g_mutex_unlock (&__cat_mutex);
1822 for_each_threshold_by_entry (gpointer data, gpointer user_data)
1824 GstDebugCategory *cat = (GstDebugCategory *) data;
1825 LevelNameEntry *entry = (LevelNameEntry *) user_data;
1827 gst_debug_apply_entry (cat, entry);
1831 * gst_debug_set_threshold_for_name:
1832 * @name: name of the categories to set
1833 * @level: level to set them to
1835 * Sets all categories which match the given glob style pattern to the given
1839 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
1842 LevelNameEntry *entry;
1844 g_return_if_fail (name != NULL);
1846 pat = g_pattern_spec_new (name);
1847 entry = g_slice_new (LevelNameEntry);
1849 entry->level = level;
1850 g_mutex_lock (&__level_name_mutex);
1851 __level_name = g_slist_prepend (__level_name, entry);
1852 g_mutex_unlock (&__level_name_mutex);
1853 g_mutex_lock (&__cat_mutex);
1854 g_slist_foreach (__categories, for_each_threshold_by_entry, entry);
1855 g_mutex_unlock (&__cat_mutex);
1859 * gst_debug_unset_threshold_for_name:
1860 * @name: name of the categories to set
1862 * Resets all categories with the given name back to the default level.
1865 gst_debug_unset_threshold_for_name (const gchar * name)
1870 g_return_if_fail (name != NULL);
1872 pat = g_pattern_spec_new (name);
1873 g_mutex_lock (&__level_name_mutex);
1874 walk = __level_name;
1875 /* improve this if you want, it's mighty slow */
1877 LevelNameEntry *entry = walk->data;
1879 if (g_pattern_spec_equal (entry->pat, pat)) {
1880 __level_name = g_slist_remove_link (__level_name, walk);
1881 g_pattern_spec_free (entry->pat);
1882 g_slice_free (LevelNameEntry, entry);
1883 g_slist_free_1 (walk);
1884 walk = __level_name;
1886 walk = g_slist_next (walk);
1889 g_mutex_unlock (&__level_name_mutex);
1890 g_pattern_spec_free (pat);
1891 gst_debug_reset_all_thresholds ();
1895 _gst_debug_category_new (const gchar * name, guint color,
1896 const gchar * description)
1898 GstDebugCategory *cat, *catfound;
1900 g_return_val_if_fail (name != NULL, NULL);
1902 cat = g_slice_new (GstDebugCategory);
1903 cat->name = g_strdup (name);
1905 if (description != NULL) {
1906 cat->description = g_strdup (description);
1908 cat->description = g_strdup ("no description");
1910 g_atomic_int_set (&cat->threshold, 0);
1911 gst_debug_reset_threshold (cat, NULL);
1913 /* add to category list */
1914 g_mutex_lock (&__cat_mutex);
1915 catfound = _gst_debug_get_category_locked (name);
1917 g_free ((gpointer) cat->name);
1918 g_free ((gpointer) cat->description);
1919 g_slice_free (GstDebugCategory, cat);
1922 __categories = g_slist_prepend (__categories, cat);
1924 g_mutex_unlock (&__cat_mutex);
1929 #ifndef GST_REMOVE_DEPRECATED
1931 * gst_debug_category_free:
1932 * @category: #GstDebugCategory to free.
1934 * Removes and frees the category and all associated resources.
1936 * Deprecated: This function can easily cause memory corruption, don't use it.
1939 gst_debug_category_free (GstDebugCategory * category)
1945 * gst_debug_category_set_threshold:
1946 * @category: a #GstDebugCategory to set threshold of.
1947 * @level: the #GstDebugLevel threshold to set.
1949 * Sets the threshold of the category to the given level. Debug information will
1950 * only be output if the threshold is lower or equal to the level of the
1951 * debugging message.
1952 * > Do not use this function in production code, because other functions may
1953 * > change the threshold of categories as side effect. It is however a nice
1954 * > function to use when debugging (even from gdb).
1957 gst_debug_category_set_threshold (GstDebugCategory * category,
1958 GstDebugLevel level)
1960 g_return_if_fail (category != NULL);
1962 if (level > _gst_debug_min) {
1963 _gst_debug_enabled = TRUE;
1964 _gst_debug_min = level;
1967 g_atomic_int_set (&category->threshold, level);
1971 * gst_debug_category_reset_threshold:
1972 * @category: a #GstDebugCategory to reset threshold of.
1974 * Resets the threshold of the category to the default level. Debug information
1975 * will only be output if the threshold is lower or equal to the level of the
1976 * debugging message.
1977 * Use this function to set the threshold back to where it was after using
1978 * gst_debug_category_set_threshold().
1981 gst_debug_category_reset_threshold (GstDebugCategory * category)
1983 gst_debug_reset_threshold (category, NULL);
1987 * gst_debug_category_get_threshold:
1988 * @category: a #GstDebugCategory to get threshold of.
1990 * Returns the threshold of a #GstDebugCategory.
1992 * Returns: the #GstDebugLevel that is used as threshold.
1995 gst_debug_category_get_threshold (GstDebugCategory * category)
1997 return (GstDebugLevel) g_atomic_int_get (&category->threshold);
2001 * gst_debug_category_get_name:
2002 * @category: a #GstDebugCategory to get name of.
2004 * Returns the name of a debug category.
2006 * Returns: the name of the category.
2009 gst_debug_category_get_name (GstDebugCategory * category)
2011 return category->name;
2015 * gst_debug_category_get_color:
2016 * @category: a #GstDebugCategory to get the color of.
2018 * Returns the color of a debug category used when printing output in this
2021 * Returns: the color of the category.
2024 gst_debug_category_get_color (GstDebugCategory * category)
2026 return category->color;
2030 * gst_debug_category_get_description:
2031 * @category: a #GstDebugCategory to get the description of.
2033 * Returns the description of a debug category.
2035 * Returns: the description of the category.
2038 gst_debug_category_get_description (GstDebugCategory * category)
2040 return category->description;
2044 * gst_debug_get_all_categories:
2046 * Returns a snapshot of a all categories that are currently in use . This list
2047 * may change anytime.
2048 * The caller has to free the list after use.
2050 * Returns: (transfer container) (element-type Gst.DebugCategory): the list of
2054 gst_debug_get_all_categories (void)
2058 g_mutex_lock (&__cat_mutex);
2059 ret = g_slist_copy (__categories);
2060 g_mutex_unlock (&__cat_mutex);
2065 static GstDebugCategory *
2066 _gst_debug_get_category_locked (const gchar * name)
2068 GstDebugCategory *ret = NULL;
2071 for (node = __categories; node; node = g_slist_next (node)) {
2072 ret = (GstDebugCategory *) node->data;
2073 if (!strcmp (name, ret->name)) {
2081 _gst_debug_get_category (const gchar * name)
2083 GstDebugCategory *ret;
2085 g_mutex_lock (&__cat_mutex);
2086 ret = _gst_debug_get_category_locked (name);
2087 g_mutex_unlock (&__cat_mutex);
2093 parse_debug_category (gchar * str, const gchar ** category)
2098 /* works in place */
2101 if (str[0] != '\0') {
2110 parse_debug_level (gchar * str, GstDebugLevel * level)
2115 /* works in place */
2118 if (g_ascii_isdigit (str[0])) {
2121 l = strtoul (str, &endptr, 10);
2122 if (endptr > str && endptr[0] == 0) {
2123 *level = (GstDebugLevel) l;
2127 } else if (strcmp (str, "NONE") == 0) {
2128 *level = GST_LEVEL_NONE;
2129 } else if (strcmp (str, "ERROR") == 0) {
2130 *level = GST_LEVEL_ERROR;
2131 } else if (strncmp (str, "WARN", 4) == 0) {
2132 *level = GST_LEVEL_WARNING;
2133 } else if (strcmp (str, "FIXME") == 0) {
2134 *level = GST_LEVEL_FIXME;
2135 } else if (strcmp (str, "INFO") == 0) {
2136 *level = GST_LEVEL_INFO;
2137 } else if (strcmp (str, "DEBUG") == 0) {
2138 *level = GST_LEVEL_DEBUG;
2139 } else if (strcmp (str, "LOG") == 0) {
2140 *level = GST_LEVEL_LOG;
2141 } else if (strcmp (str, "TRACE") == 0) {
2142 *level = GST_LEVEL_TRACE;
2143 } else if (strcmp (str, "MEMDUMP") == 0) {
2144 *level = GST_LEVEL_MEMDUMP;
2152 * gst_debug_set_threshold_from_string:
2153 * @list: comma-separated list of "category:level" pairs to be used
2154 * as debug logging levels
2155 * @reset: %TRUE to clear all previously-set debug levels before setting
2157 * %FALSE if adding the threshold described by @list to the one already set.
2159 * Sets the debug logging wanted in the same form as with the GST_DEBUG
2160 * environment variable. You can use wildcards such as '*', but note that
2161 * the order matters when you use wild cards, e.g. "foosrc:6,*src:3,*:2" sets
2162 * everything to log level 2.
2167 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2175 gst_debug_set_default_threshold (GST_LEVEL_DEFAULT);
2177 split = g_strsplit (list, ",", 0);
2179 for (walk = split; *walk; walk++) {
2180 if (strchr (*walk, ':')) {
2181 gchar **values = g_strsplit (*walk, ":", 2);
2183 if (values[0] && values[1]) {
2184 GstDebugLevel level;
2185 const gchar *category;
2187 if (parse_debug_category (values[0], &category)
2188 && parse_debug_level (values[1], &level)) {
2189 gst_debug_set_threshold_for_name (category, level);
2191 /* bump min-level anyway to allow the category to be registered in the
2193 if (level > _gst_debug_min) {
2194 _gst_debug_min = level;
2199 g_strfreev (values);
2201 GstDebugLevel level;
2203 if (parse_debug_level (*walk, &level))
2204 gst_debug_set_default_threshold (level);
2211 /*** FUNCTION POINTERS ********************************************************/
2213 static GHashTable *__gst_function_pointers; /* NULL */
2214 static GMutex __dbg_functions_mutex;
2216 /* This function MUST NOT return NULL */
2218 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2226 if (G_UNLIKELY (func == NULL))
2229 g_mutex_lock (&__dbg_functions_mutex);
2230 if (G_LIKELY (__gst_function_pointers)) {
2231 ptrname = g_hash_table_lookup (__gst_function_pointers, (gpointer) func);
2232 g_mutex_unlock (&__dbg_functions_mutex);
2233 if (G_LIKELY (ptrname))
2236 g_mutex_unlock (&__dbg_functions_mutex);
2238 /* we need to create an entry in the hash table for this one so we don't leak
2241 if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
2242 const gchar *name = g_intern_string (dl_info.dli_sname);
2244 _gst_debug_register_funcptr (func, name);
2249 gchar *name = g_strdup_printf ("%p", (gpointer) func);
2250 const gchar *iname = g_intern_string (name);
2254 _gst_debug_register_funcptr (func, iname);
2260 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2262 gpointer ptr = (gpointer) func;
2264 g_mutex_lock (&__dbg_functions_mutex);
2266 if (!__gst_function_pointers)
2267 __gst_function_pointers = g_hash_table_new (g_direct_hash, g_direct_equal);
2268 if (!g_hash_table_lookup (__gst_function_pointers, ptr)) {
2269 g_hash_table_insert (__gst_function_pointers, ptr, (gpointer) ptrname);
2272 g_mutex_unlock (&__dbg_functions_mutex);
2276 _priv_gst_debug_cleanup (void)
2278 g_mutex_lock (&__dbg_functions_mutex);
2280 if (__gst_function_pointers) {
2281 g_hash_table_unref (__gst_function_pointers);
2282 __gst_function_pointers = NULL;
2285 g_mutex_unlock (&__dbg_functions_mutex);
2287 g_mutex_lock (&__cat_mutex);
2288 while (__categories) {
2289 GstDebugCategory *cat = __categories->data;
2290 g_free ((gpointer) cat->name);
2291 g_free ((gpointer) cat->description);
2292 g_slice_free (GstDebugCategory, cat);
2293 __categories = g_slist_delete_link (__categories, __categories);
2295 g_mutex_unlock (&__cat_mutex);
2297 g_mutex_lock (&__level_name_mutex);
2298 while (__level_name) {
2299 LevelNameEntry *level_name_entry = __level_name->data;
2300 g_pattern_spec_free (level_name_entry->pat);
2301 g_slice_free (LevelNameEntry, level_name_entry);
2302 __level_name = g_slist_delete_link (__level_name, __level_name);
2304 g_mutex_unlock (&__level_name_mutex);
2306 g_mutex_lock (&__log_func_mutex);
2307 while (__log_functions) {
2308 LogFuncEntry *log_func_entry = __log_functions->data;
2309 if (log_func_entry->notify)
2310 log_func_entry->notify (log_func_entry->user_data);
2311 g_slice_free (LogFuncEntry, log_func_entry);
2312 __log_functions = g_slist_delete_link (__log_functions, __log_functions);
2314 g_mutex_unlock (&__log_func_mutex);
2318 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2319 const guint8 * mem, gsize mem_offset, gsize mem_size)
2321 gchar hexstr[50], ascstr[18], digitstr[4];
2333 while (i < mem_size) {
2334 ascstr[i] = (g_ascii_isprint (mem[i])) ? mem[i] : '.';
2335 g_snprintf (digitstr, sizeof (digitstr), "%02x ", mem[i]);
2336 g_strlcat (hexstr, digitstr, sizeof (hexstr));
2342 g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2343 (guint) mem_offset, hexstr, ascstr);
2347 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2348 const gchar * func, gint line, GObject * obj, const gchar * msg,
2349 const guint8 * data, guint length)
2353 gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2354 "-------------------------------------------------------------------");
2356 if (msg != NULL && *msg != '\0') {
2357 gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", msg);
2360 while (off < length) {
2363 /* gst_info_dump_mem_line will process 16 bytes at most */
2364 gst_info_dump_mem_line (buf, sizeof (buf), data, off, length - off);
2365 gst_debug_log (cat, GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", buf);
2369 gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2370 "-------------------------------------------------------------------");
2373 #else /* !GST_DISABLE_GST_DEBUG */
2374 #ifndef GST_REMOVE_DISABLED
2377 _gst_debug_category_new (const gchar * name, guint color,
2378 const gchar * description)
2384 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2388 /* This function MUST NOT return NULL */
2390 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2396 _priv_gst_debug_cleanup (void)
2401 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2402 const gchar * file, const gchar * function, gint line,
2403 GObject * object, const gchar * format, ...)
2408 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
2409 const gchar * file, const gchar * function, gint line,
2410 GObject * object, const gchar * format, va_list args)
2415 gst_debug_log_literal (GstDebugCategory * category, GstDebugLevel level,
2416 const gchar * file, const gchar * function, gint line,
2417 GObject * object, const gchar * message_string)
2422 gst_debug_message_get (GstDebugMessage * message)
2428 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
2429 const gchar * file, const gchar * function, gint line,
2430 GObject * object, GstDebugMessage * message, gpointer unused)
2435 gst_debug_level_get_name (GstDebugLevel level)
2441 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2442 GDestroyNotify notify)
2449 gst_debug_remove_log_function (GstLogFunction func)
2455 gst_debug_remove_log_function_by_data (gpointer data)
2461 gst_debug_set_active (gboolean active)
2466 gst_debug_is_active (void)
2472 gst_debug_set_colored (gboolean colored)
2477 gst_debug_set_color_mode (GstDebugColorMode mode)
2482 gst_debug_set_color_mode_from_string (const gchar * str)
2487 gst_debug_is_colored (void)
2493 gst_debug_get_color_mode (void)
2495 return GST_DEBUG_COLOR_MODE_OFF;
2499 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2504 gst_debug_set_default_threshold (GstDebugLevel level)
2509 gst_debug_get_default_threshold (void)
2511 return GST_LEVEL_NONE;
2515 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2520 gst_debug_unset_threshold_for_name (const gchar * name)
2524 #ifndef GST_REMOVE_DEPRECATED
2526 gst_debug_category_free (GstDebugCategory * category)
2532 gst_debug_category_set_threshold (GstDebugCategory * category,
2533 GstDebugLevel level)
2538 gst_debug_category_reset_threshold (GstDebugCategory * category)
2543 gst_debug_category_get_threshold (GstDebugCategory * category)
2545 return GST_LEVEL_NONE;
2549 gst_debug_category_get_name (GstDebugCategory * category)
2555 gst_debug_category_get_color (GstDebugCategory * category)
2561 gst_debug_category_get_description (GstDebugCategory * category)
2567 gst_debug_get_all_categories (void)
2573 _gst_debug_get_category (const gchar * name)
2579 gst_debug_construct_term_color (guint colorinfo)
2581 return g_strdup ("00");
2585 gst_debug_construct_win_color (guint colorinfo)
2591 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2592 const gchar * func, gint line, GObject * obj, const gchar * msg,
2593 const guint8 * data, guint length)
2596 #endif /* GST_REMOVE_DISABLED */
2597 #endif /* GST_DISABLE_GST_DEBUG */
2600 * gst_info_vasprintf:
2601 * @result: (out): the resulting string
2602 * @format: a printf style format string
2603 * @args: the va_list of printf arguments for @format
2605 * Allocates and fills a string large enough (including the terminating null
2606 * byte) to hold the specified printf style @format and @args.
2608 * This function deals with the GStreamer specific printf specifiers
2609 * #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT. If you do not have these specifiers
2610 * in your @format string, you do not need to use this function and can use
2611 * alternatives such as g_vasprintf().
2613 * Free @result with g_free().
2615 * Returns: the length of the string allocated into @result or -1 on any error
2620 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2622 return __gst_vasprintf (result, format, args);
2626 * gst_info_strdup_vprintf:
2627 * @format: a printf style format string
2628 * @args: the va_list of printf arguments for @format
2630 * Allocates, fills and returns a null terminated string from the printf style
2631 * @format string and @args.
2633 * See gst_info_vasprintf() for when this function is required.
2635 * Free with g_free().
2637 * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2642 gst_info_strdup_vprintf (const gchar * format, va_list args)
2646 if (gst_info_vasprintf (&ret, format, args) < 0)
2653 * gst_info_strdup_printf:
2654 * @format: a printf style format string
2655 * @...: the printf arguments for @format
2657 * Allocates, fills and returns a 0-terminated string from the printf style
2658 * @format string and corresponding arguments.
2660 * See gst_info_vasprintf() for when this function is required.
2662 * Free with g_free().
2664 * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2669 gst_info_strdup_printf (const gchar * format, ...)
2674 va_start (args, format);
2675 ret = gst_info_strdup_vprintf (format, args);
2683 * @format: a printf style format string
2684 * @...: the printf arguments for @format
2686 * Outputs a formatted message via the GLib print handler. The default print
2687 * handler simply outputs the message to stdout.
2689 * This function will not append a new-line character at the end, unlike
2690 * gst_println() which will.
2692 * All strings must be in ASCII or UTF-8 encoding.
2694 * This function differs from g_print() in that it supports all the additional
2695 * printf specifiers that are supported by GStreamer's debug logging system,
2696 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2698 * This function is primarily for printing debug output.
2703 gst_print (const gchar * format, ...)
2708 va_start (args, format);
2709 str = gst_info_strdup_vprintf (format, args);
2713 G_LOCK (win_print_mutex);
2716 g_print ("%s", str);
2719 G_UNLOCK (win_print_mutex);
2726 * @format: a printf style format string
2727 * @...: the printf arguments for @format
2729 * Outputs a formatted message via the GLib print handler. The default print
2730 * handler simply outputs the message to stdout.
2732 * This function will append a new-line character at the end, unlike
2733 * gst_print() which will not.
2735 * All strings must be in ASCII or UTF-8 encoding.
2737 * This function differs from g_print() in that it supports all the additional
2738 * printf specifiers that are supported by GStreamer's debug logging system,
2739 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2741 * This function is primarily for printing debug output.
2746 gst_println (const gchar * format, ...)
2751 va_start (args, format);
2752 str = gst_info_strdup_vprintf (format, args);
2756 G_LOCK (win_print_mutex);
2759 g_print ("%s\n", str);
2762 G_UNLOCK (win_print_mutex);
2769 * @format: a printf style format string
2770 * @...: the printf arguments for @format
2772 * Outputs a formatted message via the GLib error message handler. The default
2773 * handler simply outputs the message to stderr.
2775 * This function will not append a new-line character at the end, unlike
2776 * gst_printerrln() which will.
2778 * All strings must be in ASCII or UTF-8 encoding.
2780 * This function differs from g_printerr() in that it supports the additional
2781 * printf specifiers that are supported by GStreamer's debug logging system,
2782 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2784 * This function is primarily for printing debug output.
2789 gst_printerr (const gchar * format, ...)
2794 va_start (args, format);
2795 str = gst_info_strdup_vprintf (format, args);
2799 G_LOCK (win_print_mutex);
2802 g_printerr ("%s", str);
2805 G_UNLOCK (win_print_mutex);
2812 * @format: a printf style format string
2813 * @...: the printf arguments for @format
2815 * Outputs a formatted message via the GLib error message handler. The default
2816 * handler simply outputs the message to stderr.
2818 * This function will append a new-line character at the end, unlike
2819 * gst_printerr() which will not.
2821 * All strings must be in ASCII or UTF-8 encoding.
2823 * This function differs from g_printerr() in that it supports the additional
2824 * printf specifiers that are supported by GStreamer's debug logging system,
2825 * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2827 * This function is primarily for printing debug output.
2832 gst_printerrln (const gchar * format, ...)
2837 va_start (args, format);
2838 str = gst_info_strdup_vprintf (format, args);
2842 G_LOCK (win_print_mutex);
2845 g_printerr ("%s\n", str);
2848 G_UNLOCK (win_print_mutex);
2856 append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
2860 Dwfl_Module *module;
2861 const gchar *function_name;
2863 addr = (uintptr_t) ip;
2864 module = dwfl_addrmodule (dwfl, addr);
2865 function_name = dwfl_module_addrname (module, addr);
2867 g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
2869 line = dwfl_getsrc (dwfl, addr);
2873 const gchar *filename = dwfl_lineinfo (line, &addr,
2874 &nline, NULL, NULL, NULL);
2876 g_string_append_printf (trace, "%s:%d", strrchr (filename,
2877 G_DIR_SEPARATOR) + 1, nline);
2879 const gchar *eflfile = NULL;
2881 dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
2882 g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
2887 #endif /* HAVE_DW */
2890 generate_unwind_trace (GstStackTraceFlags flags)
2894 unw_cursor_t cursor;
2895 gboolean use_libunwind = TRUE;
2896 GString *trace = g_string_new (NULL);
2901 if ((flags & GST_STACK_TRACE_SHOW_FULL)) {
2902 dwfl = get_global_dwfl ();
2903 if (G_UNLIKELY (dwfl == NULL)) {
2904 GST_WARNING ("Failed to initialize dwlf");
2909 #endif /* HAVE_DW */
2911 unret = unw_getcontext (&uc);
2913 GST_DEBUG ("Could not get libunwind context (%d)", unret);
2917 unret = unw_init_local (&cursor, &uc);
2919 GST_DEBUG ("Could not init libunwind context (%d)", unret);
2924 /* Due to plugins being loaded, mapping of process might have changed,
2925 * so always scan it. */
2926 if (dwfl_linux_proc_report (dwfl, _gst_getpid ()) != 0)
2930 while (unw_step (&cursor) > 0) {
2935 unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
2937 GST_DEBUG ("libunwind could not read frame info (%d)", unret);
2942 if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
2943 use_libunwind = FALSE;
2944 g_string_append (trace, ")\n");
2947 #endif /* HAVE_DW */
2949 if (use_libunwind) {
2952 unw_word_t offset = 0;
2953 unw_get_proc_name (&cursor, name, sizeof (name), &offset);
2954 g_string_append_printf (trace, "%s (0x%" G_GSIZE_FORMAT ")\n", name,
2965 return g_string_free (trace, FALSE);
2968 #endif /* HAVE_UNWIND */
2970 #ifdef HAVE_BACKTRACE
2972 generate_backtrace_trace (void)
2975 void *buffer[BT_BUF_SIZE];
2979 nptrs = backtrace (buffer, BT_BUF_SIZE);
2981 strings = backtrace_symbols (buffer, nptrs);
2986 trace = g_string_new (NULL);
2988 for (j = 0; j < nptrs; j++)
2989 g_string_append_printf (trace, "%s\n", strings[j]);
2993 return g_string_free (trace, FALSE);
2996 #define generate_backtrace_trace() NULL
2997 #endif /* HAVE_BACKTRACE */
3003 DWORD (WINAPI * pSymSetOptions) (DWORD SymOptions);
3004 BOOL (WINAPI * pSymInitialize) (HANDLE hProcess,
3005 PCSTR UserSearchPath,
3006 BOOL fInvadeProcess);
3007 BOOL (WINAPI * pStackWalk64) (DWORD MachineType,
3010 LPSTACKFRAME64 StackFrame,
3011 PVOID ContextRecord,
3012 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
3013 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
3014 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
3015 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
3016 PVOID (WINAPI * pSymFunctionTableAccess64) (HANDLE hProcess,
3018 DWORD64 (WINAPI * pSymGetModuleBase64) (HANDLE hProcess,
3020 BOOL (WINAPI * pSymFromAddr) (HANDLE hProcess,
3022 PDWORD64 Displacement,
3023 PSYMBOL_INFO Symbol);
3024 BOOL (WINAPI * pSymGetModuleInfo64) (HANDLE hProcess,
3026 PIMAGEHLP_MODULE64 ModuleInfo);
3027 BOOL (WINAPI * pSymGetLineFromAddr64) (HANDLE hProcess,
3029 PDWORD pdwDisplacement,
3030 PIMAGEHLP_LINE64 Line64);
3031 } dbg_help_vtable = { NULL,};
3034 static GModule *dbg_help_module = NULL;
3037 dbghelp_load_symbol (const gchar * symbol_name, gpointer * symbol)
3039 if (dbg_help_module &&
3040 !g_module_symbol (dbg_help_module, symbol_name, symbol)) {
3041 GST_WARNING ("Cannot load %s symbol", symbol_name);
3042 g_module_close (dbg_help_module);
3043 dbg_help_module = NULL;
3046 return ! !dbg_help_module;
3050 dbghelp_initialize_symbols (HANDLE process)
3052 static gsize initialization_value = 0;
3054 if (g_once_init_enter (&initialization_value)) {
3055 GST_INFO ("Initializing Windows symbol handler");
3057 dbg_help_module = g_module_open ("dbghelp.dll", G_MODULE_BIND_LAZY);
3058 dbghelp_load_symbol ("SymSetOptions",
3059 (gpointer *) & dbg_help_vtable.pSymSetOptions);
3060 dbghelp_load_symbol ("SymInitialize",
3061 (gpointer *) & dbg_help_vtable.pSymInitialize);
3062 dbghelp_load_symbol ("StackWalk64",
3063 (gpointer *) & dbg_help_vtable.pStackWalk64);
3064 dbghelp_load_symbol ("SymFunctionTableAccess64",
3065 (gpointer *) & dbg_help_vtable.pSymFunctionTableAccess64);
3066 dbghelp_load_symbol ("SymGetModuleBase64",
3067 (gpointer *) & dbg_help_vtable.pSymGetModuleBase64);
3068 dbghelp_load_symbol ("SymFromAddr",
3069 (gpointer *) & dbg_help_vtable.pSymFromAddr);
3070 dbghelp_load_symbol ("SymGetModuleInfo64",
3071 (gpointer *) & dbg_help_vtable.pSymGetModuleInfo64);
3072 dbghelp_load_symbol ("SymGetLineFromAddr64",
3073 (gpointer *) & dbg_help_vtable.pSymGetLineFromAddr64);
3075 if (dbg_help_module) {
3076 dbg_help_vtable.pSymSetOptions (SYMOPT_LOAD_LINES);
3077 dbg_help_vtable.pSymInitialize (process, NULL, TRUE);
3078 GST_INFO ("Initialized Windows symbol handler");
3081 g_once_init_leave (&initialization_value, 1);
3084 return ! !dbg_help_module;
3088 generate_dbghelp_trace (void)
3090 HANDLE process = GetCurrentProcess ();
3091 HANDLE thread = GetCurrentThread ();
3092 IMAGEHLP_MODULE64 module_info;
3095 STACKFRAME64 frame = { 0 };
3097 GString *trace = NULL;
3099 if (!dbghelp_initialize_symbols (process))
3102 memset (&context, 0, sizeof (CONTEXT));
3103 context.ContextFlags = CONTEXT_FULL;
3105 RtlCaptureContext (&context);
3107 frame.AddrPC.Mode = AddrModeFlat;
3108 frame.AddrStack.Mode = AddrModeFlat;
3109 frame.AddrFrame.Mode = AddrModeFlat;
3111 #if (defined _M_IX86)
3112 machine = IMAGE_FILE_MACHINE_I386;
3113 frame.AddrFrame.Offset = context.Ebp;
3114 frame.AddrPC.Offset = context.Eip;
3115 frame.AddrStack.Offset = context.Esp;
3116 #elif (defined _M_X64)
3117 machine = IMAGE_FILE_MACHINE_AMD64;
3118 frame.AddrFrame.Offset = context.Rbp;
3119 frame.AddrPC.Offset = context.Rip;
3120 frame.AddrStack.Offset = context.Rsp;
3125 trace = g_string_new (NULL);
3127 module_info.SizeOfStruct = sizeof (module_info);
3128 save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
3131 char buffer[sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR)];
3132 PSYMBOL_INFO symbol = (PSYMBOL_INFO) buffer;
3133 IMAGEHLP_LINE64 line;
3134 DWORD displacement = 0;
3136 symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
3137 symbol->MaxNameLen = MAX_SYM_NAME;
3139 line.SizeOfStruct = sizeof (line);
3141 if (!dbg_help_vtable.pStackWalk64 (machine, process, thread, &frame,
3142 save_context, 0, dbg_help_vtable.pSymFunctionTableAccess64,
3143 dbg_help_vtable.pSymGetModuleBase64, 0)) {
3147 if (dbg_help_vtable.pSymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
3148 g_string_append_printf (trace, "%s ", symbol->Name);
3150 g_string_append (trace, "?? ");
3152 if (dbg_help_vtable.pSymGetLineFromAddr64 (process, frame.AddrPC.Offset,
3153 &displacement, &line))
3154 g_string_append_printf (trace, "(%s:%lu)", line.FileName,
3156 else if (dbg_help_vtable.pSymGetModuleInfo64 (process, frame.AddrPC.Offset,
3158 g_string_append_printf (trace, "(%s)", module_info.ImageName);
3160 g_string_append_printf (trace, "(%s)", "??");
3162 g_string_append (trace, "\n");
3165 return g_string_free (trace, FALSE);
3167 #endif /* HAVE_DBGHELP */
3170 * gst_debug_get_stack_trace:
3171 * @flags: A set of #GstStackTraceFlags to determine how the stack trace should
3172 * look like. Pass #GST_STACK_TRACE_SHOW_NONE to retrieve a minimal backtrace.
3174 * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
3175 * present, else %NULL.
3180 gst_debug_get_stack_trace (GstStackTraceFlags flags)
3182 gchar *trace = NULL;
3183 #ifdef HAVE_BACKTRACE
3184 gboolean have_backtrace = TRUE;
3186 gboolean have_backtrace = FALSE;
3190 if ((flags & GST_STACK_TRACE_SHOW_FULL) || !have_backtrace)
3191 trace = generate_unwind_trace (flags);
3192 #elif defined(HAVE_DBGHELP)
3193 trace = generate_dbghelp_trace ();
3198 else if (have_backtrace)
3199 return generate_backtrace_trace ();
3205 * gst_debug_print_stack_trace:
3207 * If libunwind, glibc backtrace or DbgHelp are present
3208 * a stack trace is printed.
3211 gst_debug_print_stack_trace (void)
3213 gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
3217 G_LOCK (win_print_mutex);
3220 g_print ("%s\n", trace);
3223 G_UNLOCK (win_print_mutex);
3230 #ifndef GST_DISABLE_GST_DEBUG
3233 guint max_size_per_thread;
3234 guint thread_timeout;
3236 GHashTable *thread_index;
3237 } GstRingBufferLogger;
3249 G_LOCK_DEFINE_STATIC (ring_buffer_logger);
3250 static GstRingBufferLogger *ring_buffer_logger = NULL;
3253 gst_ring_buffer_logger_log (GstDebugCategory * category,
3254 GstDebugLevel level,
3256 const gchar * function,
3257 gint line, GObject * object, GstDebugMessage * message, gpointer user_data)
3259 GstRingBufferLogger *logger = user_data;
3261 GstClockTime elapsed;
3266 GstRingBufferLog *log;
3267 gint64 now = g_get_monotonic_time ();
3268 const gchar *message_str = gst_debug_message_get (message);
3270 /* __FILE__ might be a file name or an absolute path or a
3271 * relative path, irrespective of the exact compiler used,
3272 * in which case we want to shorten it to the filename for
3275 if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
3276 file = gst_path_basename (file);
3280 obj = gst_debug_print_object (object);
3285 elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
3286 thread = g_thread_self ();
3288 /* no color, all platforms */
3289 #define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
3291 g_strdup_printf ("%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
3292 _gst_getpid (), thread, gst_debug_level_get_name (level),
3293 gst_debug_category_get_name (category), file, line, function, obj,
3297 output_len = strlen (output);
3302 G_LOCK (ring_buffer_logger);
3304 if (logger->thread_timeout > 0) {
3307 /* Remove all threads that saw no output since thread_timeout seconds.
3308 * By construction these are all at the tail of the queue, and the queue
3309 * is ordered by last use, so we just need to look at the tail.
3311 while (logger->threads.tail) {
3312 log = logger->threads.tail->data;
3313 if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
3316 g_hash_table_remove (logger->thread_index, log->thread);
3317 while ((buf = g_queue_pop_head (&log->log)))
3320 g_queue_pop_tail (&logger->threads);
3324 /* Get logger for this thread, and put it back at the
3325 * head of the threads queue */
3326 log = g_hash_table_lookup (logger->thread_index, thread);
3328 log = g_new0 (GstRingBufferLog, 1);
3329 g_queue_init (&log->log);
3331 g_queue_push_head (&logger->threads, log);
3332 log->link = logger->threads.head;
3333 log->thread = thread;
3334 g_hash_table_insert (logger->thread_index, thread, log);
3336 g_queue_unlink (&logger->threads, log->link);
3337 g_queue_push_head_link (&logger->threads, log->link);
3339 log->last_use = now;
3341 if (output_len < logger->max_size_per_thread) {
3344 /* While using a GQueue here is not the most efficient thing to do, we
3345 * have to allocate a string for every output anyway and could just store
3346 * that instead of copying it to an actual ringbuffer.
3347 * Better than GQueue would be GstQueueArray, but that one is in
3348 * libgstbase and we can't use it here. That one allocation will not make
3349 * much of a difference anymore, considering the number of allocations
3350 * needed to get to this point...
3352 while (log->log_size + output_len > logger->max_size_per_thread) {
3353 buf = g_queue_pop_head (&log->log);
3354 log->log_size -= strlen (buf);
3357 g_queue_push_tail (&log->log, output);
3358 log->log_size += output_len;
3362 /* Can't really write anything as the line is bigger than the maximum
3363 * allowed log size already, so just remove everything */
3365 while ((buf = g_queue_pop_head (&log->log)))
3371 G_UNLOCK (ring_buffer_logger);
3375 * gst_debug_ring_buffer_logger_get_logs:
3377 * Fetches the current logs per thread from the ring buffer logger. See
3378 * gst_debug_add_ring_buffer_logger() for details.
3380 * Returns: (transfer full) (array zero-terminated): NULL-terminated array of
3381 * strings with the debug output per thread
3386 gst_debug_ring_buffer_logger_get_logs (void)
3388 gchar **logs, **tmp;
3391 g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
3393 G_LOCK (ring_buffer_logger);
3395 tmp = logs = g_new0 (gchar *, ring_buffer_logger->threads.length + 1);
3396 for (l = ring_buffer_logger->threads.head; l; l = l->next) {
3397 GstRingBufferLog *log = l->data;
3402 *tmp = p = g_new0 (gchar, log->log_size + 1);
3404 for (l = log->log.head; l; l = l->next) {
3405 len = strlen (l->data);
3406 memcpy (p, l->data, len);
3413 G_UNLOCK (ring_buffer_logger);
3419 gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
3421 G_LOCK (ring_buffer_logger);
3422 if (ring_buffer_logger == logger) {
3423 GstRingBufferLog *log;
3425 while ((log = g_queue_pop_head (&logger->threads))) {
3427 while ((buf = g_queue_pop_head (&log->log)))
3432 g_hash_table_unref (logger->thread_index);
3435 ring_buffer_logger = NULL;
3437 G_UNLOCK (ring_buffer_logger);
3441 * gst_debug_add_ring_buffer_logger:
3442 * @max_size_per_thread: Maximum size of log per thread in bytes
3443 * @thread_timeout: Timeout for threads in seconds
3445 * Adds a memory ringbuffer based debug logger that stores up to
3446 * @max_size_per_thread bytes of logs per thread and times out threads after
3447 * @thread_timeout seconds of inactivity.
3449 * Logs can be fetched with gst_debug_ring_buffer_logger_get_logs() and the
3450 * logger can be removed again with gst_debug_remove_ring_buffer_logger().
3451 * Only one logger at a time is possible.
3456 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3457 guint thread_timeout)
3459 GstRingBufferLogger *logger;
3461 G_LOCK (ring_buffer_logger);
3463 if (ring_buffer_logger) {
3464 g_warn_if_reached ();
3465 G_UNLOCK (ring_buffer_logger);
3469 logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
3471 logger->max_size_per_thread = max_size_per_thread;
3472 logger->thread_timeout = thread_timeout;
3473 logger->thread_index = g_hash_table_new (g_direct_hash, g_direct_equal);
3474 g_queue_init (&logger->threads);
3476 gst_debug_add_log_function (gst_ring_buffer_logger_log, logger,
3477 (GDestroyNotify) gst_ring_buffer_logger_free);
3478 G_UNLOCK (ring_buffer_logger);
3482 * gst_debug_remove_ring_buffer_logger:
3484 * Removes any previously added ring buffer logger with
3485 * gst_debug_add_ring_buffer_logger().
3490 gst_debug_remove_ring_buffer_logger (void)
3492 gst_debug_remove_log_function (gst_ring_buffer_logger_log);
3495 #else /* GST_DISABLE_GST_DEBUG */
3496 #ifndef GST_REMOVE_DISABLED
3499 gst_debug_ring_buffer_logger_get_logs (void)
3505 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3506 guint thread_timeout)
3511 gst_debug_remove_ring_buffer_logger (void)
3515 #endif /* GST_REMOVE_DISABLED */
3516 #endif /* GST_DISABLE_GST_DEBUG */