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