gst-launch: remove newline from translatable string
[platform/upstream/gstreamer.git] / tools / gst-launch.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *               2000 Wim Taymans <wtay@chello.be>
4  *               2004 Thomas Vander Stichele <thomas@apestaart.org>
5  *
6  * gst-launch.c: tool to launch GStreamer pipelines from the command line
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 /* FIXME: hack alert */
29 #ifdef HAVE_WIN32
30 #define DISABLE_FAULT_HANDLER
31 #endif
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <signal.h>
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifndef DISABLE_FAULT_HANDLER
40 #include <sys/wait.h>
41 #endif
42 #include <locale.h>             /* for LC_ALL */
43 #include "tools.h"
44
45 /* FIXME: This is just a temporary hack.  We should have a better
46  * check for siginfo handling. */
47 #ifdef SA_SIGINFO
48 #define USE_SIGINFO
49 #endif
50
51 extern volatile gboolean glib_on_error_halt;
52
53 #ifndef DISABLE_FAULT_HANDLER
54 static void fault_restore (void);
55 static void fault_spin (void);
56 static void sigint_restore (void);
57 static gboolean caught_intr = FALSE;
58 #endif
59
60 /* event_loop return codes */
61 typedef enum _EventLoopResult
62 {
63   ELR_NO_ERROR = 0,
64   ELR_ERROR,
65   ELR_INTERRUPT
66 } EventLoopResult;
67
68 static GstElement *pipeline;
69 static EventLoopResult caught_error = ELR_NO_ERROR;
70 static gboolean quiet = FALSE;
71 static gboolean tags = FALSE;
72 static gboolean messages = FALSE;
73 static gboolean is_live = FALSE;
74 static gboolean waiting_eos = FALSE;
75
76 /* convenience macro so we don't have to litter the code with if(!quiet) */
77 #define PRINT if(!quiet)g_print
78
79 #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 static void
407 print_error_message (GstMessage * msg)
408 {
409   GError *err = NULL;
410   gchar *name, *debug = NULL;
411
412   name = gst_object_get_path_string (msg->src);
413   gst_message_parse_error (msg, &err, &debug);
414
415   g_printerr (_("ERROR: from element %s: %s\n"), name, err->message);
416   if (debug != NULL)
417     g_printerr (_("Additional debug info:\n%s\n"), debug);
418
419   g_error_free (err);
420   g_free (debug);
421   g_free (name);
422 }
423
424 static void
425 print_tag (const GstTagList * list, const gchar * tag, gpointer unused)
426 {
427   gint i, count;
428
429   count = gst_tag_list_get_tag_size (list, tag);
430
431   for (i = 0; i < count; i++) {
432     gchar *str;
433
434     if (gst_tag_get_type (tag) == G_TYPE_STRING) {
435       if (!gst_tag_list_get_string_index (list, tag, i, &str))
436         g_assert_not_reached ();
437     } else if (gst_tag_get_type (tag) == GST_TYPE_BUFFER) {
438       GstBuffer *img;
439
440       img = gst_value_get_buffer (gst_tag_list_get_value_index (list, tag, i));
441       if (img) {
442         gchar *caps_str;
443
444         caps_str = GST_BUFFER_CAPS (img) ?
445             gst_caps_to_string (GST_BUFFER_CAPS (img)) : g_strdup ("unknown");
446         str = g_strdup_printf ("buffer of %u bytes, type: %s",
447             GST_BUFFER_SIZE (img), caps_str);
448         g_free (caps_str);
449       } else {
450         str = g_strdup ("NULL buffer");
451       }
452     } else if (gst_tag_get_type (tag) == GST_TYPE_DATE_TIME) {
453       GstDateTime *dt = NULL;
454
455       gst_tag_list_get_date_time_index (list, tag, i, &dt);
456       if (gst_date_time_get_hour (dt) < 0) {
457         str = g_strdup_printf ("%02u-%02u-%04u", gst_date_time_get_day (dt),
458             gst_date_time_get_month (dt), gst_date_time_get_year (dt));
459       } else {
460         gdouble tz_offset = gst_date_time_get_time_zone_offset (dt);
461         gchar tz_str[32];
462
463         if (tz_offset != 0.0) {
464           g_snprintf (tz_str, sizeof (tz_str), "(UTC %s%gh)",
465               (tz_offset > 0.0) ? "+" : "", tz_offset);
466         } else {
467           g_snprintf (tz_str, sizeof (tz_str), "(UTC)");
468         }
469
470         str = g_strdup_printf ("%04u-%02u-%02u %02u:%02u:%02u %s",
471             gst_date_time_get_year (dt), gst_date_time_get_month (dt),
472             gst_date_time_get_day (dt), gst_date_time_get_hour (dt),
473             gst_date_time_get_minute (dt), gst_date_time_get_second (dt),
474             tz_str);
475       }
476       gst_date_time_unref (dt);
477     } else {
478       str =
479           g_strdup_value_contents (gst_tag_list_get_value_index (list, tag, i));
480     }
481
482     if (i == 0) {
483       PRINT ("%16s: %s\n", gst_tag_get_nick (tag), str);
484     } else {
485       PRINT ("%16s: %s\n", "", str);
486     }
487
488     g_free (str);
489   }
490 }
491
492 #ifndef DISABLE_FAULT_HANDLER
493 /* we only use sighandler here because the registers are not important */
494 static void
495 sigint_handler_sighandler (int signum)
496 {
497   PRINT ("Caught interrupt -- ");
498
499   /* If we were waiting for an EOS, we still want to catch
500    * the next signal to shutdown properly (and the following one
501    * will quit the program). */
502   if (waiting_eos) {
503     waiting_eos = FALSE;
504   } else {
505     sigint_restore ();
506   }
507   /* we set a flag that is checked by the mainloop, we cannot do much in the
508    * interrupt handler (no mutex or other blocking stuff) */
509   caught_intr = TRUE;
510 }
511
512 /* is called every 250 milliseconds (4 times a second), the interrupt handler
513  * will set a flag for us. We react to this by posting a message. */
514 static gboolean
515 check_intr (GstElement * pipeline)
516 {
517   if (!caught_intr) {
518     return TRUE;
519   } else {
520     caught_intr = FALSE;
521     PRINT ("handling interrupt.\n");
522
523     /* post an application specific message */
524     gst_element_post_message (GST_ELEMENT (pipeline),
525         gst_message_new_application (GST_OBJECT (pipeline),
526             gst_structure_new ("GstLaunchInterrupt",
527                 "message", G_TYPE_STRING, "Pipeline interrupted", NULL)));
528
529     /* remove timeout handler */
530     return FALSE;
531   }
532 }
533
534 static void
535 sigint_setup (void)
536 {
537   struct sigaction action;
538
539   memset (&action, 0, sizeof (action));
540   action.sa_handler = sigint_handler_sighandler;
541
542   sigaction (SIGINT, &action, NULL);
543 }
544
545 static void
546 sigint_restore (void)
547 {
548   struct sigaction action;
549
550   memset (&action, 0, sizeof (action));
551   action.sa_handler = SIG_DFL;
552
553   sigaction (SIGINT, &action, NULL);
554 }
555
556 /* FIXME 0.11: remove SIGUSR handling (also from man page) */
557 static void
558 play_handler (int signum)
559 {
560   switch (signum) {
561     case SIGUSR1:
562       PRINT ("Caught SIGUSR1 - Play request.\n");
563       gst_element_set_state (pipeline, GST_STATE_PLAYING);
564       break;
565     case SIGUSR2:
566       PRINT ("Caught SIGUSR2 - Stop request.\n");
567       gst_element_set_state (pipeline, GST_STATE_NULL);
568       break;
569   }
570 }
571
572 static void
573 play_signal_setup (void)
574 {
575   struct sigaction action;
576
577   memset (&action, 0, sizeof (action));
578   action.sa_handler = play_handler;
579   sigaction (SIGUSR1, &action, NULL);
580   sigaction (SIGUSR2, &action, NULL);
581 }
582 #endif /* DISABLE_FAULT_HANDLER */
583
584 /* returns ELR_ERROR if there was an error
585  * or ELR_INTERRUPT if we caught a keyboard interrupt
586  * or ELR_NO_ERROR otherwise. */
587 static EventLoopResult
588 event_loop (GstElement * pipeline, gboolean blocking, GstState target_state)
589 {
590 #ifndef DISABLE_FAULT_HANDLER
591   gulong timeout_id;
592 #endif
593   GstBus *bus;
594   GstMessage *message = NULL;
595   EventLoopResult res = ELR_NO_ERROR;
596   gboolean buffering = FALSE;
597
598   bus = gst_element_get_bus (GST_ELEMENT (pipeline));
599
600 #ifndef DISABLE_FAULT_HANDLER
601   timeout_id = g_timeout_add (250, (GSourceFunc) check_intr, pipeline);
602 #endif
603
604   while (TRUE) {
605     message = gst_bus_poll (bus, GST_MESSAGE_ANY, blocking ? -1 : 0);
606
607     /* if the poll timed out, only when !blocking */
608     if (message == NULL)
609       goto exit;
610
611     /* check if we need to dump messages to the console */
612     if (messages) {
613       GstObject *src_obj;
614       const GstStructure *s;
615       guint32 seqnum;
616
617       seqnum = gst_message_get_seqnum (message);
618
619       s = gst_message_get_structure (message);
620
621       src_obj = GST_MESSAGE_SRC (message);
622
623       if (GST_IS_ELEMENT (src_obj)) {
624         PRINT (_("Got message #%u from element \"%s\" (%s): "),
625             (guint) seqnum, GST_ELEMENT_NAME (src_obj),
626             GST_MESSAGE_TYPE_NAME (message));
627       } else if (GST_IS_PAD (src_obj)) {
628         PRINT (_("Got message #%u from pad \"%s:%s\" (%s): "),
629             (guint) seqnum, GST_DEBUG_PAD_NAME (src_obj),
630             GST_MESSAGE_TYPE_NAME (message));
631       } else if (GST_IS_OBJECT (src_obj)) {
632         PRINT (_("Got message #%u from object \"%s\" (%s): "),
633             (guint) seqnum, GST_OBJECT_NAME (src_obj),
634             GST_MESSAGE_TYPE_NAME (message));
635       } else {
636         PRINT (_("Got message #%u (%s): "), (guint) seqnum,
637             GST_MESSAGE_TYPE_NAME (message));
638       }
639
640       if (s) {
641         gchar *sstr;
642
643         sstr = gst_structure_to_string (s);
644         PRINT ("%s\n", sstr);
645         g_free (sstr);
646       } else {
647         PRINT ("no message details\n");
648       }
649     }
650
651     switch (GST_MESSAGE_TYPE (message)) {
652       case GST_MESSAGE_NEW_CLOCK:
653       {
654         GstClock *clock;
655
656         gst_message_parse_new_clock (message, &clock);
657
658         PRINT ("New clock: %s\n", (clock ? GST_OBJECT_NAME (clock) : "NULL"));
659         break;
660       }
661       case GST_MESSAGE_CLOCK_LOST:
662         PRINT ("Clock lost, selecting a new one\n");
663         gst_element_set_state (pipeline, GST_STATE_PAUSED);
664         gst_element_set_state (pipeline, GST_STATE_PLAYING);
665         break;
666       case GST_MESSAGE_EOS:{
667         waiting_eos = FALSE;
668         PRINT (_("Got EOS from element \"%s\".\n"),
669             GST_MESSAGE_SRC_NAME (message));
670         goto exit;
671       }
672       case GST_MESSAGE_TAG:
673         if (tags) {
674           GstTagList *tags;
675
676           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
677             PRINT (_("FOUND TAG      : found by element \"%s\".\n"),
678                 GST_MESSAGE_SRC_NAME (message));
679           } else if (GST_IS_PAD (GST_MESSAGE_SRC (message))) {
680             PRINT (_("FOUND TAG      : found by pad \"%s:%s\".\n"),
681                 GST_DEBUG_PAD_NAME (GST_MESSAGE_SRC (message)));
682           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
683             PRINT (_("FOUND TAG      : found by object \"%s\".\n"),
684                 GST_MESSAGE_SRC_NAME (message));
685           } else {
686             PRINT (_("FOUND TAG\n"));
687           }
688
689           gst_message_parse_tag (message, &tags);
690           gst_tag_list_foreach (tags, print_tag, NULL);
691           gst_tag_list_free (tags);
692         }
693         break;
694       case GST_MESSAGE_INFO:{
695         GError *gerror;
696         gchar *debug;
697         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
698
699         gst_message_parse_info (message, &gerror, &debug);
700         if (debug) {
701           PRINT (_("INFO:\n%s\n"), debug);
702         }
703         g_error_free (gerror);
704         g_free (debug);
705         g_free (name);
706         break;
707       }
708       case GST_MESSAGE_WARNING:{
709         GError *gerror;
710         gchar *debug;
711         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
712
713         /* dump graph on warning */
714         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
715             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.warning");
716
717         gst_message_parse_warning (message, &gerror, &debug);
718         PRINT (_("WARNING: from element %s: %s\n"), name, gerror->message);
719         if (debug) {
720           PRINT (_("Additional debug info:\n%s\n"), debug);
721         }
722         g_error_free (gerror);
723         g_free (debug);
724         g_free (name);
725         break;
726       }
727       case GST_MESSAGE_ERROR:{
728         /* dump graph on error */
729         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
730             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.error");
731
732         print_error_message (message);
733
734         /* we have an error */
735         res = ELR_ERROR;
736         goto exit;
737       }
738       case GST_MESSAGE_STATE_CHANGED:{
739         GstState old, new, pending;
740
741         /* we only care about pipeline state change messages */
742         if (GST_MESSAGE_SRC (message) != GST_OBJECT_CAST (pipeline))
743           break;
744
745         /* ignore when we are buffering since then we mess with the states
746          * ourselves. */
747         if (buffering) {
748           PRINT (_("Prerolled, waiting for buffering to finish...\n"));
749           break;
750         }
751
752         gst_message_parse_state_changed (message, &old, &new, &pending);
753
754         /* if we reached the final target state, exit */
755         if (target_state == GST_STATE_PAUSED && new == target_state)
756           goto exit;
757
758         /* else not an interesting message */
759         break;
760       }
761       case GST_MESSAGE_BUFFERING:{
762         gint percent;
763
764         gst_message_parse_buffering (message, &percent);
765         PRINT ("%s %d%%  \r", _("buffering..."), percent);
766
767         /* no state management needed for live pipelines */
768         if (is_live)
769           break;
770
771         if (percent == 100) {
772           /* a 100% message means buffering is done */
773           buffering = FALSE;
774           /* if the desired state is playing, go back */
775           if (target_state == GST_STATE_PLAYING) {
776             PRINT (_("Done buffering, setting pipeline to PLAYING ...\n"));
777             gst_element_set_state (pipeline, GST_STATE_PLAYING);
778           } else
779             goto exit;
780         } else {
781           /* buffering busy */
782           if (buffering == FALSE && target_state == GST_STATE_PLAYING) {
783             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
784             PRINT (_("Buffering, setting pipeline to PAUSED ...\n"));
785             gst_element_set_state (pipeline, GST_STATE_PAUSED);
786           }
787           buffering = TRUE;
788         }
789         break;
790       }
791       case GST_MESSAGE_LATENCY:
792       {
793         PRINT (_("Redistribute latency...\n"));
794         gst_bin_recalculate_latency (GST_BIN (pipeline));
795         break;
796       }
797       case GST_MESSAGE_REQUEST_STATE:
798       {
799         GstState state;
800         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
801
802         gst_message_parse_request_state (message, &state);
803
804         PRINT (_("Setting state to %s as requested by %s...\n"),
805             gst_element_state_get_name (state), name);
806
807         gst_element_set_state (pipeline, state);
808
809         g_free (name);
810         break;
811       }
812       case GST_MESSAGE_APPLICATION:{
813         const GstStructure *s;
814
815         s = gst_message_get_structure (message);
816
817         if (gst_structure_has_name (s, "GstLaunchInterrupt")) {
818           /* this application message is posted when we caught an interrupt and
819            * we need to stop the pipeline. */
820           PRINT (_("Interrupt: Stopping pipeline ...\n"));
821           res = ELR_INTERRUPT;
822           goto exit;
823         }
824       }
825       default:
826         /* just be quiet by default */
827         break;
828     }
829     if (message)
830       gst_message_unref (message);
831   }
832   g_assert_not_reached ();
833
834 exit:
835   {
836     if (message)
837       gst_message_unref (message);
838     gst_object_unref (bus);
839 #ifndef DISABLE_FAULT_HANDLER
840     g_source_remove (timeout_id);
841 #endif
842     return res;
843   }
844 }
845
846 static GstBusSyncReply
847 bus_sync_handler (GstBus * bus, GstMessage * message, gpointer data)
848 {
849   GstElement *pipeline = (GstElement *) data;
850
851   switch (GST_MESSAGE_TYPE (message)) {
852     case GST_MESSAGE_STATE_CHANGED:
853       /* we only care about pipeline state change messages */
854       if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipeline)) {
855         GstState old, new, pending;
856         gchar *state_transition_name;
857
858         gst_message_parse_state_changed (message, &old, &new, &pending);
859
860         state_transition_name = g_strdup_printf ("%s_%s",
861             gst_element_state_get_name (old), gst_element_state_get_name (new));
862
863         /* dump graph for (some) pipeline state changes */
864         {
865           gchar *dump_name = g_strconcat ("gst-launch.", state_transition_name,
866               NULL);
867           GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
868               GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
869           g_free (dump_name);
870         }
871
872         /* place a marker into e.g. strace logs */
873         {
874           gchar *access_name = g_strconcat (g_get_tmp_dir (), G_DIR_SEPARATOR_S,
875               "gst-launch", G_DIR_SEPARATOR_S, state_transition_name, NULL);
876           g_file_test (access_name, G_FILE_TEST_EXISTS);
877           g_free (access_name);
878         }
879
880         g_free (state_transition_name);
881       }
882     default:
883       break;
884   }
885   return GST_BUS_PASS;
886 }
887
888 int
889 main (int argc, char *argv[])
890 {
891   /* options */
892   gboolean verbose = FALSE;
893   gboolean no_fault = FALSE;
894   gboolean no_sigusr_handler = FALSE;
895   gboolean trace = FALSE;
896   gboolean eos_on_shutdown = FALSE;
897   gboolean check_index = FALSE;
898   gchar *savefile = NULL;
899   gchar *exclude_args = NULL;
900 #ifndef GST_DISABLE_OPTION_PARSING
901   GOptionEntry options[] = {
902     {"tags", 't', 0, G_OPTION_ARG_NONE, &tags,
903         N_("Output tags (also known as metadata)"), NULL},
904     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
905         N_("Output status information and property notifications"), NULL},
906     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
907         N_("Do not print any progress information"), NULL},
908     {"messages", 'm', 0, G_OPTION_ARG_NONE, &messages,
909         N_("Output messages"), NULL},
910     {"exclude", 'X', 0, G_OPTION_ARG_NONE, &exclude_args,
911         N_("Do not output status information of TYPE"), N_("TYPE1,TYPE2,...")},
912 #if !defined(GST_DISABLE_LOADSAVE) && !defined(GST_REMOVE_DEPRECATED)
913     {"output", 'o', 0, G_OPTION_ARG_STRING, &savefile,
914         N_("Save xml representation of pipeline to FILE and exit"), N_("FILE")},
915 #endif
916     {"no-fault", 'f', 0, G_OPTION_ARG_NONE, &no_fault,
917         N_("Do not install a fault handler"), NULL},
918     {"no-sigusr-handler", '\0', 0, G_OPTION_ARG_NONE, &no_sigusr_handler,
919         N_("Do not install signal handlers for SIGUSR1 and SIGUSR2"), NULL},
920     {"trace", 'T', 0, G_OPTION_ARG_NONE, &trace,
921         N_("Print alloc trace (if enabled at compile time)"), NULL},
922     {"eos-on-shutdown", 'e', 0, G_OPTION_ARG_NONE, &eos_on_shutdown,
923         N_("Force EOS on sources before shutting the pipeline down"), NULL},
924     {"index", 'i', 0, G_OPTION_ARG_NONE, &check_index,
925         N_("Gather and print index statistics"), NULL},
926     GST_TOOLS_GOPTION_VERSION,
927     {NULL}
928   };
929   GOptionContext *ctx;
930   GError *err = NULL;
931 #endif
932   GstIndex *index;
933   GPtrArray *index_stats = NULL;
934   gchar **argvn;
935   GError *error = NULL;
936   gint res = 0;
937
938   free (malloc (8));            /* -lefence */
939
940 #ifdef ENABLE_NLS
941   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
942   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
943   textdomain (GETTEXT_PACKAGE);
944 #endif
945
946   g_thread_init (NULL);
947
948   gst_tools_set_prgname ("gst-launch");
949
950 #ifndef GST_DISABLE_OPTION_PARSING
951   ctx = g_option_context_new ("PIPELINE-DESCRIPTION");
952   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
953   g_option_context_add_group (ctx, gst_init_get_option_group ());
954   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
955     if (err)
956       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
957     else
958       g_printerr ("Error initializing: Unknown error!\n");
959     exit (1);
960   }
961   g_option_context_free (ctx);
962 #else
963   gst_init (&argc, &argv);
964 #endif
965
966   gst_tools_print_version ("gst-launch");
967
968 #ifndef DISABLE_FAULT_HANDLER
969   if (!no_fault)
970     fault_setup ();
971
972   sigint_setup ();
973
974   if (!no_sigusr_handler)
975     play_signal_setup ();
976 #endif
977
978   if (trace) {
979     if (!gst_alloc_trace_available ()) {
980       g_warning ("Trace not available (recompile with trace enabled).");
981     }
982     gst_alloc_trace_set_flags_all (GST_ALLOC_TRACE_LIVE |
983         GST_ALLOC_TRACE_MEM_LIVE);
984     gst_alloc_trace_print_live ();
985   }
986
987   /* make a null-terminated version of argv */
988   argvn = g_new0 (char *, argc);
989   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
990 #if !defined(GST_DISABLE_LOADSAVE) && !defined(GST_REMOVE_DEPRECATED)
991   if (strstr (argv[0], "gst-xmllaunch")) {
992     /* FIXME 0.11: remove xmllaunch entirely */
993     g_warning ("gst-xmllaunch is deprecated and broken for all but the most "
994         "simple pipelines. It will most likely be removed in future. Don't "
995         "use it.\n");
996     pipeline = xmllaunch_parse_cmdline ((const gchar **) argvn);
997   } else
998 #endif
999   {
1000     pipeline =
1001         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
1002   }
1003   g_free (argvn);
1004
1005   if (!pipeline) {
1006     if (error) {
1007       g_printerr (_("ERROR: pipeline could not be constructed: %s.\n"),
1008           GST_STR_NULL (error->message));
1009       g_error_free (error);
1010     } else {
1011       g_printerr (_("ERROR: pipeline could not be constructed.\n"));
1012     }
1013     return 1;
1014   } else if (error) {
1015     g_printerr (_("WARNING: erroneous pipeline: %s\n"),
1016         GST_STR_NULL (error->message));
1017     g_error_free (error);
1018     return 1;
1019   }
1020
1021   if (verbose) {
1022     gchar **exclude_list =
1023         exclude_args ? g_strsplit (exclude_args, ",", 0) : NULL;
1024     g_signal_connect (pipeline, "deep-notify",
1025         G_CALLBACK (gst_object_default_deep_notify), exclude_list);
1026   }
1027 #if !defined(GST_DISABLE_LOADSAVE) && !defined(GST_REMOVE_DEPRECATED)
1028   if (savefile) {
1029     g_warning ("Pipeline serialization to XML is deprecated and broken for "
1030         "all but the most simple pipelines. It will most likely be removed "
1031         "in future. Don't use it.\n");
1032
1033     gst_xml_write_file (GST_ELEMENT (pipeline), fopen (savefile, "w"));
1034   }
1035 #endif
1036
1037   if (!savefile) {
1038     GstState state, pending;
1039     GstStateChangeReturn ret;
1040     GstBus *bus;
1041
1042     /* If the top-level object is not a pipeline, place it in a pipeline. */
1043     if (!GST_IS_PIPELINE (pipeline)) {
1044       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
1045
1046       if (real_pipeline == NULL) {
1047         g_printerr (_("ERROR: the 'pipeline' element wasn't found.\n"));
1048         return 1;
1049       }
1050       gst_bin_add (GST_BIN (real_pipeline), pipeline);
1051       pipeline = real_pipeline;
1052     }
1053
1054     if (check_index) {
1055       /* gst_index_new() creates a null-index, it does not store anything, but
1056        * the entry-added signal works and this is what we use to build the
1057        * statistics */
1058       index = gst_index_new ();
1059       if (index) {
1060         index_stats = g_ptr_array_new ();
1061         g_signal_connect (G_OBJECT (index), "entry-added",
1062             G_CALLBACK (entry_added), index_stats);
1063         g_object_set (G_OBJECT (index), "resolver", GST_INDEX_RESOLVER_GTYPE,
1064             NULL);
1065         gst_element_set_index (pipeline, index);
1066       }
1067     }
1068
1069     bus = gst_element_get_bus (pipeline);
1070     gst_bus_set_sync_handler (bus, bus_sync_handler, (gpointer) pipeline);
1071     gst_object_unref (bus);
1072
1073     PRINT (_("Setting pipeline to PAUSED ...\n"));
1074     ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
1075
1076     switch (ret) {
1077       case GST_STATE_CHANGE_FAILURE:
1078         g_printerr (_("ERROR: Pipeline doesn't want to pause.\n"));
1079         res = -1;
1080         event_loop (pipeline, FALSE, GST_STATE_VOID_PENDING);
1081         goto end;
1082       case GST_STATE_CHANGE_NO_PREROLL:
1083         PRINT (_("Pipeline is live and does not need PREROLL ...\n"));
1084         is_live = TRUE;
1085         break;
1086       case GST_STATE_CHANGE_ASYNC:
1087         PRINT (_("Pipeline is PREROLLING ...\n"));
1088         caught_error = event_loop (pipeline, TRUE, GST_STATE_PAUSED);
1089         if (caught_error) {
1090           g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1091           goto end;
1092         }
1093         state = GST_STATE_PAUSED;
1094         /* fallthrough */
1095       case GST_STATE_CHANGE_SUCCESS:
1096         PRINT (_("Pipeline is PREROLLED ...\n"));
1097         break;
1098     }
1099
1100     caught_error = event_loop (pipeline, FALSE, GST_STATE_PLAYING);
1101
1102     if (caught_error) {
1103       g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1104     } else {
1105       GstClockTime tfthen, tfnow;
1106       GstClockTimeDiff diff;
1107
1108       PRINT (_("Setting pipeline to PLAYING ...\n"));
1109
1110       if (gst_element_set_state (pipeline,
1111               GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
1112         GstMessage *err_msg;
1113         GstBus *bus;
1114
1115         g_printerr (_("ERROR: pipeline doesn't want to play.\n"));
1116         bus = gst_element_get_bus (pipeline);
1117         if ((err_msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0))) {
1118           print_error_message (err_msg);
1119           gst_message_unref (err_msg);
1120         }
1121         gst_object_unref (bus);
1122         res = -1;
1123         goto end;
1124       }
1125
1126       tfthen = gst_util_get_timestamp ();
1127       caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1128       if (eos_on_shutdown && caught_error == ELR_INTERRUPT) {
1129         PRINT (_("EOS on shutdown enabled -- Forcing EOS on the pipeline\n"));
1130         waiting_eos = TRUE;
1131         gst_element_send_event (pipeline, gst_event_new_eos ());
1132         PRINT (_("Waiting for EOS...\n"));
1133         caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1134
1135         if (caught_error == ELR_NO_ERROR) {
1136           /* we got EOS */
1137           PRINT (_("EOS received - stopping pipeline...\n"));
1138         } else if (caught_error == ELR_ERROR) {
1139           PRINT (_("An error happened while waiting for EOS\n"));
1140         }
1141       }
1142       tfnow = gst_util_get_timestamp ();
1143
1144       diff = GST_CLOCK_DIFF (tfthen, tfnow);
1145
1146       PRINT (_("Execution ended after %" G_GUINT64_FORMAT " ns.\n"), diff);
1147     }
1148
1149     PRINT (_("Setting pipeline to PAUSED ...\n"));
1150     gst_element_set_state (pipeline, GST_STATE_PAUSED);
1151     if (caught_error == ELR_NO_ERROR)
1152       gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1153
1154     /* iterate mainloop to process pending stuff */
1155     while (g_main_context_iteration (NULL, FALSE));
1156
1157     PRINT (_("Setting pipeline to READY ...\n"));
1158     gst_element_set_state (pipeline, GST_STATE_READY);
1159     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1160
1161     if (check_index) {
1162       print_index_stats (index_stats);
1163       g_ptr_array_free (index_stats, TRUE);
1164     }
1165
1166   end:
1167     PRINT (_("Setting pipeline to NULL ...\n"));
1168     gst_element_set_state (pipeline, GST_STATE_NULL);
1169     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1170   }
1171
1172   PRINT (_("Freeing pipeline ...\n"));
1173   gst_object_unref (pipeline);
1174
1175   gst_deinit ();
1176   if (trace)
1177     gst_alloc_trace_print_live ();
1178
1179   return res;
1180 }