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