Debian Codegraph @

libs/gst/helpers/gst_gdb.py

raw
1 # GStreamer
2 # Copyright (C) 2018 Pengutronix, Michael Olbrich <[email protected]>
3 #
4 # gst_gdb.py: gdb extension for GStreamer
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 import gdb
22 import sys
23 import re
24
25 from glib_gobject_helper import g_type_to_name, g_type_name_from_instance, \
26 g_type_to_typenode, g_quark_to_string, g_type_fundamental_name
27
28 if sys.version_info[0] >= 3:
29 long = int
30
31
32 def is_gst_type(val, klass):
33 def _is_gst_type(type):
34 if str(type) == klass:
35 return True
36
37 while type.code == gdb.TYPE_CODE_TYPEDEF:
38 type = type.target()
39
40 if type.code != gdb.TYPE_CODE_STRUCT:
41 return False
42
43 fields = type.fields()
44 if len(fields) < 1:
45 return False
46
47 first_field = fields[0]
48 return _is_gst_type(first_field.type)
49
50 type = val.type
51 if type.code != gdb.TYPE_CODE_PTR:
52 return False
53 type = type.target()
54 return _is_gst_type(type)
55
56
57 class GstMiniObjectPrettyPrinter:
58 "Prints a GstMiniObject instance pointer"
59
60 def __init__(self, val):
61 self.val = val
62
63 def to_string(self):
64 try:
65 inst = self.val.cast(gdb.lookup_type("GstMiniObject").pointer())
66 gtype = inst["type"]
67 name = g_type_to_name(gtype)
68 return "0x%x [%s]" % (long(self.val), name)
69 except RuntimeError:
70 return "0x%x" % long(self.val)
71
72
73 class GstObjectPrettyPrinter:
74 "Prints a GstObject instance"
75
76 def __init__(self, val):
77 self.val = val
78
79 def to_string(self):
80 try:
81 name = g_type_name_from_instance(self.val)
82 if not name:
83 name = str(self.val.type.target())
84 if long(self.val) != 0:
85 inst = self.val.cast(gdb.lookup_type("GstObject").pointer())
86 inst_name = inst["name"].string()
87 if inst_name:
88 name += "|" + inst_name
89 return ("0x%x [%s]") % (long(self.val), name)
90 except RuntimeError:
91 return "0x%x" % long(self.val)
92
93
94 GST_SECOND = 1000000000
95 GST_CLOCK_TIME_NONE = (2 ** 64) - 1
96 GST_CLOCK_STIME_NONE = -(2 ** 63)
97
98
99 def format_time(n, signed=False):
100 prefix = ""
101 invalid = False
102 if signed:
103 if n == GST_CLOCK_STIME_NONE:
104 invalid = True
105 prefix = "+" if n >= 0 else "-"
106 n = abs(n)
107 else:
108 if n == GST_CLOCK_TIME_NONE:
109 invalid = True
110
111 if invalid:
112 return "99:99:99.999999999"
113
114 return "%s%u:%02u:%02u.%09u" % (
115 prefix,
116 n / (GST_SECOND * 60 * 60),
117 (n / (GST_SECOND * 60)) % 60,
118 (n / GST_SECOND) % 60,
119 n % GST_SECOND)
120
121
122 def format_time_value(val):
123 return format_time(int(val), str(val.type) == "GstClockTimeDiff")
124
125
126 class GstClockTimePrinter:
127 "Prints a GstClockTime / GstClockTimeDiff"
128
129 def __init__(self, val):
130 self.val = val
131
132 def to_string(self):
133 return "%d [%s]" % (int(self.val), format_time_value(self.val))
134
135
136 def gst_pretty_printer_lookup(val):
137 if is_gst_type(val, "GstMiniObject"):
138 return GstMiniObjectPrettyPrinter(val)
139 if is_gst_type(val, "GstObject"):
140 return GstObjectPrettyPrinter(val)
141 if str(val.type) == "GstClockTime" or str(val.type) == "GstClockTimeDiff":
142 return GstClockTimePrinter(val)
143 return None
144
145
146 def save_memory_access(fallback):
147 def _save_memory_access(func):
148 def wrapper(*args, **kwargs):
149 try:
150 return func(*args, **kwargs)
151 except gdb.MemoryError:
152 return fallback
153 return wrapper
154 return _save_memory_access
155
156
157 def save_memory_access_print(message):
158 def _save_memory_access_print(func):
159 def wrapper(*args, **kwargs):
160 try:
161 func(*args, **kwargs)
162 except gdb.MemoryError:
163 _gdb_write(args[1], message)
164 return wrapper
165 return _save_memory_access_print
166
167
168 def _g_type_from_instance(instance):
169 if long(instance) != 0:
170 try:
171 inst = instance.cast(gdb.lookup_type("GTypeInstance").pointer())
172 klass = inst["g_class"]
173 gtype = klass["g_type"]
174 return gtype
175 except RuntimeError:
176 pass
177 return None
178
179
180 def g_inherits_type(val, typename):
181 if is_gst_type(val, "GstObject"):
182 gtype = _g_type_from_instance(val)
183 if gtype is None:
184 return False
185 typenode = g_type_to_typenode(gtype)
186 elif is_gst_type(val, "GstMiniObject"):
187 mini = val.cast(gdb.lookup_type("GstMiniObject").pointer())
188 try:
189 typenode = mini["type"].cast(gdb.lookup_type("TypeNode").pointer())
190 except gdb.MemoryError:
191 return False
192 else:
193 return False
194
195 for i in range(typenode["n_supers"]):
196 if g_type_to_name(typenode["supers"][i]) == typename:
197 return True
198 return False
199
200
201 def gst_is_bin(val):
202 return g_inherits_type(val, "GstBin")
203
204
205 def _g_array_iter(array, element_type):
206 if array == 0:
207 return
208 try:
209 item = array["data"].cast(element_type.pointer())
210 for i in range(int(array["len"])):
211 yield item[i]
212 except gdb.MemoryError:
213 pass
214
215
216 def _g_value_get_value(val):
217 tname = g_type_to_name(val["g_type"])
218 fname = g_type_fundamental_name(val["g_type"])
219 if fname in ("gchar", "guchar", "gboolean", "gint", "guint", "glong",
220 "gulong", "gint64", "guint64", "gfloat", "gdouble",
221 "gpointer", "GFlags"):
222 try:
223 t = gdb.lookup_type(tname).pointer()
224 except RuntimeError:
225 t = gdb.lookup_type(fname).pointer()
226 elif fname == "gchararray":
227 t = gdb.lookup_type("char").pointer().pointer()
228 elif fname == "GstBitmask":
229 t = gdb.lookup_type("guint64").pointer()
230 elif fname == "GstFlagSet":
231 t = gdb.lookup_type("guint").pointer().pointer()
232 return val["data"].cast(t)
233 elif fname == "GstFraction":
234 t = gdb.lookup_type("gint").pointer().pointer()
235 return val["data"].cast(t)
236 elif fname == "GstFractionRange":
237 t = gdb.lookup_type("GValue").pointer().pointer()
238 elif fname == "GstValueList":
239 t = gdb.lookup_type("GArray").pointer().pointer()
240 elif fname in ("GBoxed", "GObject"):
241 try:
242 t = gdb.lookup_type(tname).pointer().pointer()
243 except RuntimeError:
244 t = gdb.lookup_type(tname).pointer().pointer()
245 else:
246 return val["data"]
247
248 return val["data"].cast(t).dereference()
249
250
251 def gst_object_from_value(value):
252 if value.type.code != gdb.TYPE_CODE_PTR:
253 value = value.address
254
255 if not is_gst_type(value, "GstObject"):
256 raise Exception("'%s' is not a GstObject" % args[0])
257
258 return value.cast(gdb.lookup_type("GstObject").pointer())
259
260
261 def gst_object_pipeline(obj):
262 try:
263 while obj["parent"] != 0:
264 tmp = obj["parent"]
265 # sanity checks to handle memory corruption
266 if g_inherits_type(obj, "GstElement") and \
267 GdbGstElement(obj) not in GdbGstElement(tmp).children():
268 break
269 if g_inherits_type(obj, "GstPad"):
270 pad = GdbGstPad(obj)
271 if g_inherits_type(tmp, "GstElement"):
272 if pad not in GdbGstElement(tmp).pads():
273 break
274 elif g_inherits_type(tmp, "GstProxyPad"):
275 t = gdb.lookup_type("GstProxyPad").pointer()
276 if pad != GdbGstPad(tmp.cast(t)["priv"]["internal"]):
277 break
278 obj = tmp
279 except gdb.MemoryError:
280 pass
281
282 if not g_inherits_type(obj, "GstElement"):
283 raise Exception("Toplevel %s parent is not a GstElement" % obj)
284 return obj.cast(gdb.lookup_type("GstElement").pointer())
285
286
287 def element_state_to_name(state):
288 names = [
289 "VOID_PENDING",
290 "NULL",
291 "READY",
292 "PAUSED",
293 "PLAYING"]
294 return names[state] if state < len(names) else "UNKNOWN"
295
296
297 def task_state_to_name(state):
298 names = [
299 "STARTED",
300 "STOPPED",
301 "PAUSED"]
302 return names[state] if state < len(names) else "UNKNOWN"
303
304
305 def _gdb_write(indent, text):
306 gdb.write("%s%s\n" % (" " * indent, text))
307
308
309 class GdbCapsFeatures:
310 def __init__(self, val):
311 self.val = val
312
313 def size(self):
314 if long(self.val) == 0:
315 return 0
316 return int(self.val["array"]["len"])
317
318 def items(self):
319 if long(self.val) == 0:
320 return
321 for q in _g_array_iter(self.val["array"], gdb.lookup_type("GQuark")):
322 yield q
323
324 def __eq__(self, other):
325 if self.size() != other.size():
326 return False
327 a1 = list(self.items())
328 a2 = list(other.items())
329 for item in a1:
330 if item not in a2:
331 return False
332 return True
333
334 def __str__(self):
335 if long(self.val) == 0:
336 return ""
337 count = self.size()
338 if int(self.val["is_any"]) == 1 and count == 0:
339 return "(ANY)"
340 if count == 0:
341 return ""
342 s = ""
343 for f in self.items():
344 ss = g_quark_to_string(f)
345 if ss != "memory:SystemMemory" or count > 1:
346 s += ", " if s else ""
347 s += ss
348 return s
349
350
351 class GdbGstCaps:
352 def __init__(self, val):
353 self.val = val.cast(gdb.lookup_type("GstCapsImpl").pointer())
354
355 def size(self):
356 return int(self.val["array"]["len"])
357
358 def items(self):
359 gdb_type = gdb.lookup_type("GstCapsArrayElement")
360 for f in _g_array_iter(self.val["array"], gdb_type):
361 yield (GdbCapsFeatures(f["features"]),
362 GdbGstStructure(f["structure"]))
363
364 def __eq__(self, other):
365 if self.size() != other.size():
366 return False
367 a1 = list(self.items())
368 a2 = list(other.items())
369 for i in range(self.size()):
370 if a1[i] != a2[i]:
371 return False
372 return True
373
374 def dot(self):
375 if self.size() == 0:
376 return "ANY"
377 s = ""
378 for (features, structure) in self.items():
379 s += structure.name()
380 tmp = str(features)
381 if tmp:
382 s += "(" + tmp + ")"
383 s += "\\l"
384 if structure.size() > 0:
385 s += "\\l".join(structure.value_strings(" %18s: %s")) + "\\l"
386 return s
387
388 @save_memory_access_print("<inaccessible memory>")
389 def print(self, indent, prefix=""):
390 items = list(self.items())
391 if len(items) != 1:
392 _gdb_write(indent, prefix)
393 prefix = ""
394 s = ""
395 for (features, structure) in items:
396 s = "%s %s" % (prefix, structure.name())
397 tmp = str(features)
398 if tmp:
399 s += "(" + tmp + ")"
400 _gdb_write(indent, s)
401 for val in structure.value_strings("%s: %s", False):
402 _gdb_write(indent + 1, val)
403 return s
404
405
406 class GdbGValue:
407 def __init__(self, val):
408 self.val = val
409
410 def fundamental_typename(self):
411 typenode = g_type_to_typenode(self.val["g_type"])
412 if not typenode:
413 return None
414 return g_type_to_name(typenode["supers"][int(typenode["n_supers"])])
415
416 def value(self):
417 return _g_value_get_value(self.val)
418
419 def __str__(self):
420 try:
421 value = self.value()
422 tname = self.fundamental_typename()
423 gvalue_type = gdb.lookup_type("GValue")
424 if tname == "GstFraction":
425 v = "%d/%d" % (value[0], value[1])
426 elif tname == "GstBitmask":
427 v = "0x%016x" % long(value)
428 elif tname == "gboolean":
429 v = "false" if int(value) == 0 else "true"
430 elif tname == "GstFlagSet":
431 v = "%x:%x" % (value[0], value[1])
432 elif tname == "GstIntRange":
433 rmin = int(value[0]["v_uint64"]) >> 32
434 rmax = int(value[0]["v_uint64"]) & 0xffffffff
435 step = int(value[1]["v_int"])
436 if step == 1:
437 v = "[ %d, %d ]" % (rmin, rmax)
438 else:
439 v = "[ %d, %d, %d ]" % (rmin * step, rmax * step, step)
440 elif tname == "GstFractionRange":
441 v = "[ %s, %s ]" % (GdbGValue(value[0]), GdbGValue(value[1]))
442 elif tname in ("GstValueList", "GstValueArray"):
443 if gvalue_type.fields()[1].type == value.type:
444 gdb_type = gdb.lookup_type("GArray").pointer()
445 value = value[0]["v_pointer"].cast(gdb_type)
446 v = "<"
447 for array_val in _g_array_iter(value, gvalue_type):
448 v += " " if v == "<" else ", "
449 v += str(GdbGValue(array_val))
450 v += " >"
451 elif tname in ("GEnum"):
452 v = "%s(%s)" % (
453 g_type_to_name(g_type_to_typenode(self.val["g_type"])),
454 value["v_int"])
455 else:
456 try:
457 v = value.string()
458 except RuntimeError:
459 # it is not a string-like type
460 if gvalue_type.fields()[1].type == value.type:
461 # don't print the raw GValue union
462 v = "<unknown type: %s>" % tname
463 else:
464 v = str(value)
465 except gdb.MemoryError:
466 v = "<inaccessible memory at 0x%x>" % int(self.val)
467 return v
468
469 def __eq__(self, other):
470 return self.val == other.val
471
472
473 class GdbGstStructure:
474 def __init__(self, val):
475 self.val = val.cast(gdb.lookup_type("GstStructureImpl").pointer())
476
477 @save_memory_access("<inaccessible memory>")
478 def name(self):
479 return g_quark_to_string(self.val["s"]["name"])
480
481 @save_memory_access(0)
482 def size(self):
483 return int(self.val["fields_len"])
484
485 def values(self):
486 item = self.val["fields"].cast(gdb.lookup_type("GstStructureField").pointer())
487 for i in range(self.size()):
488 f = item[i]
489 key = g_quark_to_string(f["name"])
490 value = GdbGValue(f["value"])
491 yield (key, value)
492
493 def value(self, key):
494 for (k, value) in self.values():
495 if k == key:
496 return value
497 raise KeyError(key)
498
499 def __eq__(self, other):
500 if self.size() != other.size():
501 return False
502 a1 = list(self.values())
503 a2 = list(other.values())
504 for (key, value) in a1:
505 if (key, value) not in a2:
506 return False
507 return True
508
509 def value_strings(self, pattern, elide=True):
510 s = []
511 for (key, value) in self.values():
512 v = str(value)
513 if elide and len(v) > 25:
514 if v[0] in "[(<\"":
515 v = v[:20] + "... " + v[-1:]
516 else:
517 v = v[:22] + "..."
518 s.append(pattern % (key, v))
519 return s
520
521 @save_memory_access_print("<inaccessible memory>")
522 def print(self, indent, prefix=None):
523 if prefix is not None:
524 _gdb_write(indent, "%s: %s" % (prefix, self.name()))
525 else:
526 _gdb_write(indent, "%s:" % (self.name()))
527 for (key, value) in self.values():
528 _gdb_write(indent+1, "%s: %s" % (key, str(value)))
529
530
531 class GdbGstSegment:
532 def __init__(self, val):
533 t = gdb.lookup_type("GstSegment").pointer().pointer()
534 self.val = val.cast(t).dereference()
535 self.fmt = str(self.val["format"]).split("_")[-1].lower()
536
537 def format_value(self, n):
538 if self.fmt == "time":
539 return format_time(n, False)
540 else:
541 return str(n)
542
543 def print_optional(self, indent, key, skip=None):
544 value = int(self.val[key])
545 if skip is None or value != skip:
546 _gdb_write(indent, "%s:%s %s" %
547 (key, (8 - len(key)) * " ", self.format_value(value)))
548
549 def print(self, indent, seqnum=None):
550 s = "segment:"
551 if seqnum:
552 s += "(seqnum: %s)" % seqnum
553 _gdb_write(indent, s)
554 rate = float(self.val["rate"])
555 applied_rate = float(self.val["applied_rate"])
556 if applied_rate != 1.0:
557 applied = "(applied rate: %g)" % applied_rate
558 else:
559 applied = ""
560 _gdb_write(indent + 1, "rate: %g%s" % (rate, applied))
561 self.print_optional(indent + 1, "base", 0)
562 self.print_optional(indent + 1, "offset", 0)
563 self.print_optional(indent + 1, "start")
564 self.print_optional(indent + 1, "stop", GST_CLOCK_TIME_NONE)
565 self.print_optional(indent + 1, "time")
566 self.print_optional(indent + 1, "position")
567 self.print_optional(indent + 1, "duration", GST_CLOCK_TIME_NONE)
568
569
570 class GdbGstEvent:
571 def __init__(self, val):
572 self.val = val.cast(gdb.lookup_type("GstEventImpl").pointer())
573
574 @save_memory_access("<inaccessible memory>")
575 def typestr(self):
576 t = self.val["event"]["type"]
577 (event_quarks, _) = gdb.lookup_symbol("event_quarks")
578 event_quarks = event_quarks.value()
579 i = 0
580 while event_quarks[i]["name"] != 0:
581 if t == event_quarks[i]["type"]:
582 return event_quarks[i]["name"].string()
583 i += 1
584 return None
585
586 def structure(self):
587 return GdbGstStructure(self.val["structure"])
588
589 @save_memory_access_print("<inaccessible memory>")
590 def print(self, indent):
591 typestr = self.typestr()
592 seqnum = self.val["event"]["seqnum"]
593 if typestr == "caps":
594 caps = GdbGstCaps(self.structure().value("caps").value())
595 caps.print(indent, "caps (seqnum: %s):" % seqnum)
596 elif typestr == "stream-start":
597 stream_id = self.structure().value("stream-id").value()
598 _gdb_write(indent, "stream-start: (seqnum %s)" % seqnum)
599 _gdb_write(indent + 1, "stream-id: %s" % stream_id.string())
600 elif typestr == "segment":
601 segment = self.structure().value("segment").value()
602 GdbGstSegment(segment).print(indent, seqnum)
603 elif typestr == "tag":
604 struct = self.structure()
605 # skip 'GstTagList-'
606 name = struct.name()[11:]
607 t = gdb.lookup_type("GstTagListImpl").pointer()
608 s = struct.value("taglist").value().cast(t)["structure"]
609 structure = GdbGstStructure(s)
610 _gdb_write(indent, "tag: %s (seqnum: %s)" % (name, seqnum))
611 for (key, value) in structure.values():
612 _gdb_write(indent + 1, "%s: %s" % (key, str(value)))
613 else:
614 self.structure().print(indent, "%s (seqnum: %s)" % (typestr, seqnum))
615
616
617 class GdbGstBuffer:
618 def __init__(self, val):
619 self.val = val.cast(gdb.lookup_type("GstBuffer").pointer())
620
621 def print_optional(self, indent, key, skip=None, format_func=str):
622 value = int(self.val[key])
623 if skip is None or value != skip:
624 _gdb_write(indent, "%s:%s %s" %
625 (key, (8 - len(key)) * " ", format_func(value)))
626
627 @save_memory_access_print("<inaccessible memory>")
628 def print(self, indent):
629 _gdb_write(indent, "GstBuffer: (0x%x)" % self.val)
630 indent += 1
631 self.print_optional(indent, "pool", 0)
632 self.print_optional(indent, "pts", GST_CLOCK_TIME_NONE, format_time)
633 self.print_optional(indent, "dts", GST_CLOCK_TIME_NONE, format_time)
634 self.print_optional(indent, "duration", GST_CLOCK_TIME_NONE, format_time)
635 self.print_optional(indent, "offset", GST_CLOCK_TIME_NONE)
636 self.print_optional(indent, "offset_end", GST_CLOCK_TIME_NONE)
637
638 impl = self.val.cast(gdb.lookup_type("GstBufferImpl").pointer())
639 meta_item = impl['item']
640 if meta_item:
641 _gdb_write(indent, "Metas:")
642 indent += 1
643 while meta_item:
644 meta = meta_item['meta']
645 meta_type_name = g_type_to_name(meta['info']['type'])
646 _gdb_write(indent, "%s:" % meta_type_name)
647 indent += 1
648 meta_info = str(meta.cast(gdb.lookup_type(meta_type_name)))
649 for info in meta_info.split('\n'):
650 _gdb_write(indent, info)
651 indent -= 1
652 meta_item = meta_item['next']
653 else:
654 _gdb_write(indent, "(No meta)")
655
656
657 class GdbGstQuery:
658 def __init__(self, val):
659 self.val = val.cast(gdb.lookup_type("GstQueryImpl").pointer())
660
661 @save_memory_access("<inaccessible memory>")
662 def typestr(self):
663 t = self.val["query"]["type"]
664 (query_quarks, _) = gdb.lookup_symbol("query_quarks")
665 query_quarks = query_quarks.value()
666 i = 0
667 while query_quarks[i]["name"] != 0:
668 if t == query_quarks[i]["type"]:
669 return query_quarks[i]["name"].string()
670 i += 1
671 return None
672
673 def structure(self):
674 return GdbGstStructure(self.val["structure"])
675
676 @save_memory_access_print("<inaccessible memory>")
677 def print(self, indent):
678 typestr = self.typestr()
679 self.structure().print(indent, typestr)
680
681
682 class GdbGstObject:
683 def __init__(self, klass, val):
684 self.val = val.cast(klass)
685
686 @save_memory_access("<inaccessible memory>")
687 def name(self):
688 obj = self.val.cast(gdb.lookup_type("GstObject").pointer())
689 return obj["name"].string()
690
691 def full_name(self):
692 parent = self.parent_element()
693 return "%s%s" % (parent.name() + ":" if parent else "", self.name())
694
695 def dot_name(self):
696 ptr = self.val.cast(gdb.lookup_type("void").pointer())
697 return re.sub('[^a-zA-Z0-9<>]', '_', "%s_%s" % (self.name(), str(ptr)))
698
699 def parent(self):
700 obj = self.val.cast(gdb.lookup_type("GstObject").pointer())
701 return obj["parent"]
702
703 def parent_element(self):
704 p = self.parent()
705 if p != 0 and g_inherits_type(p, "GstElement"):
706 element = p.cast(gdb.lookup_type("GstElement").pointer())
707 return GdbGstElement(element)
708 return None
709
710 def parent_pad(self):
711 p = self.parent()
712 if p != 0 and g_inherits_type(p, "GstPad"):
713 pad = p.cast(gdb.lookup_type("GstPad").pointer())
714 return GdbGstPad(pad)
715 return None
716
717
718 class GdbGstPad(GdbGstObject):
719 def __init__(self, val):
720 gdb_type = gdb.lookup_type("GstPad").pointer()
721 super(GdbGstPad, self).__init__(gdb_type, val)
722
723 def __eq__(self, other):
724 return self.val == other.val
725
726 def is_linked(self):
727 return long(self.val["peer"]) != 0
728
729 def peer(self):
730 return GdbGstPad(self.val["peer"])
731
732 def direction(self):
733 return str(self.val["direction"])
734
735 def events(self):
736 if long(self.val["priv"]) == 0:
737 return
738 array = self.val["priv"]["events"]
739 for ev in _g_array_iter(array, gdb.lookup_type("PadEvent")):
740 yield GdbGstEvent(ev["event"])
741
742 def caps(self):
743 for ev in self.events():
744 if ev.typestr() != "caps":
745 continue
746 return GdbGstCaps(ev.structure().value("caps").value())
747 return None
748
749 def template_caps(self):
750 tmp = self.val["padtemplate"]
751 return GdbGstCaps(tmp["caps"]) if int(tmp) != 0 else None
752
753 def mode(self):
754 m = str(self.val["mode"]).split("_")[-1].lower()
755 if m in ("push", "pull"):
756 return m
757 return None
758
759 def pad_type(self):
760 s = str(self.val["direction"]).split("_")[-1].capitalize()
761 if g_inherits_type(self.val, "GstGhostPad"):
762 s += "Ghost"
763 return s + "Pad"
764
765 @save_memory_access_print("Pad(<inaccessible memory>)")
766 def print(self, indent):
767 m = ", " + self.mode() if self.mode() else ""
768 _gdb_write(indent, "%s(%s%s) {" % (self.pad_type(), self.name(), m))
769 first = True
770 for ev in self.events():
771 if first:
772 _gdb_write(indent + 1, "events:")
773 first = False
774 ev.print(indent + 2)
775
776 if self.is_linked():
777 real = self.peer().parent_pad()
778 _gdb_write(indent + 1, "peer: %s" %
779 (real.full_name() if real else self.peer().full_name()))
780
781 if g_inherits_type(self.val, "GstGhostPad"):
782 t = gdb.lookup_type("GstProxyPad").pointer()
783 internal = GdbGstPad(self.val.cast(t)["priv"]["internal"])
784 if internal and internal.peer():
785 _gdb_write(indent + 1, "inner peer: %s" %
786 internal.peer().full_name())
787
788 task = self.val["task"]
789 if long(task) != 0:
790 _gdb_write(indent + 1, "task: %s" %
791 task_state_to_name(int(task["state"])))
792
793 offset = long(self.val["offset"])
794 if offset != 0:
795 _gdb_write(indent + 1, "offset: %d [%s]" %
796 (offset, format_time(offset, True)))
797
798 _gdb_write(indent, "}")
799
800 def _dot(self, color, pname, indent):
801 spc = " " * indent
802 activation_mode = "-><"
803 style = "filled,solid"
804 template = self.val["padtemplate"]
805 if template != 0:
806 presence = template["presence"]
807 if str(presence) == "GST_PAD_SOMETIMES":
808 style = "filled,dotted"
809 if str(presence) == "GST_PAD_REQUEST":
810 style = "filled,dashed"
811 task_mode = ""
812 task = self.val["task"]
813 if long(task) != 0:
814 task_state = int(task["state"])
815 if task_state == 0: # started
816 task_mode = "[T]"
817 if task_state == 2: # paused
818 task_mode = "[t]"
819 f = int(self.val["object"]["flags"])
820 flags = "B" if f & 16 else "b" # GST_PAD_FLAG_BLOCKED
821 flags += "F" if f & 32 else "f" # GST_PAD_FLAG_FLUSHING
822 flags += "B" if f & 16 else "b" # GST_PAD_FLAG_BLOCKING
823
824 s = "%s %s_%s [color=black, fillcolor=\"%s\", " \
825 "label=\"%s%s\\n[%c][%s]%s\", height=\"0.2\", style=\"%s\"];\n" % \
826 (spc, pname, self.dot_name(), color, self.name(), "",
827 activation_mode[int(self.val["mode"])], flags, task_mode, style)
828 return s
829
830 def dot(self, indent):
831 spc = " " * indent
832 direction = self.direction()
833 element = self.parent_element()
834 ename = element.dot_name() if element else ""
835 s = ""
836 if g_inherits_type(self.val, "GstGhostPad"):
837 if direction == "GST_PAD_SRC":
838 color = "#ffdddd"
839 elif direction == "GST_PAD_SINK":
840 color = "#ddddff"
841 else:
842 color = "#ffffff"
843
844 t = gdb.lookup_type("GstProxyPad").pointer()
845 other = GdbGstPad(self.val.cast(t)["priv"]["internal"])
846 if other:
847 s += other._dot(color, "", indent)
848 pname = self.dot_name()
849 other_element = other.parent_element()
850 other_ename = other_element.dot_name() if other_element else ""
851 other_pname = other.dot_name()
852 if direction == "GST_PAD_SRC":
853 s += "%s%s_%s -> %s_%s [style=dashed, minlen=0]\n" % \
854 (spc, other_ename, other_pname, ename, pname)
855 else:
856 s += "%s%s_%s -> %s_%s [style=dashed, minlen=0]\n" % \
857 (spc, ename, pname, other_ename, other_pname)
858 else:
859 if direction == "GST_PAD_SRC":
860 color = "#ffaaaa"
861 elif direction == "GST_PAD_SINK":
862 color = "#aaaaff"
863 else:
864 color = "#cccccc"
865
866 s += self._dot(color, ename, indent)
867 return s
868
869 def link_dot(self, indent, element):
870 spc = " " * indent
871
872 peer = self.peer()
873 peer_element = peer.parent_element()
874
875 caps = self.caps()
876 if not caps:
877 caps = self.template_caps()
878 peer_caps = peer.caps()
879 if not peer_caps:
880 peer_caps = peer.template_caps()
881
882 pname = self.dot_name()
883 ename = element.dot_name() if element else ""
884 peer_pname = peer.dot_name()
885 peer_ename = peer_element.dot_name() if peer_element else ""
886
887 if caps and peer_caps and caps == peer_caps:
888 s = "%s%s_%s -> %s_%s [label=\"%s\"]\n" % \
889 (spc, ename, pname, peer_ename, peer_pname, caps.dot())
890 elif caps and peer_caps and caps != peer_caps:
891 s = "%s%s_%s -> %s_%s [labeldistance=\"10\", labelangle=\"0\", " \
892 % (spc, ename, pname, peer_ename, peer_pname)
893 s += "label=\"" + " " * 50 + "\", "
894 if self.direction() == "GST_PAD_SRC":
895 media_src = caps.dot()
896 media_dst = peer_caps.dot()
897 else:
898 media_src = peer_caps.dot()
899 media_dst = caps.dot()
900 s += "taillabel=\"%s\", headlabel=\"%s\"]\n" % \
901 (media_src, media_dst)
902 else:
903 s = "%s%s_%s -> %s_%s\n" % \
904 (spc, ename, pname, peer_ename, peer_pname)
905 return s
906
907
908 class GdbGstElement(GdbGstObject):
909 def __init__(self, val):
910 gdb_type = gdb.lookup_type("GstElement").pointer()
911 super(GdbGstElement, self).__init__(gdb_type, val)
912 self.is_bin = gst_is_bin(self.val)
913
914 def __eq__(self, other):
915 return self.val == other.val
916
917 def children(self):
918 if not self.is_bin:
919 return
920 b = self.val.cast(gdb.lookup_type("GstBin").pointer())
921 link = b["children"]
922 while link != 0:
923 yield GdbGstElement(link["data"])
924 link = link["next"]
925
926 def has_pads(self, pad_group="pads"):
927 return self.val[pad_group] != 0
928
929 def pads(self, pad_group="pads"):
930 link = self.val[pad_group]
931 while link != 0:
932 yield GdbGstPad(link["data"])
933 link = link["next"]
934
935 def _state_dot(self):
936 icons = "~0-=>"
937 current = int(self.val["current_state"])
938 pending = int(self.val["pending_state"])
939 if pending == 0:
940 # GST_ELEMENT_FLAG_LOCKED_STATE == 16
941 locked = (int(self.val["object"]["flags"]) & 16) != 0
942 return "\\n[%c]%s" % (icons[current], "(locked)" if locked else "")
943 return "\\n[%c] -> [%c]" % (icons[current], icons[pending])
944
945 @save_memory_access_print("Element(<inaccessible memory>)")
946 def print(self, indent):
947 _gdb_write(indent, "%s(%s) {" %
948 (g_type_name_from_instance(self.val), self.name()))
949 for p in self.pads():
950 p.print(indent + 2)
951
952 first = True
953 for child in self.children():
954 if first:
955 _gdb_write(indent + 2, "children:")
956 first = False
957 _gdb_write(indent + 3, child.name())
958
959 current_state = self.val["current_state"]
960 s = "state: %s" % element_state_to_name(current_state)
961 for var in ("pending", "target"):
962 state = self.val[var + "_state"]
963 if state > 0 and state != current_state:
964 s += ", %s: %s" % (var, element_state_to_name(state))
965 _gdb_write(indent + 2, s)
966
967 _gdb_write(indent + 2, "base_time: %s" %
968 format_time_value(self.val["base_time"]))
969 _gdb_write(indent + 2, "start_time: %s" %
970 format_time_value(self.val["start_time"]))
971
972 _gdb_write(indent, "}")
973
974 @save_memory_access_print("<inaccessible memory>")
975 def print_tree(self, indent):
976 _gdb_write(indent, "%s(%s)" % (self.name(), self.val))
977 for child in self.children():
978 child.print_tree(indent + 1)
979
980 def _dot(self, indent=0):
981 spc = " " * indent
982
983 s = "%ssubgraph cluster_%s {\n" % (spc, self.dot_name())
984 s += "%s fontname=\"Bitstream Vera Sans\";\n" % spc
985 s += "%s fontsize=\"8\";\n" % spc
986 s += "%s style=\"filled,rounded\";\n" % spc
987 s += "%s color=black;\n" % spc
988 s += "%s label=\"%s\\n%s%s%s\";\n" % \
989 (spc, g_type_name_from_instance(self.val), self.name(),
990 self._state_dot(), "")
991
992 sink_name = None
993 if self.has_pads("sinkpads"):
994 (ss, sink_name) = self._dot_pads(indent + 1, "sinkpads",
995 self.dot_name() + "_sink")
996 s += ss
997 src_name = None
998 if self.has_pads("srcpads"):
999 (ss, src_name) = self._dot_pads(indent + 1, "srcpads",
1000 self.dot_name() + "_src")
1001 s += ss
1002 if sink_name and src_name:
1003 name = self.dot_name()
1004 s += "%s %s_%s -> %s_%s [style=\"invis\"];\n" % \
1005 (spc, name, sink_name, name, src_name)
1006
1007 if gst_is_bin(self.val):
1008 s += "%s fillcolor=\"#ffffff\";\n" % spc
1009 s += self.dot(indent + 1)
1010 else:
1011 if src_name and not sink_name:
1012 s += "%s fillcolor=\"#ffaaaa\";\n" % spc
1013 elif not src_name and sink_name:
1014 s += "%s fillcolor=\"#aaaaff\";\n" % spc
1015 elif src_name and sink_name:
1016 s += "%s fillcolor=\"#aaffaa\";\n" % spc
1017 else:
1018 s += "%s fillcolor=\"#ffffff\";\n" % spc
1019 s += "%s}\n\n" % spc
1020
1021 for p in self.pads():
1022 if not p.is_linked():
1023 continue
1024 if p.direction() == "GST_PAD_SRC":
1025 s += p.link_dot(indent, self)
1026 else:
1027 pp = p.peer()
1028 if not g_inherits_type(pp.val, "GstGhostPad") and \
1029 g_inherits_type(pp.val, "GstProxyPad"):
1030 s += pp.link_dot(indent, None)
1031 return s
1032
1033 def _dot_pads(self, indent, pad_group, cluster_name):
1034 spc = " " * indent
1035 s = "%ssubgraph cluster_%s {\n" % (spc, cluster_name)
1036 s += "%s label=\"\";\n" % spc
1037 s += "%s style=\"invis\";\n" % spc
1038 name = None
1039 for p in self.pads(pad_group):
1040 s += p.dot(indent)
1041 if not name:
1042 name = p.dot_name()
1043 s += "%s}\n\n" % spc
1044 return (s, name)
1045
1046 def dot(self, indent):
1047 s = ""
1048 for child in self.children():
1049 try:
1050 s += child._dot(indent)
1051 except gdb.MemoryError:
1052 gdb.write("warning: inaccessible memory in element 0x%x\n" %
1053 long(child.val))
1054 return s
1055
1056 def pipeline_dot(self):
1057 t = g_type_name_from_instance(self.val)
1058
1059 s = "digraph pipeline {\n"
1060 s += " rankdir=LR;\n"
1061 s += " fontname=\"sans\";\n"
1062 s += " fontsize=\"10\";\n"
1063 s += " labelloc=t;\n"
1064 s += " nodesep=.1;\n"
1065 s += " ranksep=.2;\n"
1066 s += " label=\"<%s>\\n%s%s%s\";\n" % (t, self.name(), "", "")
1067 s += " node [style=\"filled,rounded\", shape=box, fontsize=\"9\", " \
1068 "fontname=\"sans\", margin=\"0.0,0.0\"];\n"
1069 s += " edge [labelfontsize=\"6\", fontsize=\"9\", " \
1070 "fontname=\"monospace\"];\n"
1071 s += " \n"
1072 s += " legend [\n"
1073 s += " pos=\"0,0!\",\n"
1074 s += " margin=\"0.05,0.05\",\n"
1075 s += " style=\"filled\",\n"
1076 s += " label=\"Legend\\lElement-States: [~] void-pending, " \
1077 "[0] null, [-] ready, [=] paused, [>] playing\\l" \
1078 "Pad-Activation: [-] none, [>] push, [<] pull\\l" \
1079 "Pad-Flags: [b]locked, [f]lushing, [b]locking, [E]OS; " \
1080 "upper-case is set\\lPad-Task: [T] has started task, " \
1081 "[t] has paused task\\l\",\n"
1082 s += " ];"
1083 s += "\n"
1084
1085 s += self.dot(1)
1086
1087 s += "}\n"
1088
1089 return s
1090
1091
1092 class GstDot(gdb.Command):
1093 """\
1094 Create a pipeline dot file as close as possible to the output of
1095 GST_DEBUG_BIN_TO_DOT_FILE. This command will find the top-level parent
1096 for the given gstreamer object and create the dot for that element.
1097
1098 Usage: gst-dot <gst-object> <file-name>"""
1099
1100 def __init__(self):
1101 super(GstDot, self).__init__("gst-dot", gdb.COMMAND_DATA)
1102
1103 def invoke(self, arg, from_tty):
1104 self.dont_repeat()
1105 args = gdb.string_to_argv(arg)
1106 if len(args) != 2:
1107 raise Exception("Usage: gst-dot <gst-object> <file>")
1108
1109 value = gdb.parse_and_eval(args[0])
1110 if not value:
1111 raise Exception("'%s' is not a valid object" % args[0])
1112
1113 value = gst_object_from_value(value)
1114 value = gst_object_pipeline(value)
1115
1116 dot = GdbGstElement(value).pipeline_dot()
1117 file = open(args[1], "w")
1118 file.write(dot)
1119 file.close()
1120
1121 def complete(self, text, word):
1122 cmd = gdb.string_to_argv(text)
1123 if len(cmd) == 0 or (len(cmd) == 1 and len(word) > 0):
1124 return gdb.COMPLETE_SYMBOL
1125 return gdb.COMPLETE_FILENAME
1126
1127
1128 class GstPrint(gdb.Command):
1129 """\
1130 Print high-level information for GStreamer objects
1131
1132 Usage gst-print <gstreamer-object>"""
1133
1134 def __init__(self):
1135 super(GstPrint, self).__init__("gst-print", gdb.COMMAND_DATA,
1136 gdb.COMPLETE_SYMBOL)
1137
1138 def invoke(self, arg, from_tty):
1139 value = gdb.parse_and_eval(arg)
1140 if not value:
1141 raise Exception("'%s' is not a valid object" % arg)
1142
1143 if value.type.code != gdb.TYPE_CODE_PTR:
1144 value = value.address
1145
1146 if g_inherits_type(value, "GstElement"):
1147 obj = GdbGstElement(value)
1148 elif g_inherits_type(value, "GstPad"):
1149 obj = GdbGstPad(value)
1150 elif g_inherits_type(value, "GstCaps"):
1151 obj = GdbGstCaps(value)
1152 elif g_inherits_type(value, "GstEvent"):
1153 obj = GdbGstEvent(value)
1154 elif g_inherits_type(value, "GstQuery"):
1155 obj = GdbGstQuery(value)
1156 elif g_inherits_type(value, "GstBuffer"):
1157 obj = GdbGstBuffer(value)
1158 elif is_gst_type(value, "GstStructure"):
1159 obj = GdbGstStructure(value)
1160 else:
1161 raise Exception("'%s' has an unknown type (%s)" % (arg, value))
1162
1163 obj.print(0)
1164
1165
1166 class GstPipelineTree(gdb.Command):
1167 """\
1168 Usage: gst-pipeline-tree <gst-object>"""
1169
1170 def __init__(self):
1171 super(GstPipelineTree, self).__init__("gst-pipeline-tree",
1172 gdb.COMPLETE_SYMBOL)
1173
1174 def invoke(self, arg, from_tty):
1175 self.dont_repeat()
1176 args = gdb.string_to_argv(arg)
1177 if len(args) != 1:
1178 raise Exception("Usage: gst-pipeline-tree <gst-object>")
1179
1180 value = gdb.parse_and_eval(args[0])
1181 if not value:
1182 raise Exception("'%s' is not a valid object" % args[0])
1183
1184 value = gst_object_from_value(value)
1185 value = gst_object_pipeline(value)
1186 GdbGstElement(value).print_tree(0)
1187
1188
1189 GstDot()
1190 GstPrint()
1191 GstPipelineTree()
1192
1193
1194 class GstPipeline(gdb.Function):
1195 """\
1196 Find the top-level pipeline for the given element"""
1197
1198 def __init__(self):
1199 super(GstPipeline, self).__init__("gst_pipeline")
1200
1201 def invoke(self, arg):
1202 value = gst_object_from_value(arg)
1203 return gst_object_pipeline(value)
1204
1205
1206 class GstBinGet(gdb.Function):
1207 """\
1208 Find a child element with the given name"""
1209
1210 def __init__(self):
1211 super(GstBinGet, self).__init__("gst_bin_get")
1212
1213 def find(self, obj, name, recurse):
1214 for child in obj.children():
1215 if child.name() == name:
1216 return child.val
1217 if recurse:
1218 result = self.find(child, name, recurse)
1219 if result is not None:
1220 return result
1221
1222 def invoke(self, element, arg):
1223 value = gst_object_from_value(element)
1224 if not g_inherits_type(value, "GstElement"):
1225 raise Exception("'%s' is not a GstElement" %
1226 str(value.address))
1227
1228 try:
1229 name = arg.string()
1230 except gdb.error:
1231 raise Exception("Usage: $gst_bin_get(<gst-object>, \"<name>\")")
1232
1233 obj = GdbGstElement(value)
1234 child = self.find(obj, name, False)
1235 if child is None:
1236 child = self.find(obj, name, True)
1237 if child is None:
1238 raise Exception("No child named '%s' found." % name)
1239 return child
1240
1241
1242 class GstElementPad(gdb.Function):
1243 """\
1244 Get the pad with the given name"""
1245
1246 def __init__(self):
1247 super(GstElementPad, self).__init__("gst_element_pad")
1248
1249 def invoke(self, element, arg):
1250 value = gst_object_from_value(element)
1251 if not g_inherits_type(value, "GstElement"):
1252 raise Exception("'%s' is not a GstElement" %
1253 str(value.address))
1254
1255 try:
1256 name = arg.string()
1257 except gdb.error:
1258 raise Exception("Usage: $gst_element_pad(<gst-object>, \"<pad-name>\")")
1259
1260 obj = GdbGstElement(value)
1261 for pad in obj.pads():
1262 if pad.name() == name:
1263 return pad.val
1264
1265 raise Exception("No pad named '%s' found." % name)
1266
1267
1268 GstPipeline()
1269 GstBinGet()
1270 GstElementPad()
1271
1272
1273 def register(obj):
1274 if obj is None:
1275 obj = gdb
1276
1277 # Make sure this is always used before the glib lookup function.
1278 # Otherwise the gobject pretty printer is used for GstObjects
1279 obj.pretty_printers.insert(0, gst_pretty_printer_lookup)