info: Take lock around all prinf on Windows
[platform/upstream/gstreamer.git] / gst / gstinfo.c
index 735caef..fa3adc0 100644 (file)
@@ -24,6 +24,7 @@
 
 /**
  * SECTION:gstinfo
+ * @title: GstInfo
  * @short_description: Debugging and logging facilities
  * @see_also: #gst-running for command line parameters
  * and environment variables that affect the debugging output.
@@ -154,6 +155,23 @@ static char *gst_info_printf_pointer_extension_func (const char *format,
 #define BT_BUF_SIZE 100
 #endif /* HAVE_BACKTRACE */
 
+#ifdef HAVE_DBGHELP
+#include <Windows.h>
+#include <dbghelp.h>
+#include <tlhelp32.h>
+#endif /* HAVE_DBGHELP */
+
+#ifdef G_OS_WIN32
+/* We take a lock in order to
+ * 1) keep colors and content together for a single line
+ * 2) serialise gst_print*() and gst_printerr*() with each other and the debug
+ *    log to keep the debug log colouring from interfering with those and
+ *    to prevent broken output on the windows terminal.
+ * Maybe there is a better way but for now this will do the right
+ * thing. */
+G_LOCK_DEFINE_STATIC (win_print_mutex);
+#endif
+
 extern gboolean gst_is_initialized (void);
 
 /* we want these symbols exported even if debug is disabled, to maintain
@@ -239,8 +257,6 @@ dladdr (void *address, Dl_info * dl)
 #endif /* __sgi__ */
 #endif
 
-static const gchar *_gst_debug_filter = NULL;
-
 static void gst_debug_reset_threshold (gpointer category, gpointer unused);
 static void gst_debug_reset_all_thresholds (void);
 
@@ -407,7 +423,7 @@ _priv_gst_debug_init (void)
   GST_CAT_ELEMENT_PADS = _gst_debug_category_new ("GST_ELEMENT_PADS",
       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
   GST_CAT_PADS = _gst_debug_category_new ("GST_PADS",
-      GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_RED, NULL);
+      GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
   GST_CAT_PERFORMANCE = _gst_debug_category_new ("GST_PERFORMANCE",
       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
   GST_CAT_PIPELINE = _gst_debug_category_new ("GST_PIPELINE",
@@ -463,10 +479,9 @@ _priv_gst_debug_init (void)
   if (env)
     gst_debug_set_color_mode_from_string (env);
 
-  _gst_debug_filter = g_getenv ("GST_DEBUG");
-  if (_gst_debug_filter) {
-    gst_debug_set_threshold_from_string (_gst_debug_filter, FALSE);
-  }
+  env = g_getenv ("GST_DEBUG");
+  if (env)
+    gst_debug_set_threshold_from_string (env, FALSE);
 }
 
 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
@@ -576,7 +591,7 @@ gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
  * Gets the string representation of a #GstDebugMessage. This function is used
  * in debug handlers to extract the message.
  *
- * Returns: the string representation of a #GstDebugMessage.
+ * Returns: (nullable): the string representation of a #GstDebugMessage.
  */
 const gchar *
 gst_debug_message_get (GstDebugMessage * message)
@@ -1139,9 +1154,19 @@ gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
   GstClockTime elapsed;
   gchar *obj = NULL;
   GstDebugColorMode color_mode;
+  const gchar *message_str;
   FILE *log_file = user_data ? user_data : stderr;
   gchar c;
 
+  /* Get message string first because printing it might call into our custom
+   * printf format extension mechanism which in turn might log something, e.g.
+   * from inside gst_structure_to_string() when something can't be serialised.
+   * This means we either need to do this outside of any critical section or
+   * use a recursive lock instead. As we always need the message string in all
+   * code paths, we might just as well get it here first thing and outside of
+   * the win_print_mutex critical section. */
+  message_str = gst_debug_message_get (message);
+
   /* __FILE__ might be a file name or an absolute path or a
    * relative path, irrespective of the exact compiler used,
    * in which case we want to shorten it to the filename for
@@ -1164,11 +1189,7 @@ gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
 
   if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
 #ifdef G_OS_WIN32
-    /* We take a lock to keep colors and content together.
-     * Maybe there is a better way but for now this will do the right
-     * thing. */
-    static GMutex win_print_mutex;
-    g_mutex_lock (&win_print_mutex);
+    G_LOCK (win_print_mutex);
     if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
 #endif
       /* colors, non-windows */
@@ -1188,7 +1209,7 @@ gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
           pidcolor, pid, clear, g_thread_self (), levelcolor,
           gst_debug_level_get_name (level), clear, color,
           gst_debug_category_get_name (category), file, line, function, obj,
-          clear, gst_debug_message_get (message));
+          clear, message_str);
       fflush (log_file);
 #undef PRINT_FMT
       g_free (color);
