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