Merge branch 'master' into 0.11
[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 typedef struct _GstIndexStats
181 {
182   gint id;
183   gchar *desc;
184
185   guint num_frames;
186   guint num_keyframes;
187   guint num_dltframes;
188   GstClockTime last_keyframe;
189   GstClockTime last_dltframe;
190   GstClockTime min_keyframe_gap;
191   GstClockTime max_keyframe_gap;
192   GstClockTime avg_keyframe_gap;
193 } GstIndexStats;
194
195 static void
196 entry_added (GstIndex * index, GstIndexEntry * entry, gpointer user_data)
197 {
198   GPtrArray *index_stats = (GPtrArray *) user_data;
199   GstIndexStats *s;
200
201   switch (entry->type) {
202     case GST_INDEX_ENTRY_ID:
203       /* we have a new writer */
204       GST_DEBUG_OBJECT (index, "id %d: describes writer %s", entry->id,
205           GST_INDEX_ID_DESCRIPTION (entry));
206       if (entry->id >= index_stats->len) {
207         g_ptr_array_set_size (index_stats, entry->id + 1);
208       }
209       s = g_new (GstIndexStats, 1);
210       s->id = entry->id;
211       s->desc = g_strdup (GST_INDEX_ID_DESCRIPTION (entry));
212       s->num_frames = s->num_keyframes = s->num_dltframes = 0;
213       s->last_keyframe = s->last_dltframe = GST_CLOCK_TIME_NONE;
214       s->min_keyframe_gap = s->max_keyframe_gap = s->avg_keyframe_gap =
215           GST_CLOCK_TIME_NONE;
216       g_ptr_array_index (index_stats, entry->id) = s;
217       break;
218     case GST_INDEX_ENTRY_FORMAT:
219       /* have not found any code calling this */
220       GST_DEBUG_OBJECT (index, "id %d: registered format %d for %s\n",
221           entry->id, GST_INDEX_FORMAT_FORMAT (entry),
222           GST_INDEX_FORMAT_KEY (entry));
223       break;
224     case GST_INDEX_ENTRY_ASSOCIATION:
225     {
226       gint64 ts;
227       GstAssocFlags flags = GST_INDEX_ASSOC_FLAGS (entry);
228
229       s = g_ptr_array_index (index_stats, entry->id);
230       gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
231
232       if (flags & GST_ASSOCIATION_FLAG_KEY_UNIT) {
233         s->num_keyframes++;
234
235         if (GST_CLOCK_TIME_IS_VALID (ts)) {
236           if (GST_CLOCK_TIME_IS_VALID (s->last_keyframe)) {
237             GstClockTimeDiff d = GST_CLOCK_DIFF (s->last_keyframe, ts);
238
239             if (G_UNLIKELY (d < 0)) {
240               GST_WARNING ("received out-of-order keyframe at %"
241                   GST_TIME_FORMAT, GST_TIME_ARGS (ts));
242               /* FIXME: does it still make sense to use that for the statistics */
243               d = GST_CLOCK_DIFF (ts, s->last_keyframe);
244             }
245
246             if (GST_CLOCK_TIME_IS_VALID (s->min_keyframe_gap)) {
247               if (d < s->min_keyframe_gap)
248                 s->min_keyframe_gap = d;
249             } else {
250               s->min_keyframe_gap = d;
251             }
252             if (GST_CLOCK_TIME_IS_VALID (s->max_keyframe_gap)) {
253               if (d > s->max_keyframe_gap)
254                 s->max_keyframe_gap = d;
255             } else {
256               s->max_keyframe_gap = d;
257             }
258             if (GST_CLOCK_TIME_IS_VALID (s->avg_keyframe_gap)) {
259               s->avg_keyframe_gap = (d + s->num_frames * s->avg_keyframe_gap) /
260                   (s->num_frames + 1);
261             } else {
262               s->avg_keyframe_gap = d;
263             }
264           }
265           s->last_keyframe = ts;
266         }
267       }
268       if (flags & GST_ASSOCIATION_FLAG_DELTA_UNIT) {
269         s->num_dltframes++;
270         if (GST_CLOCK_TIME_IS_VALID (ts)) {
271           s->last_dltframe = ts;
272         }
273       }
274       s->num_frames++;
275
276       break;
277     }
278     default:
279       break;
280   }
281 }
282
283 /* print statistics from the entry_added callback, free the entries */
284 static void
285 print_index_stats (GPtrArray * index_stats)
286 {
287   gint i;
288
289   if (index_stats->len) {
290     g_print ("%s:\n", _("Index statistics"));
291   }
292
293   for (i = 0; i < index_stats->len; i++) {
294     GstIndexStats *s = g_ptr_array_index (index_stats, i);
295     if (s) {
296       g_print ("id %d, %s\n", s->id, s->desc);
297       if (s->num_frames) {
298         GstClockTime last_frame = s->last_keyframe;
299
300         if (GST_CLOCK_TIME_IS_VALID (s->last_dltframe)) {
301           if (!GST_CLOCK_TIME_IS_VALID (last_frame) ||
302               (s->last_dltframe > last_frame))
303             last_frame = s->last_dltframe;
304         }
305
306         if (GST_CLOCK_TIME_IS_VALID (last_frame)) {
307           g_print ("  total time               = %" GST_TIME_FORMAT "\n",
308               GST_TIME_ARGS (last_frame));
309         }
310         g_print ("  frame/keyframe rate      = %u / %u = ", s->num_frames,
311             s->num_keyframes);
312         if (s->num_keyframes)
313           g_print ("%lf\n", s->num_frames / (gdouble) s->num_keyframes);
314         else
315           g_print ("-\n");
316         if (s->num_keyframes) {
317           g_print ("  min/avg/max keyframe gap = %" GST_TIME_FORMAT ", %"
318               GST_TIME_FORMAT ", %" GST_TIME_FORMAT "\n",
319               GST_TIME_ARGS (s->min_keyframe_gap),
320               GST_TIME_ARGS (s->avg_keyframe_gap),
321               GST_TIME_ARGS (s->max_keyframe_gap));
322         }
323       } else {
324         g_print ("  no stats\n");
325       }
326
327       g_free (s->desc);
328       g_free (s);
329     }
330   }
331 }
332
333 /* Kids, use the functions from libgstpbutils in gst-plugins-base in your
334  * own code (we can't do that here because it would introduce a circular
335  * dependency) */
336 static gboolean
337 gst_is_missing_plugin_message (GstMessage * msg)
338 {
339   if (GST_MESSAGE_TYPE (msg) != GST_MESSAGE_ELEMENT || msg->structure == NULL)
340     return FALSE;
341
342   return gst_structure_has_name (msg->structure, "missing-plugin");
343 }
344
345 static const gchar *
346 gst_missing_plugin_message_get_description (GstMessage * msg)
347 {
348   return gst_structure_get_string (msg->structure, "name");
349 }
350
351 static void
352 print_error_message (GstMessage * msg)
353 {
354   GError *err = NULL;
355   gchar *name, *debug = NULL;
356
357   name = gst_object_get_path_string (msg->src);
358   gst_message_parse_error (msg, &err, &debug);
359
360   g_printerr (_("ERROR: from element %s: %s\n"), name, err->message);
361   if (debug != NULL)
362     g_printerr (_("Additional debug info:\n%s\n"), debug);
363
364   g_error_free (err);
365   g_free (debug);
366   g_free (name);
367 }
368
369 static void
370 print_tag (const GstTagList * list, const gchar * tag, gpointer unused)
371 {
372   gint i, count;
373
374   count = gst_tag_list_get_tag_size (list, tag);
375
376   for (i = 0; i < count; i++) {
377     gchar *str;
378
379     if (gst_tag_get_type (tag) == G_TYPE_STRING) {
380       if (!gst_tag_list_get_string_index (list, tag, i, &str))
381         g_assert_not_reached ();
382     } else if (gst_tag_get_type (tag) == GST_TYPE_BUFFER) {
383       GstBuffer *img;
384
385       img = gst_value_get_buffer (gst_tag_list_get_value_index (list, tag, i));
386       if (img) {
387         gchar *caps_str;
388
389         caps_str = g_strdup ("unknown");
390         str = g_strdup_printf ("buffer of %" G_GSIZE_FORMAT " bytes, type: %s",
391             gst_buffer_get_size (img), caps_str);
392         g_free (caps_str);
393       } else {
394         str = g_strdup ("NULL buffer");
395       }
396     } else if (gst_tag_get_type (tag) == GST_TYPE_DATE_TIME) {
397       GstDateTime *dt = NULL;
398
399       gst_tag_list_get_date_time_index (list, tag, i, &dt);
400       if (gst_date_time_get_hour (dt) < 0) {
401         str = g_strdup_printf ("%02u-%02u-%04u", gst_date_time_get_day (dt),
402             gst_date_time_get_month (dt), gst_date_time_get_year (dt));
403       } else {
404         gdouble tz_offset = gst_date_time_get_time_zone_offset (dt);
405         gchar tz_str[32];
406
407         if (tz_offset != 0.0) {
408           g_snprintf (tz_str, sizeof (tz_str), "(UTC %s%gh)",
409               (tz_offset > 0.0) ? "+" : "", tz_offset);
410         } else {
411           g_snprintf (tz_str, sizeof (tz_str), "(UTC)");
412         }
413
414         str = g_strdup_printf ("%04u-%02u-%02u %02u:%02u:%02u %s",
415             gst_date_time_get_year (dt), gst_date_time_get_month (dt),
416             gst_date_time_get_day (dt), gst_date_time_get_hour (dt),
417             gst_date_time_get_minute (dt), gst_date_time_get_second (dt),
418             tz_str);
419       }
420       gst_date_time_unref (dt);
421     } else {
422       str =
423           g_strdup_value_contents (gst_tag_list_get_value_index (list, tag, i));
424     }
425
426     if (i == 0) {
427       PRINT ("%16s: %s\n", gst_tag_get_nick (tag), str);
428     } else {
429       PRINT ("%16s: %s\n", "", str);
430     }
431
432     g_free (str);
433   }
434 }
435
436 #ifndef DISABLE_FAULT_HANDLER
437 /* we only use sighandler here because the registers are not important */
438 static void
439 sigint_handler_sighandler (int signum)
440 {
441   PRINT ("Caught interrupt -- ");
442
443   /* If we were waiting for an EOS, we still want to catch
444    * the next signal to shutdown properly (and the following one
445    * will quit the program). */
446   if (waiting_eos) {
447     waiting_eos = FALSE;
448   } else {
449     sigint_restore ();
450   }
451   /* we set a flag that is checked by the mainloop, we cannot do much in the
452    * interrupt handler (no mutex or other blocking stuff) */
453   caught_intr = TRUE;
454 }
455
456 /* is called every 250 milliseconds (4 times a second), the interrupt handler
457  * will set a flag for us. We react to this by posting a message. */
458 static gboolean
459 check_intr (GstElement * pipeline)
460 {
461   if (!caught_intr) {
462     return TRUE;
463   } else {
464     caught_intr = FALSE;
465     PRINT ("handling interrupt.\n");
466
467     /* post an application specific message */
468     gst_element_post_message (GST_ELEMENT (pipeline),
469         gst_message_new_application (GST_OBJECT (pipeline),
470             gst_structure_new ("GstLaunchInterrupt",
471                 "message", G_TYPE_STRING, "Pipeline interrupted", NULL)));
472
473     /* remove timeout handler */
474     return FALSE;
475   }
476 }
477
478 static void
479 sigint_setup (void)
480 {
481   struct sigaction action;
482
483   memset (&action, 0, sizeof (action));
484   action.sa_handler = sigint_handler_sighandler;
485
486   sigaction (SIGINT, &action, NULL);
487 }
488
489 static void
490 sigint_restore (void)
491 {
492   struct sigaction action;
493
494   memset (&action, 0, sizeof (action));
495   action.sa_handler = SIG_DFL;
496
497   sigaction (SIGINT, &action, NULL);
498 }
499
500 /* FIXME 0.11: remove SIGUSR handling (also from man page) */
501 static void
502 play_handler (int signum)
503 {
504   switch (signum) {
505     case SIGUSR1:
506       PRINT ("Caught SIGUSR1 - Play request.\n");
507       gst_element_set_state (pipeline, GST_STATE_PLAYING);
508       break;
509     case SIGUSR2:
510       PRINT ("Caught SIGUSR2 - Stop request.\n");
511       gst_element_set_state (pipeline, GST_STATE_NULL);
512       break;
513   }
514 }
515
516 static void
517 play_signal_setup (void)
518 {
519   struct sigaction action;
520
521   memset (&action, 0, sizeof (action));
522   action.sa_handler = play_handler;
523   sigaction (SIGUSR1, &action, NULL);
524   sigaction (SIGUSR2, &action, NULL);
525 }
526 #endif /* DISABLE_FAULT_HANDLER */
527
528 /* returns ELR_ERROR if there was an error
529  * or ELR_INTERRUPT if we caught a keyboard interrupt
530  * or ELR_NO_ERROR otherwise. */
531 static EventLoopResult
532 event_loop (GstElement * pipeline, gboolean blocking, GstState target_state)
533 {
534 #ifndef DISABLE_FAULT_HANDLER
535   gulong timeout_id;
536 #endif
537   GstBus *bus;
538   GstMessage *message = NULL;
539   EventLoopResult res = ELR_NO_ERROR;
540   gboolean buffering = FALSE;
541
542   bus = gst_element_get_bus (GST_ELEMENT (pipeline));
543
544 #ifndef DISABLE_FAULT_HANDLER
545   timeout_id = g_timeout_add (250, (GSourceFunc) check_intr, pipeline);
546 #endif
547
548   while (TRUE) {
549     message = gst_bus_poll (bus, GST_MESSAGE_ANY, blocking ? -1 : 0);
550
551     /* if the poll timed out, only when !blocking */
552     if (message == NULL)
553       goto exit;
554
555     /* check if we need to dump messages to the console */
556     if (messages) {
557       GstObject *src_obj;
558       const GstStructure *s;
559       guint32 seqnum;
560
561       seqnum = gst_message_get_seqnum (message);
562
563       s = gst_message_get_structure (message);
564
565       src_obj = GST_MESSAGE_SRC (message);
566
567       if (GST_IS_ELEMENT (src_obj)) {
568         PRINT (_("Got message #%u from element \"%s\" (%s): "),
569             (guint) seqnum, GST_ELEMENT_NAME (src_obj),
570             GST_MESSAGE_TYPE_NAME (message));
571       } else if (GST_IS_PAD (src_obj)) {
572         PRINT (_("Got message #%u from pad \"%s:%s\" (%s): "),
573             (guint) seqnum, GST_DEBUG_PAD_NAME (src_obj),
574             GST_MESSAGE_TYPE_NAME (message));
575       } else if (GST_IS_OBJECT (src_obj)) {
576         PRINT (_("Got message #%u from object \"%s\" (%s): "),
577             (guint) seqnum, GST_OBJECT_NAME (src_obj),
578             GST_MESSAGE_TYPE_NAME (message));
579       } else {
580         PRINT (_("Got message #%u (%s): "), (guint) seqnum,
581             GST_MESSAGE_TYPE_NAME (message));
582       }
583
584       if (s) {
585         gchar *sstr;
586
587         sstr = gst_structure_to_string (s);
588         PRINT ("%s\n", sstr);
589         g_free (sstr);
590       } else {
591         PRINT ("no message details\n");
592       }
593     }
594
595     switch (GST_MESSAGE_TYPE (message)) {
596       case GST_MESSAGE_NEW_CLOCK:
597       {
598         GstClock *clock;
599
600         gst_message_parse_new_clock (message, &clock);
601
602         PRINT ("New clock: %s\n", (clock ? GST_OBJECT_NAME (clock) : "NULL"));
603         break;
604       }
605       case GST_MESSAGE_CLOCK_LOST:
606         PRINT ("Clock lost, selecting a new one\n");
607         gst_element_set_state (pipeline, GST_STATE_PAUSED);
608         gst_element_set_state (pipeline, GST_STATE_PLAYING);
609         break;
610       case GST_MESSAGE_EOS:{
611         waiting_eos = FALSE;
612         PRINT (_("Got EOS from element \"%s\".\n"),
613             GST_MESSAGE_SRC_NAME (message));
614         goto exit;
615       }
616       case GST_MESSAGE_TAG:
617         if (tags) {
618           GstTagList *tags;
619
620           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
621             PRINT (_("FOUND TAG      : found by element \"%s\".\n"),
622                 GST_MESSAGE_SRC_NAME (message));
623           } else if (GST_IS_PAD (GST_MESSAGE_SRC (message))) {
624             PRINT (_("FOUND TAG      : found by pad \"%s:%s\".\n"),
625                 GST_DEBUG_PAD_NAME (GST_MESSAGE_SRC (message)));
626           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
627             PRINT (_("FOUND TAG      : found by object \"%s\".\n"),
628                 GST_MESSAGE_SRC_NAME (message));
629           } else {
630             PRINT (_("FOUND TAG\n"));
631           }
632
633           gst_message_parse_tag (message, &tags);
634           gst_tag_list_foreach (tags, print_tag, NULL);
635           gst_tag_list_free (tags);
636         }
637         break;
638       case GST_MESSAGE_INFO:{
639         GError *gerror;
640         gchar *debug;
641         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
642
643         gst_message_parse_info (message, &gerror, &debug);
644         if (debug) {
645           PRINT (_("INFO:\n%s\n"), debug);
646         }
647         g_error_free (gerror);
648         g_free (debug);
649         g_free (name);
650         break;
651       }
652       case GST_MESSAGE_WARNING:{
653         GError *gerror;
654         gchar *debug;
655         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
656
657         /* dump graph on warning */
658         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
659             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.warning");
660
661         gst_message_parse_warning (message, &gerror, &debug);
662         PRINT (_("WARNING: from element %s: %s\n"), name, gerror->message);
663         if (debug) {
664           PRINT (_("Additional debug info:\n%s\n"), debug);
665         }
666         g_error_free (gerror);
667         g_free (debug);
668         g_free (name);
669         break;
670       }
671       case GST_MESSAGE_ERROR:{
672         /* dump graph on error */
673         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
674             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.error");
675
676         print_error_message (message);
677
678         /* we have an error */
679         res = ELR_ERROR;
680         goto exit;
681       }
682       case GST_MESSAGE_STATE_CHANGED:{
683         GstState old, new, pending;
684
685         /* we only care about pipeline state change messages */
686         if (GST_MESSAGE_SRC (message) != GST_OBJECT_CAST (pipeline))
687           break;
688
689         /* ignore when we are buffering since then we mess with the states
690          * ourselves. */
691         if (buffering) {
692           PRINT (_("Prerolled, waiting for buffering to finish...\n"));
693           break;
694         }
695
696         gst_message_parse_state_changed (message, &old, &new, &pending);
697
698         /* if we reached the final target state, exit */
699         if (target_state == GST_STATE_PAUSED && new == target_state)
700           goto exit;
701
702         /* else not an interesting message */
703         break;
704       }
705       case GST_MESSAGE_BUFFERING:{
706         gint percent;
707
708         gst_message_parse_buffering (message, &percent);
709         PRINT ("%s %d%%  \r", _("buffering..."), percent);
710
711         /* no state management needed for live pipelines */
712         if (is_live)
713           break;
714
715         if (percent == 100) {
716           /* a 100% message means buffering is done */
717           buffering = FALSE;
718           /* if the desired state is playing, go back */
719           if (target_state == GST_STATE_PLAYING) {
720             PRINT (_("Done buffering, setting pipeline to PLAYING ...\n"));
721             gst_element_set_state (pipeline, GST_STATE_PLAYING);
722           } else
723             goto exit;
724         } else {
725           /* buffering busy */
726           if (buffering == FALSE && target_state == GST_STATE_PLAYING) {
727             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
728             PRINT (_("Buffering, setting pipeline to PAUSED ...\n"));
729             gst_element_set_state (pipeline, GST_STATE_PAUSED);
730           }
731           buffering = TRUE;
732         }
733         break;
734       }
735       case GST_MESSAGE_LATENCY:
736       {
737         PRINT (_("Redistribute latency...\n"));
738         gst_bin_recalculate_latency (GST_BIN (pipeline));
739         break;
740       }
741       case GST_MESSAGE_REQUEST_STATE:
742       {
743         GstState state;
744         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
745
746         gst_message_parse_request_state (message, &state);
747
748         PRINT (_("Setting state to %s as requested by %s...\n"),
749             gst_element_state_get_name (state), name);
750
751         gst_element_set_state (pipeline, state);
752
753         g_free (name);
754         break;
755       }
756       case GST_MESSAGE_APPLICATION:{
757         const GstStructure *s;
758
759         s = gst_message_get_structure (message);
760
761         if (gst_structure_has_name (s, "GstLaunchInterrupt")) {
762           /* this application message is posted when we caught an interrupt and
763            * we need to stop the pipeline. */
764           PRINT (_("Interrupt: Stopping pipeline ...\n"));
765           res = ELR_INTERRUPT;
766           goto exit;
767         }
768         break;
769       }
770       case GST_MESSAGE_ELEMENT:{
771         if (gst_is_missing_plugin_message (message)) {
772           const gchar *desc;
773
774           desc = gst_missing_plugin_message_get_description (message);
775           PRINT (_("Missing element: %s\n"), desc ? desc : "(no description)");
776         }
777         break;
778       }
779       default:
780         /* just be quiet by default */
781         break;
782     }
783     if (message)
784       gst_message_unref (message);
785   }
786   g_assert_not_reached ();
787
788 exit:
789   {
790     if (message)
791       gst_message_unref (message);
792     gst_object_unref (bus);
793 #ifndef DISABLE_FAULT_HANDLER
794     g_source_remove (timeout_id);
795 #endif
796     return res;
797   }
798 }
799
800 static GstBusSyncReply
801 bus_sync_handler (GstBus * bus, GstMessage * message, gpointer data)
802 {
803   GstElement *pipeline = (GstElement *) data;
804
805   switch (GST_MESSAGE_TYPE (message)) {
806     case GST_MESSAGE_STATE_CHANGED:
807       /* we only care about pipeline state change messages */
808       if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipeline)) {
809         GstState old, new, pending;
810         gchar *state_transition_name;
811
812         gst_message_parse_state_changed (message, &old, &new, &pending);
813
814         state_transition_name = g_strdup_printf ("%s_%s",
815             gst_element_state_get_name (old), gst_element_state_get_name (new));
816
817         /* dump graph for (some) pipeline state changes */
818         {
819           gchar *dump_name = g_strconcat ("gst-launch.", state_transition_name,
820               NULL);
821           GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
822               GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
823           g_free (dump_name);
824         }
825
826         /* place a marker into e.g. strace logs */
827         {
828           gchar *access_name = g_strconcat (g_get_tmp_dir (), G_DIR_SEPARATOR_S,
829               "gst-launch", G_DIR_SEPARATOR_S, state_transition_name, NULL);
830           g_file_test (access_name, G_FILE_TEST_EXISTS);
831           g_free (access_name);
832         }
833
834         g_free (state_transition_name);
835       }
836     default:
837       break;
838   }
839   return GST_BUS_PASS;
840 }
841
842 int
843 main (int argc, char *argv[])
844 {
845   /* options */
846   gboolean verbose = FALSE;
847   gboolean no_fault = FALSE;
848   gboolean no_sigusr_handler = FALSE;
849   gboolean trace = FALSE;
850   gboolean eos_on_shutdown = FALSE;
851   gboolean check_index = FALSE;
852   gchar *savefile = NULL;
853   gchar *exclude_args = NULL;
854 #ifndef GST_DISABLE_OPTION_PARSING
855   GOptionEntry options[] = {
856     {"tags", 't', 0, G_OPTION_ARG_NONE, &tags,
857         N_("Output tags (also known as metadata)"), NULL},
858     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
859         N_("Output status information and property notifications"), NULL},
860     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
861         N_("Do not print any progress information"), NULL},
862     {"messages", 'm', 0, G_OPTION_ARG_NONE, &messages,
863         N_("Output messages"), NULL},
864     {"exclude", 'X', 0, G_OPTION_ARG_NONE, &exclude_args,
865         N_("Do not output status information of TYPE"), N_("TYPE1,TYPE2,...")},
866     {"no-fault", 'f', 0, G_OPTION_ARG_NONE, &no_fault,
867         N_("Do not install a fault handler"), NULL},
868     {"no-sigusr-handler", '\0', 0, G_OPTION_ARG_NONE, &no_sigusr_handler,
869         N_("Do not install signal handlers for SIGUSR1 and SIGUSR2"), NULL},
870     {"trace", 'T', 0, G_OPTION_ARG_NONE, &trace,
871         N_("Print alloc trace (if enabled at compile time)"), NULL},
872     {"eos-on-shutdown", 'e', 0, G_OPTION_ARG_NONE, &eos_on_shutdown,
873         N_("Force EOS on sources before shutting the pipeline down"), NULL},
874     {"index", 'i', 0, G_OPTION_ARG_NONE, &check_index,
875         N_("Gather and print index statistics"), NULL},
876     GST_TOOLS_GOPTION_VERSION,
877     {NULL}
878   };
879   GOptionContext *ctx;
880   GError *err = NULL;
881 #endif
882   GstIndex *index;
883   GPtrArray *index_stats = NULL;
884   gchar **argvn;
885   GError *error = NULL;
886   gint res = 0;
887
888   free (malloc (8));            /* -lefence */
889
890 #ifdef ENABLE_NLS
891   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
892   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
893   textdomain (GETTEXT_PACKAGE);
894 #endif
895
896   g_thread_init (NULL);
897
898   gst_tools_set_prgname ("gst-launch");
899
900 #ifndef GST_DISABLE_OPTION_PARSING
901   ctx = g_option_context_new ("PIPELINE-DESCRIPTION");
902   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
903   g_option_context_add_group (ctx, gst_init_get_option_group ());
904   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
905     if (err)
906       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
907     else
908       g_printerr ("Error initializing: Unknown error!\n");
909     exit (1);
910   }
911   g_option_context_free (ctx);
912 #else
913   gst_init (&argc, &argv);
914 #endif
915
916   gst_tools_print_version ("gst-launch");
917
918 #ifndef DISABLE_FAULT_HANDLER
919   if (!no_fault)
920     fault_setup ();
921
922   sigint_setup ();
923
924   if (!no_sigusr_handler)
925     play_signal_setup ();
926 #endif
927
928   if (trace) {
929     if (!gst_alloc_trace_available ()) {
930       g_warning ("Trace not available (recompile with trace enabled).");
931     }
932     gst_alloc_trace_set_flags_all (GST_ALLOC_TRACE_LIVE |
933         GST_ALLOC_TRACE_MEM_LIVE);
934     gst_alloc_trace_print_live ();
935   }
936
937   /* make a null-terminated version of argv */
938   argvn = g_new0 (char *, argc);
939   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
940   {
941     pipeline =
942         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
943   }
944   g_free (argvn);
945
946   if (!pipeline) {
947     if (error) {
948       g_printerr (_("ERROR: pipeline could not be constructed: %s.\n"),
949           GST_STR_NULL (error->message));
950       g_error_free (error);
951     } else {
952       g_printerr (_("ERROR: pipeline could not be constructed.\n"));
953     }
954     return 1;
955   } else if (error) {
956     g_printerr (_("WARNING: erroneous pipeline: %s\n"),
957         GST_STR_NULL (error->message));
958     g_error_free (error);
959     return 1;
960   }
961
962   if (verbose) {
963     gchar **exclude_list =
964         exclude_args ? g_strsplit (exclude_args, ",", 0) : NULL;
965     g_signal_connect (pipeline, "deep-notify",
966         G_CALLBACK (gst_object_default_deep_notify), exclude_list);
967   }
968
969   if (!savefile) {
970     GstState state, pending;
971     GstStateChangeReturn ret;
972     GstBus *bus;
973
974     /* If the top-level object is not a pipeline, place it in a pipeline. */
975     if (!GST_IS_PIPELINE (pipeline)) {
976       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
977
978       if (real_pipeline == NULL) {
979         g_printerr (_("ERROR: the 'pipeline' element wasn't found.\n"));
980         return 1;
981       }
982       gst_bin_add (GST_BIN (real_pipeline), pipeline);
983       pipeline = real_pipeline;
984     }
985
986     if (check_index) {
987       /* gst_index_new() creates a null-index, it does not store anything, but
988        * the entry-added signal works and this is what we use to build the
989        * statistics */
990       index = gst_index_new ();
991       if (index) {
992         index_stats = g_ptr_array_new ();
993         g_signal_connect (G_OBJECT (index), "entry-added",
994             G_CALLBACK (entry_added), index_stats);
995         g_object_set (G_OBJECT (index), "resolver", GST_INDEX_RESOLVER_GTYPE,
996             NULL);
997         gst_element_set_index (pipeline, index);
998       }
999     }
1000
1001     bus = gst_element_get_bus (pipeline);
1002     gst_bus_set_sync_handler (bus, bus_sync_handler, (gpointer) pipeline);
1003     gst_object_unref (bus);
1004
1005     PRINT (_("Setting pipeline to PAUSED ...\n"));
1006     ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
1007
1008     switch (ret) {
1009       case GST_STATE_CHANGE_FAILURE:
1010         g_printerr (_("ERROR: Pipeline doesn't want to pause.\n"));
1011         res = -1;
1012         event_loop (pipeline, FALSE, GST_STATE_VOID_PENDING);
1013         goto end;
1014       case GST_STATE_CHANGE_NO_PREROLL:
1015         PRINT (_("Pipeline is live and does not need PREROLL ...\n"));
1016         is_live = TRUE;
1017         break;
1018       case GST_STATE_CHANGE_ASYNC:
1019         PRINT (_("Pipeline is PREROLLING ...\n"));
1020         caught_error = event_loop (pipeline, TRUE, GST_STATE_PAUSED);
1021         if (caught_error) {
1022           g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1023           goto end;
1024         }
1025         state = GST_STATE_PAUSED;
1026         /* fallthrough */
1027       case GST_STATE_CHANGE_SUCCESS:
1028         PRINT (_("Pipeline is PREROLLED ...\n"));
1029         break;
1030     }
1031
1032     caught_error = event_loop (pipeline, FALSE, GST_STATE_PLAYING);
1033
1034     if (caught_error) {
1035       g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1036     } else {
1037       GstClockTime tfthen, tfnow;
1038       GstClockTimeDiff diff;
1039
1040       PRINT (_("Setting pipeline to PLAYING ...\n"));
1041
1042       if (gst_element_set_state (pipeline,
1043               GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
1044         GstMessage *err_msg;
1045         GstBus *bus;
1046
1047         g_printerr (_("ERROR: pipeline doesn't want to play.\n"));
1048         bus = gst_element_get_bus (pipeline);
1049         if ((err_msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0))) {
1050           print_error_message (err_msg);
1051           gst_message_unref (err_msg);
1052         }
1053         gst_object_unref (bus);
1054         res = -1;
1055         goto end;
1056       }
1057
1058       tfthen = gst_util_get_timestamp ();
1059       caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1060       if (eos_on_shutdown && caught_error == ELR_INTERRUPT) {
1061         PRINT (_("EOS on shutdown enabled -- Forcing EOS on the pipeline\n"));
1062         waiting_eos = TRUE;
1063         gst_element_send_event (pipeline, gst_event_new_eos ());
1064         PRINT (_("Waiting for EOS...\n"));
1065         caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1066
1067         if (caught_error == ELR_NO_ERROR) {
1068           /* we got EOS */
1069           PRINT (_("EOS received - stopping pipeline...\n"));
1070         } else if (caught_error == ELR_ERROR) {
1071           PRINT (_("An error happened while waiting for EOS\n"));
1072         }
1073       }
1074       tfnow = gst_util_get_timestamp ();
1075
1076       diff = GST_CLOCK_DIFF (tfthen, tfnow);
1077
1078       PRINT (_("Execution ended after %" G_GUINT64_FORMAT " ns.\n"), diff);
1079     }
1080
1081     PRINT (_("Setting pipeline to PAUSED ...\n"));
1082     gst_element_set_state (pipeline, GST_STATE_PAUSED);
1083     if (caught_error == ELR_NO_ERROR)
1084       gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1085
1086     /* iterate mainloop to process pending stuff */
1087     while (g_main_context_iteration (NULL, FALSE));
1088
1089     PRINT (_("Setting pipeline to READY ...\n"));
1090     gst_element_set_state (pipeline, GST_STATE_READY);
1091     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1092
1093     if (check_index) {
1094       print_index_stats (index_stats);
1095       g_ptr_array_free (index_stats, TRUE);
1096     }
1097
1098   end:
1099     PRINT (_("Setting pipeline to NULL ...\n"));
1100     gst_element_set_state (pipeline, GST_STATE_NULL);
1101     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1102   }
1103
1104   PRINT (_("Freeing pipeline ...\n"));
1105   gst_object_unref (pipeline);
1106
1107   gst_deinit ();
1108   if (trace)
1109     gst_alloc_trace_print_live ();
1110
1111   return res;
1112 }