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