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