trace: rework alloc tracing
[platform/upstream/gstreamer.git] / tools / gst-launch.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *               2000 Wim Taymans <wtay@chello.be>
4  *               2004 Thomas Vander Stichele <thomas@apestaart.org>
5  *
6  * gst-launch.c: tool to launch GStreamer pipelines from the command line
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 /* FIXME: hack alert */
29 #ifdef HAVE_WIN32
30 #define DISABLE_FAULT_HANDLER
31 #endif
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <signal.h>
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifndef DISABLE_FAULT_HANDLER
40 #include <sys/wait.h>
41 #endif
42 #include <locale.h>             /* for LC_ALL */
43 #include "tools.h"
44
45 /* FIXME: This is just a temporary hack.  We should have a better
46  * check for siginfo handling. */
47 #ifdef SA_SIGINFO
48 #define USE_SIGINFO
49 #endif
50
51 extern volatile gboolean glib_on_error_halt;
52
53 #ifndef DISABLE_FAULT_HANDLER
54 static void fault_restore (void);
55 static void fault_spin (void);
56 static void sigint_restore (void);
57 static gboolean caught_intr = FALSE;
58 #endif
59
60 /* event_loop return codes */
61 typedef enum _EventLoopResult
62 {
63   ELR_NO_ERROR = 0,
64   ELR_ERROR,
65   ELR_INTERRUPT
66 } EventLoopResult;
67
68 static GstElement *pipeline;
69 static EventLoopResult caught_error = ELR_NO_ERROR;
70 static gboolean quiet = FALSE;
71 static gboolean tags = FALSE;
72 static gboolean messages = FALSE;
73 static gboolean is_live = FALSE;
74 static gboolean waiting_eos = FALSE;
75
76 /* convenience macro so we don't have to litter the code with if(!quiet) */
77 #define PRINT if(!quiet)g_print
78
79 #ifndef DISABLE_FAULT_HANDLER
80 #ifndef USE_SIGINFO
81 static void
82 fault_handler_sighandler (int signum)
83 {
84   fault_restore ();
85
86   /* printf is used instead of g_print(), since it's less likely to
87    * deadlock */
88   switch (signum) {
89     case SIGSEGV:
90       fprintf (stderr, "Caught SIGSEGV\n");
91       break;
92     case SIGQUIT:
93       if (!quiet)
94         printf ("Caught SIGQUIT\n");
95       break;
96     default:
97       fprintf (stderr, "signo:  %d\n", signum);
98       break;
99   }
100
101   fault_spin ();
102 }
103
104 #else /* USE_SIGINFO */
105
106 static void
107 fault_handler_sigaction (int signum, siginfo_t * si, void *misc)
108 {
109   fault_restore ();
110
111   /* printf is used instead of g_print(), since it's less likely to
112    * deadlock */
113   switch (si->si_signo) {
114     case SIGSEGV:
115       fprintf (stderr, "Caught SIGSEGV accessing address %p\n", si->si_addr);
116       break;
117     case SIGQUIT:
118       if (!quiet)
119         printf ("Caught SIGQUIT\n");
120       break;
121     default:
122       fprintf (stderr, "signo:  %d\n", si->si_signo);
123       fprintf (stderr, "errno:  %d\n", si->si_errno);
124       fprintf (stderr, "code:   %d\n", si->si_code);
125       break;
126   }
127
128   fault_spin ();
129 }
130 #endif /* USE_SIGINFO */
131
132 static void
133 fault_spin (void)
134 {
135   int spinning = TRUE;
136
137   glib_on_error_halt = FALSE;
138   g_on_error_stack_trace ("gst-launch");
139
140   wait (NULL);
141
142   /* FIXME how do we know if we were run by libtool? */
143   fprintf (stderr,
144       "Spinning.  Please run 'gdb gst-launch %d' to continue debugging, "
145       "Ctrl-C to quit, or Ctrl-\\ to dump core.\n", (gint) getpid ());
146   while (spinning)
147     g_usleep (1000000);
148 }
149
150 static void
151 fault_restore (void)
152 {
153   struct sigaction action;
154
155   memset (&action, 0, sizeof (action));
156   action.sa_handler = SIG_DFL;
157
158   sigaction (SIGSEGV, &action, NULL);
159   sigaction (SIGQUIT, &action, NULL);
160 }
161
162 static void
163 fault_setup (void)
164 {
165   struct sigaction action;
166
167   memset (&action, 0, sizeof (action));
168 #ifdef USE_SIGINFO
169   action.sa_sigaction = fault_handler_sigaction;
170   action.sa_flags = SA_SIGINFO;
171 #else
172   action.sa_handler = fault_handler_sighandler;
173 #endif
174
175   sigaction (SIGSEGV, &action, NULL);
176   sigaction (SIGQUIT, &action, NULL);
177 }
178 #endif /* DISABLE_FAULT_HANDLER */
179
180 #if 0
181 typedef struct _GstIndexStats
182 {
183   gint id;
184   gchar *desc;
185
186   guint num_frames;
187   guint num_keyframes;
188   guint num_dltframes;
189   GstClockTime last_keyframe;
190   GstClockTime last_dltframe;
191   GstClockTime min_keyframe_gap;
192   GstClockTime max_keyframe_gap;
193   GstClockTime avg_keyframe_gap;
194 } GstIndexStats;
195
196 static void
197 entry_added (GstIndex * index, GstIndexEntry * entry, gpointer user_data)
198 {
199   GPtrArray *index_stats = (GPtrArray *) user_data;
200   GstIndexStats *s;
201
202   switch (entry->type) {
203     case GST_INDEX_ENTRY_ID:
204       /* we have a new writer */
205       GST_DEBUG_OBJECT (index, "id %d: describes writer %s", entry->id,
206           GST_INDEX_ID_DESCRIPTION (entry));
207       if (entry->id >= index_stats->len) {
208         g_ptr_array_set_size (index_stats, entry->id + 1);
209       }
210       s = g_new (GstIndexStats, 1);
211       s->id = entry->id;
212       s->desc = g_strdup (GST_INDEX_ID_DESCRIPTION (entry));
213       s->num_frames = s->num_keyframes = s->num_dltframes = 0;
214       s->last_keyframe = s->last_dltframe = GST_CLOCK_TIME_NONE;
215       s->min_keyframe_gap = s->max_keyframe_gap = s->avg_keyframe_gap =
216           GST_CLOCK_TIME_NONE;
217       g_ptr_array_index (index_stats, entry->id) = s;
218       break;
219     case GST_INDEX_ENTRY_FORMAT:
220       /* have not found any code calling this */
221       GST_DEBUG_OBJECT (index, "id %d: registered format %d for %s\n",
222           entry->id, GST_INDEX_FORMAT_FORMAT (entry),
223           GST_INDEX_FORMAT_KEY (entry));
224       break;
225     case GST_INDEX_ENTRY_ASSOCIATION:
226     {
227       gint64 ts;
228       GstAssocFlags flags = GST_INDEX_ASSOC_FLAGS (entry);
229
230       s = g_ptr_array_index (index_stats, entry->id);
231       gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
232
233       if (flags & GST_ASSOCIATION_FLAG_KEY_UNIT) {
234         s->num_keyframes++;
235
236         if (GST_CLOCK_TIME_IS_VALID (ts)) {
237           if (GST_CLOCK_TIME_IS_VALID (s->last_keyframe)) {
238             GstClockTimeDiff d = GST_CLOCK_DIFF (s->last_keyframe, ts);
239
240             if (G_UNLIKELY (d < 0)) {
241               GST_WARNING ("received out-of-order keyframe at %"
242                   GST_TIME_FORMAT, GST_TIME_ARGS (ts));
243               /* FIXME: does it still make sense to use that for the statistics */
244               d = GST_CLOCK_DIFF (ts, s->last_keyframe);
245             }
246
247             if (GST_CLOCK_TIME_IS_VALID (s->min_keyframe_gap)) {
248               if (d < s->min_keyframe_gap)
249                 s->min_keyframe_gap = d;
250             } else {
251               s->min_keyframe_gap = d;
252             }
253             if (GST_CLOCK_TIME_IS_VALID (s->max_keyframe_gap)) {
254               if (d > s->max_keyframe_gap)
255                 s->max_keyframe_gap = d;
256             } else {
257               s->max_keyframe_gap = d;
258             }
259             if (GST_CLOCK_TIME_IS_VALID (s->avg_keyframe_gap)) {
260               s->avg_keyframe_gap = (d + s->num_frames * s->avg_keyframe_gap) /
261                   (s->num_frames + 1);
262             } else {
263               s->avg_keyframe_gap = d;
264             }
265           }
266           s->last_keyframe = ts;
267         }
268       }
269       if (flags & GST_ASSOCIATION_FLAG_DELTA_UNIT) {
270         s->num_dltframes++;
271         if (GST_CLOCK_TIME_IS_VALID (ts)) {
272           s->last_dltframe = ts;
273         }
274       }
275       s->num_frames++;
276
277       break;
278     }
279     default:
280       break;
281   }
282 }
283
284 /* print statistics from the entry_added callback, free the entries */
285 static void
286 print_index_stats (GPtrArray * index_stats)
287 {
288   gint i;
289
290   if (index_stats->len) {
291     g_print ("%s:\n", _("Index statistics"));
292   }
293
294   for (i = 0; i < index_stats->len; i++) {
295     GstIndexStats *s = g_ptr_array_index (index_stats, i);
296     if (s) {
297       g_print ("id %d, %s\n", s->id, s->desc);
298       if (s->num_frames) {
299         GstClockTime last_frame = s->last_keyframe;
300
301         if (GST_CLOCK_TIME_IS_VALID (s->last_dltframe)) {
302           if (!GST_CLOCK_TIME_IS_VALID (last_frame) ||
303               (s->last_dltframe > last_frame))
304             last_frame = s->last_dltframe;
305         }
306
307         if (GST_CLOCK_TIME_IS_VALID (last_frame)) {
308           g_print ("  total time               = %" GST_TIME_FORMAT "\n",
309               GST_TIME_ARGS (last_frame));
310         }
311         g_print ("  frame/keyframe rate      = %u / %u = ", s->num_frames,
312             s->num_keyframes);
313         if (s->num_keyframes)
314           g_print ("%lf\n", s->num_frames / (gdouble) s->num_keyframes);
315         else
316           g_print ("-\n");
317         if (s->num_keyframes) {
318           g_print ("  min/avg/max keyframe gap = %" GST_TIME_FORMAT ", %"
319               GST_TIME_FORMAT ", %" GST_TIME_FORMAT "\n",
320               GST_TIME_ARGS (s->min_keyframe_gap),
321               GST_TIME_ARGS (s->avg_keyframe_gap),
322               GST_TIME_ARGS (s->max_keyframe_gap));
323         }
324       } else {
325         g_print ("  no stats\n");
326       }
327
328       g_free (s->desc);
329       g_free (s);
330     }
331   }
332 }
333 #endif
334
335 /* Kids, use the functions from libgstpbutils in gst-plugins-base in your
336  * own code (we can't do that here because it would introduce a circular
337  * dependency) */
338 static gboolean
339 gst_is_missing_plugin_message (GstMessage * msg)
340 {
341   if (GST_MESSAGE_TYPE (msg) != GST_MESSAGE_ELEMENT
342       || gst_message_get_structure (msg) == NULL)
343     return FALSE;
344
345   return gst_structure_has_name (gst_message_get_structure (msg),
346       "missing-plugin");
347 }
348
349 static const gchar *
350 gst_missing_plugin_message_get_description (GstMessage * msg)
351 {
352   return gst_structure_get_string (gst_message_get_structure (msg), "name");
353 }
354
355 static void
356 print_error_message (GstMessage * msg)
357 {
358   GError *err = NULL;
359   gchar *name, *debug = NULL;
360
361   name = gst_object_get_path_string (msg->src);
362   gst_message_parse_error (msg, &err, &debug);
363
364   g_printerr (_("ERROR: from element %s: %s\n"), name, err->message);
365   if (debug != NULL)
366     g_printerr (_("Additional debug info:\n%s\n"), debug);
367
368   g_error_free (err);
369   g_free (debug);
370   g_free (name);
371 }
372
373 static void
374 print_tag (const GstTagList * list, const gchar * tag, gpointer unused)
375 {
376   gint i, count;
377
378   count = gst_tag_list_get_tag_size (list, tag);
379
380   for (i = 0; i < count; i++) {
381     gchar *str;
382
383     if (gst_tag_get_type (tag) == G_TYPE_STRING) {
384       if (!gst_tag_list_get_string_index (list, tag, i, &str))
385         g_assert_not_reached ();
386     } else if (gst_tag_get_type (tag) == GST_TYPE_BUFFER) {
387       GstBuffer *img;
388
389       img = gst_value_get_buffer (gst_tag_list_get_value_index (list, tag, i));
390       if (img) {
391         gchar *caps_str;
392
393         caps_str = g_strdup ("unknown");
394         str = g_strdup_printf ("buffer of %" G_GSIZE_FORMAT " bytes, type: %s",
395             gst_buffer_get_size (img), caps_str);
396         g_free (caps_str);
397       } else {
398         str = g_strdup ("NULL buffer");
399       }
400     } else if (gst_tag_get_type (tag) == GST_TYPE_DATE_TIME) {
401       GstDateTime *dt = NULL;
402
403       gst_tag_list_get_date_time_index (list, tag, i, &dt);
404       if (gst_date_time_get_hour (dt) < 0) {
405         str = g_strdup_printf ("%02u-%02u-%04u", gst_date_time_get_day (dt),
406             gst_date_time_get_month (dt), gst_date_time_get_year (dt));
407       } else {
408         gdouble tz_offset = gst_date_time_get_time_zone_offset (dt);
409         gchar tz_str[32];
410
411         if (tz_offset != 0.0) {
412           g_snprintf (tz_str, sizeof (tz_str), "(UTC %s%gh)",
413               (tz_offset > 0.0) ? "+" : "", tz_offset);
414         } else {
415           g_snprintf (tz_str, sizeof (tz_str), "(UTC)");
416         }
417
418         str = g_strdup_printf ("%04u-%02u-%02u %02u:%02u:%02u %s",
419             gst_date_time_get_year (dt), gst_date_time_get_month (dt),
420             gst_date_time_get_day (dt), gst_date_time_get_hour (dt),
421             gst_date_time_get_minute (dt), gst_date_time_get_second (dt),
422             tz_str);
423       }
424       gst_date_time_unref (dt);
425     } else {
426       str =
427           g_strdup_value_contents (gst_tag_list_get_value_index (list, tag, i));
428     }
429
430     if (i == 0) {
431       PRINT ("%16s: %s\n", gst_tag_get_nick (tag), str);
432     } else {
433       PRINT ("%16s: %s\n", "", str);
434     }
435
436     g_free (str);
437   }
438 }
439
440 #ifndef DISABLE_FAULT_HANDLER
441 /* we only use sighandler here because the registers are not important */
442 static void
443 sigint_handler_sighandler (int signum)
444 {
445   PRINT ("Caught interrupt -- ");
446
447   /* If we were waiting for an EOS, we still want to catch
448    * the next signal to shutdown properly (and the following one
449    * will quit the program). */
450   if (waiting_eos) {
451     waiting_eos = FALSE;
452   } else {
453     sigint_restore ();
454   }
455   /* we set a flag that is checked by the mainloop, we cannot do much in the
456    * interrupt handler (no mutex or other blocking stuff) */
457   caught_intr = TRUE;
458 }
459
460 /* is called every 250 milliseconds (4 times a second), the interrupt handler
461  * will set a flag for us. We react to this by posting a message. */
462 static gboolean
463 check_intr (GstElement * pipeline)
464 {
465   if (!caught_intr) {
466     return TRUE;
467   } else {
468     caught_intr = FALSE;
469     PRINT ("handling interrupt.\n");
470
471     /* post an application specific message */
472     gst_element_post_message (GST_ELEMENT (pipeline),
473         gst_message_new_application (GST_OBJECT (pipeline),
474             gst_structure_new ("GstLaunchInterrupt",
475                 "message", G_TYPE_STRING, "Pipeline interrupted", NULL)));
476
477     /* remove timeout handler */
478     return FALSE;
479   }
480 }
481
482 static void
483 sigint_setup (void)
484 {
485   struct sigaction action;
486
487   memset (&action, 0, sizeof (action));
488   action.sa_handler = sigint_handler_sighandler;
489
490   sigaction (SIGINT, &action, NULL);
491 }
492
493 static void
494 sigint_restore (void)
495 {
496   struct sigaction action;
497
498   memset (&action, 0, sizeof (action));
499   action.sa_handler = SIG_DFL;
500
501   sigaction (SIGINT, &action, NULL);
502 }
503 #endif /* DISABLE_FAULT_HANDLER */
504
505 /* returns ELR_ERROR if there was an error
506  * or ELR_INTERRUPT if we caught a keyboard interrupt
507  * or ELR_NO_ERROR otherwise. */
508 static EventLoopResult
509 event_loop (GstElement * pipeline, gboolean blocking, GstState target_state)
510 {
511 #ifndef DISABLE_FAULT_HANDLER
512   gulong timeout_id;
513 #endif
514   GstBus *bus;
515   GstMessage *message = NULL;
516   EventLoopResult res = ELR_NO_ERROR;
517   gboolean buffering = FALSE;
518
519   bus = gst_element_get_bus (GST_ELEMENT (pipeline));
520
521 #ifndef DISABLE_FAULT_HANDLER
522   timeout_id = g_timeout_add (250, (GSourceFunc) check_intr, pipeline);
523 #endif
524
525   while (TRUE) {
526     message = gst_bus_poll (bus, GST_MESSAGE_ANY, blocking ? -1 : 0);
527
528     /* if the poll timed out, only when !blocking */
529     if (message == NULL)
530       goto exit;
531
532     /* check if we need to dump messages to the console */
533     if (messages) {
534       GstObject *src_obj;
535       const GstStructure *s;
536       guint32 seqnum;
537
538       seqnum = gst_message_get_seqnum (message);
539
540       s = gst_message_get_structure (message);
541
542       src_obj = GST_MESSAGE_SRC (message);
543
544       if (GST_IS_ELEMENT (src_obj)) {
545         PRINT (_("Got message #%u from element \"%s\" (%s): "),
546             (guint) seqnum, GST_ELEMENT_NAME (src_obj),
547             GST_MESSAGE_TYPE_NAME (message));
548       } else if (GST_IS_PAD (src_obj)) {
549         PRINT (_("Got message #%u from pad \"%s:%s\" (%s): "),
550             (guint) seqnum, GST_DEBUG_PAD_NAME (src_obj),
551             GST_MESSAGE_TYPE_NAME (message));
552       } else if (GST_IS_OBJECT (src_obj)) {
553         PRINT (_("Got message #%u from object \"%s\" (%s): "),
554             (guint) seqnum, GST_OBJECT_NAME (src_obj),
555             GST_MESSAGE_TYPE_NAME (message));
556       } else {
557         PRINT (_("Got message #%u (%s): "), (guint) seqnum,
558             GST_MESSAGE_TYPE_NAME (message));
559       }
560
561       if (s) {
562         gchar *sstr;
563
564         sstr = gst_structure_to_string (s);
565         PRINT ("%s\n", sstr);
566         g_free (sstr);
567       } else {
568         PRINT ("no message details\n");
569       }
570     }
571
572     switch (GST_MESSAGE_TYPE (message)) {
573       case GST_MESSAGE_NEW_CLOCK:
574       {
575         GstClock *clock;
576
577         gst_message_parse_new_clock (message, &clock);
578
579         PRINT ("New clock: %s\n", (clock ? GST_OBJECT_NAME (clock) : "NULL"));
580         break;
581       }
582       case GST_MESSAGE_CLOCK_LOST:
583         PRINT ("Clock lost, selecting a new one\n");
584         gst_element_set_state (pipeline, GST_STATE_PAUSED);
585         gst_element_set_state (pipeline, GST_STATE_PLAYING);
586         break;
587       case GST_MESSAGE_EOS:{
588         waiting_eos = FALSE;
589         PRINT (_("Got EOS from element \"%s\".\n"),
590             GST_MESSAGE_SRC_NAME (message));
591         goto exit;
592       }
593       case GST_MESSAGE_TAG:
594         if (tags) {
595           GstTagList *tags;
596
597           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
598             PRINT (_("FOUND TAG      : found by element \"%s\".\n"),
599                 GST_MESSAGE_SRC_NAME (message));
600           } else if (GST_IS_PAD (GST_MESSAGE_SRC (message))) {
601             PRINT (_("FOUND TAG      : found by pad \"%s:%s\".\n"),
602                 GST_DEBUG_PAD_NAME (GST_MESSAGE_SRC (message)));
603           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
604             PRINT (_("FOUND TAG      : found by object \"%s\".\n"),
605                 GST_MESSAGE_SRC_NAME (message));
606           } else {
607             PRINT (_("FOUND TAG\n"));
608           }
609
610           gst_message_parse_tag (message, &tags);
611           gst_tag_list_foreach (tags, print_tag, NULL);
612           gst_tag_list_free (tags);
613         }
614         break;
615       case GST_MESSAGE_INFO:{
616         GError *gerror;
617         gchar *debug;
618         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
619
620         gst_message_parse_info (message, &gerror, &debug);
621         if (debug) {
622           PRINT (_("INFO:\n%s\n"), debug);
623         }
624         g_error_free (gerror);
625         g_free (debug);
626         g_free (name);
627         break;
628       }
629       case GST_MESSAGE_WARNING:{
630         GError *gerror;
631         gchar *debug;
632         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
633
634         /* dump graph on warning */
635         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
636             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.warning");
637
638         gst_message_parse_warning (message, &gerror, &debug);
639         PRINT (_("WARNING: from element %s: %s\n"), name, gerror->message);
640         if (debug) {
641           PRINT (_("Additional debug info:\n%s\n"), debug);
642         }
643         g_error_free (gerror);
644         g_free (debug);
645         g_free (name);
646         break;
647       }
648       case GST_MESSAGE_ERROR:{
649         /* dump graph on error */
650         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
651             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.error");
652
653         print_error_message (message);
654
655         /* we have an error */
656         res = ELR_ERROR;
657         goto exit;
658       }
659       case GST_MESSAGE_STATE_CHANGED:{
660         GstState old, new, pending;
661
662         /* we only care about pipeline state change messages */
663         if (GST_MESSAGE_SRC (message) != GST_OBJECT_CAST (pipeline))
664           break;
665
666         /* ignore when we are buffering since then we mess with the states
667          * ourselves. */
668         if (buffering) {
669           PRINT (_("Prerolled, waiting for buffering to finish...\n"));
670           break;
671         }
672
673         gst_message_parse_state_changed (message, &old, &new, &pending);
674
675         /* if we reached the final target state, exit */
676         if (target_state == GST_STATE_PAUSED && new == target_state)
677           goto exit;
678
679         /* else not an interesting message */
680         break;
681       }
682       case GST_MESSAGE_BUFFERING:{
683         gint percent;
684
685         gst_message_parse_buffering (message, &percent);
686         PRINT ("%s %d%%  \r", _("buffering..."), percent);
687
688         /* no state management needed for live pipelines */
689         if (is_live)
690           break;
691
692         if (percent == 100) {
693           /* a 100% message means buffering is done */
694           buffering = FALSE;
695           /* if the desired state is playing, go back */
696           if (target_state == GST_STATE_PLAYING) {
697             PRINT (_("Done buffering, setting pipeline to PLAYING ...\n"));
698             gst_element_set_state (pipeline, GST_STATE_PLAYING);
699           } else
700             goto exit;
701         } else {
702           /* buffering busy */
703           if (buffering == FALSE && target_state == GST_STATE_PLAYING) {
704             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
705             PRINT (_("Buffering, setting pipeline to PAUSED ...\n"));
706             gst_element_set_state (pipeline, GST_STATE_PAUSED);
707           }
708           buffering = TRUE;
709         }
710         break;
711       }
712       case GST_MESSAGE_LATENCY:
713       {
714         PRINT (_("Redistribute latency...\n"));
715         gst_bin_recalculate_latency (GST_BIN (pipeline));
716         break;
717       }
718       case GST_MESSAGE_REQUEST_STATE:
719       {
720         GstState state;
721         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
722
723         gst_message_parse_request_state (message, &state);
724
725         PRINT (_("Setting state to %s as requested by %s...\n"),
726             gst_element_state_get_name (state), name);
727
728         gst_element_set_state (pipeline, state);
729
730         g_free (name);
731         break;
732       }
733       case GST_MESSAGE_APPLICATION:{
734         const GstStructure *s;
735
736         s = gst_message_get_structure (message);
737
738         if (gst_structure_has_name (s, "GstLaunchInterrupt")) {
739           /* this application message is posted when we caught an interrupt and
740            * we need to stop the pipeline. */
741           PRINT (_("Interrupt: Stopping pipeline ...\n"));
742           res = ELR_INTERRUPT;
743           goto exit;
744         }
745         break;
746       }
747       case GST_MESSAGE_ELEMENT:{
748         if (gst_is_missing_plugin_message (message)) {
749           const gchar *desc;
750
751           desc = gst_missing_plugin_message_get_description (message);
752           PRINT (_("Missing element: %s\n"), desc ? desc : "(no description)");
753         }
754         break;
755       }
756       default:
757         /* just be quiet by default */
758         break;
759     }
760     if (message)
761       gst_message_unref (message);
762   }
763   g_assert_not_reached ();
764
765 exit:
766   {
767     if (message)
768       gst_message_unref (message);
769     gst_object_unref (bus);
770 #ifndef DISABLE_FAULT_HANDLER
771     g_source_remove (timeout_id);
772 #endif
773     return res;
774   }
775 }
776
777 static GstBusSyncReply
778 bus_sync_handler (GstBus * bus, GstMessage * message, gpointer data)
779 {
780   GstElement *pipeline = (GstElement *) data;
781
782   switch (GST_MESSAGE_TYPE (message)) {
783     case GST_MESSAGE_STATE_CHANGED:
784       /* we only care about pipeline state change messages */
785       if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipeline)) {
786         GstState old, new, pending;
787         gchar *state_transition_name;
788
789         gst_message_parse_state_changed (message, &old, &new, &pending);
790
791         state_transition_name = g_strdup_printf ("%s_%s",
792             gst_element_state_get_name (old), gst_element_state_get_name (new));
793
794         /* dump graph for (some) pipeline state changes */
795         {
796           gchar *dump_name = g_strconcat ("gst-launch.", state_transition_name,
797               NULL);
798           GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
799               GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
800           g_free (dump_name);
801         }
802
803         /* place a marker into e.g. strace logs */
804         {
805           gchar *access_name = g_strconcat (g_get_tmp_dir (), G_DIR_SEPARATOR_S,
806               "gst-launch", G_DIR_SEPARATOR_S, state_transition_name, NULL);
807           g_file_test (access_name, G_FILE_TEST_EXISTS);
808           g_free (access_name);
809         }
810
811         g_free (state_transition_name);
812       }
813     default:
814       break;
815   }
816   return GST_BUS_PASS;
817 }
818
819 int
820 main (int argc, char *argv[])
821 {
822   /* options */
823   gboolean verbose = FALSE;
824   gboolean no_fault = FALSE;
825   gboolean eos_on_shutdown = FALSE;
826 #if 0
827   gboolean check_index = FALSE;
828 #endif
829   gchar *savefile = NULL;
830   gchar *exclude_args = NULL;
831 #ifndef GST_DISABLE_OPTION_PARSING
832   GOptionEntry options[] = {
833     {"tags", 't', 0, G_OPTION_ARG_NONE, &tags,
834         N_("Output tags (also known as metadata)"), NULL},
835     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
836         N_("Output status information and property notifications"), NULL},
837     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
838         N_("Do not print any progress information"), NULL},
839     {"messages", 'm', 0, G_OPTION_ARG_NONE, &messages,
840         N_("Output messages"), NULL},
841     {"exclude", 'X', 0, G_OPTION_ARG_NONE, &exclude_args,
842         N_("Do not output status information of TYPE"), N_("TYPE1,TYPE2,...")},
843     {"no-fault", 'f', 0, G_OPTION_ARG_NONE, &no_fault,
844         N_("Do not install a fault handler"), NULL},
845     {"eos-on-shutdown", 'e', 0, G_OPTION_ARG_NONE, &eos_on_shutdown,
846         N_("Force EOS on sources before shutting the pipeline down"), NULL},
847 #if 0
848     {"index", 'i', 0, G_OPTION_ARG_NONE, &check_index,
849         N_("Gather and print index statistics"), NULL},
850 #endif
851     GST_TOOLS_GOPTION_VERSION,
852     {NULL}
853   };
854   GOptionContext *ctx;
855   GError *err = NULL;
856 #endif
857 #if 0
858   GstIndex *index;
859   GPtrArray *index_stats = NULL;
860 #endif
861   gchar **argvn;
862   GError *error = NULL;
863   gint res = 0;
864
865   free (malloc (8));            /* -lefence */
866
867 #ifdef ENABLE_NLS
868   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
869   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
870   textdomain (GETTEXT_PACKAGE);
871 #endif
872
873   gst_tools_set_prgname ("gst-launch");
874
875 #ifndef GST_DISABLE_OPTION_PARSING
876   ctx = g_option_context_new ("PIPELINE-DESCRIPTION");
877   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
878   g_option_context_add_group (ctx, gst_init_get_option_group ());
879   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
880     if (err)
881       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
882     else
883       g_printerr ("Error initializing: Unknown error!\n");
884     exit (1);
885   }
886   g_option_context_free (ctx);
887 #else
888   gst_init (&argc, &argv);
889 #endif
890
891   gst_tools_print_version ("gst-launch");
892
893 #ifndef DISABLE_FAULT_HANDLER
894   if (!no_fault)
895     fault_setup ();
896
897   sigint_setup ();
898 #endif
899
900   /* make a null-terminated version of argv */
901   argvn = g_new0 (char *, argc);
902   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
903   {
904     pipeline =
905         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
906   }
907   g_free (argvn);
908
909   if (!pipeline) {
910     if (error) {
911       g_printerr (_("ERROR: pipeline could not be constructed: %s.\n"),
912           GST_STR_NULL (error->message));
913       g_error_free (error);
914     } else {
915       g_printerr (_("ERROR: pipeline could not be constructed.\n"));
916     }
917     return 1;
918   } else if (error) {
919     g_printerr (_("WARNING: erroneous pipeline: %s\n"),
920         GST_STR_NULL (error->message));
921     g_error_free (error);
922     return 1;
923   }
924
925   if (verbose) {
926     gchar **exclude_list =
927         exclude_args ? g_strsplit (exclude_args, ",", 0) : NULL;
928     g_signal_connect (pipeline, "deep-notify",
929         G_CALLBACK (gst_object_default_deep_notify), exclude_list);
930   }
931
932   if (!savefile) {
933     GstState state, pending;
934     GstStateChangeReturn ret;
935     GstBus *bus;
936
937     /* If the top-level object is not a pipeline, place it in a pipeline. */
938     if (!GST_IS_PIPELINE (pipeline)) {
939       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
940
941       if (real_pipeline == NULL) {
942         g_printerr (_("ERROR: the 'pipeline' element wasn't found.\n"));
943         return 1;
944       }
945       gst_bin_add (GST_BIN (real_pipeline), pipeline);
946       pipeline = real_pipeline;
947     }
948 #if 0
949     if (check_index) {
950       /* gst_index_new() creates a null-index, it does not store anything, but
951        * the entry-added signal works and this is what we use to build the
952        * statistics */
953       index = gst_index_new ();
954       if (index) {
955         index_stats = g_ptr_array_new ();
956         g_signal_connect (G_OBJECT (index), "entry-added",
957             G_CALLBACK (entry_added), index_stats);
958         g_object_set (G_OBJECT (index), "resolver", GST_INDEX_RESOLVER_GTYPE,
959             NULL);
960         gst_element_set_index (pipeline, index);
961       }
962     }
963 #endif
964
965     bus = gst_element_get_bus (pipeline);
966     gst_bus_set_sync_handler (bus, bus_sync_handler, (gpointer) pipeline);
967     gst_object_unref (bus);
968
969     PRINT (_("Setting pipeline to PAUSED ...\n"));
970     ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
971
972     switch (ret) {
973       case GST_STATE_CHANGE_FAILURE:
974         g_printerr (_("ERROR: Pipeline doesn't want to pause.\n"));
975         res = -1;
976         event_loop (pipeline, FALSE, GST_STATE_VOID_PENDING);
977         goto end;
978       case GST_STATE_CHANGE_NO_PREROLL:
979         PRINT (_("Pipeline is live and does not need PREROLL ...\n"));
980         is_live = TRUE;
981         break;
982       case GST_STATE_CHANGE_ASYNC:
983         PRINT (_("Pipeline is PREROLLING ...\n"));
984         caught_error = event_loop (pipeline, TRUE, GST_STATE_PAUSED);
985         if (caught_error) {
986           g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
987           goto end;
988         }
989         state = GST_STATE_PAUSED;
990         /* fallthrough */
991       case GST_STATE_CHANGE_SUCCESS:
992         PRINT (_("Pipeline is PREROLLED ...\n"));
993         break;
994     }
995
996     caught_error = event_loop (pipeline, FALSE, GST_STATE_PLAYING);
997
998     if (caught_error) {
999       g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1000     } else {
1001       GstClockTime tfthen, tfnow;
1002       GstClockTimeDiff diff;
1003
1004       PRINT (_("Setting pipeline to PLAYING ...\n"));
1005
1006       if (gst_element_set_state (pipeline,
1007               GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
1008         GstMessage *err_msg;
1009         GstBus *bus;
1010
1011         g_printerr (_("ERROR: pipeline doesn't want to play.\n"));
1012         bus = gst_element_get_bus (pipeline);
1013         if ((err_msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0))) {
1014           print_error_message (err_msg);
1015           gst_message_unref (err_msg);
1016         }
1017         gst_object_unref (bus);
1018         res = -1;
1019         goto end;
1020       }
1021
1022       tfthen = gst_util_get_timestamp ();
1023       caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1024       if (eos_on_shutdown && caught_error == ELR_INTERRUPT) {
1025         PRINT (_("EOS on shutdown enabled -- Forcing EOS on the pipeline\n"));
1026         waiting_eos = TRUE;
1027         gst_element_send_event (pipeline, gst_event_new_eos ());
1028         PRINT (_("Waiting for EOS...\n"));
1029         caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1030
1031         if (caught_error == ELR_NO_ERROR) {
1032           /* we got EOS */
1033           PRINT (_("EOS received - stopping pipeline...\n"));
1034         } else if (caught_error == ELR_ERROR) {
1035           PRINT (_("An error happened while waiting for EOS\n"));
1036         }
1037       }
1038       tfnow = gst_util_get_timestamp ();
1039
1040       diff = GST_CLOCK_DIFF (tfthen, tfnow);
1041
1042       PRINT (_("Execution ended after %" G_GUINT64_FORMAT " ns.\n"), diff);
1043     }
1044
1045     PRINT (_("Setting pipeline to PAUSED ...\n"));
1046     gst_element_set_state (pipeline, GST_STATE_PAUSED);
1047     if (caught_error == ELR_NO_ERROR)
1048       gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1049
1050     /* iterate mainloop to process pending stuff */
1051     while (g_main_context_iteration (NULL, FALSE));
1052
1053     PRINT (_("Setting pipeline to READY ...\n"));
1054     gst_element_set_state (pipeline, GST_STATE_READY);
1055     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1056
1057 #if 0
1058     if (check_index) {
1059       print_index_stats (index_stats);
1060       g_ptr_array_free (index_stats, TRUE);
1061     }
1062 #endif
1063
1064   end:
1065     PRINT (_("Setting pipeline to NULL ...\n"));
1066     gst_element_set_state (pipeline, GST_STATE_NULL);
1067     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1068   }
1069
1070   PRINT (_("Freeing pipeline ...\n"));
1071   gst_object_unref (pipeline);
1072
1073   gst_deinit ();
1074
1075   return res;
1076 }