tools: Count argc after parsing GOption on Windows
[platform/upstream/gstreamer.git] / subprojects / gstreamer / gst / gstdebugutils.c
1 /* GStreamer
2  * Copyright (C) 2007 Stefan Kost <ensonic@users.sf.net>
3  *
4  * gstdebugutils.c: debugging and analysis utilities
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /* TODO:
22  * edge [ constraint=false ];
23  *   this creates strange graphs ("minlen=0" is better)
24  * try putting src/sink ghostpads for each bin into invisible clusters
25  *
26  * for more compact nodes, try
27  * - changing node-shape from box into record
28  * - use labels like : element [ label="{element | <src> src | <sink> sink}"]
29  * - point to record-connectors : element1:src -> element2:sink
30  * - we use head/tail labels for pad-caps right now
31  *   - this does not work well, as dot seems to not look at their size when
32  *     doing the layout
33  *   - we could add the caps to the pad itself, then we should use one line per
34  *     caps (simple caps = one line)
35  */
36
37 /**
38  * SECTION: debugutils
39  * @title: Debugging utilities
40  * @short_description: A set of utilities for debugging and development
41  *
42  * These utility functions help with generating dot graphs which can
43  * be rendered with [graphviz] to multiple formats.
44  *
45  * [graphviz]: https://graphviz.org/
46  */
47
48 #include "gst_private.h"
49 #include "gstdebugutils.h"
50
51 #ifndef GST_DISABLE_GST_DEBUG
52
53 #include <stdlib.h>
54 #include <stdio.h>
55 #include <string.h>
56 #include <errno.h>
57
58 #include "gstinfo.h"
59 #include "gstbin.h"
60 #include "gstobject.h"
61 #include "gstghostpad.h"
62 #include "gstpad.h"
63 #include "gstutils.h"
64 #include "gstvalue.h"
65
66 /*** PIPELINE GRAPHS **********************************************************/
67
68 extern const gchar *priv_gst_dump_dot_dir;      /* NULL *//* set from gst.c */
69
70 #define PARAM_MAX_LENGTH 80
71
72 static const gchar spaces[] = {
73   "                                "    /* 32 */
74       "                                "        /* 64 */
75       "                                "        /* 96 */
76       "                                "        /* 128 */
77 };
78
79 #define MAKE_INDENT(indent) \
80   &spaces[MAX (sizeof (spaces) - (1 + (indent) * 2), 0)]
81
82 static gchar *
83 debug_dump_make_object_name (GstObject * obj)
84 {
85   return g_strcanon (g_strdup_printf ("%s_%p", GST_OBJECT_NAME (obj), obj),
86       G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_", '_');
87 }
88
89 static gchar *
90 debug_dump_get_element_state (GstElement * element)
91 {
92   gchar *state_name = NULL;
93   const gchar *state_icons = "~0-=>";
94   GstState state = GST_STATE_VOID_PENDING, pending = GST_STATE_VOID_PENDING;
95
96   gst_element_get_state (element, &state, &pending, 0);
97   if (pending == GST_STATE_VOID_PENDING) {
98     gboolean is_locked = gst_element_is_locked_state (element);
99     state_name = g_strdup_printf ("\\n[%c]%s", state_icons[state],
100         (is_locked ? "(locked)" : ""));
101   } else {
102     state_name = g_strdup_printf ("\\n[%c] -> [%c]", state_icons[state],
103         state_icons[pending]);
104   }
105   return state_name;
106 }
107
108 static gchar *
109 debug_dump_get_object_params (GObject * object,
110     GstDebugGraphDetails details, const char *const *ignored_propnames)
111 {
112   gchar *param_name = NULL;
113   GParamSpec **properties, *property;
114   GValue value = { 0, };
115   guint i, number_of_properties;
116   gchar *tmp, *value_str;
117   const gchar *ellipses;
118
119   /* get paramspecs and show non-default properties */
120   properties =
121       g_object_class_list_properties (G_OBJECT_GET_CLASS (object),
122       &number_of_properties);
123   if (properties) {
124     for (i = 0; i < number_of_properties; i++) {
125       gint j;
126       gboolean ignore = FALSE;
127       property = properties[i];
128
129       /* skip some properties */
130       if (!(property->flags & G_PARAM_READABLE))
131         continue;
132       if (!strcmp (property->name, "name")
133           || !strcmp (property->name, "parent"))
134         continue;
135
136       if (ignored_propnames)
137         for (j = 0; ignored_propnames[j]; j++)
138           if (!g_strcmp0 (ignored_propnames[j], property->name))
139             ignore = TRUE;
140
141       if (ignore)
142         continue;
143
144       g_value_init (&value, property->value_type);
145       g_object_get_property (G_OBJECT (object), property->name, &value);
146       if (!(g_param_value_defaults (property, &value))) {
147         /* we need to serialise enums and flags ourselves to make sure the
148          * enum/flag nick is used and not the enum/flag name, which would be the
149          * C header enum/flag for public enums/flags, but for element-specific
150          * enums/flags we abuse the name field for the property description,
151          * and we don't want to print that in the dot file. The nick will
152          * always work, and it's also shorter. */
153         if (G_VALUE_HOLDS_ENUM (&value)) {
154           GEnumClass *e_class = g_type_class_ref (G_VALUE_TYPE (&value));
155           gint idx, e_val;
156
157           tmp = NULL;
158           e_val = g_value_get_enum (&value);
159           for (idx = 0; idx < e_class->n_values; ++idx) {
160             if (e_class->values[idx].value == e_val) {
161               tmp = g_strdup (e_class->values[idx].value_nick);
162               break;
163             }
164           }
165           if (tmp == NULL) {
166             g_value_unset (&value);
167             continue;
168           }
169         } else if (G_VALUE_HOLDS_FLAGS (&value)) {
170           GFlagsClass *f_class = g_type_class_ref (G_VALUE_TYPE (&value));
171           GFlagsValue *vals = f_class->values;
172           GString *s = NULL;
173           guint idx, flags_left;
174
175           s = g_string_new (NULL);
176
177           /* we assume the values are sorted from lowest to highest value */
178           flags_left = g_value_get_flags (&value);
179           idx = f_class->n_values;
180           while (idx > 0) {
181             --idx;
182             if (vals[idx].value != 0
183                 && (flags_left & vals[idx].value) == vals[idx].value) {
184               if (s->len > 0)
185                 g_string_prepend_c (s, '+');
186               g_string_prepend (s, vals[idx].value_nick);
187               flags_left -= vals[idx].value;
188               if (flags_left == 0)
189                 break;
190             }
191           }
192
193           if (s->len == 0)
194             g_string_assign (s, "(none)");
195
196           tmp = g_string_free (s, FALSE);
197         } else {
198           tmp = g_strdup_value_contents (&value);
199         }
200         value_str = g_strescape (tmp, NULL);
201         g_free (tmp);
202
203         /* too long, ellipsize */
204         if (!(details & GST_DEBUG_GRAPH_SHOW_FULL_PARAMS) &&
205             strlen (value_str) > PARAM_MAX_LENGTH)
206           ellipses = "…";
207         else
208           ellipses = "";
209
210         if (param_name)
211           tmp = param_name;
212         else
213           tmp = (char *) "";
214
215         if (details & GST_DEBUG_GRAPH_SHOW_FULL_PARAMS) {
216           param_name = g_strdup_printf ("%s\\n%s=%s", tmp, property->name,
217               value_str);
218         } else {
219           param_name = g_strdup_printf ("%s\\n%s=%."
220               G_STRINGIFY (PARAM_MAX_LENGTH) "s%s", tmp, property->name,
221               value_str, ellipses);
222         }
223
224         if (tmp[0] != '\0')
225           g_free (tmp);
226
227         g_free (value_str);
228       }
229       g_value_unset (&value);
230     }
231     g_free (properties);
232   }
233   return param_name;
234 }
235
236 static void
237 debug_dump_pad (GstPad * pad, const gchar * color_name,
238     const gchar * element_name, GstDebugGraphDetails details, GString * str,
239     const gint indent)
240 {
241   GstPadTemplate *pad_templ;
242   GstPadPresence presence;
243   gchar *pad_name, *param_name = NULL;
244   const gchar *style_name;
245   static const char *const ignore_propnames[] = { "direction", "template",
246     "caps", NULL
247   };
248   const gchar *spc = MAKE_INDENT (indent);
249
250   pad_name = debug_dump_make_object_name (GST_OBJECT (pad));
251
252   /* pad availability */
253   style_name = "filled,solid";
254   if ((pad_templ = gst_pad_get_pad_template (pad))) {
255     presence = GST_PAD_TEMPLATE_PRESENCE (pad_templ);
256     gst_object_unref (pad_templ);
257     if (presence == GST_PAD_SOMETIMES) {
258       style_name = "filled,dotted";
259     } else if (presence == GST_PAD_REQUEST) {
260       style_name = "filled,dashed";
261     }
262   }
263
264   param_name =
265       debug_dump_get_object_params (G_OBJECT (pad), details, ignore_propnames);
266   if (details & GST_DEBUG_GRAPH_SHOW_STATES) {
267     gchar pad_flags[5];
268     const gchar *activation_mode = "-><";
269     const gchar *task_mode = "";
270     GstTask *task;
271
272     GST_OBJECT_LOCK (pad);
273     task = GST_PAD_TASK (pad);
274     if (task) {
275       switch (gst_task_get_state (task)) {
276         case GST_TASK_STARTED:
277           task_mode = "[T]";
278           break;
279         case GST_TASK_PAUSED:
280           task_mode = "[t]";
281           break;
282         default:
283           /* Invalid task state, ignoring */
284           break;
285       }
286     }
287     GST_OBJECT_UNLOCK (pad);
288
289     /* check if pad flags */
290     pad_flags[0] =
291         GST_OBJECT_FLAG_IS_SET (pad, GST_PAD_FLAG_BLOCKED) ? 'B' : 'b';
292     pad_flags[1] =
293         GST_OBJECT_FLAG_IS_SET (pad, GST_PAD_FLAG_FLUSHING) ? 'F' : 'f';
294     pad_flags[2] =
295         GST_OBJECT_FLAG_IS_SET (pad, GST_PAD_FLAG_BLOCKING) ? 'B' : 'b';
296     pad_flags[3] = GST_OBJECT_FLAG_IS_SET (pad, GST_PAD_FLAG_EOS) ? 'E' : '\0';
297     pad_flags[4] = '\0';
298
299     g_string_append_printf (str,
300         "%s  %s_%s [color=black, fillcolor=\"%s\", label=\"%s%s\\n[%c][%s]%s\", height=\"0.2\", style=\"%s\"];\n",
301         spc, element_name, pad_name, color_name, GST_OBJECT_NAME (pad),
302         (param_name ? param_name : ""),
303         activation_mode[pad->mode], pad_flags, task_mode, style_name);
304   } else {
305     g_string_append_printf (str,
306         "%s  %s_%s [color=black, fillcolor=\"%s\", label=\"%s%s\", height=\"0.2\", style=\"%s\"];\n",
307         spc, element_name, pad_name, color_name, GST_OBJECT_NAME (pad),
308         (param_name ? param_name : ""), style_name);
309   }
310
311   g_free (param_name);
312   g_free (pad_name);
313 }
314
315 static void
316 debug_dump_element_pad (GstPad * pad, GstElement * element,
317     GstDebugGraphDetails details, GString * str, const gint indent)
318 {
319   GstElement *target_element;
320   GstPad *target_pad, *tmp_pad;
321   GstPadDirection dir;
322   gchar *element_name;
323   gchar *target_element_name;
324   const gchar *color_name;
325
326   dir = gst_pad_get_direction (pad);
327   element_name = debug_dump_make_object_name (GST_OBJECT (element));
328   if (GST_IS_GHOST_PAD (pad)) {
329     color_name =
330         (dir == GST_PAD_SRC) ? "#ffdddd" : ((dir ==
331             GST_PAD_SINK) ? "#ddddff" : "#ffffff");
332     /* output target-pad so that it belongs to this element */
333     if ((tmp_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad)))) {
334       if ((target_pad = gst_pad_get_peer (tmp_pad))) {
335         gchar *pad_name, *target_pad_name;
336         const gchar *spc = MAKE_INDENT (indent);
337
338         if ((target_element = gst_pad_get_parent_element (target_pad))) {
339           target_element_name =
340               debug_dump_make_object_name (GST_OBJECT (target_element));
341         } else {
342           target_element_name = g_strdup ("");
343         }
344         debug_dump_pad (target_pad, color_name, target_element_name, details,
345             str, indent);
346         /* src ghostpad relationship */
347         pad_name = debug_dump_make_object_name (GST_OBJECT (pad));
348         target_pad_name = debug_dump_make_object_name (GST_OBJECT (target_pad));
349         if (dir == GST_PAD_SRC) {
350           g_string_append_printf (str,
351               "%s%s_%s -> %s_%s [style=dashed, minlen=0]\n", spc,
352               target_element_name, target_pad_name, element_name, pad_name);
353         } else {
354           g_string_append_printf (str,
355               "%s%s_%s -> %s_%s [style=dashed, minlen=0]\n", spc,
356               element_name, pad_name, target_element_name, target_pad_name);
357         }
358         g_free (target_pad_name);
359         g_free (target_element_name);
360         if (target_element)
361           gst_object_unref (target_element);
362         gst_object_unref (target_pad);
363         g_free (pad_name);
364       }
365       gst_object_unref (tmp_pad);
366     }
367   } else {
368     color_name =
369         (dir == GST_PAD_SRC) ? "#ffaaaa" : ((dir ==
370             GST_PAD_SINK) ? "#aaaaff" : "#cccccc");
371   }
372   /* pads */
373   debug_dump_pad (pad, color_name, element_name, details, str, indent);
374   g_free (element_name);
375 }
376
377 static gboolean
378 string_append_field (GQuark field, const GValue * value, gpointer ptr)
379 {
380   GString *str = (GString *) ptr;
381   gchar *value_str = gst_value_serialize (value);
382   gchar *esc_value_str;
383
384   if (value_str == NULL) {
385     g_string_append_printf (str, "  %18s: NULL\\l", g_quark_to_string (field));
386     return TRUE;
387   }
388
389   /* some enums can become really long */
390   if (strlen (value_str) > 25) {
391     gint pos = 24;
392
393     /* truncate */
394     value_str[25] = '\0';
395
396     /* mirror any brackets and quotes */
397     if (value_str[0] == '<')
398       value_str[pos--] = '>';
399     if (value_str[0] == '[')
400       value_str[pos--] = ']';
401     if (value_str[0] == '(')
402       value_str[pos--] = ')';
403     if (value_str[0] == '{')
404       value_str[pos--] = '}';
405     if (value_str[0] == '"')
406       value_str[pos--] = '"';
407     if (pos != 24)
408       value_str[pos--] = ' ';
409     /* elippsize */
410     value_str[pos--] = '.';
411     value_str[pos--] = '.';
412     value_str[pos--] = '.';
413   }
414   esc_value_str = g_strescape (value_str, NULL);
415
416   g_string_append_printf (str, "  %18s: %s\\l", g_quark_to_string (field),
417       esc_value_str);
418
419   g_free (value_str);
420   g_free (esc_value_str);
421   return TRUE;
422 }
423
424 static gchar *
425 debug_dump_describe_caps (GstCaps * caps, GstDebugGraphDetails details)
426 {
427   gchar *media = NULL;
428
429   if (details & GST_DEBUG_GRAPH_SHOW_CAPS_DETAILS) {
430
431     if (gst_caps_is_any (caps) || gst_caps_is_empty (caps)) {
432       media = gst_caps_to_string (caps);
433
434     } else {
435       GString *str = NULL;
436       guint i;
437       guint slen = 0;
438
439       for (i = 0; i < gst_caps_get_size (caps); i++) {
440         slen += 25 +
441             STRUCTURE_ESTIMATED_STRING_LEN (gst_caps_get_structure (caps, i));
442       }
443
444       str = g_string_sized_new (slen);
445       for (i = 0; i < gst_caps_get_size (caps); i++) {
446         GstCapsFeatures *features = __gst_caps_get_features_unchecked (caps, i);
447         GstStructure *structure = gst_caps_get_structure (caps, i);
448
449         g_string_append (str, gst_structure_get_name (structure));
450
451         if (features && (gst_caps_features_is_any (features)
452                 || !gst_caps_features_is_equal (features,
453                     GST_CAPS_FEATURES_MEMORY_SYSTEM_MEMORY))) {
454           g_string_append_c (str, '(');
455           priv_gst_caps_features_append_to_gstring (features, str);
456           g_string_append_c (str, ')');
457         }
458         g_string_append (str, "\\l");
459
460         gst_structure_foreach (structure, string_append_field, (gpointer) str);
461       }
462
463       media = g_string_free (str, FALSE);
464     }
465
466   } else {
467     if (GST_CAPS_IS_SIMPLE (caps))
468       media =
469           g_strdup (gst_structure_get_name (gst_caps_get_structure (caps, 0)));
470     else
471       media = g_strdup ("*");
472   }
473   return media;
474 }
475
476 static void
477 debug_dump_element_pad_link (GstPad * pad, GstElement * element,
478     GstDebugGraphDetails details, GString * str, const gint indent)
479 {
480   GstElement *peer_element;
481   GstPad *peer_pad;
482   GstCaps *caps, *peer_caps;
483   gchar *media = NULL;
484   gchar *media_src = NULL, *media_sink = NULL;
485   gchar *pad_name, *element_name;
486   gchar *peer_pad_name, *peer_element_name;
487   const gchar *spc = MAKE_INDENT (indent);
488
489   if ((peer_pad = gst_pad_get_peer (pad))) {
490     if ((details & GST_DEBUG_GRAPH_SHOW_MEDIA_TYPE) ||
491         (details & GST_DEBUG_GRAPH_SHOW_CAPS_DETAILS)
492         ) {
493       caps = gst_pad_get_current_caps (pad);
494       if (!caps)
495         caps = gst_pad_get_pad_template_caps (pad);
496       peer_caps = gst_pad_get_current_caps (peer_pad);
497       if (!peer_caps)
498         peer_caps = gst_pad_get_pad_template_caps (peer_pad);
499
500       media = debug_dump_describe_caps (caps, details);
501       /* check if peer caps are different */
502       if (peer_caps && !gst_caps_is_equal (caps, peer_caps)) {
503         gchar *tmp;
504
505         tmp = debug_dump_describe_caps (peer_caps, details);
506         if (gst_pad_get_direction (pad) == GST_PAD_SRC) {
507           media_src = media;
508           media_sink = tmp;
509         } else {
510           media_src = tmp;
511           media_sink = media;
512         }
513         media = NULL;
514       }
515       gst_caps_unref (peer_caps);
516       gst_caps_unref (caps);
517     }
518
519     pad_name = debug_dump_make_object_name (GST_OBJECT (pad));
520     if (element) {
521       element_name = debug_dump_make_object_name (GST_OBJECT (element));
522     } else {
523       element_name = g_strdup ("");
524     }
525     peer_pad_name = debug_dump_make_object_name (GST_OBJECT (peer_pad));
526     if ((peer_element = gst_pad_get_parent_element (peer_pad))) {
527       peer_element_name =
528           debug_dump_make_object_name (GST_OBJECT (peer_element));
529     } else {
530       peer_element_name = g_strdup ("");
531     }
532
533     /* pad link */
534     if (media) {
535       g_string_append_printf (str, "%s%s_%s -> %s_%s [label=\"%s\"]\n", spc,
536           element_name, pad_name, peer_element_name, peer_pad_name, media);
537       g_free (media);
538     } else if (media_src && media_sink) {
539       /* dot has some issues with placement of head and taillabels,
540        * we need an empty label to make space */
541       g_string_append_printf (str,
542           "%s%s_%s -> %s_%s [labeldistance=\"10\", labelangle=\"0\", "
543           "label=\"                                                  \", "
544           "taillabel=\"%s\", headlabel=\"%s\"]\n",
545           spc, element_name, pad_name, peer_element_name, peer_pad_name,
546           media_src, media_sink);
547       g_free (media_src);
548       g_free (media_sink);
549     } else {
550       g_string_append_printf (str, "%s%s_%s -> %s_%s\n", spc,
551           element_name, pad_name, peer_element_name, peer_pad_name);
552     }
553
554     g_free (pad_name);
555     g_free (element_name);
556     g_free (peer_pad_name);
557     g_free (peer_element_name);
558     if (peer_element)
559       gst_object_unref (peer_element);
560     gst_object_unref (peer_pad);
561   }
562 }
563
564 static void
565 debug_dump_element_pads (GstIterator * pad_iter, GstPad * pad,
566     GstElement * element, GstDebugGraphDetails details, GString * str,
567     const gint indent, guint * num_pads, gchar * cluster_name,
568     gchar ** first_pad_name)
569 {
570   GValue item = { 0, };
571   gboolean pads_done;
572   const gchar *spc = MAKE_INDENT (indent);
573
574   pads_done = FALSE;
575   while (!pads_done) {
576     switch (gst_iterator_next (pad_iter, &item)) {
577       case GST_ITERATOR_OK:
578         pad = g_value_get_object (&item);
579         if (!*num_pads) {
580           g_string_append_printf (str, "%ssubgraph cluster_%s {\n", spc,
581               cluster_name);
582           g_string_append_printf (str, "%s  label=\"\";\n", spc);
583           g_string_append_printf (str, "%s  style=\"invis\";\n", spc);
584           (*first_pad_name) = debug_dump_make_object_name (GST_OBJECT (pad));
585         }
586         debug_dump_element_pad (pad, element, details, str, indent);
587         (*num_pads)++;
588         g_value_reset (&item);
589         break;
590       case GST_ITERATOR_RESYNC:
591         gst_iterator_resync (pad_iter);
592         break;
593       case GST_ITERATOR_ERROR:
594       case GST_ITERATOR_DONE:
595         pads_done = TRUE;
596         break;
597     }
598   }
599   if (*num_pads) {
600     g_string_append_printf (str, "%s}\n\n", spc);
601   }
602 }
603
604 /*
605  * debug_dump_element:
606  * @bin: the bin that should be analyzed
607  * @out: file to write to
608  * @indent: level of graph indentation
609  *
610  * Helper for gst_debug_bin_to_dot_file() to recursively dump a pipeline.
611  */
612 static void
613 debug_dump_element (GstBin * bin, GstDebugGraphDetails details,
614     GString * str, const gint indent)
615 {
616   GstIterator *element_iter, *pad_iter;
617   gboolean elements_done, pads_done;
618   GValue item = { 0, };
619   GValue item2 = { 0, };
620   GstElement *element;
621   GstPad *pad = NULL;
622   guint src_pads, sink_pads;
623   gchar *src_pad_name = NULL, *sink_pad_name = NULL;
624   gchar *element_name;
625   gchar *state_name = NULL;
626   gchar *param_name = NULL;
627   const gchar *spc = MAKE_INDENT (indent);
628   static const char *const ignore_propnames[] = { "stats", NULL };
629
630   element_iter = gst_bin_iterate_elements (bin);
631   elements_done = FALSE;
632   while (!elements_done) {
633     switch (gst_iterator_next (element_iter, &item)) {
634       case GST_ITERATOR_OK:
635         element = g_value_get_object (&item);
636         element_name = debug_dump_make_object_name (GST_OBJECT (element));
637
638         if (details & GST_DEBUG_GRAPH_SHOW_STATES) {
639           state_name = debug_dump_get_element_state (GST_ELEMENT (element));
640         }
641         if (details & GST_DEBUG_GRAPH_SHOW_NON_DEFAULT_PARAMS) {
642           param_name = debug_dump_get_object_params (G_OBJECT (element),
643               details, ignore_propnames);
644         }
645         /* elements */
646         g_string_append_printf (str, "%ssubgraph cluster_%s {\n", spc,
647             element_name);
648         g_string_append_printf (str, "%s  fontname=\"Bitstream Vera Sans\";\n",
649             spc);
650         g_string_append_printf (str, "%s  fontsize=\"8\";\n", spc);
651         g_string_append_printf (str, "%s  style=\"filled,rounded\";\n", spc);
652         g_string_append_printf (str, "%s  color=black;\n", spc);
653         g_string_append_printf (str, "%s  label=\"%s\\n%s%s%s\";\n", spc,
654             G_OBJECT_TYPE_NAME (element), GST_OBJECT_NAME (element),
655             (state_name ? state_name : ""), (param_name ? param_name : "")
656             );
657         if (state_name) {
658           g_free (state_name);
659           state_name = NULL;
660         }
661         if (param_name) {
662           g_free (param_name);
663           param_name = NULL;
664         }
665
666         src_pads = sink_pads = 0;
667         if ((pad_iter = gst_element_iterate_sink_pads (element))) {
668           gchar *cluster_name = g_strdup_printf ("%s_sink", element_name);
669           debug_dump_element_pads (pad_iter, pad, element, details, str,
670               indent + 1, &sink_pads, cluster_name, &sink_pad_name);
671           g_free (cluster_name);
672           gst_iterator_free (pad_iter);
673         }
674         if ((pad_iter = gst_element_iterate_src_pads (element))) {
675           gchar *cluster_name = g_strdup_printf ("%s_src", element_name);
676           debug_dump_element_pads (pad_iter, pad, element, details, str,
677               indent + 1, &src_pads, cluster_name, &src_pad_name);
678           g_free (cluster_name);
679           gst_iterator_free (pad_iter);
680         }
681         if (sink_pads && src_pads) {
682           /* add invisible link from first sink to first src pad */
683           g_string_append_printf (str,
684               "%s  %s_%s -> %s_%s [style=\"invis\"];\n",
685               spc, element_name, sink_pad_name, element_name, src_pad_name);
686         }
687         g_free (sink_pad_name);
688         g_free (src_pad_name);
689         g_free (element_name);
690         sink_pad_name = src_pad_name = NULL;
691         if (GST_IS_BIN (element)) {
692           g_string_append_printf (str, "%s  fillcolor=\"#ffffff\";\n", spc);
693           /* recurse */
694           debug_dump_element (GST_BIN (element), details, str, indent + 1);
695         } else {
696           if (src_pads && !sink_pads)
697             g_string_append_printf (str, "%s  fillcolor=\"#ffaaaa\";\n", spc);
698           else if (!src_pads && sink_pads)
699             g_string_append_printf (str, "%s  fillcolor=\"#aaaaff\";\n", spc);
700           else if (src_pads && sink_pads)
701             g_string_append_printf (str, "%s  fillcolor=\"#aaffaa\";\n", spc);
702           else
703             g_string_append_printf (str, "%s  fillcolor=\"#ffffff\";\n", spc);
704         }
705         g_string_append_printf (str, "%s}\n\n", spc);
706         if ((pad_iter = gst_element_iterate_pads (element))) {
707           pads_done = FALSE;
708           while (!pads_done) {
709             switch (gst_iterator_next (pad_iter, &item2)) {
710               case GST_ITERATOR_OK:
711                 pad = g_value_get_object (&item2);
712                 if (gst_pad_is_linked (pad)) {
713                   if (gst_pad_get_direction (pad) == GST_PAD_SRC) {
714                     debug_dump_element_pad_link (pad, element, details, str,
715                         indent);
716                   } else {
717                     GstPad *peer_pad = gst_pad_get_peer (pad);
718
719                     if (peer_pad) {
720                       if (!GST_IS_GHOST_PAD (peer_pad)
721                           && GST_IS_PROXY_PAD (peer_pad)) {
722                         debug_dump_element_pad_link (peer_pad, NULL, details,
723                             str, indent);
724                       }
725                       gst_object_unref (peer_pad);
726                     }
727                   }
728                 }
729                 g_value_reset (&item2);
730                 break;
731               case GST_ITERATOR_RESYNC:
732                 gst_iterator_resync (pad_iter);
733                 break;
734               case GST_ITERATOR_ERROR:
735               case GST_ITERATOR_DONE:
736                 pads_done = TRUE;
737                 break;
738             }
739           }
740           g_value_unset (&item2);
741           gst_iterator_free (pad_iter);
742         }
743         g_value_reset (&item);
744         break;
745       case GST_ITERATOR_RESYNC:
746         gst_iterator_resync (element_iter);
747         break;
748       case GST_ITERATOR_ERROR:
749       case GST_ITERATOR_DONE:
750         elements_done = TRUE;
751         break;
752     }
753   }
754
755   g_value_unset (&item);
756   gst_iterator_free (element_iter);
757 }
758
759 static void
760 debug_dump_header (GstBin * bin, GstDebugGraphDetails details, GString * str)
761 {
762   gchar *state_name = NULL;
763   gchar *param_name = NULL;
764
765   if (details & GST_DEBUG_GRAPH_SHOW_STATES) {
766     state_name = debug_dump_get_element_state (GST_ELEMENT (bin));
767   }
768   if (details & GST_DEBUG_GRAPH_SHOW_NON_DEFAULT_PARAMS) {
769     param_name = debug_dump_get_object_params (G_OBJECT (bin), details, NULL);
770   }
771
772   /* write header */
773   g_string_append_printf (str,
774       "digraph pipeline {\n"
775       "  rankdir=LR;\n"
776       "  fontname=\"sans\";\n"
777       "  fontsize=\"10\";\n"
778       "  labelloc=t;\n"
779       "  nodesep=.1;\n"
780       "  ranksep=.2;\n"
781       "  label=\"<%s>\\n%s%s%s\";\n"
782       "  node [style=\"filled,rounded\", shape=box, fontsize=\"9\", fontname=\"sans\", margin=\"0.0,0.0\"];\n"
783       "  edge [labelfontsize=\"6\", fontsize=\"9\", fontname=\"monospace\"];\n"
784       "  \n"
785       "  legend [\n"
786       "    pos=\"0,0!\",\n"
787       "    margin=\"0.05,0.05\",\n"
788       "    style=\"filled\",\n"
789       "    label=\"Legend\\lElement-States: [~] void-pending, [0] null, [-] ready, [=] paused, [>] playing\\lPad-Activation: [-] none, [>] push, [<] pull\\lPad-Flags: [b]locked, [f]lushing, [b]locking, [E]OS; upper-case is set\\lPad-Task: [T] has started task, [t] has paused task\\l\",\n"
790       "  ];"
791       "\n", G_OBJECT_TYPE_NAME (bin), GST_OBJECT_NAME (bin),
792       (state_name ? state_name : ""), (param_name ? param_name : "")
793       );
794
795   if (state_name)
796     g_free (state_name);
797   if (param_name)
798     g_free (param_name);
799 }
800
801 static void
802 debug_dump_footer (GString * str)
803 {
804   g_string_append_printf (str, "}\n");
805 }
806
807 /**
808  * gst_debug_bin_to_dot_data:
809  * @bin: the top-level pipeline that should be analyzed
810  * @details: type of #GstDebugGraphDetails to use
811  *
812  * To aid debugging applications one can use this method to obtain the whole
813  * network of gstreamer elements that form the pipeline into a dot file.
814  * This data can be processed with graphviz to get an image.
815  *
816  * Returns: (transfer full): a string containing the pipeline in graphviz
817  * dot format.
818  */
819 gchar *
820 gst_debug_bin_to_dot_data (GstBin * bin, GstDebugGraphDetails details)
821 {
822   GString *str;
823
824   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
825
826   str = g_string_new (NULL);
827
828   debug_dump_header (bin, details, str);
829   debug_dump_element (bin, details, str, 1);
830   debug_dump_footer (str);
831
832   return g_string_free (str, FALSE);
833 }
834
835 /**
836  * gst_debug_bin_to_dot_file:
837  * @bin: the top-level pipeline that should be analyzed
838  * @details: type of #GstDebugGraphDetails to use
839  * @file_name: (type filename): output base filename (e.g. "myplayer")
840  *
841  * To aid debugging applications one can use this method to write out the whole
842  * network of gstreamer elements that form the pipeline into a dot file.
843  * This file can be processed with graphviz to get an image.
844  *
845  * ``` shell
846  *  dot -Tpng -oimage.png graph_lowlevel.dot
847  * ```
848  */
849 void
850 gst_debug_bin_to_dot_file (GstBin * bin, GstDebugGraphDetails details,
851     const gchar * file_name)
852 {
853   gchar *full_file_name = NULL;
854   FILE *out;
855
856   g_return_if_fail (GST_IS_BIN (bin));
857
858   if (G_LIKELY (priv_gst_dump_dot_dir == NULL))
859     return;
860
861   if (!file_name) {
862     file_name = g_get_application_name ();
863     if (!file_name)
864       file_name = "unnamed";
865   }
866
867   full_file_name = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "%s.dot",
868       priv_gst_dump_dot_dir, file_name);
869
870   if ((out = fopen (full_file_name, "wb"))) {
871     gchar *buf;
872
873     buf = gst_debug_bin_to_dot_data (bin, details);
874     fputs (buf, out);
875
876     g_free (buf);
877     fclose (out);
878
879     GST_INFO ("wrote bin graph to : '%s'", full_file_name);
880   } else {
881     GST_WARNING ("Failed to open file '%s' for writing: %s", full_file_name,
882         g_strerror (errno));
883   }
884   g_free (full_file_name);
885 }
886
887 /**
888  * gst_debug_bin_to_dot_file_with_ts:
889  * @bin: the top-level pipeline that should be analyzed
890  * @details: type of #GstDebugGraphDetails to use
891  * @file_name: (type filename): output base filename (e.g. "myplayer")
892  *
893  * This works like gst_debug_bin_to_dot_file(), but adds the current timestamp
894  * to the filename, so that it can be used to take multiple snapshots.
895  */
896 void
897 gst_debug_bin_to_dot_file_with_ts (GstBin * bin,
898     GstDebugGraphDetails details, const gchar * file_name)
899 {
900   gchar *ts_file_name = NULL;
901   GstClockTime elapsed;
902
903   g_return_if_fail (GST_IS_BIN (bin));
904
905   if (!file_name) {
906     file_name = g_get_application_name ();
907     if (!file_name)
908       file_name = "unnamed";
909   }
910
911   /* add timestamp */
912   elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
913
914   /* we don't use GST_TIME_FORMAT as such filenames would fail on some
915    * filesystems like fat */
916   ts_file_name =
917       g_strdup_printf ("%u.%02u.%02u.%09u-%s", GST_TIME_ARGS (elapsed),
918       file_name);
919
920   gst_debug_bin_to_dot_file (bin, details, ts_file_name);
921   g_free (ts_file_name);
922 }
923 #else /* !GST_DISABLE_GST_DEBUG */
924 #ifndef GST_REMOVE_DISABLED
925 void
926 gst_debug_bin_to_dot_file (GstBin * bin, GstDebugGraphDetails details,
927     const gchar * file_name)
928 {
929 }
930
931 void
932 gst_debug_bin_to_dot_file_with_ts (GstBin * bin, GstDebugGraphDetails details,
933     const gchar * file_name)
934 {
935 }
936 #endif /* GST_REMOVE_DISABLED */
937 #endif /* GST_DISABLE_GST_DEBUG */