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