@@ -1223,10 +1244,10 @@ gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
       fflush (log_file);
       /* message */
       SET_COLOR (clear);
-      fprintf (log_file, " %s\n", gst_debug_message_get (message));
+      fprintf (log_file, " %s\n", message_str);
       fflush (log_file);
     }
-    g_mutex_unlock (&win_print_mutex);
+    G_UNLOCK (win_print_mutex);
 #endif
   } else {
     /* no color, all platforms */
@@ -1234,7 +1255,7 @@ gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
     fprintf (log_file, "%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
         pid, g_thread_self (), gst_debug_level_get_name (level),
         gst_debug_category_get_name (category), file, line, function, obj,
-        gst_debug_message_get (message));
+        message_str);
     fflush (log_file);
 #undef PRINT_FMT
   }
@@ -1524,8 +1545,8 @@ gst_debug_get_color_mode (void)
  * If activated, debugging messages are sent to the debugging
  * handlers.
  * It makes sense to deactivate it for speed issues.
- * <note><para>This function is not threadsafe. It makes sense to only call it
- * during initialization.</para></note>
+ * This function is not threadsafe. It makes sense to only call it
+ * during initialization.
  */
 void
 gst_debug_set_active (gboolean active)
@@ -1579,6 +1600,20 @@ gst_debug_get_default_threshold (void)
   return (GstDebugLevel) g_atomic_int_get (&__default_level);
 }
 
+static gboolean
+gst_debug_apply_entry (GstDebugCategory * cat, LevelNameEntry * entry)
+{
+  if (!g_pattern_match_string (entry->pat, cat->name))
+    return FALSE;
+
+  if (gst_is_initialized ())
+    GST_LOG ("category %s matches pattern %p - gets set to level %d",
+        cat->name, entry->pat, entry->level);
+
+  gst_debug_category_set_threshold (cat, entry->level);
+  return TRUE;
+}
+
 static void
 gst_debug_reset_threshold (gpointer category, gpointer unused)
 {
@@ -1586,23 +1621,16 @@ gst_debug_reset_threshold (gpointer category, gpointer unused)
   GSList *walk;
 
   g_mutex_lock (&__level_name_mutex);
-  walk = __level_name;
-  while (walk) {
-    LevelNameEntry *entry = walk->data;
 
-    walk = g_slist_next (walk);
-    if (g_pattern_match_string (entry->pat, cat->name)) {
-      if (gst_is_initialized ())
-        GST_LOG ("category %s matches pattern %p - gets set to level %d",
-            cat->name, entry->pat, entry->level);
-      gst_debug_category_set_threshold (cat, entry->level);
-      goto exit;
-    }
+  for (walk = __level_name; walk != NULL; walk = walk->next) {
+    if (gst_debug_apply_entry (cat, walk->data))
+      break;
   }
-  gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
 
-exit:
   g_mutex_unlock (&__level_name_mutex);
+
+  if (walk == NULL)
+    gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
 }
 
 static void
@@ -1619,12 +1647,7 @@ for_each_threshold_by_entry (gpointer data, gpointer user_data)
   GstDebugCategory *cat = (GstDebugCategory *) data;
   LevelNameEntry *entry = (LevelNameEntry *) user_data;
 
-  if (g_pattern_match_string (entry->pat, cat->name)) {
-    if (gst_is_initialized ())
-      GST_LOG ("category %s matches pattern %p - gets set to level %d",
-          cat->name, entry->pat, entry->level);
-    gst_debug_category_set_threshold (cat, entry->level);
-  }
+  gst_debug_apply_entry (cat, entry);
 }
 
 /**
@@ -1723,11 +1746,6 @@ _gst_debug_category_new (const gchar * name, guint color,
   }
   g_mutex_unlock (&__cat_mutex);
 
-  /* ensure the filter is applied to categories registered after _debug_init */
-  if (_gst_debug_filter) {
-    gst_debug_set_threshold_from_string (_gst_debug_filter, FALSE);
-  }
-
   return cat;
 }
 
