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