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