@@ -1761,11 +1779,9 @@ gst_debug_category_free (GstDebugCategory * category)
  * Sets the threshold of the category to the given level. Debug information will
  * only be output if the threshold is lower or equal to the level of the
  * debugging message.
- * <note><para>
- * Do not use this function in production code, because other functions may
- * change the threshold of categories as side effect. It is however a nice
- * function to use when debugging (even from gdb).
- * </para></note>
+ * > Do not use this function in production code, because other functions may
+ * > change the threshold of categories as side effect. It is however a nice
+ * > function to use when debugging (even from gdb).
  */
 void
 gst_debug_category_set_threshold (GstDebugCategory * category,
@@ -1984,7 +2000,7 @@ gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
   g_assert (list);
 
   if (reset)
-    gst_debug_set_default_threshold (0);
+    gst_debug_set_default_threshold (GST_LEVEL_DEFAULT);
 
   split = g_strsplit (list, ",", 0);
 
@@ -2051,7 +2067,7 @@ _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
    * the name */
 #ifdef HAVE_DLADDR
   if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
-    gchar *name = g_strdup (dl_info.dli_sname);
+    const gchar *name = g_intern_string (dl_info.dli_sname);
 
     _gst_debug_register_funcptr (func, name);
     return name;
@@ -2059,9 +2075,12 @@ _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
 #endif
   {
     gchar *name = g_strdup_printf ("%p", (gpointer) func);
+    const gchar *iname = g_intern_string (name);
 
-    _gst_debug_register_funcptr (func, name);
-    return name;
+    g_free (name);
+
+    _gst_debug_register_funcptr (func, iname);
+    return iname;
   }
 }
 
@@ -2074,8 +2093,22 @@ _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
 
   if (!__gst_function_pointers)
     __gst_function_pointers = g_hash_table_new (g_direct_hash, g_direct_equal);
-  if (!g_hash_table_lookup (__gst_function_pointers, ptr))
+  if (!g_hash_table_lookup (__gst_function_pointers, ptr)) {
     g_hash_table_insert (__gst_function_pointers, ptr, (gpointer) ptrname);
+  }
+
+  g_mutex_unlock (&__dbg_functions_mutex);
+}
+
+void
+_priv_gst_debug_cleanup (void)
+{
+  g_mutex_lock (&__dbg_functions_mutex);
+
+  if (__gst_function_pointers) {
+    g_hash_table_unref (__gst_function_pointers);
+    __gst_function_pointers = NULL;
+  }
 
   g_mutex_unlock (&__dbg_functions_mutex);
 }
@@ -2159,6 +2192,11 @@ _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
 }
 
 void
+_priv_gst_debug_cleanup (void)
+{
+}
+
+void
 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
     const gchar * file, const gchar * function, gint line,
     GObject * object, const gchar * format, ...)
@@ -2433,7 +2471,7 @@ gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
  *
  * Free with g_free().
  *
- * Returns: a newly allocated null terminated string or %NULL on any error
+ * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
  *
  * Since: 1.8
  */
@@ -2460,7 +2498,7 @@ gst_info_strdup_vprintf (const gchar * format, va_list args)
  *
  * Free with g_free().
  *
- * Returns: a newly allocated null terminated string or %NULL on any error
+ * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
  *
  * Since: 1.8
  */
@@ -2508,7 +2546,15 @@ gst_print (const gchar * format, ...)
   str = gst_info_strdup_vprintf (format, args);
   va_end (args);
 
+#ifdef G_OS_WIN32
+  G_LOCK (win_print_mutex);
+#endif
+
   g_print ("%s", str);
+
+#ifdef G_OS_WIN32
+  G_UNLOCK (win_print_mutex);
+#endif
   g_free (str);
 }
 
@@ -2543,7 +2589,15 @@ gst_println (const gchar * format, ...)
   str = gst_info_strdup_vprintf (format, args);
   va_end (args);
 
