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