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