+#ifdef G_OS_WIN32
+  G_LOCK (win_print_mutex);
+#endif
+
   g_print ("%s\n", str);
+
+#ifdef G_OS_WIN32
+  G_UNLOCK (win_print_mutex);
+#endif
   g_free (str);
 }
 
@@ -2578,7 +2632,15 @@ gst_printerr (const gchar * format, ...)
   str = gst_info_strdup_vprintf (format, args);
   va_end (args);
 
+#ifdef G_OS_WIN32
+  G_LOCK (win_print_mutex);
+#endif
+
   g_printerr ("%s", str);
+
+#ifdef G_OS_WIN32
+  G_UNLOCK (win_print_mutex);
+#endif
   g_free (str);
 }
 
@@ -2613,7 +2675,15 @@ gst_printerrln (const gchar * format, ...)
   str = gst_info_strdup_vprintf (format, args);
   va_end (args);
 
+#ifdef G_OS_WIN32
+  G_LOCK (win_print_mutex);
+#endif
+
   g_printerr ("%s\n", str);
+
+#ifdef G_OS_WIN32
+  G_UNLOCK (win_print_mutex);
+#endif
   g_free (str);
 }
 
@@ -2662,6 +2732,7 @@ append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
 static gchar *
 generate_unwind_trace (GstStackTraceFlags flags)
 {
+  gint unret;
   unw_context_t uc;
   unw_cursor_t cursor;
   gboolean use_libunwind = TRUE;
@@ -2678,15 +2749,31 @@ generate_unwind_trace (GstStackTraceFlags flags)
     dwfl = dwfl_begin (&callbacks);
 #endif /* HAVE_DW */
 
-  unw_getcontext (&uc);
-  unw_init_local (&cursor, &uc);
+  unret = unw_getcontext (&uc);
+  if (unret) {
+    GST_DEBUG ("Could not get libunwind context (%d)", unret);
+
+    goto done;
+  }
+  unret = unw_init_local (&cursor, &uc);
+  if (unret) {
+    GST_DEBUG ("Could not init libunwind context (%d)", unret);
+
+    goto done;
+  }
 
   while (unw_step (&cursor) > 0) {
 #ifdef HAVE_DW
     if (dwfl) {
       unw_word_t ip;
 
-      unw_get_reg (&cursor, UNW_REG_IP, &ip);
+      unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
+      if (unret) {
+        GST_DEBUG ("libunwind could read frame info (%d)", unret);
+
+        goto done;
+      }
+
       if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
         use_libunwind = FALSE;
         g_string_append (trace, ")\n");
@@ -2704,6 +2791,7 @@ generate_unwind_trace (GstStackTraceFlags flags)
     }
   }
 
+done:
 #ifdef HAVE_DW
   if (dwfl)
     dwfl_end (dwfl);
@@ -2734,19 +2822,113 @@ generate_backtrace_trace (void)
   for (j = 0; j < nptrs; j++)
     g_string_append_printf (trace, "%s\n", strings[j]);
 
+  free (strings);
+
   return g_string_free (trace, FALSE);
 }
 #else
 #define generate_backtrace_trace() NULL
 #endif /* HAVE_BACKTRACE */
 
