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