tools: Count argc after parsing GOption on Windows
[platform/upstream/gstreamer.git] / subprojects / gstreamer / gst / gstinfo.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
5  * Copyright (C) 2008-2009 Tim-Philipp Müller <tim centricular net>
6  *
7  * gstinfo.c: debugging functions
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /**
26  * SECTION:gstinfo
27  * @title: GstInfo
28  * @short_description: Debugging and logging facilities
29  * @see_also: #gst-running for command line parameters
30  * and environment variables that affect the debugging output.
31  *
32  * GStreamer's debugging subsystem is an easy way to get information about what
33  * the application is doing.  It is not meant for programming errors. Use GLib
34  * methods (g_warning and friends) for that.
35  *
36  * The debugging subsystem works only after GStreamer has been initialized
37  * - for example by calling gst_init().
38  *
39  * The debugging subsystem is used to log informational messages while the
40  * application runs.  Each messages has some properties attached to it. Among
41  * these properties are the debugging category, the severity (called "level"
42  * here) and an optional #GObject it belongs to. Each of these messages is sent
43  * to all registered debugging handlers, which then handle the messages.
44  * GStreamer attaches a default handler on startup, which outputs requested
45  * messages to stderr.
46  *
47  * Messages are output by using shortcut macros like #GST_DEBUG,
48  * #GST_CAT_ERROR_OBJECT or similar. These all expand to calling gst_debug_log()
49  * with the right parameters.
50  * The only thing a developer will probably want to do is define his own
51  * categories. This is easily done with 3 lines. At the top of your code,
52  * declare
53  * the variables and set the default category.
54  * |[<!-- language="C" -->
55  *   GST_DEBUG_CATEGORY_STATIC (my_category);  // define category (statically)
56  *   #define GST_CAT_DEFAULT my_category       // set as default
57  * ]|
58  * After that you only need to initialize the category.
59  * |[<!-- language="C" -->
60  *   GST_DEBUG_CATEGORY_INIT (my_category, "my category",
61  *                            0, "This is my very own");
62  * ]|
63  * Initialization must be done before the category is used first.
64  * Plugins do this
65  * in their plugin_init function, libraries and applications should do that
66  * during their initialization.
67  *
68  * The whole debugging subsystem can be disabled at build time with passing the
69  * --disable-gst-debug switch to configure. If this is done, every function,
70  * macro and even structs described in this file evaluate to default values or
71  * nothing at all.
72  * So don't take addresses of these functions or use other tricks.
73  * If you must do that for some reason, there is still an option.
74  * If the debugging
75  * subsystem was compiled out, GST_DISABLE_GST_DEBUG is defined in
76  * <gst/gst.h>,
77  * so you can check that before doing your trick.
78  * Disabling the debugging subsystem will give you a slight (read: unnoticeable)
79  * speed increase and will reduce the size of your compiled code. The GStreamer
80  * library itself becomes around 10% smaller.
81  *
82  * Please note that there are naming conventions for the names of debugging
83  * categories. These are explained at GST_DEBUG_CATEGORY_INIT().
84  */
85
86 #define GST_INFO_C
87 #include "gst_private.h"
88 #include "gstinfo.h"
89
90 #undef gst_debug_remove_log_function
91 #undef gst_debug_add_log_function
92
93 #ifndef GST_DISABLE_GST_DEBUG
94 #ifdef HAVE_DLFCN_H
95 #  include <dlfcn.h>
96 #endif
97 #include <stdio.h>              /* fprintf */
98 #include <glib/gstdio.h>
99 #include <errno.h>
100 #include <string.h>             /* G_VA_COPY */
101
102 #include "gst_private.h"
103 #include "gstutils.h"
104 #include "gstquark.h"
105 #include "gstsegment.h"
106 #include "gstvalue.h"
107 #include "gstcapsfeatures.h"
108
109 #ifdef HAVE_VALGRIND_VALGRIND_H
110 #  include <valgrind/valgrind.h>
111 #endif
112 #endif /* GST_DISABLE_GST_DEBUG */
113
114 #include <glib/gprintf.h>       /* g_sprintf */
115
116 /* our own printf implementation with custom extensions to %p for caps etc. */
117 #include "printf/printf.h"
118 #include "printf/printf-extension.h"
119
120 static char *gst_info_printf_pointer_extension_func (const char *format,
121     void *ptr);
122
123 #ifdef HAVE_UNISTD_H
124 #  include <unistd.h>           /* getpid on UNIX */
125 #endif
126
127 #ifdef G_OS_WIN32
128 #  define WIN32_LEAN_AND_MEAN   /* prevents from including too many things */
129 #  include <windows.h>          /* GetStdHandle, windows console */
130 #  include <processthreadsapi.h>        /* GetCurrentProcessId */
131 /* getpid() is not allowed in case of UWP, use GetCurrentProcessId() instead
132  * which can be used on both desktop and UWP */
133 #endif
134
135 /* use glib's abstraction once it's landed
136  * https://gitlab.gnome.org/GNOME/glib/-/merge_requests/2475 */
137 #ifdef G_OS_WIN32
138 static inline DWORD
139 _gst_getpid (void)
140 {
141   return GetCurrentProcessId ();
142 }
143 #else
144 static inline pid_t
145 _gst_getpid (void)
146 {
147   return getpid ();
148 }
149 #endif
150
151 #ifdef HAVE_UNWIND
152 /* No need for remote debugging so turn on the 'local only' optimizations in
153  * libunwind */
154 #define UNW_LOCAL_ONLY
155
156 #include <libunwind.h>
157 #include <stdio.h>
158 #include <stdlib.h>
159 #include <string.h>
160 #include <stdarg.h>
161 #include <unistd.h>
162 #include <errno.h>
163
164 #ifdef HAVE_DW
165 #include <elfutils/libdwfl.h>
166 static Dwfl *_global_dwfl = NULL;
167 static GMutex _dwfl_mutex;
168
169 #define GST_DWFL_LOCK() g_mutex_lock(&_dwfl_mutex);
170 #define GST_DWFL_UNLOCK() g_mutex_unlock(&_dwfl_mutex);
171
172 static Dwfl *
173 get_global_dwfl (void)
174 {
175   if (g_once_init_enter (&_global_dwfl)) {
176     static Dwfl_Callbacks callbacks = {
177       .find_elf = dwfl_linux_proc_find_elf,
178       .find_debuginfo = dwfl_standard_find_debuginfo,
179     };
180     Dwfl *_dwfl = dwfl_begin (&callbacks);
181     g_mutex_init (&_dwfl_mutex);
182     g_once_init_leave (&_global_dwfl, _dwfl);
183   }
184
185   return _global_dwfl;
186 }
187
188 #endif /* HAVE_DW */
189 #endif /* HAVE_UNWIND */
190
191 #ifdef HAVE_BACKTRACE
192 #include <execinfo.h>
193 #define BT_BUF_SIZE 100
194 #endif /* HAVE_BACKTRACE */
195
196 #ifdef HAVE_DBGHELP
197 #include <windows.h>
198 #include <dbghelp.h>
199 #include <tlhelp32.h>
200 #include <gmodule.h>
201 #endif /* HAVE_DBGHELP */
202
203 #ifdef G_OS_WIN32
204 /* We take a lock in order to
205  * 1) keep colors and content together for a single line
206  * 2) serialise gst_print*() and gst_printerr*() with each other and the debug
207  *    log to keep the debug log colouring from interfering with those and
208  *    to prevent broken output on the windows terminal.
209  * Maybe there is a better way but for now this will do the right
210  * thing. */
211 G_LOCK_DEFINE_STATIC (win_print_mutex);
212 #endif
213
214 extern gboolean gst_is_initialized (void);
215
216 /* we want these symbols exported even if debug is disabled, to maintain
217  * ABI compatibility. Unless GST_REMOVE_DISABLED is defined. */
218 #if !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED)
219
220 /* disabled by default, as soon as some threshold is set > NONE,
221  * it becomes enabled. */
222 gboolean _gst_debug_enabled = FALSE;
223 GstDebugLevel _gst_debug_min = GST_LEVEL_NONE;
224
225 GstDebugCategory *GST_CAT_DEFAULT = NULL;
226
227 GstDebugCategory *GST_CAT_GST_INIT = NULL;
228 GstDebugCategory *GST_CAT_MEMORY = NULL;
229 GstDebugCategory *GST_CAT_PARENTAGE = NULL;
230 GstDebugCategory *GST_CAT_STATES = NULL;
231 GstDebugCategory *GST_CAT_SCHEDULING = NULL;
232
233 GstDebugCategory *GST_CAT_BUFFER = NULL;
234 GstDebugCategory *GST_CAT_BUFFER_LIST = NULL;
235 GstDebugCategory *GST_CAT_BUS = NULL;
236 GstDebugCategory *GST_CAT_CAPS = NULL;
237 GstDebugCategory *GST_CAT_CLOCK = NULL;
238 GstDebugCategory *GST_CAT_ELEMENT_PADS = NULL;
239 GstDebugCategory *GST_CAT_PADS = NULL;
240 GstDebugCategory *GST_CAT_PERFORMANCE = NULL;
241 GstDebugCategory *GST_CAT_PIPELINE = NULL;
242 GstDebugCategory *GST_CAT_PLUGIN_LOADING = NULL;
243 GstDebugCategory *GST_CAT_PLUGIN_INFO = NULL;
244 GstDebugCategory *GST_CAT_PROPERTIES = NULL;
245 GstDebugCategory *GST_CAT_NEGOTIATION = NULL;
246 GstDebugCategory *GST_CAT_REFCOUNTING = NULL;
247 GstDebugCategory *GST_CAT_ERROR_SYSTEM = NULL;
248 GstDebugCategory *GST_CAT_EVENT = NULL;
249 GstDebugCategory *GST_CAT_MESSAGE = NULL;
250 GstDebugCategory *GST_CAT_PARAMS = NULL;
251 GstDebugCategory *GST_CAT_CALL_TRACE = NULL;
252 GstDebugCategory *GST_CAT_SIGNAL = NULL;
253 GstDebugCategory *GST_CAT_PROBE = NULL;
254 GstDebugCategory *GST_CAT_REGISTRY = NULL;
255 GstDebugCategory *GST_CAT_QOS = NULL;
256 GstDebugCategory *_priv_GST_CAT_POLL = NULL;
257 GstDebugCategory *GST_CAT_META = NULL;
258 GstDebugCategory *GST_CAT_LOCKING = NULL;
259 GstDebugCategory *GST_CAT_CONTEXT = NULL;
260 GstDebugCategory *_priv_GST_CAT_PROTECTION = NULL;
261
262
263 #endif /* !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED) */
264
265 #ifndef GST_DISABLE_GST_DEBUG
266
267 /* underscore is to prevent conflict with GST_CAT_DEBUG define */
268 GST_DEBUG_CATEGORY_STATIC (_GST_CAT_DEBUG);
269
270 #if 0
271 #if defined __sgi__
272 #include <rld_interface.h>
273 typedef struct DL_INFO
274 {
275   const char *dli_fname;
276   void *dli_fbase;
277   const char *dli_sname;
278   void *dli_saddr;
279   int dli_version;
280   int dli_reserved1;
281   long dli_reserved[4];
282 }
283 Dl_info;
284
285 #define _RLD_DLADDR             14
286 int dladdr (void *address, Dl_info * dl);
287
288 int
289 dladdr (void *address, Dl_info * dl)
290 {
291   void *v;
292
293   v = _rld_new_interface (_RLD_DLADDR, address, dl);
294   return (int) v;
295 }
296 #endif /* __sgi__ */
297 #endif
298
299 static void gst_debug_reset_threshold (gpointer category, gpointer unused);
300 static void gst_debug_reset_all_thresholds (void);
301
302 struct _GstDebugMessage
303 {
304   gchar *message;
305   const gchar *format;
306   va_list arguments;
307
308   /* The emitter of the message (can be NULL) */
309   GObject *object;
310
311   /* Provider of the message. Can be user-provided, or generated dynamically
312    * from object */
313   gchar *object_id;
314
315   /* Whether object_id was dynamically allocated and should be freed */
316   gboolean free_object_id;
317
318   /* heap-allocated write area for short names */
319   gchar tmp_id[32];
320 };
321
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;
325 typedef struct
326 {
327   GPatternSpec *pat;
328   GstDebugLevel level;
329 }
330 LevelNameEntry;
331
332 static void clear_level_names (void);
333
334 /* list of all categories */
335 static GMutex __cat_mutex;
336 static GSList *__categories = NULL;
337
338 static GstDebugCategory *_gst_debug_get_category_locked (const gchar * name);
339
340
341 /* all registered debug handlers */
342 typedef struct
343 {
344   GstLogFunction func;
345   gpointer user_data;
346   GDestroyNotify notify;
347 }
348 LogFuncEntry;
349 static GMutex __log_func_mutex;
350 static GSList *__log_functions = NULL;
351
352 /* whether to add the default log function in gst_init() */
353 static gboolean add_default_log_func = TRUE;
354
355 #define PRETTY_TAGS_DEFAULT  TRUE
356 static gboolean pretty_tags = PRETTY_TAGS_DEFAULT;
357
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;
360
361 static gchar *
362 _replace_pattern_in_gst_debug_file_name (gchar * name, const char *token,
363     guint val)
364 {
365   gchar *token_start;
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);
373   }
374   return name;
375 }
376
377 static gchar *
378 _priv_gst_debug_file_name (const gchar * env)
379 {
380   gchar *name;
381
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 ());
385
386   return name;
387 }
388
389 /* Initialize the debugging system */
390 void
391 _priv_gst_debug_init (void)
392 {
393   const gchar *env;
394   FILE *log_file;
395
396   if (add_default_log_func) {
397     env = g_getenv ("GST_DEBUG_FILE");
398     if (env != NULL && *env != '\0') {
399       if (strcmp (env, "-") == 0) {
400         log_file = stdout;
401       } else {
402         gchar *name = _priv_gst_debug_file_name (env);
403         log_file = g_fopen (name, "w");
404         g_free (name);
405         if (log_file == NULL) {
406           g_printerr ("Could not open log file '%s' for writing: %s\n", env,
407               g_strerror (errno));
408           log_file = stderr;
409         }
410       }
411     } else {
412       log_file = stderr;
413     }
414
415     gst_debug_add_log_function (gst_debug_log_default, log_file, NULL);
416   }
417
418   __gst_printf_pointer_extension_set_func
419       (gst_info_printf_pointer_extension_func);
420
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");
426
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);
467
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");
488
489   env = g_getenv ("GST_DEBUG_OPTIONS");
490   if (env != NULL) {
491     if (strstr (env, "full_tags") || strstr (env, "full-tags"))
492       pretty_tags = FALSE;
493     else if (strstr (env, "pretty_tags") || strstr (env, "pretty-tags"))
494       pretty_tags = TRUE;
495   }
496
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");
500   if (env)
501     gst_debug_set_color_mode_from_string (env);
502
503   env = g_getenv ("GST_DEBUG");
504   if (env)
505     gst_debug_set_threshold_from_string (env, FALSE);
506 }
507
508 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
509 #define GST_CAT_DEFAULT _GST_CAT_DEBUG
510
511 /**
512  * gst_debug_log:
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,
519  *     or %NULL if none
520  * @format: a printf style format string
521  * @...: optional arguments for the format
522  *
523  * Logs the given message using the currently registered debugging handlers.
524  */
525 void
526 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
527     const gchar * file, const gchar * function, gint line,
528     GObject * object, const gchar * format, ...)
529 {
530   va_list var_args;
531
532   va_start (var_args, format);
533   gst_debug_log_valist (category, level, file, function, line, object, format,
534       var_args);
535   va_end (var_args);
536 }
537
538 /**
539  * gst_debug_log_id:
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
549  *
550  * Logs the given message using the currently registered debugging handlers.
551  *
552  * Since: 1.22
553  */
554 void
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, ...)
558 {
559   va_list var_args;
560
561   va_start (var_args, format);
562   gst_debug_log_id_valist (category, level, file, function, line, id, format,
563       var_args);
564   va_end (var_args);
565 }
566
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)
570 {
571   register const gchar *base;
572
573   base = strrchr (file_name, G_DIR_SEPARATOR);
574
575   {
576     const gchar *q = strrchr (file_name, '/');
577     if (base == NULL || (q != NULL && q > base))
578       base = q;
579   }
580
581   if (base)
582     return base + 1;
583
584   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
585     return file_name + 2;
586
587   return file_name;
588 }
589
590 static void
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)
594 {
595   GstDebugMessage message;
596   LogFuncEntry *entry;
597   GSList *handler;
598
599   g_return_if_fail (category != NULL);
600
601   if (level > gst_debug_category_get_threshold (category))
602     return;
603
604   g_return_if_fail (file != NULL);
605   g_return_if_fail (function != NULL);
606   g_return_if_fail (format != NULL);
607
608 #ifdef GST_ENABLE_EXTRA_CHECKS
609   g_return_if_fail (id != NULL || object == NULL || G_IS_OBJECT (object));
610 #endif
611
612   message.message = NULL;
613   message.format = format;
614   message.object = object;
615   message.object_id = (gchar *) id;
616   message.free_object_id = FALSE;
617
618   G_VA_COPY (message.arguments, args);
619
620   handler = __log_functions;
621   while (handler) {
622     entry = handler->data;
623     handler = g_slist_next (handler);
624     entry->func (category, level, file, function, line, object, &message,
625         entry->user_data);
626   }
627   g_free (message.message);
628   if (message.free_object_id)
629     g_free (message.object_id);
630   va_end (message.arguments);
631 }
632
633 /**
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,
641  *     or %NULL if none
642  * @format: a printf style format string
643  * @args: optional arguments for the format
644  *
645  * Logs the given message using the currently registered debugging handlers.
646  */
647 void
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)
651 {
652 #ifdef GST_ENABLE_EXTRA_CHECKS
653   g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
654 #endif
655
656   gst_debug_log_full_valist (category, level, file, function, line, object,
657       NULL, format, args);
658 }
659
660 /**
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
671  *
672  * Logs the given message using the currently registered debugging handlers.
673  *
674  * Since: 1.22
675  */
676 void
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)
680 {
681   gst_debug_log_full_valist (category, level, file, function, line, NULL, id,
682       format, args);
683 }
684
685 static void
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)
689 {
690   GstDebugMessage message;
691   LogFuncEntry *entry;
692   GSList *handler;
693
694   g_return_if_fail (category != NULL);
695
696   if (level > gst_debug_category_get_threshold (category))
697     return;
698
699 #ifdef GST_ENABLE_EXTRA_CHECKS
700   g_return_if_fail (id != NULL || object == NULL || G_IS_OBJECT (object));
701 #endif
702
703   g_return_if_fail (file != NULL);
704   g_return_if_fail (function != NULL);
705   g_return_if_fail (message_string != NULL);
706
707   message.message = (gchar *) message_string;
708   message.object = object;
709   message.object_id = (gchar *) id;
710   message.free_object_id = FALSE;
711
712   handler = __log_functions;
713   while (handler) {
714     entry = handler->data;
715     handler = g_slist_next (handler);
716     entry->func (category, level, file, function, line, object, &message,
717         entry->user_data);
718   }
719
720   if (message.free_object_id)
721     g_free (message.object_id);
722 }
723
724 /**
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,
732  *     or %NULL if none
733  * @message_string: a message string
734  *
735  * Logs the given message using the currently registered debugging handlers.
736  *
737  * Since: 1.20
738  */
739 void
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)
743 {
744 #ifdef GST_ENABLE_EXTRA_CHECKS
745   g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
746 #endif
747
748   gst_debug_log_literal_full (category, level, file, function, line, object,
749       NULL, message_string);
750 }
751
752 /**
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
760  *    or %NULL if none
761  * @message_string: a message string
762  *
763  * Logs the given message using the currently registered debugging handlers.
764  *
765  * Since: 1.22
766  */
767 void
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)
771 {
772   gst_debug_log_literal_full (category, level, file, function, line, NULL, id,
773       message_string);
774 }
775
776 /**
777  * gst_debug_message_get:
778  * @message: a debug message
779  *
780  * Gets the string representation of a #GstDebugMessage. This function is used
781  * in debug handlers to extract the message.
782  *
783  * Returns: (nullable): the string representation of a #GstDebugMessage.
784  */
785 const gchar *
786 gst_debug_message_get (GstDebugMessage * message)
787 {
788   if (message->message == NULL) {
789     int len;
790
791     len = __gst_vasprintf (&message->message, message->format,
792         message->arguments);
793
794     if (len < 0)
795       message->message = NULL;
796   }
797   return message->message;
798 }
799
800 /* Return the pad name. Will use the provided 32 byte write_area if it fits
801  * within */
802 static inline gchar *
803 _heap_pad_name (GstPad * pad, gchar * write_area, gboolean * allocated)
804 {
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));
809
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);
813     *allocated = FALSE;
814     return write_area;
815   }
816   *allocated = TRUE;
817   return g_strdup_printf ("%s:%s", parentname, padname);
818 }
819
820 /* Returns the object id. Allocated is set to TRUE if a memory allocation
821  * happened and the returned value should be freed */
822 static gchar *
823 _get_object_id (GObject * object, gboolean * allocated, gchar * write_area)
824 {
825   gchar *object_id;
826
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);
832     *allocated = FALSE;
833   } else if (G_IS_OBJECT (object)) {
834     object_id = g_strdup_printf ("%s@%p", G_OBJECT_TYPE_NAME (object), object);
835     *allocated = TRUE;
836   } else {
837     object_id = g_strdup_printf ("%p", object);
838     *allocated = TRUE;
839   }
840
841   return object_id;
842 }
843
844 /**
845  * gst_debug_message_get_id:
846  * @message: a debug message
847  *
848  * Get the id of the object that emitted this message. This function is used in
849  * debug handlers. Can be empty.
850  *
851  * Since: 1.22
852  *
853  * Returns: (nullable): The emitter of a #GstDebugMessage.
854  */
855 const gchar *
856 gst_debug_message_get_id (GstDebugMessage * message)
857 {
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 */
862     message->object_id =
863         _get_object_id (message->object, &message->free_object_id,
864         (gchar *) & message->tmp_id);
865   }
866   return message->object_id;
867 }
868
869 #define MAX_BUFFER_DUMP_STRING_LEN  100
870
871 /* structure_to_pretty_string:
872  * @str: a serialized #GstStructure
873  *
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
876  * readable.
877  *
878  * Returns: the filtered string
879  */
880 static gchar *
881 prettify_structure_string (gchar * str)
882 {
883   gchar *pos = str, *end;
884
885   while ((pos = strstr (pos, "(buffer)"))) {
886     guint count = 0;
887
888     pos += strlen ("(buffer)");
889     for (end = pos; *end != '\0' && *end != ';' && *end != ' '; ++end)
890       ++count;
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;
897     }
898   }
899
900   return str;
901 }
902
903 static inline gchar *
904 gst_info_structure_to_string (const GstStructure * s)
905 {
906   if (G_LIKELY (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);
910     else
911       return str;
912   }
913   return NULL;
914 }
915
916 static inline gchar *
917 gst_info_describe_buffer (GstBuffer * buffer)
918 {
919   const gchar *offset_str = "none";
920   const gchar *offset_end_str = "none";
921   gchar offset_buf[32], offset_end_buf[32];
922
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;
927   }
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;
932   }
933
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));
942 }
943
944 static inline gchar *
945 gst_info_describe_buffer_list (GstBufferList * list)
946 {
947   GstClockTime pts = GST_CLOCK_TIME_NONE;
948   GstClockTime dts = GST_CLOCK_TIME_NONE;
949   gsize total_size = 0;
950   guint n, i;
951
952   n = gst_buffer_list_length (list);
953   for (i = 0; i < n; ++i) {
954     GstBuffer *buf = gst_buffer_list_get (list, i);
955
956     if (i == 0) {
957       pts = GST_BUFFER_PTS (buf);
958       dts = GST_BUFFER_DTS (buf);
959     }
960
961     total_size += gst_buffer_get_size (buf);
962   }
963
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);
967 }
968
969 static inline gchar *
970 gst_info_describe_event (GstEvent * event)
971 {
972   gchar *s, *ret;
973
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),
978       (s ? s : "(NULL)"));
979   g_free (s);
980   return ret;
981 }
982
983 static inline gchar *
984 gst_info_describe_message (GstMessage * message)
985 {
986   gchar *s, *ret;
987
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)"),
994       (s ? s : "(NULL)"));
995   g_free (s);
996   return ret;
997 }
998
999 static inline gchar *
1000 gst_info_describe_query (GstQuery * query)
1001 {
1002   gchar *s, *ret;
1003
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)"));
1007   g_free (s);
1008   return ret;
1009 }
1010
1011 static inline gchar *
1012 gst_info_describe_stream (GstStream * stream)
1013 {
1014   gchar *ret, *caps_str = NULL, *tags_str = NULL;
1015   GstCaps *caps;
1016   GstTagList *tags;
1017
1018   caps = gst_stream_get_caps (stream);
1019   if (caps) {
1020     caps_str = gst_caps_to_string (caps);
1021     gst_caps_unref (caps);
1022   }
1023
1024   tags = gst_stream_get_tags (stream);
1025   if (tags) {
1026     tags_str = gst_tag_list_to_string (tags);
1027     gst_tag_list_unref (tags);
1028   }
1029
1030   ret =
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 : "");
1035
1036   g_free (caps_str);
1037   g_free (tags_str);
1038
1039   return ret;
1040 }
1041
1042 static inline gchar *
1043 gst_info_describe_stream_collection (GstStreamCollection * collection)
1044 {
1045   gchar *ret;
1046   GString *streams_str;
1047   guint i;
1048
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);
1052     gchar *s;
1053
1054     s = gst_info_describe_stream (stream);
1055     g_string_append_printf (streams_str, " %s,", s);
1056     g_free (s);
1057   }
1058   g_string_append (streams_str, " >");
1059
1060   ret = g_strdup_printf ("collection %p (%d streams) %s", collection,
1061       gst_stream_collection_get_size (collection), streams_str->str);
1062
1063   g_string_free (streams_str, TRUE);
1064   return ret;
1065 }
1066
1067 static gchar *
1068 gst_debug_print_object (gpointer ptr)
1069 {
1070   GObject *object = (GObject *) ptr;
1071
1072 #ifdef unused
1073   /* This is a cute trick to detect unmapped memory, but is unportable,
1074    * slow, screws around with madvise, and not actually that useful. */
1075   {
1076     int ret;
1077
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);
1081     }
1082   }
1083 #endif
1084
1085   /* nicely printed object */
1086   if (object == NULL) {
1087     return g_strdup ("(NULL)");
1088   }
1089   if (GST_IS_CAPS (ptr)) {
1090     return gst_caps_to_string ((const GstCaps *) ptr);
1091   }
1092   if (GST_IS_STRUCTURE (ptr)) {
1093     return gst_info_structure_to_string ((const GstStructure *) ptr);
1094   }
1095   if (*(GType *) ptr == GST_TYPE_CAPS_FEATURES) {
1096     return gst_caps_features_to_string ((const GstCapsFeatures *) ptr);
1097   }
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);
1102     else
1103       return str;
1104   }
1105   if (*(GType *) ptr == GST_TYPE_DATE_TIME) {
1106     return __gst_date_time_serialize ((GstDateTime *) ptr, TRUE);
1107   }
1108   if (GST_IS_BUFFER (ptr)) {
1109     return gst_info_describe_buffer (GST_BUFFER_CAST (ptr));
1110   }
1111   if (GST_IS_BUFFER_LIST (ptr)) {
1112     return gst_info_describe_buffer_list (GST_BUFFER_LIST_CAST (ptr));
1113   }
1114 #ifdef USE_POISONING
1115   if (*(guint32 *) ptr == 0xffffffff) {
1116     return g_strdup_printf ("<poisoned@%p>", ptr);
1117   }
1118 #endif
1119   if (GST_IS_MESSAGE (object)) {
1120     return gst_info_describe_message (GST_MESSAGE_CAST (object));
1121   }
1122   if (GST_IS_QUERY (object)) {
1123     return gst_info_describe_query (GST_QUERY_CAST (object));
1124   }
1125   if (GST_IS_EVENT (object)) {
1126     return gst_info_describe_event (GST_EVENT_CAST (object));
1127   }
1128   if (GST_IS_CONTEXT (object)) {
1129     GstContext *context = GST_CONTEXT_CAST (object);
1130     gchar *s, *ret;
1131     const gchar *type;
1132     const GstStructure *structure;
1133
1134     type = gst_context_get_context_type (context);
1135     structure = gst_context_get_structure (context);
1136
1137     s = gst_info_structure_to_string (structure);
1138
1139     ret = g_strdup_printf ("context '%s'='%s'", type, s);
1140     g_free (s);
1141     return ret;
1142   }
1143   if (GST_IS_STREAM (object)) {
1144     return gst_info_describe_stream (GST_STREAM_CAST (object));
1145   }
1146   if (GST_IS_STREAM_COLLECTION (object)) {
1147     return
1148         gst_info_describe_stream_collection (GST_STREAM_COLLECTION_CAST
1149         (object));
1150   }
1151   if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
1152     return g_strdup_printf ("<%s:%s>", GST_DEBUG_PAD_NAME (object));
1153   }
1154   if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object)) {
1155     return g_strdup_printf ("<%s>", GST_OBJECT_NAME (object));
1156   }
1157   if (G_IS_OBJECT (object)) {
1158     return g_strdup_printf ("<%s@%p>", G_OBJECT_TYPE_NAME (object), object);
1159   }
1160
1161   return g_strdup_printf ("%p", ptr);
1162 }
1163
1164 static gchar *
1165 gst_debug_print_segment (gpointer ptr)
1166 {
1167   GstSegment *segment = (GstSegment *) ptr;
1168
1169   /* nicely printed segment */
1170   if (segment == NULL) {
1171     return g_strdup ("(NULL)");
1172   }
1173
1174   switch (segment->format) {
1175     case GST_FORMAT_UNDEFINED:{
1176       return g_strdup_printf ("UNDEFINED segment");
1177     }
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));
1188     }
1189     default:{
1190       const gchar *format_name;
1191
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);
1203     }
1204   }
1205 }
1206
1207 static char *
1208 gst_info_printf_pointer_extension_func (const char *format, void *ptr)
1209 {
1210   char *s = NULL;
1211
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);
1216         break;
1217       case 'B':                /* GST_SEGMENT_FORMAT */
1218         s = gst_debug_print_segment (ptr);
1219         break;
1220       case 'T':                /* GST_TIMEP_FORMAT */
1221         if (ptr)
1222           s = g_strdup_printf ("%" GST_TIME_FORMAT,
1223               GST_TIME_ARGS (*(GstClockTime *) ptr));
1224         break;
1225       case 'S':                /* GST_STIMEP_FORMAT */
1226         if (ptr)
1227           s = g_strdup_printf ("%" GST_STIME_FORMAT,
1228               GST_STIME_ARGS (*(gint64 *) ptr));
1229         break;
1230       case 'a':                /* GST_WRAPPED_PTR_FORMAT */
1231         s = priv_gst_string_take_and_wrap (gst_debug_print_object (ptr));
1232         break;
1233       default:
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 */
1236         break;
1237     }
1238   }
1239   if (s == NULL)
1240     s = g_strdup_printf ("%p", ptr);
1241
1242   return s;
1243 }
1244
1245 /* Allocation-less generator of color escape code. Provide a 20 byte write
1246  * area */
1247 static void
1248 _construct_term_color (guint colorinfo, gchar write_area[20])
1249 {
1250   guint offset;
1251
1252   memcpy (write_area, "\033[00", 4);
1253   offset = 4;
1254
1255   if (colorinfo & GST_DEBUG_BOLD) {
1256     memcpy (write_area + offset, ";01", 3);
1257     offset += 3;
1258   }
1259   if (colorinfo & GST_DEBUG_UNDERLINE) {
1260     memcpy (write_area + offset, ";04", 3);
1261     offset += 3;
1262   }
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);
1266     offset += 3;
1267   }
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);
1271     offset += 3;
1272   }
1273   strncpy (write_area + offset, "m", 2);
1274 }
1275
1276 /**
1277  * gst_debug_construct_term_color:
1278  * @colorinfo: the color info
1279  *
1280  * Constructs a string that can be used for getting the desired color in color
1281  * terminals.
1282  * You need to free the string after use.
1283  *
1284  * Returns: (transfer full) (type gchar*): a string containing the color
1285  *     definition
1286  */
1287 gchar *
1288 gst_debug_construct_term_color (guint colorinfo)
1289 {
1290   gchar tmp_color[20];
1291
1292   _construct_term_color (colorinfo, tmp_color);
1293
1294   return g_strdup (tmp_color);
1295 }
1296
1297 /**
1298  * gst_debug_construct_win_color:
1299  * @colorinfo: the color info
1300  *
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.
1304  *
1305  * This function returns 0 on non-windows machines.
1306  *
1307  * Returns: an integer containing the color definition
1308  */
1309 gint
1310 gst_debug_construct_win_color (guint colorinfo)
1311 {
1312   gint color = 0;
1313 #ifdef G_OS_WIN32
1314   static const guchar ansi_to_win_fg[8] = {
1315     0,                          /* black   */
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   */
1323   };
1324   static const guchar ansi_to_win_bg[8] = {
1325     0,
1326     BACKGROUND_RED,
1327     BACKGROUND_GREEN,
1328     BACKGROUND_RED | BACKGROUND_GREEN,
1329     BACKGROUND_BLUE,
1330     BACKGROUND_RED | BACKGROUND_BLUE,
1331     BACKGROUND_GREEN | FOREGROUND_BLUE,
1332     BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
1333   };
1334
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];
1338   }
1339   if (colorinfo & GST_DEBUG_UNDERLINE) {
1340     color |= BACKGROUND_INTENSITY;
1341   }
1342   if (colorinfo & GST_DEBUG_BOLD) {
1343     color |= FOREGROUND_INTENSITY;
1344   }
1345   if (colorinfo & GST_DEBUG_FG_MASK) {
1346     color |= ansi_to_win_fg[colorinfo & GST_DEBUG_FG_MASK];
1347   }
1348   if (colorinfo & GST_DEBUG_BG_MASK) {
1349     color |= ansi_to_win_bg[(colorinfo & GST_DEBUG_BG_MASK) >> 4];
1350   }
1351 #endif
1352   return color;
1353 }
1354
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"
1361 #else
1362 #define PTR_FMT "%10p"
1363 #endif
1364 #ifdef G_OS_WIN32
1365 #define PID_FMT "%5lu"
1366 #else
1367 #define PID_FMT "%5d"
1368 #endif
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"
1373
1374 #ifdef G_OS_WIN32
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,
1386   /* GST_LEVEL_LOG */
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 */
1393   0,
1394   /* GST_LEVEL_MEMDUMP */
1395   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
1396 };
1397
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,
1402 };
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 */
1415 };
1416
1417 static void
1418 _gst_debug_log_preamble (GstDebugMessage * message, const gchar ** file,
1419     const gchar ** message_str, const gchar ** object_id,
1420     GstClockTime * elapsed)
1421 {
1422   gchar c;
1423
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);
1432
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
1436    * readability. */
1437   c = (*file)[0];
1438   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && (*file)[1] == ':')) {
1439     *file = gst_path_basename (*file);
1440   }
1441
1442   *object_id = gst_debug_message_get_id (message);
1443   *elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
1444 }
1445
1446 /**
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,
1454  *     or %NULL if none
1455  * @message: the actual message
1456  *
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
1461  * would write out.
1462  *
1463  * Since: 1.18
1464  */
1465 gchar *
1466 gst_debug_log_get_line (GstDebugCategory * category, GstDebugLevel level,
1467     const gchar * file, const gchar * function, gint line,
1468     GObject * object, GstDebugMessage * message)
1469 {
1470   GstClockTime elapsed;
1471   gchar *ret;
1472   const gchar *message_str, *object_id;
1473
1474   _gst_debug_log_preamble (message, &file, &message_str, &object_id, &elapsed);
1475
1476   if (object_id)
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);
1481   else
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);
1486
1487   return ret;
1488 }
1489
1490 #ifdef G_OS_WIN32
1491 static void
1492 _gst_debug_fprintf (FILE * file, const gchar * format, ...)
1493 {
1494   va_list args;
1495   gchar *str = NULL;
1496   gint length;
1497
1498   va_start (args, format);
1499   length = gst_info_vasprintf (&str, format, args);
1500   va_end (args);
1501
1502   if (length == 0 || !str)
1503     return;
1504
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.
1509    */
1510   if (file == stderr) {
1511     g_printerr ("%s", str);
1512   } else if (file == stdout) {
1513     g_print ("%s", str);
1514   } else {
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);
1518
1519     /* FIXME: fflush here might be redundant if setvbuf works as expected */
1520     fflush (file);
1521   }
1522
1523   g_free (str);
1524 }
1525 #endif
1526
1527 /**
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,
1536  *     or %NULL if none
1537  * @user_data: the FILE* to log to
1538  *
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
1543  * @user_data.
1544  *
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);
1548  */
1549 void
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)
1553 {
1554   gint pid;
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;
1560 #ifdef G_OS_WIN32
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))
1564 #else
1565 #define FPRINTF_DEBUG fprintf
1566 #define FFLUSH_DEBUG(f) G_STMT_START { \
1567     fflush (f); \
1568   } G_STMT_END
1569 #endif
1570
1571 #ifdef GST_ENABLE_EXTRA_CHECKS
1572   g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1573 #endif
1574
1575   _gst_debug_log_preamble (message, &file, &message_str, &object_id, &elapsed);
1576
1577   pid = _gst_getpid ();
1578   color_mode = gst_debug_get_color_mode ();
1579
1580   if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
1581 #ifdef G_OS_WIN32
1582     G_LOCK (win_print_mutex);
1583     if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
1584 #endif
1585       /* colors, non-windows */
1586       gchar color[20];
1587       const gchar *clear;
1588       gchar pidcolor[10];
1589       const gchar *levelcolor;
1590
1591       _construct_term_color (gst_debug_category_get_color (category), color);
1592       clear = "\033[00m";
1593       g_sprintf (pidcolor, "\033[%02dm", pid % 6 + 31);
1594       levelcolor = levelcolormap[level];
1595
1596       if (object_id) {
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);
1603       } else {
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);
1610       }
1611       FFLUSH_DEBUG (log_file);
1612 #undef PRINT_FMT
1613 #undef PRINT_FMT_ID
1614 #ifdef G_OS_WIN32
1615     } else {
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)); \
1621   } G_STMT_END
1622       /* timestamp */
1623       FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT " ",
1624           GST_TIME_ARGS (elapsed));
1625       /* pid */
1626       SET_COLOR (available_colors[pid % G_N_ELEMENTS (available_colors)]);
1627       FPRINTF_DEBUG (log_file, PID_FMT, pid);
1628       /* thread */
1629       SET_COLOR (clear);
1630       FPRINTF_DEBUG (log_file, " " PTR_FMT " ", g_thread_self ());
1631       /* level */
1632       SET_COLOR (levelcolormap_w32[level]);
1633       FPRINTF_DEBUG (log_file, "%s ", gst_debug_level_get_name (level));
1634       /* category */
1635       SET_COLOR (gst_debug_construct_win_color (gst_debug_category_get_color
1636               (category)));
1637       if (object_id) {
1638         FPRINTF_DEBUG (log_file, CAT_FMT_ID,
1639             gst_debug_category_get_name (category), file, line, function,
1640             object_id);
1641       } else {
1642         FPRINTF_DEBUG (log_file, CAT_FMT,
1643             gst_debug_category_get_name (category), file, line, function, "");
1644       }
1645       /* message */
1646       SET_COLOR (clear);
1647       FPRINTF_DEBUG (log_file, " %s\n", message_str);
1648     }
1649     G_UNLOCK (win_print_mutex);
1650 #endif
1651   } else {
1652     /* no color, all platforms */
1653     if (object_id) {
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);
1659     } else {
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, "",
1664           message_str);
1665     }
1666     FFLUSH_DEBUG (log_file);
1667   }
1668 }
1669
1670 /**
1671  * gst_debug_level_get_name:
1672  * @level: the level to get the name for
1673  *
1674  * Get the string representation of a debugging level
1675  *
1676  * Returns: the name
1677  */
1678 const gchar *
1679 gst_debug_level_get_name (GstDebugLevel level)
1680 {
1681   switch (level) {
1682     case GST_LEVEL_NONE:
1683       return "";
1684     case GST_LEVEL_ERROR:
1685       return "ERROR  ";
1686     case GST_LEVEL_WARNING:
1687       return "WARN   ";
1688     case GST_LEVEL_INFO:
1689       return "INFO   ";
1690     case GST_LEVEL_DEBUG:
1691       return "DEBUG  ";
1692     case GST_LEVEL_LOG:
1693       return "LOG    ";
1694     case GST_LEVEL_FIXME:
1695       return "FIXME  ";
1696     case GST_LEVEL_TRACE:
1697       return "TRACE  ";
1698     case GST_LEVEL_MEMDUMP:
1699       return "MEMDUMP";
1700     default:
1701       g_warning ("invalid level specified for gst_debug_level_get_name");
1702       return "";
1703   }
1704 }
1705
1706 /**
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
1711  *
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.
1714  */
1715 void
1716 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
1717     GDestroyNotify notify)
1718 {
1719   LogFuncEntry *entry;
1720   GSList *list;
1721
1722   if (func == NULL)
1723     func = gst_debug_log_default;
1724
1725   entry = g_slice_new (LogFuncEntry);
1726   entry->func = func;
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.
1734    */
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);
1739
1740   if (gst_is_initialized ())
1741     GST_DEBUG ("prepended log function %p (user data %p) to log functions",
1742         func, user_data);
1743 }
1744
1745 static gint
1746 gst_debug_compare_log_function_by_func (gconstpointer entry, gconstpointer func)
1747 {
1748   gpointer entryfunc = (gpointer) (((LogFuncEntry *) entry)->func);
1749
1750   return (entryfunc < func) ? -1 : (entryfunc > func) ? 1 : 0;
1751 }
1752
1753 static gint
1754 gst_debug_compare_log_function_by_data (gconstpointer entry, gconstpointer data)
1755 {
1756   gpointer entrydata = ((LogFuncEntry *) entry)->user_data;
1757
1758   return (entrydata < data) ? -1 : (entrydata > data) ? 1 : 0;
1759 }
1760
1761 static guint
1762 gst_debug_remove_with_compare_func (GCompareFunc func, gpointer data)
1763 {
1764   GSList *found;
1765   GSList *new, *cleanup = NULL;
1766   guint removals = 0;
1767
1768   g_mutex_lock (&__log_func_mutex);
1769   new = __log_functions;
1770   cleanup = NULL;
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);
1776       continue;
1777     }
1778     cleanup = g_slist_prepend (cleanup, found->data);
1779     new = g_slist_delete_link (new, found);
1780     removals++;
1781   }
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);
1785
1786   while (cleanup) {
1787     LogFuncEntry *entry = cleanup->data;
1788
1789     if (entry->notify)
1790       entry->notify (entry->user_data);
1791
1792     g_slice_free (LogFuncEntry, entry);
1793     cleanup = g_slist_delete_link (cleanup, cleanup);
1794   }
1795   return removals;
1796 }
1797
1798 /**
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
1802  *
1803  * Removes all registered instances of the given logging functions.
1804  *
1805  * Returns: How many instances of the function were removed
1806  */
1807 guint
1808 gst_debug_remove_log_function (GstLogFunction func)
1809 {
1810   guint removals;
1811
1812   if (func == NULL)
1813     func = gst_debug_log_default;
1814
1815   removals =
1816       gst_debug_remove_with_compare_func
1817       (gst_debug_compare_log_function_by_func, (gpointer) func);
1818
1819   if (gst_is_initialized ()) {
1820     GST_DEBUG ("removed log function %p %d times from log function list", func,
1821         removals);
1822   } else {
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;
1827       ++removals;
1828     }
1829   }
1830
1831   return removals;
1832 }
1833
1834 /**
1835  * gst_debug_remove_log_function_by_data:
1836  * @data: user data of the log function to remove
1837  *
1838  * Removes all registered instances of log functions with the given user data.
1839  *
1840  * Returns: How many instances of the function were removed
1841  */
1842 guint
1843 gst_debug_remove_log_function_by_data (gpointer data)
1844 {
1845   guint removals;
1846
1847   removals =
1848       gst_debug_remove_with_compare_func
1849       (gst_debug_compare_log_function_by_data, data);
1850
1851   if (gst_is_initialized ())
1852     GST_DEBUG
1853         ("removed %d log functions with user data %p from log function list",
1854         removals, data);
1855
1856   return removals;
1857 }
1858
1859 /**
1860  * gst_debug_set_colored:
1861  * @colored: Whether to use colored output or not
1862  *
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.
1866  *
1867  * This function may be called before gst_init().
1868  */
1869 void
1870 gst_debug_set_colored (gboolean colored)
1871 {
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);
1875 }
1876
1877 /**
1878  * gst_debug_set_color_mode:
1879  * @mode: The coloring mode for debug output. See @GstDebugColorMode.
1880  *
1881  * Changes the coloring mode for debug output.
1882  *
1883  * This function may be called before gst_init().
1884  *
1885  * Since: 1.2
1886  */
1887 void
1888 gst_debug_set_color_mode (GstDebugColorMode mode)
1889 {
1890   g_atomic_int_set (&__use_color, mode);
1891 }
1892
1893 /**
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".
1897  *
1898  * Changes the coloring mode for debug output.
1899  *
1900  * This function may be called before gst_init().
1901  *
1902  * Since: 1.2
1903  */
1904 void
1905 gst_debug_set_color_mode_from_string (const gchar * mode)
1906 {
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);
1913 }
1914
1915 /**
1916  * gst_debug_is_colored:
1917  *
1918  * Checks if the debugging output should be colored.
1919  *
1920  * Returns: %TRUE, if the debug output should be colored.
1921  */
1922 gboolean
1923 gst_debug_is_colored (void)
1924 {
1925   GstDebugColorMode mode = g_atomic_int_get (&__use_color);
1926   return (mode == GST_DEBUG_COLOR_MODE_UNIX || mode == GST_DEBUG_COLOR_MODE_ON);
1927 }
1928
1929 /**
1930  * gst_debug_get_color_mode:
1931  *
1932  * Changes the coloring mode for debug output.
1933  *
1934  * Returns: see @GstDebugColorMode for possible values.
1935  *
1936  * Since: 1.2
1937  */
1938 GstDebugColorMode
1939 gst_debug_get_color_mode (void)
1940 {
1941   return g_atomic_int_get (&__use_color);
1942 }
1943
1944 /**
1945  * gst_debug_set_active:
1946  * @active: Whether to use debugging output or not
1947  *
1948  * If activated, debugging messages are sent to the debugging
1949  * handlers.
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.
1953  */
1954 void
1955 gst_debug_set_active (gboolean active)
1956 {
1957   _gst_debug_enabled = active;
1958   if (active)
1959     _gst_debug_min = GST_LEVEL_COUNT;
1960   else
1961     _gst_debug_min = GST_LEVEL_NONE;
1962 }
1963
1964 /**
1965  * gst_debug_is_active:
1966  *
1967  * Checks if debugging output is activated.
1968  *
1969  * Returns: %TRUE, if debugging is activated
1970  */
1971 gboolean
1972 gst_debug_is_active (void)
1973 {
1974   return _gst_debug_enabled;
1975 }
1976
1977 /**
1978  * gst_debug_set_default_threshold:
1979  * @level: level to set
1980  *
1981  * Sets the default threshold to the given level and updates all categories to
1982  * use this threshold.
1983  *
1984  * This function may be called before gst_init().
1985  */
1986 void
1987 gst_debug_set_default_threshold (GstDebugLevel level)
1988 {
1989   g_atomic_int_set (&__default_level, level);
1990   gst_debug_reset_all_thresholds ();
1991 }
1992
1993 /**
1994  * gst_debug_get_default_threshold:
1995  *
1996  * Returns the default threshold that is used for new categories.
1997  *
1998  * Returns: the default threshold level
1999  */
2000 GstDebugLevel
2001 gst_debug_get_default_threshold (void)
2002 {
2003   return (GstDebugLevel) g_atomic_int_get (&__default_level);
2004 }
2005
2006 #if !GLIB_CHECK_VERSION(2,70,0)
2007 #define g_pattern_spec_match_string g_pattern_match_string
2008 #endif
2009
2010 static gboolean
2011 gst_debug_apply_entry (GstDebugCategory * cat, LevelNameEntry * entry)
2012 {
2013   if (!g_pattern_spec_match_string (entry->pat, cat->name))
2014     return FALSE;
2015
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);
2019
2020   gst_debug_category_set_threshold (cat, entry->level);
2021   return TRUE;
2022 }
2023
2024 static void
2025 gst_debug_reset_threshold (gpointer category, gpointer unused)
2026 {
2027   GstDebugCategory *cat = (GstDebugCategory *) category;
2028   GSList *walk;
2029
2030   g_mutex_lock (&__level_name_mutex);
2031
2032   for (walk = __level_name; walk != NULL; walk = walk->next) {
2033     if (gst_debug_apply_entry (cat, walk->data))
2034       break;
2035   }
2036
2037   g_mutex_unlock (&__level_name_mutex);
2038
2039   if (walk == NULL)
2040     gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
2041 }
2042
2043 static void
2044 gst_debug_reset_all_thresholds (void)
2045 {
2046   g_mutex_lock (&__cat_mutex);
2047   g_slist_foreach (__categories, gst_debug_reset_threshold, NULL);
2048   g_mutex_unlock (&__cat_mutex);
2049 }
2050
2051 static void
2052 for_each_threshold_by_entry (gpointer data, gpointer user_data)
2053 {
2054   GstDebugCategory *cat = (GstDebugCategory *) data;
2055   LevelNameEntry *entry = (LevelNameEntry *) user_data;
2056
2057   gst_debug_apply_entry (cat, entry);
2058 }
2059
2060 /**
2061  * gst_debug_set_threshold_for_name:
2062  * @name: name of the categories to set
2063  * @level: level to set them to
2064  *
2065  * Sets all categories which match the given glob style pattern to the given
2066  * level.
2067  */
2068 void
2069 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2070 {
2071   GPatternSpec *pat;
2072   LevelNameEntry *entry;
2073
2074   g_return_if_fail (name != NULL);
2075
2076   pat = g_pattern_spec_new (name);
2077   entry = g_slice_new (LevelNameEntry);
2078   entry->pat = pat;
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);
2086 }
2087
2088 /**
2089  * gst_debug_unset_threshold_for_name:
2090  * @name: name of the categories to set
2091  *
2092  * Resets all categories with the given name back to the default level.
2093  */
2094 void
2095 gst_debug_unset_threshold_for_name (const gchar * name)
2096 {
2097   GSList *walk;
2098   GPatternSpec *pat;
2099
2100   g_return_if_fail (name != NULL);
2101
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 */
2106   while (walk) {
2107     LevelNameEntry *entry = walk->data;
2108
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;
2115     } else {
2116       walk = g_slist_next (walk);
2117     }
2118   }
2119   g_mutex_unlock (&__level_name_mutex);
2120   g_pattern_spec_free (pat);
2121   gst_debug_reset_all_thresholds ();
2122 }
2123
2124 GstDebugCategory *
2125 _gst_debug_category_new (const gchar * name, guint color,
2126     const gchar * description)
2127 {
2128   GstDebugCategory *cat, *catfound;
2129
2130   g_return_val_if_fail (name != NULL, NULL);
2131
2132   cat = g_slice_new (GstDebugCategory);
2133   cat->name = g_strdup (name);
2134   cat->color = color;
2135   if (description != NULL) {
2136     cat->description = g_strdup (description);
2137   } else {
2138     cat->description = g_strdup ("no description");
2139   }
2140   g_atomic_int_set (&cat->threshold, 0);
2141   gst_debug_reset_threshold (cat, NULL);
2142
2143   /* add to category list */
2144   g_mutex_lock (&__cat_mutex);
2145   catfound = _gst_debug_get_category_locked (name);
2146   if (catfound) {
2147     g_free ((gpointer) cat->name);
2148     g_free ((gpointer) cat->description);
2149     g_slice_free (GstDebugCategory, cat);
2150     cat = catfound;
2151   } else {
2152     __categories = g_slist_prepend (__categories, cat);
2153   }
2154   g_mutex_unlock (&__cat_mutex);
2155
2156   return cat;
2157 }
2158
2159 #ifndef GST_REMOVE_DEPRECATED
2160 /**
2161  * gst_debug_category_free:
2162  * @category: #GstDebugCategory to free.
2163  *
2164  * Removes and frees the category and all associated resources.
2165  *
2166  * Deprecated: This function can easily cause memory corruption, don't use it.
2167  */
2168 void
2169 gst_debug_category_free (GstDebugCategory * category)
2170 {
2171 }
2172 #endif
2173
2174 /**
2175  * gst_debug_category_set_threshold:
2176  * @category: a #GstDebugCategory to set threshold of.
2177  * @level: the #GstDebugLevel threshold to set.
2178  *
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).
2185  */
2186 void
2187 gst_debug_category_set_threshold (GstDebugCategory * category,
2188     GstDebugLevel level)
2189 {
2190   g_return_if_fail (category != NULL);
2191
2192   if (level > _gst_debug_min) {
2193     _gst_debug_enabled = TRUE;
2194     _gst_debug_min = level;
2195   }
2196
2197   g_atomic_int_set (&category->threshold, level);
2198 }
2199
2200 /**
2201  * gst_debug_category_reset_threshold:
2202  * @category: a #GstDebugCategory to reset threshold of.
2203  *
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().
2209  */
2210 void
2211 gst_debug_category_reset_threshold (GstDebugCategory * category)
2212 {
2213   gst_debug_reset_threshold (category, NULL);
2214 }
2215
2216 /**
2217  * gst_debug_category_get_threshold:
2218  * @category: a #GstDebugCategory to get threshold of.
2219  *
2220  * Returns the threshold of a #GstDebugCategory.
2221  *
2222  * Returns: the #GstDebugLevel that is used as threshold.
2223  */
2224 GstDebugLevel
2225 gst_debug_category_get_threshold (GstDebugCategory * category)
2226 {
2227   return (GstDebugLevel) g_atomic_int_get (&category->threshold);
2228 }
2229
2230 /**
2231  * gst_debug_category_get_name:
2232  * @category: a #GstDebugCategory to get name of.
2233  *
2234  * Returns the name of a debug category.
2235  *
2236  * Returns: the name of the category.
2237  */
2238 const gchar *
2239 gst_debug_category_get_name (GstDebugCategory * category)
2240 {
2241   return category->name;
2242 }
2243
2244 /**
2245  * gst_debug_category_get_color:
2246  * @category: a #GstDebugCategory to get the color of.
2247  *
2248  * Returns the color of a debug category used when printing output in this
2249  * category.
2250  *
2251  * Returns: the color of the category.
2252  */
2253 guint
2254 gst_debug_category_get_color (GstDebugCategory * category)
2255 {
2256   return category->color;
2257 }
2258
2259 /**
2260  * gst_debug_category_get_description:
2261  * @category: a #GstDebugCategory to get the description of.
2262  *
2263  * Returns the description of a debug category.
2264  *
2265  * Returns: the description of the category.
2266  */
2267 const gchar *
2268 gst_debug_category_get_description (GstDebugCategory * category)
2269 {
2270   return category->description;
2271 }
2272
2273 /**
2274  * gst_debug_get_all_categories:
2275  *
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.
2279  *
2280  * Returns: (transfer container) (element-type Gst.DebugCategory): the list of
2281  *     debug categories
2282  */
2283 GSList *
2284 gst_debug_get_all_categories (void)
2285 {
2286   GSList *ret;
2287
2288   g_mutex_lock (&__cat_mutex);
2289   ret = g_slist_copy (__categories);
2290   g_mutex_unlock (&__cat_mutex);
2291
2292   return ret;
2293 }
2294
2295 static GstDebugCategory *
2296 _gst_debug_get_category_locked (const gchar * name)
2297 {
2298   GstDebugCategory *ret = NULL;
2299   GSList *node;
2300
2301   for (node = __categories; node; node = g_slist_next (node)) {
2302     ret = (GstDebugCategory *) node->data;
2303     if (!strcmp (name, ret->name)) {
2304       return ret;
2305     }
2306   }
2307   return NULL;
2308 }
2309
2310 GstDebugCategory *
2311 _gst_debug_get_category (const gchar * name)
2312 {
2313   GstDebugCategory *ret;
2314
2315   g_mutex_lock (&__cat_mutex);
2316   ret = _gst_debug_get_category_locked (name);
2317   g_mutex_unlock (&__cat_mutex);
2318
2319   return ret;
2320 }
2321
2322 static gboolean
2323 parse_debug_category (gchar * str, const gchar ** category)
2324 {
2325   if (!str)
2326     return FALSE;
2327
2328   /* works in place */
2329   g_strstrip (str);
2330
2331   if (str[0] != '\0') {
2332     *category = str;
2333     return TRUE;
2334   }
2335
2336   return FALSE;
2337 }
2338
2339 static gboolean
2340 parse_debug_level (gchar * str, GstDebugLevel * level)
2341 {
2342   if (!str)
2343     return FALSE;
2344
2345   /* works in place */
2346   g_strstrip (str);
2347
2348   if (g_ascii_isdigit (str[0])) {
2349     unsigned long l;
2350     char *endptr;
2351     l = strtoul (str, &endptr, 10);
2352     if (endptr > str && endptr[0] == 0) {
2353       *level = (GstDebugLevel) l;
2354     } else {
2355       return FALSE;
2356     }
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;
2375   } else
2376     return FALSE;
2377
2378   return TRUE;
2379 }
2380
2381 /**
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
2386  *     new thresholds
2387  * %FALSE if adding the threshold described by @list to the one already set.
2388  *
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.
2393  *
2394  * Since: 1.2
2395  */
2396 void
2397 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2398 {
2399   gchar **split;
2400   gchar **walk;
2401
2402   g_assert (list);
2403
2404   if (reset) {
2405     clear_level_names ();
2406     gst_debug_set_default_threshold (GST_LEVEL_DEFAULT);
2407   }
2408
2409   split = g_strsplit (list, ",", 0);
2410
2411   for (walk = split; *walk; walk++) {
2412     if (strchr (*walk, ':')) {
2413       gchar **values = g_strsplit (*walk, ":", 2);
2414
2415       if (values[0] && values[1]) {
2416         GstDebugLevel level;
2417         const gchar *category;
2418
2419         if (parse_debug_category (values[0], &category)
2420             && parse_debug_level (values[1], &level)) {
2421           gst_debug_set_threshold_for_name (category, level);
2422
2423           /* bump min-level anyway to allow the category to be registered in the
2424            * future still */
2425           if (level > _gst_debug_min) {
2426             _gst_debug_min = level;
2427           }
2428         }
2429       }
2430
2431       g_strfreev (values);
2432     } else {
2433       GstDebugLevel level;
2434
2435       if (parse_debug_level (*walk, &level))
2436         gst_debug_set_default_threshold (level);
2437     }
2438   }
2439
2440   g_strfreev (split);
2441 }
2442
2443 /*** FUNCTION POINTERS ********************************************************/
2444
2445 static GHashTable *__gst_function_pointers;     /* NULL */
2446 static GMutex __dbg_functions_mutex;
2447
2448 /* This function MUST NOT return NULL */
2449 const gchar *
2450 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2451 {
2452   gchar *ptrname;
2453
2454 #ifdef HAVE_DLADDR
2455   Dl_info dl_info;
2456 #endif
2457
2458   if (G_UNLIKELY (func == NULL))
2459     return "(NULL)";
2460
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))
2466       return ptrname;
2467   } else {
2468     g_mutex_unlock (&__dbg_functions_mutex);
2469   }
2470   /* we need to create an entry in the hash table for this one so we don't leak
2471    * the name */
2472 #ifdef HAVE_DLADDR
2473   if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
2474     const gchar *name = g_intern_string (dl_info.dli_sname);
2475
2476     _gst_debug_register_funcptr (func, name);
2477     return name;
2478   } else
2479 #endif
2480   {
2481     gchar *name = g_strdup_printf ("%p", (gpointer) func);
2482     const gchar *iname = g_intern_string (name);
2483
2484     g_free (name);
2485
2486     _gst_debug_register_funcptr (func, iname);
2487     return iname;
2488   }
2489 }
2490
2491 void
2492 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2493 {
2494   gpointer ptr = (gpointer) func;
2495
2496   g_mutex_lock (&__dbg_functions_mutex);
2497
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);
2502   }
2503
2504   g_mutex_unlock (&__dbg_functions_mutex);
2505 }
2506
2507 static void
2508 clear_level_names (void)
2509 {
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);
2516   }
2517   g_mutex_unlock (&__level_name_mutex);
2518 }
2519
2520 void
2521 _priv_gst_debug_cleanup (void)
2522 {
2523   g_mutex_lock (&__dbg_functions_mutex);
2524
2525   if (__gst_function_pointers) {
2526     g_hash_table_unref (__gst_function_pointers);
2527     __gst_function_pointers = NULL;
2528   }
2529
2530   g_mutex_unlock (&__dbg_functions_mutex);
2531
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);
2539   }
2540   g_mutex_unlock (&__cat_mutex);
2541
2542   clear_level_names ();
2543
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);
2551   }
2552   g_mutex_unlock (&__log_func_mutex);
2553 }
2554
2555 static void
2556 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2557     const guint8 * mem, gsize mem_offset, gsize mem_size)
2558 {
2559   gchar hexstr[50], ascstr[18], digitstr[4];
2560
2561   if (mem_size > 16)
2562     mem_size = 16;
2563
2564   hexstr[0] = '\0';
2565   ascstr[0] = '\0';
2566
2567   if (mem != NULL) {
2568     guint i = 0;
2569
2570     mem += mem_offset;
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));
2575       ++i;
2576     }
2577     ascstr[i] = '\0';
2578   }
2579
2580   g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2581       (guint) mem_offset, hexstr, ascstr);
2582 }
2583
2584 static void
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)
2588 {
2589   guint off = 0;
2590   gboolean free_object_id = FALSE;
2591   gchar tmp_id[32];
2592
2593   if (object_id == NULL && obj)
2594     object_id = _get_object_id (obj, &free_object_id, (gchar *) & tmp_id);
2595
2596   gst_debug_log_id ((cat), GST_LEVEL_MEMDUMP, file, func, line, object_id,
2597       "--------"
2598       "-------------------------------------------------------------------");
2599
2600   if (msg != NULL && *msg != '\0') {
2601     gst_debug_log_id ((cat), GST_LEVEL_MEMDUMP, file, func, line, object_id,
2602         "%s", msg);
2603   }
2604
2605   while (off < length) {
2606     gchar buf[128];
2607
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",
2611         buf);
2612     off += 16;
2613   }
2614
2615   gst_debug_log_id ((cat), GST_LEVEL_MEMDUMP, file, func, line, object_id,
2616       "--------"
2617       "-------------------------------------------------------------------");
2618
2619   if (free_object_id)
2620     g_free ((gchar *) object_id);
2621 }
2622
2623 void
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)
2627 {
2628   _gst_debug_dump_mem_full (cat, file, func, line, obj, NULL, msg, data,
2629       length);
2630 }
2631
2632 void
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)
2636 {
2637   _gst_debug_dump_mem_full (cat, file, func, line, NULL, object_id, msg, data,
2638       length);
2639 }
2640
2641
2642 #else /* !GST_DISABLE_GST_DEBUG */
2643 #ifndef GST_REMOVE_DISABLED
2644
2645 GstDebugCategory *
2646 _gst_debug_category_new (const gchar * name, guint color,
2647     const gchar * description)
2648 {
2649   return NULL;
2650 }
2651
2652 void
2653 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2654 {
2655 }
2656
2657 /* This function MUST NOT return NULL */
2658 const gchar *
2659 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2660 {
2661   return "(NULL)";
2662 }
2663
2664 void
2665 _priv_gst_debug_cleanup (void)
2666 {
2667 }
2668
2669 void
2670 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2671     const gchar * file, const gchar * function, gint line,
2672     GObject * object, const gchar * format, ...)
2673 {
2674 }
2675
2676 void
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)
2680 {
2681 }
2682
2683 void
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)
2687 {
2688 }
2689
2690 const gchar *
2691 gst_debug_message_get (GstDebugMessage * message)
2692 {
2693   return "";
2694 }
2695
2696 const gchar *
2697 gst_debug_message_get_id (GstDebugMessage * message)
2698 {
2699   return NULL;
2700 }
2701
2702 void
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)
2706 {
2707 }
2708
2709 const gchar *
2710 gst_debug_level_get_name (GstDebugLevel level)
2711 {
2712   return "NONE";
2713 }
2714
2715 void
2716 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2717     GDestroyNotify notify)
2718 {
2719   if (notify)
2720     notify (user_data);
2721 }
2722
2723 guint
2724 gst_debug_remove_log_function (GstLogFunction func)
2725 {
2726   return 0;
2727 }
2728
2729 guint
2730 gst_debug_remove_log_function_by_data (gpointer data)
2731 {
2732   return 0;
2733 }
2734
2735 void
2736 gst_debug_set_active (gboolean active)
2737 {
2738 }
2739
2740 gboolean
2741 gst_debug_is_active (void)
2742 {
2743   return FALSE;
2744 }
2745
2746 void
2747 gst_debug_set_colored (gboolean colored)
2748 {
2749 }
2750
2751 void
2752 gst_debug_set_color_mode (GstDebugColorMode mode)
2753 {
2754 }
2755
2756 void
2757 gst_debug_set_color_mode_from_string (const gchar * str)
2758 {
2759 }
2760
2761 gboolean
2762 gst_debug_is_colored (void)
2763 {
2764   return FALSE;
2765 }
2766
2767 GstDebugColorMode
2768 gst_debug_get_color_mode (void)
2769 {
2770   return GST_DEBUG_COLOR_MODE_OFF;
2771 }
2772
2773 void
2774 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2775 {
2776 }
2777
2778 void
2779 gst_debug_set_default_threshold (GstDebugLevel level)
2780 {
2781 }
2782
2783 GstDebugLevel
2784 gst_debug_get_default_threshold (void)
2785 {
2786   return GST_LEVEL_NONE;
2787 }
2788
2789 void
2790 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2791 {
2792 }
2793
2794 void
2795 gst_debug_unset_threshold_for_name (const gchar * name)
2796 {
2797 }
2798
2799 #ifndef GST_REMOVE_DEPRECATED
2800 void
2801 gst_debug_category_free (GstDebugCategory * category)
2802 {
2803 }
2804 #endif
2805
2806 void
2807 gst_debug_category_set_threshold (GstDebugCategory * category,
2808     GstDebugLevel level)
2809 {
2810 }
2811
2812 void
2813 gst_debug_category_reset_threshold (GstDebugCategory * category)
2814 {
2815 }
2816
2817 GstDebugLevel
2818 gst_debug_category_get_threshold (GstDebugCategory * category)
2819 {
2820   return GST_LEVEL_NONE;
2821 }
2822
2823 const gchar *
2824 gst_debug_category_get_name (GstDebugCategory * category)
2825 {
2826   return "";
2827 }
2828
2829 guint
2830 gst_debug_category_get_color (GstDebugCategory * category)
2831 {
2832   return 0;
2833 }
2834
2835 const gchar *
2836 gst_debug_category_get_description (GstDebugCategory * category)
2837 {
2838   return "";
2839 }
2840
2841 GSList *
2842 gst_debug_get_all_categories (void)
2843 {
2844   return NULL;
2845 }
2846
2847 GstDebugCategory *
2848 _gst_debug_get_category (const gchar * name)
2849 {
2850   return NULL;
2851 }
2852
2853 gchar *
2854 gst_debug_construct_term_color (guint colorinfo)
2855 {
2856   return g_strdup ("00");
2857 }
2858
2859 gint
2860 gst_debug_construct_win_color (guint colorinfo)
2861 {
2862   return 0;
2863 }
2864
2865 void
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)
2869 {
2870 }
2871 #endif /* GST_REMOVE_DISABLED */
2872 #endif /* GST_DISABLE_GST_DEBUG */
2873
2874 /**
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
2879  *
2880  * Allocates and fills a string large enough (including the terminating null
2881  * byte) to hold the specified printf style @format and @args.
2882  *
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().
2887  *
2888  * Free @result with g_free().
2889  *
2890  * Returns: the length of the string allocated into @result or -1 on any error
2891  *
2892  * Since: 1.8
2893  */
2894 gint
2895 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2896 {
2897   return __gst_vasprintf (result, format, args);
2898 }
2899
2900 /**
2901  * gst_info_strdup_vprintf:
2902  * @format: a printf style format string
2903  * @args: the va_list of printf arguments for @format
2904  *
2905  * Allocates, fills and returns a null terminated string from the printf style
2906  * @format string and @args.
2907  *
2908  * See gst_info_vasprintf() for when this function is required.
2909  *
2910  * Free with g_free().
2911  *
2912  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2913  *
2914  * Since: 1.8
2915  */
2916 gchar *
2917 gst_info_strdup_vprintf (const gchar * format, va_list args)
2918 {
2919   gchar *ret;
2920
2921   if (gst_info_vasprintf (&ret, format, args) < 0)
2922     ret = NULL;
2923
2924   return ret;
2925 }
2926
2927 /**
2928  * gst_info_strdup_printf:
2929  * @format: a printf style format string
2930  * @...: the printf arguments for @format
2931  *
2932  * Allocates, fills and returns a 0-terminated string from the printf style
2933  * @format string and corresponding arguments.
2934  *
2935  * See gst_info_vasprintf() for when this function is required.
2936  *
2937  * Free with g_free().
2938  *
2939  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2940  *
2941  * Since: 1.8
2942  */
2943 gchar *
2944 gst_info_strdup_printf (const gchar * format, ...)
2945 {
2946   gchar *ret;
2947   va_list args;
2948
2949   va_start (args, format);
2950   ret = gst_info_strdup_vprintf (format, args);
2951   va_end (args);
2952
2953   return ret;
2954 }
2955
2956 /**
2957  * gst_print:
2958  * @format: a printf style format string
2959  * @...: the printf arguments for @format
2960  *
2961  * Outputs a formatted message via the GLib print handler. The default print
2962  * handler simply outputs the message to stdout.
2963  *
2964  * This function will not append a new-line character at the end, unlike
2965  * gst_println() which will.
2966  *
2967  * All strings must be in ASCII or UTF-8 encoding.
2968  *
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.
2972  *
2973  * This function is primarily for printing debug output.
2974  *
2975  * Since: 1.12
2976  */
2977 void
2978 gst_print (const gchar * format, ...)
2979 {
2980   va_list args;
2981   gchar *str;
2982
2983   va_start (args, format);
2984   str = gst_info_strdup_vprintf (format, args);
2985   va_end (args);
2986
2987 #ifdef G_OS_WIN32
2988   G_LOCK (win_print_mutex);
2989 #endif
2990
2991   g_print ("%s", str);
2992
2993 #ifdef G_OS_WIN32
2994   G_UNLOCK (win_print_mutex);
2995 #endif
2996   g_free (str);
2997 }
2998
2999 /**
3000  * gst_println:
3001  * @format: a printf style format string
3002  * @...: the printf arguments for @format
3003  *
3004  * Outputs a formatted message via the GLib print handler. The default print
3005  * handler simply outputs the message to stdout.
3006  *
3007  * This function will append a new-line character at the end, unlike
3008  * gst_print() which will not.
3009  *
3010  * All strings must be in ASCII or UTF-8 encoding.
3011  *
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.
3015  *
3016  * This function is primarily for printing debug output.
3017  *
3018  * Since: 1.12
3019  */
3020 void
3021 gst_println (const gchar * format, ...)
3022 {
3023   va_list args;
3024   gchar *str;
3025
3026   va_start (args, format);
3027   str = gst_info_strdup_vprintf (format, args);
3028   va_end (args);
3029
3030 #ifdef G_OS_WIN32
3031   G_LOCK (win_print_mutex);
3032 #endif
3033
3034   g_print ("%s\n", str);
3035
3036 #ifdef G_OS_WIN32
3037   G_UNLOCK (win_print_mutex);
3038 #endif
3039   g_free (str);
3040 }
3041
3042 /**
3043  * gst_printerr:
3044  * @format: a printf style format string
3045  * @...: the printf arguments for @format
3046  *
3047  * Outputs a formatted message via the GLib error message handler. The default
3048  * handler simply outputs the message to stderr.
3049  *
3050  * This function will not append a new-line character at the end, unlike
3051  * gst_printerrln() which will.
3052  *
3053  * All strings must be in ASCII or UTF-8 encoding.
3054  *
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.
3058  *
3059  * This function is primarily for printing debug output.
3060  *
3061  * Since: 1.12
3062  */
3063 void
3064 gst_printerr (const gchar * format, ...)
3065 {
3066   va_list args;
3067   gchar *str;
3068
3069   va_start (args, format);
3070   str = gst_info_strdup_vprintf (format, args);
3071   va_end (args);
3072
3073 #ifdef G_OS_WIN32
3074   G_LOCK (win_print_mutex);
3075 #endif
3076
3077   g_printerr ("%s", str);
3078
3079 #ifdef G_OS_WIN32
3080   G_UNLOCK (win_print_mutex);
3081 #endif
3082   g_free (str);
3083 }
3084
3085 /**
3086  * gst_printerrln:
3087  * @format: a printf style format string
3088  * @...: the printf arguments for @format
3089  *
3090  * Outputs a formatted message via the GLib error message handler. The default
3091  * handler simply outputs the message to stderr.
3092  *
3093  * This function will append a new-line character at the end, unlike
3094  * gst_printerr() which will not.
3095  *
3096  * All strings must be in ASCII or UTF-8 encoding.
3097  *
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.
3101  *
3102  * This function is primarily for printing debug output.
3103  *
3104  * Since: 1.12
3105  */
3106 void
3107 gst_printerrln (const gchar * format, ...)
3108 {
3109   va_list args;
3110   gchar *str;
3111
3112   va_start (args, format);
3113   str = gst_info_strdup_vprintf (format, args);
3114   va_end (args);
3115
3116 #ifdef G_OS_WIN32
3117   G_LOCK (win_print_mutex);
3118 #endif
3119
3120   g_printerr ("%s\n", str);
3121
3122 #ifdef G_OS_WIN32
3123   G_UNLOCK (win_print_mutex);
3124 #endif
3125   g_free (str);
3126 }
3127
3128 #ifdef HAVE_UNWIND
3129 #ifdef HAVE_DW
3130 static gboolean
3131 append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
3132 {
3133   Dwfl_Line *line;
3134   Dwarf_Addr addr;
3135   Dwfl_Module *module;
3136   const gchar *function_name;
3137
3138   addr = (uintptr_t) ip;
3139   module = dwfl_addrmodule (dwfl, addr);
3140   function_name = dwfl_module_addrname (module, addr);
3141
3142   g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
3143
3144   line = dwfl_getsrc (dwfl, addr);
3145   if (line != NULL) {
3146     gint nline;
3147     Dwarf_Addr addr;
3148     const gchar *filename = dwfl_lineinfo (line, &addr,
3149         &nline, NULL, NULL, NULL);
3150
3151     g_string_append_printf (trace, "%s:%d", strrchr (filename,
3152             G_DIR_SEPARATOR) + 1, nline);
3153   } else {
3154     const gchar *eflfile = NULL;
3155
3156     dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
3157     g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
3158   }
3159
3160   return TRUE;
3161 }
3162 #endif /* HAVE_DW */
3163
3164 static gchar *
3165 generate_unwind_trace (GstStackTraceFlags flags)
3166 {
3167   gint unret;
3168   unw_context_t uc;
3169   unw_cursor_t cursor;
3170   gboolean use_libunwind = TRUE;
3171   GString *trace = g_string_new (NULL);
3172
3173 #ifdef HAVE_DW
3174   Dwfl *dwfl = NULL;
3175
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");
3180       goto done;
3181     }
3182     GST_DWFL_LOCK ();
3183   }
3184 #endif /* HAVE_DW */
3185
3186   unret = unw_getcontext (&uc);
3187   if (unret) {
3188     GST_DEBUG ("Could not get libunwind context (%d)", unret);
3189
3190     goto done;
3191   }
3192   unret = unw_init_local (&cursor, &uc);
3193   if (unret) {
3194     GST_DEBUG ("Could not init libunwind context (%d)", unret);
3195
3196     goto done;
3197   }
3198 #ifdef HAVE_DW
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)
3202     goto done;
3203 #endif
3204
3205   while (unw_step (&cursor) > 0) {
3206 #ifdef HAVE_DW
3207     if (dwfl) {
3208       unw_word_t ip;
3209
3210       unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
3211       if (unret) {
3212         GST_DEBUG ("libunwind could not read frame info (%d)", unret);
3213
3214         goto done;
3215       }
3216
3217       if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
3218         use_libunwind = FALSE;
3219         g_string_append (trace, ")\n");
3220       }
3221     }
3222 #endif /* HAVE_DW */
3223
3224     if (use_libunwind) {
3225       char name[32];
3226
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,
3230           (gsize) offset);
3231     }
3232   }
3233
3234 done:
3235 #ifdef HAVE_DW
3236   if (dwfl)
3237     GST_DWFL_UNLOCK ();
3238 #endif
3239
3240   return g_string_free (trace, FALSE);
3241 }
3242
3243 #endif /* HAVE_UNWIND */
3244
3245 #ifdef HAVE_BACKTRACE
3246 static gchar *
3247 generate_backtrace_trace (void)
3248 {
3249   int j, nptrs;
3250   void *buffer[BT_BUF_SIZE];
3251   char **strings;
3252   GString *trace;
3253
3254   nptrs = backtrace (buffer, BT_BUF_SIZE);
3255
3256   strings = backtrace_symbols (buffer, nptrs);
3257
3258   if (!strings)
3259     return NULL;
3260
3261   trace = g_string_new (NULL);
3262
3263   for (j = 0; j < nptrs; j++)
3264     g_string_append_printf (trace, "%s\n", strings[j]);
3265
3266   free (strings);
3267
3268   return g_string_free (trace, FALSE);
3269 }
3270 #else
3271 #define generate_backtrace_trace() NULL
3272 #endif /* HAVE_BACKTRACE */
3273
3274 #ifdef HAVE_DBGHELP
3275 /* *INDENT-OFF* */
3276 static struct
3277 {
3278   DWORD (WINAPI * pSymSetOptions) (DWORD SymOptions);
3279   BOOL  (WINAPI * pSymInitialize) (HANDLE hProcess,
3280                                    PCSTR UserSearchPath,
3281                                    BOOL fInvadeProcess);
3282   BOOL  (WINAPI * pStackWalk64)   (DWORD MachineType,
3283                                    HANDLE hProcess,
3284                                    HANDLE hThread,
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,
3292                                               DWORD64 AddrBase);
3293   DWORD64 (WINAPI * pSymGetModuleBase64) (HANDLE hProcess,
3294                                           DWORD64 qwAddr);
3295   BOOL (WINAPI * pSymFromAddr) (HANDLE hProcess,
3296                                 DWORD64 Address,
3297                                 PDWORD64 Displacement,
3298                                 PSYMBOL_INFO Symbol);
3299   BOOL (WINAPI * pSymGetModuleInfo64) (HANDLE hProcess,
3300                                        DWORD64 qwAddr,
3301                                        PIMAGEHLP_MODULE64 ModuleInfo);
3302   BOOL (WINAPI * pSymGetLineFromAddr64) (HANDLE hProcess,
3303                                          DWORD64 qwAddr,
3304                                          PDWORD pdwDisplacement,
3305                                          PIMAGEHLP_LINE64 Line64);
3306 } dbg_help_vtable = { NULL,};
3307 /* *INDENT-ON* */
3308
3309 static GModule *dbg_help_module = NULL;
3310
3311 static gboolean
3312 dbghelp_load_symbol (const gchar * symbol_name, gpointer * symbol)
3313 {
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;
3319   }
3320
3321   return dbg_help_module != NULL;
3322 }
3323
3324 static gboolean
3325 dbghelp_initialize_symbols (HANDLE process)
3326 {
3327   static gsize initialization_value = 0;
3328
3329   if (g_once_init_enter (&initialization_value)) {
3330     GST_INFO ("Initializing Windows symbol handler");
3331
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);
3349
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");
3354     }
3355
3356     g_once_init_leave (&initialization_value, 1);
3357   }
3358
3359   return dbg_help_module != NULL;
3360 }
3361
3362 static gchar *
3363 generate_dbghelp_trace (void)
3364 {
3365   HANDLE process = GetCurrentProcess ();
3366   HANDLE thread = GetCurrentThread ();
3367   IMAGEHLP_MODULE64 module_info;
3368   DWORD machine;
3369   CONTEXT context;
3370   STACKFRAME64 frame = { 0 };
3371   PVOID save_context;
3372   GString *trace = NULL;
3373
3374   if (!dbghelp_initialize_symbols (process))
3375     return NULL;
3376
3377   memset (&context, 0, sizeof (CONTEXT));
3378   context.ContextFlags = CONTEXT_FULL;
3379
3380   RtlCaptureContext (&context);
3381
3382   frame.AddrPC.Mode = AddrModeFlat;
3383   frame.AddrStack.Mode = AddrModeFlat;
3384   frame.AddrFrame.Mode = AddrModeFlat;
3385
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;
3396 #else
3397   return NULL;
3398 #endif
3399
3400   trace = g_string_new (NULL);
3401
3402   module_info.SizeOfStruct = sizeof (module_info);
3403   save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
3404
3405   while (TRUE) {
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;
3410
3411     symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
3412     symbol->MaxNameLen = MAX_SYM_NAME;
3413
3414     line.SizeOfStruct = sizeof (line);
3415
3416     if (!dbg_help_vtable.pStackWalk64 (machine, process, thread, &frame,
3417             save_context, 0, dbg_help_vtable.pSymFunctionTableAccess64,
3418             dbg_help_vtable.pSymGetModuleBase64, 0)) {
3419       break;
3420     }
3421
3422     if (dbg_help_vtable.pSymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
3423       g_string_append_printf (trace, "%s ", symbol->Name);
3424     else
3425       g_string_append (trace, "?? ");
3426
3427     if (dbg_help_vtable.pSymGetLineFromAddr64 (process, frame.AddrPC.Offset,
3428             &displacement, &line))
3429       g_string_append_printf (trace, "(%s:%lu)", line.FileName,
3430           line.LineNumber);
3431     else if (dbg_help_vtable.pSymGetModuleInfo64 (process, frame.AddrPC.Offset,
3432             &module_info))
3433       g_string_append_printf (trace, "(%s)", module_info.ImageName);
3434     else
3435       g_string_append_printf (trace, "(%s)", "??");
3436
3437     g_string_append (trace, "\n");
3438   }
3439
3440   return g_string_free (trace, FALSE);
3441 }
3442 #endif /* HAVE_DBGHELP */
3443
3444 /**
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.
3448  *
3449  * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
3450  * present, else %NULL.
3451  *
3452  * Since: 1.12
3453  */
3454 gchar *
3455 gst_debug_get_stack_trace (GstStackTraceFlags flags)
3456 {
3457   gchar *trace = NULL;
3458 #ifdef HAVE_BACKTRACE
3459   gboolean have_backtrace = TRUE;
3460 #else
3461   gboolean have_backtrace = FALSE;
3462 #endif
3463
3464 #ifdef HAVE_UNWIND
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 ();
3469 #endif
3470
3471   if (trace)
3472     return trace;
3473   else if (have_backtrace)
3474     return generate_backtrace_trace ();
3475
3476   return NULL;
3477 }
3478
3479 /**
3480  * gst_debug_print_stack_trace:
3481  *
3482  * If libunwind, glibc backtrace or DbgHelp are present
3483  * a stack trace is printed.
3484  */
3485 void
3486 gst_debug_print_stack_trace (void)
3487 {
3488   gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
3489
3490   if (trace) {
3491 #ifdef G_OS_WIN32
3492     G_LOCK (win_print_mutex);
3493 #endif
3494
3495     g_print ("%s\n", trace);
3496
3497 #ifdef G_OS_WIN32
3498     G_UNLOCK (win_print_mutex);
3499 #endif
3500   }
3501
3502   g_free (trace);
3503 }
3504
3505 #ifndef GST_DISABLE_GST_DEBUG
3506 typedef struct
3507 {
3508   guint max_size_per_thread;
3509   guint thread_timeout;
3510   GQueue threads;
3511   GHashTable *thread_index;
3512 } GstRingBufferLogger;
3513
3514 typedef struct
3515 {
3516   GList *link;
3517   gint64 last_use;
3518   GThread *thread;
3519
3520   GQueue log;
3521   gsize log_size;
3522 } GstRingBufferLog;
3523
3524 G_LOCK_DEFINE_STATIC (ring_buffer_logger);
3525 static GstRingBufferLogger *ring_buffer_logger = NULL;
3526
3527 static void
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)
3531 {
3532   GstRingBufferLogger *logger = user_data;
3533   GThread *thread;
3534   GstClockTime elapsed;
3535   gchar c;
3536   gchar *output;
3537   gsize output_len;
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);
3542
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
3546    * readability. */
3547   c = file[0];
3548   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
3549     file = gst_path_basename (file);
3550   }
3551
3552   elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
3553   thread = g_thread_self ();
3554
3555   if (object_id) {
3556     /* no color, all platforms */
3557     output =
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);
3563   } else {
3564     /* no color, all platforms */
3565     output =
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, "",
3570         message_str);
3571   }
3572
3573   output_len = strlen (output);
3574
3575
3576   G_LOCK (ring_buffer_logger);
3577
3578   if (logger->thread_timeout > 0) {
3579     gchar *buf;
3580
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.
3584      */
3585     while (logger->threads.tail) {
3586       log = logger->threads.tail->data;
3587       if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
3588         break;
3589
3590       g_hash_table_remove (logger->thread_index, log->thread);
3591       while ((buf = g_queue_pop_head (&log->log)))
3592         g_free (buf);
3593       g_free (log);
3594       g_queue_pop_tail (&logger->threads);
3595     }
3596   }
3597
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);
3601   if (!log) {
3602     log = g_new0 (GstRingBufferLog, 1);
3603     g_queue_init (&log->log);
3604     log->log_size = 0;
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);
3609   } else {
3610     g_queue_unlink (&logger->threads, log->link);
3611     g_queue_push_head_link (&logger->threads, log->link);
3612   }
3613   log->last_use = now;
3614
3615   if (output_len < logger->max_size_per_thread) {
3616     gchar *buf;
3617
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...
3625      */
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);
3629       g_free (buf);
3630     }
3631     g_queue_push_tail (&log->log, output);
3632     log->log_size += output_len;
3633   } else {
3634     gchar *buf;
3635
3636     /* Can't really write anything as the line is bigger than the maximum
3637      * allowed log size already, so just remove everything */
3638
3639     while ((buf = g_queue_pop_head (&log->log)))
3640       g_free (buf);
3641     g_free (output);
3642     log->log_size = 0;
3643   }
3644
3645   G_UNLOCK (ring_buffer_logger);
3646 }
3647
3648 /**
3649  * gst_debug_ring_buffer_logger_get_logs:
3650  *
3651  * Fetches the current logs per thread from the ring buffer logger. See
3652  * gst_debug_add_ring_buffer_logger() for details.
3653  *
3654  * Returns: (transfer full) (array zero-terminated=1): NULL-terminated array of
3655  * strings with the debug output per thread
3656  *
3657  * Since: 1.14
3658  */
3659 gchar **
3660 gst_debug_ring_buffer_logger_get_logs (void)
3661 {
3662   gchar **logs, **tmp;
3663   GList *l;
3664
3665   g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
3666
3667   G_LOCK (ring_buffer_logger);
3668
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;
3672     GList *l;
3673     gchar *p;
3674     gsize len;
3675
3676     *tmp = p = g_new0 (gchar, log->log_size + 1);
3677
3678     for (l = log->log.head; l; l = l->next) {
3679       len = strlen (l->data);
3680       memcpy (p, l->data, len);
3681       p += len;
3682     }
3683
3684     tmp++;
3685   }
3686
3687   G_UNLOCK (ring_buffer_logger);
3688
3689   return logs;
3690 }
3691
3692 static void
3693 gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
3694 {
3695   G_LOCK (ring_buffer_logger);
3696   if (ring_buffer_logger == logger) {
3697     GstRingBufferLog *log;
3698
3699     while ((log = g_queue_pop_head (&logger->threads))) {
3700       gchar *buf;
3701       while ((buf = g_queue_pop_head (&log->log)))
3702         g_free (buf);
3703       g_free (log);
3704     }
3705
3706     g_hash_table_unref (logger->thread_index);
3707
3708     g_free (logger);
3709     ring_buffer_logger = NULL;
3710   }
3711   G_UNLOCK (ring_buffer_logger);
3712 }
3713
3714 /**
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
3718  *
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.
3722  *
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.
3726  *
3727  * Since: 1.14
3728  */
3729 void
3730 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3731     guint thread_timeout)
3732 {
3733   GstRingBufferLogger *logger;
3734
3735   G_LOCK (ring_buffer_logger);
3736
3737   if (ring_buffer_logger) {
3738     g_warn_if_reached ();
3739     G_UNLOCK (ring_buffer_logger);
3740     return;
3741   }
3742
3743   logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
3744
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);
3749
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);
3753 }
3754
3755 /**
3756  * gst_debug_remove_ring_buffer_logger:
3757  *
3758  * Removes any previously added ring buffer logger with
3759  * gst_debug_add_ring_buffer_logger().
3760  *
3761  * Since: 1.14
3762  */
3763 void
3764 gst_debug_remove_ring_buffer_logger (void)
3765 {
3766   gst_debug_remove_log_function (gst_ring_buffer_logger_log);
3767 }
3768
3769 #else /* GST_DISABLE_GST_DEBUG */
3770 #ifndef GST_REMOVE_DISABLED
3771
3772 gchar **
3773 gst_debug_ring_buffer_logger_get_logs (void)
3774 {
3775   return NULL;
3776 }
3777
3778 void
3779 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3780     guint thread_timeout)
3781 {
3782 }
3783
3784 void
3785 gst_debug_remove_ring_buffer_logger (void)
3786 {
3787 }
3788
3789 #endif /* GST_REMOVE_DISABLED */
3790 #endif /* GST_DISABLE_GST_DEBUG */