+#ifdef HAVE_DBGHELP
+static void
+dbghelp_initialize_symbols (HANDLE process)
+{
+  static gsize initialization_value = 0;
+
+  if (g_once_init_enter (&initialization_value)) {
+    GST_INFO ("Initializing Windows symbol handler");
+    SymSetOptions (SYMOPT_LOAD_LINES);
+    SymInitialize (process, NULL, TRUE);
+    GST_INFO ("Initialized Windows symbol handler");
+
+    g_once_init_leave (&initialization_value, 1);
+  }
+}
+
+static gchar *
+generate_dbghelp_trace (void)
+{
+  HANDLE process = GetCurrentProcess ();
+  HANDLE thread = GetCurrentThread ();
+  IMAGEHLP_MODULE64 module_info;
+  DWORD machine;
+  CONTEXT context;
+  STACKFRAME64 frame = { 0 };
+  PVOID save_context;
+  GString *trace = g_string_new (NULL);
+
+  dbghelp_initialize_symbols (process);
+
+  memset (&context, 0, sizeof (CONTEXT));
+  context.ContextFlags = CONTEXT_FULL;
+
+  RtlCaptureContext (&context);
+
+  frame.AddrPC.Mode = AddrModeFlat;
+  frame.AddrStack.Mode = AddrModeFlat;
+  frame.AddrFrame.Mode = AddrModeFlat;
+
+#if (defined _M_IX86)
+  machine = IMAGE_FILE_MACHINE_I386;
+  frame.AddrFrame.Offset = context.Ebp;
+  frame.AddrPC.Offset = context.Eip;
+  frame.AddrStack.Offset = context.Esp;
+#elif (defined _M_X64)
+  machine = IMAGE_FILE_MACHINE_AMD64;
+  frame.AddrFrame.Offset = context.Rbp;
+  frame.AddrPC.Offset = context.Rip;
+  frame.AddrStack.Offset = context.Rsp;
+#else
+  goto done;
+#endif
+
+  module_info.SizeOfStruct = sizeof (module_info);
+  save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
+
+  while (TRUE) {
+    char buffer[sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR)];
+    PSYMBOL_INFO symbol = (PSYMBOL_INFO) buffer;
+    IMAGEHLP_LINE64 line;
+    DWORD displacement = 0;
+
+    symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
+    symbol->MaxNameLen = MAX_SYM_NAME;
+
+    line.SizeOfStruct = sizeof (line);
+
+    if (!StackWalk64 (machine, process, thread, &frame, save_context, 0,
+            SymFunctionTableAccess64, SymGetModuleBase64, 0))
+      break;
+
+    if (SymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
+      g_string_append_printf (trace, "%s ", symbol->Name);
+    else
+      g_string_append (trace, "?? ");
+
+    if (SymGetLineFromAddr64 (process, frame.AddrPC.Offset, &displacement,
+            &line))
+      g_string_append_printf (trace, "(%s:%u)", line.FileName, line.LineNumber);
+    else if (SymGetModuleInfo64 (process, frame.AddrPC.Offset, &module_info))
+      g_string_append_printf (trace, "(%s)", module_info.ImageName);
+    else
+      g_string_append_printf (trace, "(%s)", "??");
+
+    g_string_append (trace, "\n");
+  }
+
+done:
+  return g_string_free (trace, FALSE);
+}
+#endif /* HAVE_DBGHELP */
+
 /**
  * gst_debug_get_stack_trace:
  * @flags: A set of #GstStackTraceFlags to determine how the stack
  * trace should look like. Pass 0 to retrieve a minimal backtrace.
  *
- * If libunwind or glibc backtrace are present, a stack trace
- * is returned.
+ * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
+ * present, else %NULL.
  *
  * Since: 1.12
  */
@@ -2765,6 +2947,10 @@ gst_debug_get_stack_trace (GstStackTraceFlags flags)
     trace = generate_unwind_trace (flags);
 #endif /* HAVE_UNWIND */
 
+#ifdef HAVE_DBGHELP
+  trace = generate_dbghelp_trace ();
+#endif
+
   if (trace)
     return trace;
   else if (have_backtrace)
@@ -2776,7 +2962,7 @@ gst_debug_get_stack_trace (GstStackTraceFlags flags)
 /**
  * gst_debug_print_stack_trace:
  *
- * If libunwind or glibc backtrace are present
+ * If libunwind, glibc backtrace or DbgHelp are present
  * a stack trace is printed.
  */
 void
@@ -2784,8 +2970,307 @@ gst_debug_print_stack_trace (void)
 {
   gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
 
-  if (trace)
+  if (trace) {
+#ifdef G_OS_WIN32
+    G_LOCK (win_print_mutex);
+#endif
+
     g_print ("%s\n", trace);
 
+#ifdef G_OS_WIN32
+    G_UNLOCK (win_print_mutex);
+#endif
+  }
+
   g_free (trace);
 }
