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