gstreamer: Fix memory leaks when context parse fails
[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_clear_error (&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_clear_error (&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_clear_error (&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_STRING_ARRAY, &exclude_args,
929           N_("Do not output status information for the specified property "
930               "if verbose output is enabled (can be used multiple times)"),
931         N_("PROPERTY-NAME")},
932     {"no-fault", 'f', 0, G_OPTION_ARG_NONE, &no_fault,
933         N_("Do not install a fault handler"), NULL},
934     {"eos-on-shutdown", 'e', 0, G_OPTION_ARG_NONE, &eos_on_shutdown,
935         N_("Force EOS on sources before shutting the pipeline down"), NULL},
936 #if 0
937     {"index", 'i', 0, G_OPTION_ARG_NONE, &check_index,
938         N_("Gather and print index statistics"), NULL},
939 #endif
940     GST_TOOLS_GOPTION_VERSION,
941     {NULL}
942   };
943   GOptionContext *ctx;
944   GError *err = NULL;
945 #endif
946 #if 0
947   GstIndex *index;
948   GPtrArray *index_stats = NULL;
949 #endif
950   gchar **argvn;
951   GError *error = NULL;
952   gulong deep_notify_id = 0;
953   gint res = 0;
954
955   free (malloc (8));            /* -lefence */
956
957   setlocale (LC_ALL, "");
958
959 #ifdef ENABLE_NLS
960   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
961   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
962   textdomain (GETTEXT_PACKAGE);
963 #endif
964
965   g_set_prgname ("gst-launch-" GST_API_VERSION);
966
967 #ifndef GST_DISABLE_OPTION_PARSING
968   ctx = g_option_context_new ("PIPELINE-DESCRIPTION");
969   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
970   g_option_context_add_group (ctx, gst_init_get_option_group ());
971   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
972     if (err)
973       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
974     else
975       g_printerr ("Error initializing: Unknown error!\n");
976     g_clear_error (&error);
977     g_option_context_free (ctx);
978     exit (1);
979   }
980   g_option_context_free (ctx);
981 #else
982   gst_init (&argc, &argv);
983 #endif
984
985   gst_tools_print_version ();
986
987 #ifdef G_OS_UNIX
988   if (!no_fault)
989     fault_setup ();
990 #endif
991
992   /* make a null-terminated version of argv */
993   argvn = g_new0 (char *, argc);
994   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
995   {
996     pipeline =
997         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
998   }
999   g_free (argvn);
1000
1001   if (!pipeline) {
1002     if (error) {
1003       g_printerr (_("ERROR: pipeline could not be constructed: %s.\n"),
1004           GST_STR_NULL (error->message));
1005       g_clear_error (&error);
1006     } else {
1007       g_printerr (_("ERROR: pipeline could not be constructed.\n"));
1008     }
1009     return 1;
1010   } else if (error) {
1011     g_printerr (_("WARNING: erroneous pipeline: %s\n"),
1012         GST_STR_NULL (error->message));
1013     g_clear_error (&error);
1014     return 1;
1015   }
1016
1017   if (!savefile) {
1018     GstState state, pending;
1019     GstStateChangeReturn ret;
1020     GstBus *bus;
1021
1022     /* If the top-level object is not a pipeline, place it in a pipeline. */
1023     if (!GST_IS_PIPELINE (pipeline)) {
1024       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
1025
1026       if (real_pipeline == NULL) {
1027         g_printerr (_("ERROR: the 'pipeline' element wasn't found.\n"));
1028         return 1;
1029       }
1030       gst_bin_add (GST_BIN (real_pipeline), pipeline);
1031       pipeline = real_pipeline;
1032     }
1033     if (verbose) {
1034       deep_notify_id = g_signal_connect (pipeline, "deep-notify",
1035           G_CALLBACK (gst_object_default_deep_notify), exclude_args);
1036     }
1037 #if 0
1038     if (check_index) {
1039       /* gst_index_new() creates a null-index, it does not store anything, but
1040        * the entry-added signal works and this is what we use to build the
1041        * statistics */
1042       index = gst_index_new ();
1043       if (index) {
1044         index_stats = g_ptr_array_new ();
1045         g_signal_connect (G_OBJECT (index), "entry-added",
1046             G_CALLBACK (entry_added), index_stats);
1047         g_object_set (G_OBJECT (index), "resolver", GST_INDEX_RESOLVER_GTYPE,
1048             NULL);
1049         gst_element_set_index (pipeline, index);
1050       }
1051     }
1052 #endif
1053
1054     bus = gst_element_get_bus (pipeline);
1055     gst_bus_set_sync_handler (bus, bus_sync_handler, (gpointer) pipeline, NULL);
1056     gst_object_unref (bus);
1057
1058     PRINT (_("Setting pipeline to PAUSED ...\n"));
1059     ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
1060
1061     switch (ret) {
1062       case GST_STATE_CHANGE_FAILURE:
1063         g_printerr (_("ERROR: Pipeline doesn't want to pause.\n"));
1064         res = -1;
1065         event_loop (pipeline, FALSE, FALSE, GST_STATE_VOID_PENDING);
1066         goto end;
1067       case GST_STATE_CHANGE_NO_PREROLL:
1068         PRINT (_("Pipeline is live and does not need PREROLL ...\n"));
1069         is_live = TRUE;
1070         break;
1071       case GST_STATE_CHANGE_ASYNC:
1072         PRINT (_("Pipeline is PREROLLING ...\n"));
1073         caught_error = event_loop (pipeline, TRUE, TRUE, GST_STATE_PAUSED);
1074         if (caught_error) {
1075           g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1076           res = caught_error;
1077           goto end;
1078         }
1079         state = GST_STATE_PAUSED;
1080         /* fallthrough */
1081       case GST_STATE_CHANGE_SUCCESS:
1082         PRINT (_("Pipeline is PREROLLED ...\n"));
1083         break;
1084     }
1085
1086     caught_error = event_loop (pipeline, FALSE, TRUE, GST_STATE_PLAYING);
1087
1088     if (caught_error) {
1089       g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1090       res = caught_error;
1091     } else {
1092       GstClockTime tfthen, tfnow;
1093       GstClockTimeDiff diff;
1094
1095       PRINT (_("Setting pipeline to PLAYING ...\n"));
1096
1097       if (gst_element_set_state (pipeline,
1098               GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
1099         GstMessage *err_msg;
1100         GstBus *bus;
1101
1102         g_printerr (_("ERROR: pipeline doesn't want to play.\n"));
1103         bus = gst_element_get_bus (pipeline);
1104         if ((err_msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0))) {
1105           print_error_message (err_msg);
1106           gst_message_unref (err_msg);
1107         }
1108         gst_object_unref (bus);
1109         res = -1;
1110         goto end;
1111       }
1112
1113       tfthen = gst_util_get_timestamp ();
1114       caught_error = event_loop (pipeline, TRUE, FALSE, GST_STATE_PLAYING);
1115       if (eos_on_shutdown && caught_error != ELR_NO_ERROR) {
1116         gboolean ignore_errors;
1117
1118         waiting_eos = TRUE;
1119         if (caught_error == ELR_INTERRUPT) {
1120           PRINT (_("EOS on shutdown enabled -- Forcing EOS on the pipeline\n"));
1121           gst_element_send_event (pipeline, gst_event_new_eos ());
1122           ignore_errors = FALSE;
1123         } else {
1124           PRINT (_("EOS on shutdown enabled -- waiting for EOS after Error\n"));
1125           ignore_errors = TRUE;
1126         }
1127         PRINT (_("Waiting for EOS...\n"));
1128
1129         while (TRUE) {
1130           caught_error = event_loop (pipeline, TRUE, FALSE, GST_STATE_PLAYING);
1131
1132           if (caught_error == ELR_NO_ERROR) {
1133             /* we got EOS */
1134             PRINT (_("EOS received - stopping pipeline...\n"));
1135             break;
1136           } else if (caught_error == ELR_INTERRUPT) {
1137             PRINT (_
1138                 ("Interrupt while waiting for EOS - stopping pipeline...\n"));
1139             res = caught_error;
1140             break;
1141           } else if (caught_error == ELR_ERROR) {
1142             if (!ignore_errors) {
1143               PRINT (_("An error happened while waiting for EOS\n"));
1144               res = caught_error;
1145               break;
1146             }
1147           }
1148         }
1149       }
1150       tfnow = gst_util_get_timestamp ();
1151
1152       diff = GST_CLOCK_DIFF (tfthen, tfnow);
1153
1154       PRINT (_("Execution ended after %" GST_TIME_FORMAT "\n"),
1155           GST_TIME_ARGS (diff));
1156     }
1157
1158     PRINT (_("Setting pipeline to PAUSED ...\n"));
1159     gst_element_set_state (pipeline, GST_STATE_PAUSED);
1160     if (caught_error == ELR_NO_ERROR)
1161       gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1162
1163     /* iterate mainloop to process pending stuff */
1164     while (g_main_context_iteration (NULL, FALSE));
1165
1166     /* No need to see all those pad caps going to NULL etc., it's just noise */
1167     if (deep_notify_id != 0)
1168       g_signal_handler_disconnect (pipeline, deep_notify_id);
1169
1170     PRINT (_("Setting pipeline to READY ...\n"));
1171     gst_element_set_state (pipeline, GST_STATE_READY);
1172     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1173
1174 #if 0
1175     if (check_index) {
1176       print_index_stats (index_stats);
1177       g_ptr_array_free (index_stats, TRUE);
1178     }
1179 #endif
1180
1181   end:
1182     PRINT (_("Setting pipeline to NULL ...\n"));
1183     gst_element_set_state (pipeline, GST_STATE_NULL);
1184   }
1185
1186   PRINT (_("Freeing pipeline ...\n"));
1187   gst_object_unref (pipeline);
1188
1189   gst_deinit ();
1190
1191   return res;
1192 }