+
+#ifndef GST_DISABLE_GST_DEBUG
+typedef struct
+{
+  guint max_size_per_thread;
+  guint thread_timeout;
+  GQueue threads;
+  GHashTable *thread_index;
+} GstRingBufferLogger;
+
+typedef struct
+{
+  GList *link;
+  gint64 last_use;
+  GThread *thread;
+
+  GQueue log;
+  gsize log_size;
+} GstRingBufferLog;
+
+G_LOCK_DEFINE_STATIC (ring_buffer_logger);
+static GstRingBufferLogger *ring_buffer_logger = NULL;
+
+static void
+gst_ring_buffer_logger_log (GstDebugCategory * category,
+    GstDebugLevel level,
+    const gchar * file,
+    const gchar * function,
+    gint line, GObject * object, GstDebugMessage * message, gpointer user_data)
+{
+  GstRingBufferLogger *logger = user_data;
+  gint pid;
+  GThread *thread;
+  GstClockTime elapsed;
+  gchar *obj = NULL;
+  gchar c;
+  gchar *output;
+  gsize output_len;
+  GstRingBufferLog *log;
+  gint64 now = g_get_monotonic_time ();
+  const gchar *message_str = gst_debug_message_get (message);
+
+  /* __FILE__ might be a file name or an absolute path or a
+   * relative path, irrespective of the exact compiler used,
+   * in which case we want to shorten it to the filename for
+   * readability. */
+  c = file[0];
+  if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
+    file = gst_path_basename (file);
+  }
+
+  if (object) {
+    obj = gst_debug_print_object (object);
+  } else {
+    obj = (gchar *) "";
+  }
+
+  elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
+  pid = getpid ();
+  thread = g_thread_self ();
+
+  /* no color, all platforms */
+#define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
+  output =
+      g_strdup_printf ("%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
+      pid, thread, gst_debug_level_get_name (level),
+      gst_debug_category_get_name (category), file, line, function, obj,
+      message_str);
+#undef PRINT_FMT
+
+  output_len = strlen (output);
+
+  if (object != NULL)
+    g_free (obj);
+
+  G_LOCK (ring_buffer_logger);
+
+  if (logger->thread_timeout > 0) {
+    gchar *buf;
+
+    /* Remove all threads that saw no output since thread_timeout seconds.
+     * By construction these are all at the tail of the queue, and the queue
+     * is ordered by last use, so we just need to look at the tail.
+     */
+    while (logger->threads.tail) {
+      log = logger->threads.tail->data;
+      if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
+        break;
+
+      g_hash_table_remove (logger->thread_index, log->thread);
+      while ((buf = g_queue_pop_head (&log->log)))
+        g_free (buf);
+      g_free (log);
+      g_queue_pop_tail (&logger->threads);
+    }
+  }
+
+  /* Get logger for this thread, and put it back at the
+   * head of the threads queue */
+  log = g_hash_table_lookup (logger->thread_index, thread);
+  if (!log) {
+    log = g_new0 (GstRingBufferLog, 1);
+    g_queue_init (&log->log);
+    log->log_size = 0;
+    g_queue_push_head (&logger->threads, log);
+    log->link = logger->threads.head;
+    log->thread = thread;
+    g_hash_table_insert (logger->thread_index, thread, log);
+  } else {
+    g_queue_unlink (&logger->threads, log->link);
+    g_queue_push_head_link (&logger->threads, log->link);
+  }
+  log->last_use = now;
+
+  if (output_len < logger->max_size_per_thread) {
+    gchar *buf;
+
+    /* While using a GQueue here is not the most efficient thing to do, we
+     * have to allocate a string for every output anyway and could just store
+     * that instead of copying it to an actual ringbuffer.
+     * Better than GQueue would be GstQueueArray, but that one is in
+     * libgstbase and we can't use it here. That one allocation will not make
+     * much of a difference anymore, considering the number of allocations
+     * needed to get to this point...
+     */
+    while (log->log_size + output_len > logger->max_size_per_thread) {
+      buf = g_queue_pop_head (&log->log);
+      log->log_size -= strlen (buf);
+      g_free (buf);
+    }
+    g_queue_push_tail (&log->log, output);
+    log->log_size += output_len;
+  } else {
+    gchar *buf;
+
+    /* Can't really write anything as the line is bigger than the maximum
+     * allowed log size already, so just remove everything */
+
+    while ((buf = g_queue_pop_head (&log->log)))
+      g_free (buf);
+    g_free (output);
+    log->log_size = 0;
+  }
+
+  G_UNLOCK (ring_buffer_logger);
+}
+
+/**
+ * gst_debug_ring_buffer_logger_get_logs:
+ *
+ * Fetches the current logs per thread from the ring buffer logger. See
+ * gst_debug_add_ring_buffer_logger() for details.
+ *
+ * Returns: (transfer full) (array zero-terminated): NULL-terminated array of
+ * strings with the debug output per thread
+ *
+ * Since: 1.14
+ */
+gchar **
+gst_debug_ring_buffer_logger_get_logs (void)
+{
+  gchar **logs, **tmp;
+  GList *l;
+
+  g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
+
+  G_LOCK (ring_buffer_logger);
+
+  tmp = logs = g_new0 (gchar *, ring_buffer_logger->threads.length + 1);
+  for (l = ring_buffer_logger->threads.head; l; l = l->next) {
+    GstRingBufferLog *log = l->data;
+    GList *l;
+    gchar *p;
+    gsize len;
+
+    *tmp = p = g_new0 (gchar, log->log_size + 1);
+
+    for (l = log->log.head; l; l = l->next) {
+      len = strlen (l->data);
+      memcpy (p, l->data, len);
+      p += len;
+    }
+
+    tmp++;
+  }
+
+  G_UNLOCK (ring_buffer_logger);
+
+  return logs;
+}
+
+static void
+gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
+{
+  G_LOCK (ring_buffer_logger);
+  if (ring_buffer_logger == logger) {
+    GstRingBufferLog *log;
+
+    while ((log = g_queue_pop_head (&logger->threads))) {
+      gchar *buf;
+      while ((buf = g_queue_pop_head (&log->log)))
+        g_free (buf);
+      g_free (log);
+    }
+
+    g_hash_table_unref (logger->thread_index);
+
+    g_free (logger);
+    ring_buffer_logger = NULL;
+  }
+  G_UNLOCK (ring_buffer_logger);
+}
+
+/**
+ * gst_debug_add_ring_buffer_logger:
+ * @max_size_per_thread: Maximum size of log per thread in bytes
+ * @thread_timeout: Timeout for threads in seconds
+ *
+ * Adds a memory ringbuffer based debug logger that stores up to
+ * @max_size_per_thread bytes of logs per thread and times out threads after
+ * @thread_timeout seconds of inactivity.
+ *
+ * Logs can be fetched with gst_debug_ring_buffer_logger_get_logs() and the
+ * logger can be removed again with gst_debug_remove_ring_buffer_logger().
+ * Only one logger at a time is possible.
+ *
+ * Since: 1.14
+ */
+void
+gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
+    guint thread_timeout)
+{
+  GstRingBufferLogger *logger;
+
+  G_LOCK (ring_buffer_logger);
+
+  if (ring_buffer_logger) {
+    g_warn_if_reached ();
+    G_UNLOCK (ring_buffer_logger);
+    return;
+  }
+
+  logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
+
+  logger->max_size_per_thread = max_size_per_thread;
+  logger->thread_timeout = thread_timeout;
+  logger->thread_index = g_hash_table_new (g_direct_hash, g_direct_equal);
+  g_queue_init (&logger->threads);
+
+  gst_debug_add_log_function (gst_ring_buffer_logger_log, logger,
+      (GDestroyNotify) gst_ring_buffer_logger_free);
+  G_UNLOCK (ring_buffer_logger);
+}
+
+/**
+ * gst_debug_remove_ring_buffer_logger:
+ *
+ * Removes any previously added ring buffer logger with
+ * gst_debug_add_ring_buffer_logger().
+ *
+ * Since: 1.14
+ */
+void
+gst_debug_remove_ring_buffer_logger (void)
+{
+  gst_debug_remove_log_function (gst_ring_buffer_logger_log);
+}
+
+#else /* GST_DISABLE_GST_DEBUG */
+#ifndef GST_REMOVE_DISABLED
+
+gchar **
+gst_debug_ring_buffer_logger_get_logs (void)
+{
+  return NULL;
+}
+
+void
+gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
+    guint thread_timeout)
+{
+}
+
+void
+gst_debug_remove_ring_buffer_logger (void)
+{
+}
+
+#endif /* GST_REMOVE_DISABLED */
+#endif /* GST_DISABLE_GST_DEBUG */