stats: add a stats frontend
[platform/upstream/gstreamer.git] / tools / gst-stats.c
1 /* GStreamer
2  * Copyright (C) 2013 Stefan Sauer <ensonic@users.sf.net>
3  *
4  * gst-stats.c: statistics tracing front end
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
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29
30 #include "tools.h"
31
32 /* log parser */
33 static GRegex *raw_log = NULL;
34 static GRegex *ansi_log = NULL;
35
36 /* global statistics */
37 static GHashTable *threads = NULL;
38 static GPtrArray *elements = NULL;
39 static GPtrArray *pads = NULL;
40 static guint64 num_buffers = 0, num_events = 0, num_messages = 0, num_queries =
41     0;
42 static guint num_elements = 0, num_bins = 0, num_pads = 0, num_ghostpads = 0;
43
44 typedef struct
45 {
46   /* human readable pad name and details */
47   gchar *name, *type_name;
48   guint index;
49   gboolean is_ghost_pad;
50   GstPadDirection dir;
51   /* buffer statistics */
52   guint num_buffers;
53   guint num_readonly, num_preroll, num_discont, num_gap, num_delta;
54   guint min_size, max_size, avg_size;
55   /* first and last activity on the pad, expected next_ts */
56   GstClockTime first_ts, last_ts, next_ts;
57   /* in which thread does it operate */
58   guint thread_id;
59   /* hierarchy */
60   guint parent_ix;
61 } GstPadStats;
62
63 typedef struct
64 {
65   /* human readable element name */
66   gchar *name, *type_name;
67   guint index;
68   gboolean is_bin;
69   /* buffer statistics */
70   guint recv_buffers, sent_buffers;
71   guint64 recv_bytes, sent_bytes;
72   /* event, message statistics */
73   guint num_events, num_messages, num_queries;
74   /* first activity on the element */
75   GstClockTime first_ts, last_ts;
76   /* time spend in this element */
77   GstClockTime treal;
78   /* hierarchy */
79   guint parent_ix;
80 } GstElementStats;
81
82 typedef struct
83 {
84   /* time spend in this thread */
85   GstClockTime treal;
86   guint max_cpuload;
87 } GstThreadStats;
88
89 /* stats helper */
90
91 static void
92 free_element_stats (gpointer data)
93 {
94   g_slice_free (GstElementStats, data);
95 }
96
97 static inline GstElementStats *
98 get_element_stats (guint ix)
99 {
100   return (ix != G_MAXUINT) ? g_ptr_array_index (elements, ix) : NULL;
101 }
102
103 static inline GstPadStats *
104 get_pad_stats (guint ix)
105 {
106   return (ix != G_MAXUINT) ? g_ptr_array_index (pads, ix) : NULL;
107 }
108
109 static void
110 free_pad_stats (gpointer data)
111 {
112   g_slice_free (GstPadStats, data);
113 }
114
115 static void
116 new_pad_stats (GstStructure * s)
117 {
118   GstPadStats *stats;
119   guint ix;
120   gchar *type, *name;
121   gboolean is_ghost_pad;
122   GstPadDirection dir;
123   guint thread_id;
124
125   gst_structure_get (s,
126       "ix", G_TYPE_UINT, &ix,
127       "name", G_TYPE_STRING, &name,
128       "type", G_TYPE_STRING, &type,
129       "is-ghostpad", G_TYPE_BOOLEAN, &is_ghost_pad,
130       "pad-direction", GST_TYPE_PAD_DIRECTION, &dir,
131       "thread-id", G_TYPE_UINT, &thread_id, NULL);
132
133   stats = g_slice_new0 (GstPadStats);
134   if (is_ghost_pad)
135     num_ghostpads++;
136   num_pads++;
137   stats->name = name;
138   stats->type_name = type;
139   stats->index = ix;
140   stats->is_ghost_pad = is_ghost_pad;
141   stats->dir = dir;
142   stats->min_size = G_MAXUINT;
143   stats->first_ts = stats->last_ts = stats->next_ts = GST_CLOCK_TIME_NONE;
144   stats->thread_id = thread_id;
145
146   if (pads->len <= ix)
147     g_ptr_array_set_size (pads, ix + 1);
148   g_ptr_array_index (pads, ix) = stats;
149
150   if (thread_id) {
151     GstThreadStats *thread_stats;
152     if (!(thread_stats = g_hash_table_lookup (threads,
153                 GUINT_TO_POINTER (thread_id)))) {
154       thread_stats = g_slice_new0 (GstThreadStats);
155       g_hash_table_insert (threads, GUINT_TO_POINTER (thread_id), thread_stats);
156     }
157   }
158 }
159
160 static void
161 new_element_stats (GstStructure * s)
162 {
163   GstElementStats *stats;
164   guint ix;
165   gchar *type, *name;
166   gboolean is_bin;
167
168   gst_structure_get (s,
169       "ix", G_TYPE_UINT, &ix,
170       "name", G_TYPE_STRING, &name,
171       "type", G_TYPE_STRING, &type, "is-bin", G_TYPE_BOOLEAN, &is_bin, NULL);
172
173   stats = g_slice_new0 (GstElementStats);
174   if (is_bin)
175     num_bins++;
176   num_elements++;
177   stats->index = ix;
178   stats->name = name;
179   stats->type_name = type;
180   stats->is_bin = is_bin;
181   stats->first_ts = GST_CLOCK_TIME_NONE;
182   stats->parent_ix = G_MAXUINT;
183
184   if (elements->len <= ix)
185     g_ptr_array_set_size (elements, ix + 1);
186   g_ptr_array_index (elements, ix) = stats;
187 }
188
189 static void
190 free_thread_stats (gpointer data)
191 {
192   g_slice_free (GstThreadStats, data);
193 }
194
195 static void
196 do_pad_stats (GstPadStats * stats, guint elem_ix, guint size, guint64 ts,
197     guint64 buffer_ts, guint64 buffer_dur, GstBufferFlags buffer_flags)
198 {
199   gulong avg_size;
200
201   /* parentage */
202   if (stats->parent_ix == G_MAXUINT) {
203     stats->parent_ix = elem_ix;
204   }
205
206   /* size stats */
207   avg_size = (((gulong) stats->avg_size * (gulong) stats->num_buffers) + size);
208   stats->num_buffers++;
209   stats->avg_size = (guint) (avg_size / stats->num_buffers);
210   if (size < stats->min_size)
211     stats->min_size = size;
212   else if (size > stats->max_size)
213     stats->max_size = size;
214   /* time stats */
215   if (!GST_CLOCK_TIME_IS_VALID (stats->last_ts))
216     stats->first_ts = ts;
217   stats->last_ts = ts;
218   /* flag stats */
219   if (buffer_flags & GST_BUFFER_FLAG_GAP)
220     stats->num_gap++;
221   if (buffer_flags & GST_BUFFER_FLAG_DELTA_UNIT)
222     stats->num_delta++;
223   if (buffer_flags & GST_BUFFER_FLAG_DISCONT)
224     stats->num_discont++;
225   /* TODO(ensonic): there is a bunch of new flags in 1.0 */
226   /* update timestamps */
227   if (GST_CLOCK_TIME_IS_VALID (buffer_ts) &&
228       GST_CLOCK_TIME_IS_VALID (buffer_dur)) {
229     stats->next_ts = buffer_ts + buffer_dur;
230   } else {
231     stats->next_ts = GST_CLOCK_TIME_NONE;
232   }
233 }
234
235 static void
236 do_element_stats (GstElementStats * stats, GstElementStats * peer_stats,
237     guint size, guint64 ts)
238 {
239   stats->sent_buffers++;
240   peer_stats->recv_buffers++;
241   stats->sent_bytes += size;
242   peer_stats->recv_bytes += size;
243   /* time stats */
244   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (stats->first_ts))) {
245     stats->first_ts = ts;
246   }
247   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (peer_stats->first_ts))) {
248     peer_stats->first_ts = ts + 1;
249   }
250 }
251
252 static void
253 do_buffer_stats (GstStructure * s)
254 {
255   guint64 ts, buffer_ts, buffer_dur;
256   guint pad_ix, elem_ix, peer_elem_ix;
257   guint size;
258   GstBufferFlags buffer_flags;
259   GstPadStats *pad_stats;
260   GstElementStats *elem_stats, *peer_elem_stats;
261
262   num_buffers++;
263   gst_structure_get (s, "ts", G_TYPE_UINT64, &ts,
264       "pad-ix", G_TYPE_UINT, &pad_ix,
265       "elem-ix", G_TYPE_UINT, &elem_ix,
266       "peer-elem-ix", G_TYPE_UINT, &peer_elem_ix,
267       "buffer-size", G_TYPE_UINT, &size,
268       "buffer-ts", G_TYPE_UINT64, &buffer_ts,
269       "buffer-duration", G_TYPE_UINT64, &buffer_dur,
270       "buffer-flags", GST_TYPE_BUFFER_FLAGS, &buffer_flags, NULL);
271   if (!(pad_stats = get_pad_stats (pad_ix))) {
272     GST_WARNING ("no pad stats found for ix=%u", pad_ix);
273     return;
274   }
275   if (!(elem_stats = get_element_stats (elem_ix))) {
276     GST_WARNING ("no element stats found for ix=%u", elem_ix);
277     return;
278   }
279   if (!(peer_elem_stats = get_element_stats (peer_elem_ix))) {
280     GST_WARNING ("no element stats found for ix=%u", peer_elem_ix);
281     return;
282   }
283   do_pad_stats (pad_stats, elem_ix, size, ts, buffer_ts, buffer_dur,
284       buffer_flags);
285   if (pad_stats->dir == GST_PAD_SRC) {
286     /* push */
287     do_element_stats (elem_stats, peer_elem_stats, size, ts);
288   } else {
289     /* pull */
290     do_element_stats (peer_elem_stats, elem_stats, size, ts);
291   }
292 }
293
294 static void
295 do_event_stats (GstStructure * s)
296 {
297   guint64 ts;
298   guint pad_ix, elem_ix;
299   GstPadStats *pad_stats;
300   GstElementStats *elem_stats;
301
302   num_events++;
303   gst_structure_get (s, "ts", G_TYPE_UINT64, &ts,
304       "pad-ix", G_TYPE_UINT, &pad_ix, "elem-ix", G_TYPE_UINT, &elem_ix, NULL);
305   if (!(pad_stats = get_pad_stats (pad_ix))) {
306     GST_WARNING ("no pad stats found for ix=%u", pad_ix);
307     return;
308   }
309   if (!(elem_stats = get_element_stats (elem_ix))) {
310     GST_WARNING ("no element stats found for ix=%u", elem_ix);
311     return;
312   }
313   elem_stats->num_events++;
314 }
315
316 static void
317 do_message_stats (GstStructure * s)
318 {
319   guint64 ts;
320   guint elem_ix;
321   GstElementStats *elem_stats;
322
323   num_messages++;
324   gst_structure_get (s, "ts", G_TYPE_UINT64, &ts,
325       "elem-ix", G_TYPE_UINT, &elem_ix, NULL);
326   if (!(elem_stats = get_element_stats (elem_ix))) {
327     GST_WARNING ("no element stats found for ix=%u", elem_ix);
328     return;
329   }
330   elem_stats->num_messages++;
331 }
332
333 static void
334 do_query_stats (GstStructure * s)
335 {
336   guint64 ts;
337   guint elem_ix;
338   GstElementStats *elem_stats;
339
340   num_queries++;
341   gst_structure_get (s, "ts", G_TYPE_UINT64, &ts,
342       "elem-ix", G_TYPE_UINT, &elem_ix, NULL);
343   if (!(elem_stats = get_element_stats (elem_ix))) {
344     GST_WARNING ("no element stats found for ix=%u", elem_ix);
345     return;
346   }
347   elem_stats->num_queries++;
348 }
349
350 /* reporting */
351
352 static void
353 print_pad_stats (gpointer value, gpointer user_data)
354 {
355   GstPadStats *stats = (GstPadStats *) value;
356
357   if (stats->thread_id == GPOINTER_TO_UINT (user_data)) {
358     /* there seem to be some temporary pads */
359     if (stats->num_buffers) {
360       GstClockTimeDiff running =
361           GST_CLOCK_DIFF (stats->first_ts, stats->last_ts);
362       GstElementStats *elem_stats = get_element_stats (stats->parent_ix);
363       gchar fullname[30 + 1];
364
365       g_snprintf (fullname, 30, "%s.%s", elem_stats->name, stats->name);
366
367       printf
368           ("    %c %-30.30s: buffers %7u (ro %5u,pre %3u,dis %5u,gap %5u,dlt %5u),",
369           (stats->dir == GST_PAD_SRC) ? '>' : '<', fullname,
370           stats->num_buffers, stats->num_readonly, stats->num_preroll,
371           stats->num_discont, stats->num_gap, stats->num_delta);
372       if (stats->min_size == stats->max_size) {
373         printf (" size (min/avg/max) ......./%7u/.......,", stats->avg_size);
374       } else {
375         printf (" size (min/avg/max) %7u/%7u/%7u,",
376             stats->min_size, stats->avg_size, stats->max_size);
377       }
378       printf (" time %" GST_TIME_FORMAT ","
379           " bytes/sec %lf\n",
380           GST_TIME_ARGS (running),
381           ((gdouble) (stats->num_buffers * stats->avg_size) * GST_SECOND) /
382           ((gdouble) running));
383     }
384   }
385 }
386
387 static void
388 print_thread_stats (gpointer key, gpointer value, gpointer user_data)
389 {
390   GSList *list = user_data;
391 #if 0
392   GstThreadStats *stats = (GstThreadStats *) value;
393   guint cpuload = 0;
394   guint time_percent;
395
396   time_percent =
397       (guint) gst_util_uint64_scale (stats->treal, G_GINT64_CONSTANT (100),
398       last_ts);
399
400   if (tusersys) {
401     guint64 total;
402     /* cpuload for the process, scaled by the timeslice of this thread */
403     //cpuload = (guint) gst_util_uint64_scale (tusersys, G_GINT64_CONSTANT(100) * stats->treal, last_ts * last_ts);
404
405     total = gst_util_uint64_scale (tusersys, G_GINT64_CONSTANT (100), last_ts);
406     cpuload = gst_util_uint64_scale (total, stats->treal, last_ts);
407   }
408
409   printf ("Thread %p Statistics:\n", key);
410   printf ("  Time: %" GST_TIME_FORMAT ", %u %%\n", GST_TIME_ARGS (stats->treal),
411       (guint) time_percent);
412   printf ("  Avg/Max CPU load: %u %%, %u %%\n", cpuload, stats->max_cpuload);
413 #endif
414   /* FIXME: would be nice to skip, if there are no pads for that thread
415    * (e.g. a pipeline), we would need to pass as struct to
416    * g_hash_table_foreach::user_data
417    */
418   puts ("  Pad Statistics:");
419   g_slist_foreach (list, print_pad_stats, key);
420 }
421
422 static void
423 print_element_stats (gpointer value, gpointer user_data)
424 {
425   GstElementStats *stats = (GstElementStats *) value;
426
427   /* skip temporary elements */
428   if (stats->first_ts != GST_CLOCK_TIME_NONE) {
429     //GstClockTimeDiff running = GST_CLOCK_DIFF (stats->first_ts, stats->last_ts);
430     gchar fullname[45 + 1];
431
432     g_snprintf (fullname, 45, "%s:%s", stats->type_name, stats->name);
433
434     printf ("  %-45s:", fullname);
435     if (stats->recv_buffers)
436       printf (" buffers in/out %7u", stats->recv_buffers);
437     else
438       printf (" buffers in/out %7s", "-");
439     if (stats->sent_buffers)
440       printf ("/%7u", stats->sent_buffers);
441     else
442       printf ("/%7s", "-");
443     if (stats->recv_bytes)
444       printf (" bytes in/out %12" G_GUINT64_FORMAT, stats->recv_bytes);
445     else
446       printf (" bytes in/out %12s", "-");
447     if (stats->sent_bytes)
448       printf ("/%12" G_GUINT64_FORMAT, stats->sent_bytes);
449     else
450       printf ("/%12s", "-");
451     printf (" first activity %" GST_TIME_FORMAT ", " " ev/msg/qry sent %5u/%5u/%5u"     /*", "
452                                                                                            " cpu usage %u %%" */
453         "\n", GST_TIME_ARGS (stats->first_ts), stats->num_events, stats->num_messages, stats->num_queries       /*,
454                                                                                                                    (guint)(100*stats->treal/last_ts) */ );
455   }
456 }
457
458 static void
459 accum_element_stats (gpointer value, gpointer user_data)
460 {
461   GstElementStats *stats = (GstElementStats *) value;
462
463   if (stats->parent_ix != G_MAXUINT) {
464     GstElementStats *parent_stats = get_element_stats (stats->parent_ix);
465
466     parent_stats->num_events += stats->num_events;
467     parent_stats->num_messages += stats->num_messages;
468     parent_stats->num_queries += stats->num_queries;
469     if (!GST_CLOCK_TIME_IS_VALID (parent_stats->first_ts)) {
470       parent_stats->first_ts = stats->first_ts;
471     } else if (GST_CLOCK_TIME_IS_VALID (stats->first_ts)) {
472       parent_stats->first_ts = MIN (parent_stats->first_ts, stats->first_ts);
473     }
474     if (!GST_CLOCK_TIME_IS_VALID (parent_stats->last_ts)) {
475       parent_stats->last_ts = stats->last_ts;
476     } else if (GST_CLOCK_TIME_IS_VALID (stats->last_ts)) {
477       parent_stats->last_ts = MAX (parent_stats->last_ts, stats->last_ts);
478     }
479   }
480 }
481
482 /* sorting */
483
484 static gint
485 sort_pad_stats_by_first_activity (gconstpointer ps1, gconstpointer ps2)
486 {
487   GstPadStats *s1 = (GstPadStats *) ps1;
488   GstPadStats *s2 = (GstPadStats *) ps2;
489
490   gint order = GST_CLOCK_DIFF (s2->first_ts, s1->first_ts);
491
492   if (!order) {
493     order = s1->dir - s2->dir;
494   }
495   return (order);
496 }
497
498 static void
499 sort_pad_stats (gpointer value, gpointer user_data)
500 {
501   GSList **list = user_data;
502
503   *list =
504       g_slist_insert_sorted (*list, value, sort_pad_stats_by_first_activity);
505 }
506
507 static gint
508 sort_element_stats_by_first_activity (gconstpointer es1, gconstpointer es2)
509 {
510   return (GST_CLOCK_DIFF (((GstElementStats *) es2)->first_ts,
511           ((GstElementStats *) es1)->first_ts));
512 }
513
514 static void
515 sort_bin_stats (gpointer value, gpointer user_data)
516 {
517   if (((GstElementStats *) value)->is_bin) {
518     GSList **list = user_data;
519
520     *list =
521         g_slist_insert_sorted (*list, value,
522         sort_element_stats_by_first_activity);
523   }
524 }
525
526 static void
527 sort_element_stats (gpointer value, gpointer user_data)
528 {
529   if (!(((GstElementStats *) value)->is_bin)) {
530     GSList **list = user_data;
531
532     *list =
533         g_slist_insert_sorted (*list, value,
534         sort_element_stats_by_first_activity);
535   }
536 }
537
538 static gboolean
539 check_bin_parent (gpointer key, gpointer value, gpointer user_data)
540 {
541   GstElementStats *stats = (GstElementStats *) value;
542
543   return (stats->parent_ix == GPOINTER_TO_UINT (user_data));
544 }
545
546 static gboolean
547 process_leaf_bins (gpointer key, gpointer value, gpointer user_data)
548 {
549   GHashTable *accum_bins = user_data;
550
551   /* if we find no bin that has this bin as a parent ... */
552   if (!g_hash_table_find (accum_bins, check_bin_parent, key)) {
553     /* accumulate stats to the parent and remove */
554     accum_element_stats (value, NULL);
555     return TRUE;
556   }
557   return FALSE;
558 }
559
560 /* main */
561
562 static gboolean
563 init (void)
564 {
565   /* compile the parser regexps */
566   /* 0:00:00.004925027 31586      0x1c5c600 DEBUG           GST_REGISTRY gstregistry.c:463:gst_registry_add_plugin:<registry0> adding plugin 0x1c79160 for filename "/usr/lib/gstreamer-1.0/libgstxxx.so" */
567   raw_log = g_regex_new (
568       /* 1: ts */
569       "^([0-9:.]+) +"
570       /* 2: pid */
571       "([0-9]+) +"
572       /* 3: thread */
573       "(0x[0-9a-fA-F]+) +"
574       /* 4: level */
575       "([A-Z]+) +"
576       /* 5: category */
577       "([a-zA-Z_-]+) +"
578       /* 6: file:line:func: */
579       "([^:]+:[0-9]+:[^:]+:)"
580       /* 7: (obj)? log-text */
581       "(.*)$", 0, 0, NULL);
582   if (!raw_log) {
583     GST_WARNING ("failed to compile the 'raw' parser");
584     return FALSE;
585   }
586
587   ansi_log = g_regex_new (
588       /* 1: ts */
589       "^([0-9:.]+) +"
590       /* 2: pid */
591       "\\\e\\\[[0-9;]+m *([0-9]+)\\\e\\\[00m +"
592       /* 3: thread */
593       "(0x[0-9a-fA-F]+) +"
594       /* 4: level */
595       "(?:\\\e\\\[[0-9;]+m)?([A-Z]+) +\\\e\\\[00m +"
596       /* 5: category */
597       "\\\e\\\[[0-9;]+m +([a-zA-Z_-]+) +"
598       /* 6: file:line:func: */
599       "([^:]+:[0-9]+:[^:]+:)(?:\\\e\\\[00m)?"
600       /* 7: (obj)? log-text */
601       "(.*)$", 0, 0, NULL);
602   if (!raw_log) {
603     GST_WARNING ("failed to compile the 'ansi' parser");
604     return FALSE;
605   }
606
607   elements = g_ptr_array_new_with_free_func (free_element_stats);
608   pads = g_ptr_array_new_with_free_func (free_pad_stats);
609   threads = g_hash_table_new_full (NULL, NULL, NULL, free_thread_stats);
610
611   return TRUE;
612 }
613
614 static void
615 done (void)
616 {
617   if (pads)
618     g_ptr_array_free (pads, TRUE);
619   if (elements)
620     g_ptr_array_free (elements, TRUE);
621   if (threads)
622     g_hash_table_destroy (threads);
623
624   if (raw_log)
625     g_regex_unref (raw_log);
626   if (ansi_log)
627     g_regex_unref (ansi_log);
628 }
629
630 static void
631 print_stats (void)
632 {
633   guint num_threads = g_hash_table_size (threads);
634
635   /* print overall stats */
636   puts ("\nOverall Statistics:");
637   printf ("Number of Threads: %u\n", num_threads);
638   printf ("Number of Elements: %u\n", num_elements - num_bins);
639   printf ("Number of Bins: %u\n", num_bins);
640   printf ("Number of Pads: %u\n", num_pads - num_ghostpads);
641   printf ("Number of GhostPads: %u\n", num_ghostpads);
642   printf ("Number of Buffers passed: %" G_GUINT64_FORMAT "\n", num_buffers);
643   printf ("Number of Events sent: %" G_GUINT64_FORMAT "\n", num_events);
644   printf ("Number of Message sent: %" G_GUINT64_FORMAT "\n", num_messages);
645   printf ("Number of Queries sent: %" G_GUINT64_FORMAT "\n", num_queries);
646   puts ("");
647
648   /* thread stats */
649   if (num_threads) {
650     GSList *list = NULL;
651
652     g_ptr_array_foreach (pads, sort_pad_stats, &list);
653     g_hash_table_foreach (threads, print_thread_stats, list);
654     puts ("");
655     g_slist_free (list);
656   }
657
658   /* element stats */
659   if (num_elements) {
660     GSList *list = NULL;
661
662     puts ("Element Statistics:");
663     /* sort by first_activity */
664     g_ptr_array_foreach (elements, sort_element_stats, &list);
665     /* attribute element stats to bins */
666     g_slist_foreach (list, accum_element_stats, NULL);
667     g_slist_foreach (list, print_element_stats, NULL);
668     puts ("");
669     g_slist_free (list);
670   }
671
672   /* bin stats */
673   if (num_bins) {
674     GSList *list = NULL;
675     guint i;
676     GHashTable *accum_bins = g_hash_table_new_full (NULL, NULL, NULL, NULL);
677
678     puts ("Bin Statistics:");
679     /* attribute bin stats to parent-bins */
680     for (i = 0; i < num_elements; i++) {
681       GstElementStats *stats = g_ptr_array_index (elements, i);
682       if (stats->is_bin) {
683         g_hash_table_insert (accum_bins, GUINT_TO_POINTER (i), stats);
684       }
685     }
686     while (g_hash_table_size (accum_bins)) {
687       g_hash_table_foreach_remove (accum_bins, process_leaf_bins, accum_bins);
688     }
689     g_hash_table_destroy (accum_bins);
690     /* sort by first_activity */
691     g_ptr_array_foreach (elements, sort_bin_stats, &list);
692     g_slist_foreach (list, print_element_stats, NULL);
693     puts ("");
694     g_slist_free (list);
695   }
696 }
697
698 static void
699 collect_stats (const gchar * filename)
700 {
701   FILE *log;
702
703   if ((log = fopen (filename, "rt"))) {
704     gchar line[5001];
705
706     /* probe format */
707     if (fgets (line, 5000, log)) {
708       GMatchInfo *match_info;
709       GRegex *parser;
710       GstStructure *s;
711       guint lnr = 0;
712       gchar *level, *data;
713
714       if (strchr (line, 27)) {
715         parser = ansi_log;
716         GST_INFO ("format is 'ansi'");
717       } else {
718         parser = raw_log;
719         GST_INFO ("format is 'raw'");
720       }
721       rewind (log);
722
723       /* parse the log */
724       while (!feof (log)) {
725         if (fgets (line, 5000, log)) {
726           if (g_regex_match (parser, line, 0, &match_info)) {
727             /* filter by level */
728             level = g_match_info_fetch (match_info, 4);
729             if (!strcmp (level, "TRACE")) {
730               data = g_match_info_fetch (match_info, 7);
731               if ((s = gst_structure_from_string (data, NULL))) {
732                 const gchar *name = gst_structure_get_name (s);
733
734                 // TODO(ensonic): add a function for each name-id quark
735                 // these function will do the actual stats tracking
736                 if (!strcmp (name, "new-pad")) {
737                   new_pad_stats (s);
738                 } else if (!strcmp (name, "new-element")) {
739                   new_element_stats (s);
740                 } else if (!strcmp (name, "buffer")) {
741                   do_buffer_stats (s);
742                 } else if (!strcmp (name, "event")) {
743                   do_event_stats (s);
744                 } else if (!strcmp (name, "message")) {
745                   do_message_stats (s);
746                 } else if (!strcmp (name, "query")) {
747                   do_query_stats (s);
748                 } else {
749                   GST_WARNING ("unknown log entry: '%s'", data);
750                 }
751                 gst_structure_free (s);
752               } else {
753                 GST_WARNING ("unknown log entry: '%s'", data);
754               }
755             }
756           } else {
757             if (*line) {
758               GST_WARNING ("foreign log entry: %s:%d:'%s'", filename, lnr,
759                   g_strchomp (line));
760             }
761           }
762           g_match_info_free (match_info);
763           match_info = NULL;
764           lnr++;
765         } else {
766           if (!feof (log)) {
767             // TODO(ensonic): run wc -L on the log file
768             fprintf (stderr, "line too long");
769           }
770         }
771       }
772       fclose (log);
773       // TODO(ensonic): print stats
774     } else {
775       GST_WARNING ("empty log");
776     }
777   }
778 }
779
780 gint
781 main (gint argc, gchar * argv[])
782 {
783   gchar **filenames = NULL;
784   guint num;
785   GError *err = NULL;
786   GOptionContext *ctx;
787   GOptionEntry options[] = {
788     GST_TOOLS_GOPTION_VERSION,
789     // TODO(ensonic): add a summary flag, if set read the whole thing, print
790     // stats once, and exit
791     {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &filenames, NULL}
792     ,
793     {NULL}
794   };
795
796 #ifdef ENABLE_NLS
797   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
798   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
799   textdomain (GETTEXT_PACKAGE);
800 #endif
801
802   g_set_prgname ("gst-stats-" GST_API_VERSION);
803
804   ctx = g_option_context_new ("FILE");
805   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
806   g_option_context_add_group (ctx, gst_init_get_option_group ());
807   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
808     g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
809     exit (1);
810   }
811   g_option_context_free (ctx);
812
813   gst_tools_print_version ();
814
815   if (filenames == NULL || *filenames == NULL) {
816     g_print ("Please give one filename to %s\n\n", g_get_prgname ());
817     return 1;
818   }
819   num = g_strv_length (filenames);
820   if (num == 0 || num > 1) {
821     g_print ("Please give exactly one filename to %s (%d given).\n\n",
822         g_get_prgname (), num);
823     return 1;
824   }
825
826   if (init ()) {
827     collect_stats (filenames[0]);
828     print_stats ();
829   }
830   done ();
831
832   g_strfreev (filenames);
833   return 0;
834 }