gst-inspect: fix unused-const-variable error in windows
[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 #ifdef G_OS_UNIX
470 static guint signal_watch_hup_id;
471 #endif
472 #if defined(G_OS_UNIX) || defined(G_OS_WIN32)
473 static guint signal_watch_intr_id;
474 #if defined(G_OS_WIN32)
475 static GstElement *intr_pipeline;
476 #endif
477 #endif
478
479 #if defined(G_OS_UNIX) || defined(G_OS_WIN32)
480 /* As the interrupt handler is dispatched from GMainContext as a GSourceFunc
481  * handler, we can react to this by posting a message. */
482 static gboolean
483 intr_handler (gpointer user_data)
484 {
485   GstElement *pipeline = (GstElement *) user_data;
486
487   PRINT ("handling interrupt.\n");
488
489   /* post an application specific message */
490   gst_element_post_message (GST_ELEMENT (pipeline),
491       gst_message_new_application (GST_OBJECT (pipeline),
492           gst_structure_new ("GstLaunchInterrupt",
493               "message", G_TYPE_STRING, "Pipeline interrupted", NULL)));
494
495   /* remove signal handler */
496   signal_watch_intr_id = 0;
497   return G_SOURCE_REMOVE;
498 }
499
500 #ifdef G_OS_UNIX
501 static gboolean
502 hup_handler (gpointer user_data)
503 {
504   GstElement *pipeline = (GstElement *) user_data;
505
506   if (g_getenv ("GST_DEBUG_DUMP_DOT_DIR") != NULL) {
507     PRINT ("SIGHUP: dumping dot file snapshot ...\n");
508   } else {
509     PRINT ("SIGHUP: not dumping dot file snapshot, GST_DEBUG_DUMP_DOT_DIR "
510         "environment variable not set.\n");
511   }
512
513   /* dump graph on hup */
514   GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
515       GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.snapshot");
516
517   return G_SOURCE_CONTINUE;
518 }
519 #endif
520
521 #if defined(G_OS_WIN32)         /* G_OS_UNIX */
522 static BOOL WINAPI
523 w32_intr_handler (DWORD dwCtrlType)
524 {
525   intr_handler ((gpointer) intr_pipeline);
526   intr_pipeline = NULL;
527   return TRUE;
528 }
529 #endif /* G_OS_WIN32 */
530 #endif /* G_OS_UNIX */
531
532 /* returns ELR_ERROR if there was an error
533  * or ELR_INTERRUPT if we caught a keyboard interrupt
534  * or ELR_NO_ERROR otherwise. */
535 static EventLoopResult
536 event_loop (GstElement * pipeline, gboolean blocking, gboolean do_progress,
537     GstState target_state)
538 {
539   GstBus *bus;
540   GstMessage *message = NULL;
541   EventLoopResult res = ELR_NO_ERROR;
542   gboolean buffering = FALSE, in_progress = FALSE;
543   gboolean prerolled = target_state != GST_STATE_PAUSED;
544
545   bus = gst_element_get_bus (GST_ELEMENT (pipeline));
546
547 #ifdef G_OS_UNIX
548   signal_watch_intr_id =
549       g_unix_signal_add (SIGINT, (GSourceFunc) intr_handler, pipeline);
550   signal_watch_hup_id =
551       g_unix_signal_add (SIGHUP, (GSourceFunc) hup_handler, pipeline);
552 #elif defined(G_OS_WIN32)
553   intr_pipeline = NULL;
554   if (SetConsoleCtrlHandler (w32_intr_handler, TRUE))
555     intr_pipeline = pipeline;
556 #endif
557
558   while (TRUE) {
559     message = gst_bus_poll (bus, GST_MESSAGE_ANY, blocking ? -1 : 0);
560
561     /* if the poll timed out, only when !blocking */
562     if (message == NULL)
563       goto exit;
564
565     /* check if we need to dump messages to the console */
566     if (messages) {
567       GstObject *src_obj;
568       const GstStructure *s;
569       guint32 seqnum;
570
571       seqnum = gst_message_get_seqnum (message);
572
573       s = gst_message_get_structure (message);
574
575       src_obj = GST_MESSAGE_SRC (message);
576
577       if (GST_IS_ELEMENT (src_obj)) {
578         PRINT (_("Got message #%u from element \"%s\" (%s): "),
579             (guint) seqnum, GST_ELEMENT_NAME (src_obj),
580             GST_MESSAGE_TYPE_NAME (message));
581       } else if (GST_IS_PAD (src_obj)) {
582         PRINT (_("Got message #%u from pad \"%s:%s\" (%s): "),
583             (guint) seqnum, GST_DEBUG_PAD_NAME (src_obj),
584             GST_MESSAGE_TYPE_NAME (message));
585       } else if (GST_IS_OBJECT (src_obj)) {
586         PRINT (_("Got message #%u from object \"%s\" (%s): "),
587             (guint) seqnum, GST_OBJECT_NAME (src_obj),
588             GST_MESSAGE_TYPE_NAME (message));
589       } else {
590         PRINT (_("Got message #%u (%s): "), (guint) seqnum,
591             GST_MESSAGE_TYPE_NAME (message));
592       }
593
594       if (s) {
595         gchar *sstr;
596
597         sstr = gst_structure_to_string (s);
598         PRINT ("%s\n", sstr);
599         g_free (sstr);
600       } else {
601         PRINT ("no message details\n");
602       }
603     }
604
605     switch (GST_MESSAGE_TYPE (message)) {
606       case GST_MESSAGE_NEW_CLOCK:
607       {
608         GstClock *clock;
609
610         gst_message_parse_new_clock (message, &clock);
611
612         PRINT ("New clock: %s\n", (clock ? GST_OBJECT_NAME (clock) : "NULL"));
613         break;
614       }
615       case GST_MESSAGE_CLOCK_LOST:
616         PRINT ("Clock lost, selecting a new one\n");
617         gst_element_set_state (pipeline, GST_STATE_PAUSED);
618         gst_element_set_state (pipeline, GST_STATE_PLAYING);
619         break;
620       case GST_MESSAGE_EOS:{
621         waiting_eos = FALSE;
622         PRINT (_("Got EOS from element \"%s\".\n"),
623             GST_MESSAGE_SRC_NAME (message));
624         goto exit;
625       }
626       case GST_MESSAGE_TAG:
627         if (tags) {
628           GstTagList *tag_list;
629
630           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
631             PRINT (_("FOUND TAG      : found by element \"%s\".\n"),
632                 GST_MESSAGE_SRC_NAME (message));
633           } else if (GST_IS_PAD (GST_MESSAGE_SRC (message))) {
634             PRINT (_("FOUND TAG      : found by pad \"%s:%s\".\n"),
635                 GST_DEBUG_PAD_NAME (GST_MESSAGE_SRC (message)));
636           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
637             PRINT (_("FOUND TAG      : found by object \"%s\".\n"),
638                 GST_MESSAGE_SRC_NAME (message));
639           } else {
640             PRINT (_("FOUND TAG\n"));
641           }
642
643           gst_message_parse_tag (message, &tag_list);
644           gst_tag_list_foreach (tag_list, print_tag, NULL);
645           gst_tag_list_unref (tag_list);
646         }
647         break;
648       case GST_MESSAGE_TOC:
649         if (toc) {
650           GstToc *toc;
651           GList *entries;
652           gboolean updated;
653
654           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
655             PRINT (_("FOUND TOC      : found by element \"%s\".\n"),
656                 GST_MESSAGE_SRC_NAME (message));
657           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
658             PRINT (_("FOUND TOC      : found by object \"%s\".\n"),
659                 GST_MESSAGE_SRC_NAME (message));
660           } else {
661             PRINT (_("FOUND TOC\n"));
662           }
663
664           gst_message_parse_toc (message, &toc, &updated);
665           /* recursively loop over toc entries */
666           entries = gst_toc_get_entries (toc);
667           g_list_foreach (entries, print_toc_entry, GUINT_TO_POINTER (0));
668           gst_toc_unref (toc);
669         }
670         break;
671       case GST_MESSAGE_INFO:{
672         GError *gerror;
673         gchar *debug;
674         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
675
676         gst_message_parse_info (message, &gerror, &debug);
677         if (debug) {
678           PRINT (_("INFO:\n%s\n"), debug);
679         }
680         g_clear_error (&gerror);
681         g_free (debug);
682         g_free (name);
683         break;
684       }
685       case GST_MESSAGE_WARNING:{
686         GError *gerror;
687         gchar *debug;
688         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
689
690         /* dump graph on warning */
691         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
692             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.warning");
693
694         gst_message_parse_warning (message, &gerror, &debug);
695         PRINT (_("WARNING: from element %s: %s\n"), name, gerror->message);
696         if (debug) {
697           PRINT (_("Additional debug info:\n%s\n"), debug);
698         }
699         g_clear_error (&gerror);
700         g_free (debug);
701         g_free (name);
702         break;
703       }
704       case GST_MESSAGE_ERROR:{
705         /* dump graph on error */
706         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
707             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.error");
708
709         print_error_message (message);
710
711         /* we have an error */
712         res = ELR_ERROR;
713         goto exit;
714       }
715       case GST_MESSAGE_STATE_CHANGED:{
716         GstState old, new, pending;
717
718         /* we only care about pipeline state change messages */
719         if (GST_MESSAGE_SRC (message) != GST_OBJECT_CAST (pipeline))
720           break;
721
722         gst_message_parse_state_changed (message, &old, &new, &pending);
723
724         /* if we reached the final target state, exit */
725         if (target_state == GST_STATE_PAUSED && new == target_state) {
726           prerolled = TRUE;
727           /* ignore when we are buffering since then we mess with the states
728            * ourselves. */
729           if (buffering) {
730             PRINT (_("Prerolled, waiting for buffering to finish...\n"));
731             break;
732           }
733           if (in_progress) {
734             PRINT (_("Prerolled, waiting for progress to finish...\n"));
735             break;
736           }
737           goto exit;
738         }
739         /* else not an interesting message */
740         break;
741       }
742       case GST_MESSAGE_BUFFERING:{
743         gint percent;
744
745         gst_message_parse_buffering (message, &percent);
746         PRINT ("%s %d%%  \r", _("buffering..."), percent);
747
748         /* no state management needed for live pipelines */
749         if (is_live)
750           break;
751
752         if (percent == 100) {
753           /* a 100% message means buffering is done */
754           buffering = FALSE;
755           /* if the desired state is playing, go back */
756           if (target_state == GST_STATE_PLAYING) {
757             PRINT (_("Done buffering, setting pipeline to PLAYING ...\n"));
758             gst_element_set_state (pipeline, GST_STATE_PLAYING);
759           } else if (prerolled && !in_progress)
760             goto exit;
761         } else {
762           /* buffering busy */
763           if (!buffering && target_state == GST_STATE_PLAYING) {
764             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
765             PRINT (_("Buffering, setting pipeline to PAUSED ...\n"));
766             gst_element_set_state (pipeline, GST_STATE_PAUSED);
767           }
768           buffering = TRUE;
769         }
770         break;
771       }
772       case GST_MESSAGE_LATENCY:
773       {
774         PRINT (_("Redistribute latency...\n"));
775         gst_bin_recalculate_latency (GST_BIN (pipeline));
776         break;
777       }
778       case GST_MESSAGE_REQUEST_STATE:
779       {
780         GstState state;
781         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
782
783         gst_message_parse_request_state (message, &state);
784
785         PRINT (_("Setting state to %s as requested by %s...\n"),
786             gst_element_state_get_name (state), name);
787
788         gst_element_set_state (pipeline, state);
789
790         g_free (name);
791         break;
792       }
793       case GST_MESSAGE_APPLICATION:{
794         const GstStructure *s;
795
796         s = gst_message_get_structure (message);
797
798         if (gst_structure_has_name (s, "GstLaunchInterrupt")) {
799           /* this application message is posted when we caught an interrupt and
800            * we need to stop the pipeline. */
801           PRINT (_("Interrupt: Stopping pipeline ...\n"));
802           res = ELR_INTERRUPT;
803           goto exit;
804         }
805         break;
806       }
807       case GST_MESSAGE_PROGRESS:
808       {
809         GstProgressType type;
810         gchar *code, *text;
811
812         gst_message_parse_progress (message, &type, &code, &text);
813
814         switch (type) {
815           case GST_PROGRESS_TYPE_START:
816           case GST_PROGRESS_TYPE_CONTINUE:
817             if (do_progress) {
818               in_progress = TRUE;
819               blocking = TRUE;
820             }
821             break;
822           case GST_PROGRESS_TYPE_COMPLETE:
823           case GST_PROGRESS_TYPE_CANCELED:
824           case GST_PROGRESS_TYPE_ERROR:
825             in_progress = FALSE;
826             break;
827           default:
828             break;
829         }
830         PRINT (_("Progress: (%s) %s\n"), code, text);
831         g_free (code);
832         g_free (text);
833
834         if (do_progress && !in_progress && !buffering && prerolled)
835           goto exit;
836         break;
837       }
838       case GST_MESSAGE_ELEMENT:{
839         if (gst_is_missing_plugin_message (message)) {
840           const gchar *desc;
841
842           desc = gst_missing_plugin_message_get_description (message);
843           PRINT (_("Missing element: %s\n"), desc ? desc : "(no description)");
844         }
845         break;
846       }
847       case GST_MESSAGE_HAVE_CONTEXT:{
848         GstContext *context;
849         const gchar *context_type;
850         gchar *context_str;
851
852         gst_message_parse_have_context (message, &context);
853
854         context_type = gst_context_get_context_type (context);
855         context_str =
856             gst_structure_to_string (gst_context_get_structure (context));
857         PRINT (_("Got context from element '%s': %s=%s\n"),
858             GST_ELEMENT_NAME (GST_MESSAGE_SRC (message)), context_type,
859             context_str);
860         g_free (context_str);
861         gst_context_unref (context);
862         break;
863       }
864       case GST_MESSAGE_PROPERTY_NOTIFY:{
865         const GValue *val;
866         const gchar *name;
867         GstObject *obj;
868         gchar *val_str = NULL;
869         gchar **ex_prop, *obj_name;
870
871         if (quiet)
872           break;
873
874         gst_message_parse_property_notify (message, &obj, &name, &val);
875
876         /* Let's not print anything for excluded properties... */
877         ex_prop = exclude_args;
878         while (ex_prop != NULL && *ex_prop != NULL) {
879           if (strcmp (name, *ex_prop) == 0)
880             break;
881           ex_prop++;
882         }
883         if (ex_prop != NULL && *ex_prop != NULL)
884           break;
885
886         obj_name = gst_object_get_path_string (GST_OBJECT (obj));
887         if (val != NULL) {
888           if (G_VALUE_HOLDS_STRING (val))
889             val_str = g_value_dup_string (val);
890           else if (G_VALUE_TYPE (val) == GST_TYPE_CAPS)
891             val_str = gst_caps_to_string (g_value_get_boxed (val));
892           else if (G_VALUE_TYPE (val) == GST_TYPE_TAG_LIST)
893             val_str = gst_tag_list_to_string (g_value_get_boxed (val));
894           else if (G_VALUE_TYPE (val) == GST_TYPE_STRUCTURE)
895             val_str = gst_structure_to_string (g_value_get_boxed (val));
896           else
897             val_str = gst_value_serialize (val);
898         } else {
899           val_str = g_strdup ("(no value)");
900         }
901
902         g_print ("%s: %s = %s\n", obj_name, name, val_str);
903         g_free (obj_name);
904         g_free (val_str);
905         break;
906       }
907       default:
908         /* just be quiet by default */
909         break;
910     }
911     if (message)
912       gst_message_unref (message);
913   }
914   g_assert_not_reached ();
915
916 exit:
917   {
918     if (message)
919       gst_message_unref (message);
920     gst_object_unref (bus);
921 #ifdef G_OS_UNIX
922     if (signal_watch_intr_id > 0)
923       g_source_remove (signal_watch_intr_id);
924     if (signal_watch_hup_id > 0)
925       g_source_remove (signal_watch_hup_id);
926 #elif defined(G_OS_WIN32)
927     intr_pipeline = NULL;
928     SetConsoleCtrlHandler (w32_intr_handler, FALSE);
929 #endif
930     return res;
931   }
932 }
933
934 static GstBusSyncReply
935 bus_sync_handler (GstBus * bus, GstMessage * message, gpointer data)
936 {
937   GstElement *pipeline = (GstElement *) data;
938
939   switch (GST_MESSAGE_TYPE (message)) {
940     case GST_MESSAGE_STATE_CHANGED:
941       /* we only care about pipeline state change messages */
942       if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipeline)) {
943         GstState old, new, pending;
944         gchar *state_transition_name;
945
946         gst_message_parse_state_changed (message, &old, &new, &pending);
947
948         state_transition_name = g_strdup_printf ("%s_%s",
949             gst_element_state_get_name (old), gst_element_state_get_name (new));
950
951         /* dump graph for (some) pipeline state changes */
952         {
953           gchar *dump_name = g_strconcat ("gst-launch.", state_transition_name,
954               NULL);
955           GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
956               GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
957           g_free (dump_name);
958         }
959
960         /* place a marker into e.g. strace logs */
961         {
962           gchar *access_name = g_strconcat (g_get_tmp_dir (), G_DIR_SEPARATOR_S,
963               "gst-launch", G_DIR_SEPARATOR_S, state_transition_name, NULL);
964           g_file_test (access_name, G_FILE_TEST_EXISTS);
965           g_free (access_name);
966         }
967
968         g_free (state_transition_name);
969       }
970       break;
971     default:
972       break;
973   }
974   return GST_BUS_PASS;
975 }
976
977 int
978 main (int argc, char *argv[])
979 {
980   /* options */
981   gboolean verbose = FALSE;
982   gboolean no_fault = FALSE;
983   gboolean eos_on_shutdown = FALSE;
984 #if 0
985   gboolean check_index = FALSE;
986 #endif
987   gchar *savefile = NULL;
988 #ifndef GST_DISABLE_OPTION_PARSING
989   GOptionEntry options[] = {
990     {"tags", 't', 0, G_OPTION_ARG_NONE, &tags,
991         N_("Output tags (also known as metadata)"), NULL},
992     {"toc", 'c', 0, G_OPTION_ARG_NONE, &toc,
993         N_("Output TOC (chapters and editions)"), NULL},
994     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
995         N_("Output status information and property notifications"), NULL},
996     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
997         N_("Do not print any progress information"), NULL},
998     {"messages", 'm', 0, G_OPTION_ARG_NONE, &messages,
999         N_("Output messages"), NULL},
1000     {"exclude", 'X', 0, G_OPTION_ARG_STRING_ARRAY, &exclude_args,
1001           N_("Do not output status information for the specified property "
1002               "if verbose output is enabled (can be used multiple times)"),
1003         N_("PROPERTY-NAME")},
1004     {"no-fault", 'f', 0, G_OPTION_ARG_NONE, &no_fault,
1005         N_("Do not install a fault handler"), NULL},
1006     {"eos-on-shutdown", 'e', 0, G_OPTION_ARG_NONE, &eos_on_shutdown,
1007         N_("Force EOS on sources before shutting the pipeline down"), NULL},
1008 #if 0
1009     {"index", 'i', 0, G_OPTION_ARG_NONE, &check_index,
1010         N_("Gather and print index statistics"), NULL},
1011 #endif
1012     GST_TOOLS_GOPTION_VERSION,
1013     {NULL}
1014   };
1015   GOptionContext *ctx;
1016   GError *err = NULL;
1017 #endif
1018 #if 0
1019   GstIndex *index;
1020   GPtrArray *index_stats = NULL;
1021 #endif
1022   gchar **argvn;
1023   GError *error = NULL;
1024   gulong deep_notify_id = 0;
1025   gint res = 0;
1026
1027   free (malloc (8));            /* -lefence */
1028
1029   setlocale (LC_ALL, "");
1030
1031 #ifdef ENABLE_NLS
1032   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
1033   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1034   textdomain (GETTEXT_PACKAGE);
1035 #endif
1036
1037   g_set_prgname ("gst-launch-" GST_API_VERSION);
1038   /* Ensure XInitThreads() is called if/when needed */
1039   g_setenv ("GST_GL_XINITTHREADS", "1", TRUE);
1040
1041 #ifndef GST_DISABLE_OPTION_PARSING
1042   ctx = g_option_context_new ("PIPELINE-DESCRIPTION");
1043   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
1044   g_option_context_add_group (ctx, gst_init_get_option_group ());
1045   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
1046     if (err)
1047       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
1048     else
1049       g_printerr ("Error initializing: Unknown error!\n");
1050     g_clear_error (&err);
1051     g_option_context_free (ctx);
1052     exit (1);
1053   }
1054   g_option_context_free (ctx);
1055 #else
1056   gst_init (&argc, &argv);
1057 #endif
1058
1059   gst_tools_print_version ();
1060
1061 #ifdef G_OS_UNIX
1062   if (!no_fault)
1063     fault_setup ();
1064 #endif
1065
1066   /* make a null-terminated version of argv */
1067   argvn = g_new0 (char *, argc);
1068   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
1069   {
1070     pipeline =
1071         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
1072   }
1073   g_free (argvn);
1074
1075   if (!pipeline) {
1076     if (error) {
1077       g_printerr (_("ERROR: pipeline could not be constructed: %s.\n"),
1078           GST_STR_NULL (error->message));
1079       g_clear_error (&error);
1080     } else {
1081       g_printerr (_("ERROR: pipeline could not be constructed.\n"));
1082     }
1083     return 1;
1084   } else if (error) {
1085     g_printerr (_("WARNING: erroneous pipeline: %s\n"),
1086         GST_STR_NULL (error->message));
1087     g_clear_error (&error);
1088     return 1;
1089   }
1090
1091   if (!savefile) {
1092     GstState state, pending;
1093     GstStateChangeReturn ret;
1094     GstBus *bus;
1095
1096     /* If the top-level object is not a pipeline, place it in a pipeline. */
1097     if (!GST_IS_PIPELINE (pipeline)) {
1098       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
1099
1100       if (real_pipeline == NULL) {
1101         g_printerr (_("ERROR: the 'pipeline' element wasn't found.\n"));
1102         return 1;
1103       }
1104       gst_bin_add (GST_BIN (real_pipeline), pipeline);
1105       pipeline = real_pipeline;
1106     }
1107     if (verbose) {
1108       deep_notify_id =
1109           gst_element_add_property_deep_notify_watch (pipeline, NULL, TRUE);
1110     }
1111 #if 0
1112     if (check_index) {
1113       /* gst_index_new() creates a null-index, it does not store anything, but
1114        * the entry-added signal works and this is what we use to build the
1115        * statistics */
1116       index = gst_index_new ();
1117       if (index) {
1118         index_stats = g_ptr_array_new ();
1119         g_signal_connect (G_OBJECT (index), "entry-added",
1120             G_CALLBACK (entry_added), index_stats);
1121         g_object_set (G_OBJECT (index), "resolver", GST_INDEX_RESOLVER_GTYPE,
1122             NULL);
1123         gst_element_set_index (pipeline, index);
1124       }
1125     }
1126 #endif
1127
1128     bus = gst_element_get_bus (pipeline);
1129     gst_bus_set_sync_handler (bus, bus_sync_handler, (gpointer) pipeline, NULL);
1130     gst_object_unref (bus);
1131
1132     PRINT (_("Setting pipeline to PAUSED ...\n"));
1133     ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
1134
1135     switch (ret) {
1136       case GST_STATE_CHANGE_FAILURE:
1137         g_printerr (_("ERROR: Pipeline doesn't want to pause.\n"));
1138         res = -1;
1139         event_loop (pipeline, FALSE, FALSE, GST_STATE_VOID_PENDING);
1140         goto end;
1141       case GST_STATE_CHANGE_NO_PREROLL:
1142         PRINT (_("Pipeline is live and does not need PREROLL ...\n"));
1143         is_live = TRUE;
1144         break;
1145       case GST_STATE_CHANGE_ASYNC:
1146         PRINT (_("Pipeline is PREROLLING ...\n"));
1147         caught_error = event_loop (pipeline, TRUE, TRUE, GST_STATE_PAUSED);
1148         if (caught_error) {
1149           g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1150           res = caught_error;
1151           goto end;
1152         }
1153         state = GST_STATE_PAUSED;
1154         /* fallthrough */
1155       case GST_STATE_CHANGE_SUCCESS:
1156         PRINT (_("Pipeline is PREROLLED ...\n"));
1157         break;
1158     }
1159
1160     caught_error = event_loop (pipeline, FALSE, TRUE, GST_STATE_PLAYING);
1161
1162     if (caught_error) {
1163       g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1164       res = caught_error;
1165     } else {
1166       GstClockTime tfthen, tfnow;
1167       GstClockTimeDiff diff;
1168
1169       PRINT (_("Setting pipeline to PLAYING ...\n"));
1170
1171       if (gst_element_set_state (pipeline,
1172               GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
1173         GstMessage *err_msg;
1174         GstBus *bus;
1175
1176         g_printerr (_("ERROR: pipeline doesn't want to play.\n"));
1177         bus = gst_element_get_bus (pipeline);
1178         if ((err_msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0))) {
1179           print_error_message (err_msg);
1180           gst_message_unref (err_msg);
1181         }
1182         gst_object_unref (bus);
1183         res = -1;
1184         goto end;
1185       }
1186
1187       tfthen = gst_util_get_timestamp ();
1188       caught_error = event_loop (pipeline, TRUE, FALSE, GST_STATE_PLAYING);
1189       res = caught_error;
1190       if (eos_on_shutdown && caught_error != ELR_NO_ERROR) {
1191         gboolean ignore_errors;
1192
1193         waiting_eos = TRUE;
1194         if (caught_error == ELR_INTERRUPT) {
1195           PRINT (_("EOS on shutdown enabled -- Forcing EOS on the pipeline\n"));
1196           gst_element_send_event (pipeline, gst_event_new_eos ());
1197           ignore_errors = FALSE;
1198         } else {
1199           PRINT (_("EOS on shutdown enabled -- waiting for EOS after Error\n"));
1200           ignore_errors = TRUE;
1201         }
1202         PRINT (_("Waiting for EOS...\n"));
1203
1204         while (TRUE) {
1205           caught_error = event_loop (pipeline, TRUE, FALSE, GST_STATE_PLAYING);
1206
1207           if (caught_error == ELR_NO_ERROR) {
1208             /* we got EOS */
1209             PRINT (_("EOS received - stopping pipeline...\n"));
1210             break;
1211           } else if (caught_error == ELR_INTERRUPT) {
1212             PRINT (_
1213                 ("Interrupt while waiting for EOS - stopping pipeline...\n"));
1214             res = caught_error;
1215             break;
1216           } else if (caught_error == ELR_ERROR) {
1217             if (!ignore_errors) {
1218               PRINT (_("An error happened while waiting for EOS\n"));
1219               res = caught_error;
1220               break;
1221             }
1222           }
1223         }
1224       }
1225       tfnow = gst_util_get_timestamp ();
1226
1227       diff = GST_CLOCK_DIFF (tfthen, tfnow);
1228
1229       PRINT (_("Execution ended after %" GST_TIME_FORMAT "\n"),
1230           GST_TIME_ARGS (diff));
1231     }
1232
1233     PRINT (_("Setting pipeline to PAUSED ...\n"));
1234     gst_element_set_state (pipeline, GST_STATE_PAUSED);
1235     if (caught_error == ELR_NO_ERROR)
1236       gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1237
1238     /* iterate mainloop to process pending stuff */
1239     while (g_main_context_iteration (NULL, FALSE));
1240
1241     /* No need to see all those pad caps going to NULL etc., it's just noise */
1242     if (deep_notify_id != 0)
1243       g_signal_handler_disconnect (pipeline, deep_notify_id);
1244
1245     PRINT (_("Setting pipeline to READY ...\n"));
1246     gst_element_set_state (pipeline, GST_STATE_READY);
1247     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1248
1249 #if 0
1250     if (check_index) {
1251       print_index_stats (index_stats);
1252       g_ptr_array_free (index_stats, TRUE);
1253     }
1254 #endif
1255
1256   end:
1257     PRINT (_("Setting pipeline to NULL ...\n"));
1258     gst_element_set_state (pipeline, GST_STATE_NULL);
1259   }
1260
1261   PRINT (_("Freeing pipeline ...\n"));
1262   gst_object_unref (pipeline);
1263
1264   gst_deinit ();
1265
1266   return res;
1267 }