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