]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - glsdk/gstreamer0-10.git/blob - tools/gst-launch.c
gst-launch: add --loop argument
[glsdk/gstreamer0-10.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., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
28 /* FIXME: hack alert */
29 #ifdef HAVE_WIN32
30 #define DISABLE_FAULT_HANDLER
31 #endif
33 #include <stdio.h>
34 #include <string.h>
35 #include <signal.h>
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifndef DISABLE_FAULT_HANDLER
40 #include <sys/wait.h>
41 #endif
42 #include <locale.h>             /* for LC_ALL */
43 #include "tools.h"
45 /* FIXME: This is just a temporary hack.  We should have a better
46  * check for siginfo handling. */
47 #ifdef SA_SIGINFO
48 #define USE_SIGINFO
49 #endif
51 extern volatile gboolean glib_on_error_halt;
53 #ifndef DISABLE_FAULT_HANDLER
54 static void fault_restore (void);
55 static void fault_spin (void);
56 static void sigint_restore (void);
57 static gboolean caught_intr = FALSE;
58 #endif
60 /* event_loop return codes */
61 typedef enum _EventLoopResult
62 {
63   ELR_NO_ERROR = 0,
64   ELR_ERROR,
65   ELR_INTERRUPT
66 } EventLoopResult;
68 static GstElement *pipeline;
69 static EventLoopResult caught_error = ELR_NO_ERROR;
70 static gboolean quiet = FALSE;
71 static gboolean tags = FALSE;
72 static gboolean messages = FALSE;
73 static gboolean is_live = FALSE;
74 static gboolean waiting_eos = FALSE;
76 /* convenience macro so we don't have to litter the code with if(!quiet) */
77 #define PRINT if(!quiet)g_print
79 #if !defined(GST_DISABLE_LOADSAVE) && !defined(GST_REMOVE_DEPRECATED)
80 static GstElement *
81 xmllaunch_parse_cmdline (const gchar ** argv)
82 {
83   GstElement *pipeline = NULL, *e;
84   GstXML *xml;
85   gboolean err;
86   const gchar *arg;
87   gchar *element, *property, *value;
88   GList *l;
89   gint i = 0;
91   if (!(arg = argv[0])) {
92     g_printerr ("%s",
93         _("Usage: gst-xmllaunch <file.xml> [ element.property=value ... ]\n"));
94     exit (1);
95   }
97   xml = gst_xml_new ();
98   /* FIXME guchar from gstxml.c */
99   err = gst_xml_parse_file (xml, (guchar *) arg, NULL);
101   if (err != TRUE) {
102     g_printerr (_("ERROR: parse of xml file '%s' failed.\n"), arg);
103     exit (1);
104   }
106   l = gst_xml_get_topelements (xml);
107   if (!l) {
108     g_printerr (_("ERROR: no toplevel pipeline element in file '%s'.\n"), arg);
109     exit (1);
110   }
112   if (l->next) {
113     g_printerr ("%s",
114         _("WARNING: only one toplevel element is supported at this time.\n"));
115   }
117   pipeline = GST_ELEMENT (l->data);
119   while ((arg = argv[++i])) {
120     element = g_strdup (arg);
121     property = strchr (element, '.');
122     value = strchr (element, '=');
124     if (!(element < property && property < value)) {
125       g_printerr (_("ERROR: could not parse command line argument %d: %s.\n"),
126           i, element);
127       g_free (element);
128       exit (1);
129     }
131     *property++ = '\0';
132     *value++ = '\0';
134     e = gst_bin_get_by_name (GST_BIN (pipeline), element);
135     if (!e) {
136       g_printerr (_("WARNING: element named '%s' not found.\n"), element);
137     } else {
138       gst_util_set_object_arg (G_OBJECT (e), property, value);
139     }
140     g_free (element);
141   }
143   if (!l)
144     return NULL;
146   gst_object_ref (pipeline);
147   gst_object_unref (xml);
148   return pipeline;
150 #endif
152 #ifndef DISABLE_FAULT_HANDLER
153 #ifndef USE_SIGINFO
154 static void
155 fault_handler_sighandler (int signum)
157   fault_restore ();
159   /* printf is used instead of g_print(), since it's less likely to
160    * deadlock */
161   switch (signum) {
162     case SIGSEGV:
163       fprintf (stderr, "Caught SIGSEGV\n");
164       break;
165     case SIGQUIT:
166       if (!quiet)
167         printf ("Caught SIGQUIT\n");
168       break;
169     default:
170       fprintf (stderr, "signo:  %d\n", signum);
171       break;
172   }
174   fault_spin ();
177 #else /* USE_SIGINFO */
179 static void
180 fault_handler_sigaction (int signum, siginfo_t * si, void *misc)
182   fault_restore ();
184   /* printf is used instead of g_print(), since it's less likely to
185    * deadlock */
186   switch (si->si_signo) {
187     case SIGSEGV:
188       fprintf (stderr, "Caught SIGSEGV accessing address %p\n", si->si_addr);
189       break;
190     case SIGQUIT:
191       if (!quiet)
192         printf ("Caught SIGQUIT\n");
193       break;
194     default:
195       fprintf (stderr, "signo:  %d\n", si->si_signo);
196       fprintf (stderr, "errno:  %d\n", si->si_errno);
197       fprintf (stderr, "code:   %d\n", si->si_code);
198       break;
199   }
201   fault_spin ();
203 #endif /* USE_SIGINFO */
205 static void
206 fault_spin (void)
208   int spinning = TRUE;
210   glib_on_error_halt = FALSE;
211   g_on_error_stack_trace ("gst-launch");
213   wait (NULL);
215   /* FIXME how do we know if we were run by libtool? */
216   fprintf (stderr,
217       "Spinning.  Please run 'gdb gst-launch %d' to continue debugging, "
218       "Ctrl-C to quit, or Ctrl-\\ to dump core.\n", (gint) getpid ());
219   while (spinning)
220     g_usleep (1000000);
223 static void
224 fault_restore (void)
226   struct sigaction action;
228   memset (&action, 0, sizeof (action));
229   action.sa_handler = SIG_DFL;
231   sigaction (SIGSEGV, &action, NULL);
232   sigaction (SIGQUIT, &action, NULL);
235 static void
236 fault_setup (void)
238   struct sigaction action;
240   memset (&action, 0, sizeof (action));
241 #ifdef USE_SIGINFO
242   action.sa_sigaction = fault_handler_sigaction;
243   action.sa_flags = SA_SIGINFO;
244 #else
245   action.sa_handler = fault_handler_sighandler;
246 #endif
248   sigaction (SIGSEGV, &action, NULL);
249   sigaction (SIGQUIT, &action, NULL);
251 #endif /* DISABLE_FAULT_HANDLER */
253 typedef struct _GstIndexStats
255   gint id;
256   gchar *desc;
258   guint num_frames;
259   guint num_keyframes;
260   guint num_dltframes;
261   GstClockTime last_keyframe;
262   GstClockTime last_dltframe;
263   GstClockTime min_keyframe_gap;
264   GstClockTime max_keyframe_gap;
265   GstClockTime avg_keyframe_gap;
266 } GstIndexStats;
268 static void
269 entry_added (GstIndex * index, GstIndexEntry * entry, gpointer user_data)
271   GPtrArray *index_stats = (GPtrArray *) user_data;
272   GstIndexStats *s;
274   switch (entry->type) {
275     case GST_INDEX_ENTRY_ID:
276       /* we have a new writer */
277       GST_DEBUG_OBJECT (index, "id %d: describes writer %s", entry->id,
278           GST_INDEX_ID_DESCRIPTION (entry));
279       if (entry->id >= index_stats->len) {
280         g_ptr_array_set_size (index_stats, entry->id + 1);
281       }
282       s = g_new (GstIndexStats, 1);
283       s->id = entry->id;
284       s->desc = g_strdup (GST_INDEX_ID_DESCRIPTION (entry));
285       s->num_frames = s->num_keyframes = s->num_dltframes = 0;
286       s->last_keyframe = s->last_dltframe = GST_CLOCK_TIME_NONE;
287       s->min_keyframe_gap = s->max_keyframe_gap = s->avg_keyframe_gap =
288           GST_CLOCK_TIME_NONE;
289       g_ptr_array_index (index_stats, entry->id) = s;
290       break;
291     case GST_INDEX_ENTRY_FORMAT:
292       /* have not found any code calling this */
293       GST_DEBUG_OBJECT (index, "id %d: registered format %d for %s\n",
294           entry->id, GST_INDEX_FORMAT_FORMAT (entry),
295           GST_INDEX_FORMAT_KEY (entry));
296       break;
297     case GST_INDEX_ENTRY_ASSOCIATION:
298     {
299       gint64 ts;
300       GstAssocFlags flags = GST_INDEX_ASSOC_FLAGS (entry);
302       s = g_ptr_array_index (index_stats, entry->id);
303       gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
305       if (flags & GST_ASSOCIATION_FLAG_KEY_UNIT) {
306         s->num_keyframes++;
308         if (GST_CLOCK_TIME_IS_VALID (ts)) {
309           if (GST_CLOCK_TIME_IS_VALID (s->last_keyframe)) {
310             GstClockTimeDiff d = GST_CLOCK_DIFF (s->last_keyframe, ts);
312             if (G_UNLIKELY (d < 0)) {
313               GST_WARNING ("received out-of-order keyframe at %"
314                   GST_TIME_FORMAT, GST_TIME_ARGS (ts));
315               /* FIXME: does it still make sense to use that for the statistics */
316               d = GST_CLOCK_DIFF (ts, s->last_keyframe);
317             }
319             if (GST_CLOCK_TIME_IS_VALID (s->min_keyframe_gap)) {
320               if (d < s->min_keyframe_gap)
321                 s->min_keyframe_gap = d;
322             } else {
323               s->min_keyframe_gap = d;
324             }
325             if (GST_CLOCK_TIME_IS_VALID (s->max_keyframe_gap)) {
326               if (d > s->max_keyframe_gap)
327                 s->max_keyframe_gap = d;
328             } else {
329               s->max_keyframe_gap = d;
330             }
331             if (GST_CLOCK_TIME_IS_VALID (s->avg_keyframe_gap)) {
332               s->avg_keyframe_gap = (d + s->num_frames * s->avg_keyframe_gap) /
333                   (s->num_frames + 1);
334             } else {
335               s->avg_keyframe_gap = d;
336             }
337           }
338           s->last_keyframe = ts;
339         }
340       }
341       if (flags & GST_ASSOCIATION_FLAG_DELTA_UNIT) {
342         s->num_dltframes++;
343         if (GST_CLOCK_TIME_IS_VALID (ts)) {
344           s->last_dltframe = ts;
345         }
346       }
347       s->num_frames++;
349       break;
350     }
351     default:
352       break;
353   }
356 /* print statistics from the entry_added callback, free the entries */
357 static void
358 print_index_stats (GPtrArray * index_stats)
360   gint i;
362   if (index_stats->len) {
363     g_print ("%s:\n", _("Index statistics"));
364   }
366   for (i = 0; i < index_stats->len; i++) {
367     GstIndexStats *s = g_ptr_array_index (index_stats, i);
368     if (s) {
369       g_print ("id %d, %s\n", s->id, s->desc);
370       if (s->num_frames) {
371         GstClockTime last_frame = s->last_keyframe;
373         if (GST_CLOCK_TIME_IS_VALID (s->last_dltframe)) {
374           if (!GST_CLOCK_TIME_IS_VALID (last_frame) ||
375               (s->last_dltframe > last_frame))
376             last_frame = s->last_dltframe;
377         }
379         if (GST_CLOCK_TIME_IS_VALID (last_frame)) {
380           g_print ("  total time               = %" GST_TIME_FORMAT "\n",
381               GST_TIME_ARGS (last_frame));
382         }
383         g_print ("  frame/keyframe rate      = %u / %u = ", s->num_frames,
384             s->num_keyframes);
385         if (s->num_keyframes)
386           g_print ("%lf\n", s->num_frames / (gdouble) s->num_keyframes);
387         else
388           g_print ("-\n");
389         if (s->num_keyframes) {
390           g_print ("  min/avg/max keyframe gap = %" GST_TIME_FORMAT ", %"
391               GST_TIME_FORMAT ", %" GST_TIME_FORMAT "\n",
392               GST_TIME_ARGS (s->min_keyframe_gap),
393               GST_TIME_ARGS (s->avg_keyframe_gap),
394               GST_TIME_ARGS (s->max_keyframe_gap));
395         }
396       } else {
397         g_print ("  no stats\n");
398       }
400       g_free (s->desc);
401       g_free (s);
402     }
403   }
406 /* Kids, use the functions from libgstpbutils in gst-plugins-base in your
407  * own code (we can't do that here because it would introduce a circular
408  * dependency) */
409 static gboolean
410 gst_is_missing_plugin_message (GstMessage * msg)
412   if (GST_MESSAGE_TYPE (msg) != GST_MESSAGE_ELEMENT || msg->structure == NULL)
413     return FALSE;
415   return gst_structure_has_name (msg->structure, "missing-plugin");
418 static const gchar *
419 gst_missing_plugin_message_get_description (GstMessage * msg)
421   return gst_structure_get_string (msg->structure, "name");
424 static void
425 print_error_message (GstMessage * msg)
427   GError *err = NULL;
428   gchar *name, *debug = NULL;
430   name = gst_object_get_path_string (msg->src);
431   gst_message_parse_error (msg, &err, &debug);
433   g_printerr (_("ERROR: from element %s: %s\n"), name, err->message);
434   if (debug != NULL)
435     g_printerr (_("Additional debug info:\n%s\n"), debug);
437   g_error_free (err);
438   g_free (debug);
439   g_free (name);
442 static void
443 print_tag (const GstTagList * list, const gchar * tag, gpointer unused)
445   gint i, count;
447   count = gst_tag_list_get_tag_size (list, tag);
449   for (i = 0; i < count; i++) {
450     gchar *str;
452     if (gst_tag_get_type (tag) == G_TYPE_STRING) {
453       if (!gst_tag_list_get_string_index (list, tag, i, &str))
454         g_assert_not_reached ();
455     } else if (gst_tag_get_type (tag) == GST_TYPE_BUFFER) {
456       GstBuffer *img;
458       img = gst_value_get_buffer (gst_tag_list_get_value_index (list, tag, i));
459       if (img) {
460         gchar *caps_str;
462         caps_str = GST_BUFFER_CAPS (img) ?
463             gst_caps_to_string (GST_BUFFER_CAPS (img)) : g_strdup ("unknown");
464         str = g_strdup_printf ("buffer of %u bytes, type: %s",
465             GST_BUFFER_SIZE (img), caps_str);
466         g_free (caps_str);
467       } else {
468         str = g_strdup ("NULL buffer");
469       }
470     } else if (gst_tag_get_type (tag) == GST_TYPE_DATE_TIME) {
471       GstDateTime *dt = NULL;
473       gst_tag_list_get_date_time_index (list, tag, i, &dt);
474       if (gst_date_time_get_hour (dt) < 0) {
475         str = g_strdup_printf ("%02u-%02u-%04u", gst_date_time_get_day (dt),
476             gst_date_time_get_month (dt), gst_date_time_get_year (dt));
477       } else {
478         gdouble tz_offset = gst_date_time_get_time_zone_offset (dt);
479         gchar tz_str[32];
481         if (tz_offset != 0.0) {
482           g_snprintf (tz_str, sizeof (tz_str), "(UTC %s%gh)",
483               (tz_offset > 0.0) ? "+" : "", tz_offset);
484         } else {
485           g_snprintf (tz_str, sizeof (tz_str), "(UTC)");
486         }
488         str = g_strdup_printf ("%04u-%02u-%02u %02u:%02u:%02u %s",
489             gst_date_time_get_year (dt), gst_date_time_get_month (dt),
490             gst_date_time_get_day (dt), gst_date_time_get_hour (dt),
491             gst_date_time_get_minute (dt), gst_date_time_get_second (dt),
492             tz_str);
493       }
494       gst_date_time_unref (dt);
495     } else {
496       str =
497           g_strdup_value_contents (gst_tag_list_get_value_index (list, tag, i));
498     }
500     if (i == 0) {
501       PRINT ("%16s: %s\n", gst_tag_get_nick (tag), str);
502     } else {
503       PRINT ("%16s: %s\n", "", str);
504     }
506     g_free (str);
507   }
510 #ifndef DISABLE_FAULT_HANDLER
511 /* we only use sighandler here because the registers are not important */
512 static void
513 sigint_handler_sighandler (int signum)
515   PRINT ("Caught interrupt -- ");
517   /* If we were waiting for an EOS, we still want to catch
518    * the next signal to shutdown properly (and the following one
519    * will quit the program). */
520   if (waiting_eos) {
521     waiting_eos = FALSE;
522   } else {
523     sigint_restore ();
524   }
525   /* we set a flag that is checked by the mainloop, we cannot do much in the
526    * interrupt handler (no mutex or other blocking stuff) */
527   caught_intr = TRUE;
530 /* is called every 250 milliseconds (4 times a second), the interrupt handler
531  * will set a flag for us. We react to this by posting a message. */
532 static gboolean
533 check_intr (GstElement * pipeline)
535   if (!caught_intr) {
536     return TRUE;
537   } else {
538     caught_intr = FALSE;
539     PRINT ("handling interrupt.\n");
541     /* post an application specific message */
542     gst_element_post_message (GST_ELEMENT (pipeline),
543         gst_message_new_application (GST_OBJECT (pipeline),
544             gst_structure_new ("GstLaunchInterrupt",
545                 "message", G_TYPE_STRING, "Pipeline interrupted", NULL)));
547     /* remove timeout handler */
548     return FALSE;
549   }
552 static void
553 sigint_setup (void)
555   struct sigaction action;
557   memset (&action, 0, sizeof (action));
558   action.sa_handler = sigint_handler_sighandler;
560   sigaction (SIGINT, &action, NULL);
563 static void
564 sigint_restore (void)
566   struct sigaction action;
568   memset (&action, 0, sizeof (action));
569   action.sa_handler = SIG_DFL;
571   sigaction (SIGINT, &action, NULL);
574 /* FIXME 0.11: remove SIGUSR handling (also from man page) */
575 static void
576 play_handler (int signum)
578   switch (signum) {
579     case SIGUSR1:
580       PRINT ("Caught SIGUSR1 - Play request.\n");
581       gst_element_set_state (pipeline, GST_STATE_PLAYING);
582       break;
583     case SIGUSR2:
584       PRINT ("Caught SIGUSR2 - Stop request.\n");
585       gst_element_set_state (pipeline, GST_STATE_NULL);
586       break;
587   }
590 static void
591 play_signal_setup (void)
593   struct sigaction action;
595   memset (&action, 0, sizeof (action));
596   action.sa_handler = play_handler;
597   sigaction (SIGUSR1, &action, NULL);
598   sigaction (SIGUSR2, &action, NULL);
600 #endif /* DISABLE_FAULT_HANDLER */
602 /* returns ELR_ERROR if there was an error
603  * or ELR_INTERRUPT if we caught a keyboard interrupt
604  * or ELR_NO_ERROR otherwise. */
605 static EventLoopResult
606 event_loop (GstElement * pipeline, gboolean blocking, GstState target_state)
608 #ifndef DISABLE_FAULT_HANDLER
609   gulong timeout_id;
610 #endif
611   GstBus *bus;
612   GstMessage *message = NULL;
613   EventLoopResult res = ELR_NO_ERROR;
614   gboolean buffering = FALSE;
616   bus = gst_element_get_bus (GST_ELEMENT (pipeline));
618 #ifndef DISABLE_FAULT_HANDLER
619   timeout_id = g_timeout_add (250, (GSourceFunc) check_intr, pipeline);
620 #endif
622   while (TRUE) {
623     message = gst_bus_poll (bus, GST_MESSAGE_ANY, blocking ? -1 : 0);
625     /* if the poll timed out, only when !blocking */
626     if (message == NULL)
627       goto exit;
629     /* check if we need to dump messages to the console */
630     if (messages) {
631       GstObject *src_obj;
632       const GstStructure *s;
633       guint32 seqnum;
635       seqnum = gst_message_get_seqnum (message);
637       s = gst_message_get_structure (message);
639       src_obj = GST_MESSAGE_SRC (message);
641       if (GST_IS_ELEMENT (src_obj)) {
642         PRINT (_("Got message #%u from element \"%s\" (%s): "),
643             (guint) seqnum, GST_ELEMENT_NAME (src_obj),
644             GST_MESSAGE_TYPE_NAME (message));
645       } else if (GST_IS_PAD (src_obj)) {
646         PRINT (_("Got message #%u from pad \"%s:%s\" (%s): "),
647             (guint) seqnum, GST_DEBUG_PAD_NAME (src_obj),
648             GST_MESSAGE_TYPE_NAME (message));
649       } else if (GST_IS_OBJECT (src_obj)) {
650         PRINT (_("Got message #%u from object \"%s\" (%s): "),
651             (guint) seqnum, GST_OBJECT_NAME (src_obj),
652             GST_MESSAGE_TYPE_NAME (message));
653       } else {
654         PRINT (_("Got message #%u (%s): "), (guint) seqnum,
655             GST_MESSAGE_TYPE_NAME (message));
656       }
658       if (s) {
659         gchar *sstr;
661         sstr = gst_structure_to_string (s);
662         PRINT ("%s\n", sstr);
663         g_free (sstr);
664       } else {
665         PRINT ("no message details\n");
666       }
667     }
669     switch (GST_MESSAGE_TYPE (message)) {
670       case GST_MESSAGE_NEW_CLOCK:
671       {
672         GstClock *clock;
674         gst_message_parse_new_clock (message, &clock);
676         PRINT ("New clock: %s\n", (clock ? GST_OBJECT_NAME (clock) : "NULL"));
677         break;
678       }
679       case GST_MESSAGE_CLOCK_LOST:
680         PRINT ("Clock lost, selecting a new one\n");
681         gst_element_set_state (pipeline, GST_STATE_PAUSED);
682         gst_element_set_state (pipeline, GST_STATE_PLAYING);
683         break;
684       case GST_MESSAGE_EOS:{
685         waiting_eos = FALSE;
686         PRINT (_("Got EOS from element \"%s\".\n"),
687             GST_MESSAGE_SRC_NAME (message));
688         goto exit;
689       }
690       case GST_MESSAGE_TAG:
691         if (tags) {
692           GstTagList *tags;
694           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
695             PRINT (_("FOUND TAG      : found by element \"%s\".\n"),
696                 GST_MESSAGE_SRC_NAME (message));
697           } else if (GST_IS_PAD (GST_MESSAGE_SRC (message))) {
698             PRINT (_("FOUND TAG      : found by pad \"%s:%s\".\n"),
699                 GST_DEBUG_PAD_NAME (GST_MESSAGE_SRC (message)));
700           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
701             PRINT (_("FOUND TAG      : found by object \"%s\".\n"),
702                 GST_MESSAGE_SRC_NAME (message));
703           } else {
704             PRINT (_("FOUND TAG\n"));
705           }
707           gst_message_parse_tag (message, &tags);
708           gst_tag_list_foreach (tags, print_tag, NULL);
709           gst_tag_list_free (tags);
710         }
711         break;
712       case GST_MESSAGE_INFO:{
713         GError *gerror;
714         gchar *debug;
715         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
717         gst_message_parse_info (message, &gerror, &debug);
718         if (debug) {
719           PRINT (_("INFO:\n%s\n"), debug);
720         }
721         g_error_free (gerror);
722         g_free (debug);
723         g_free (name);
724         break;
725       }
726       case GST_MESSAGE_WARNING:{
727         GError *gerror;
728         gchar *debug;
729         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
731         /* dump graph on warning */
732         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
733             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.warning");
735         gst_message_parse_warning (message, &gerror, &debug);
736         PRINT (_("WARNING: from element %s: %s\n"), name, gerror->message);
737         if (debug) {
738           PRINT (_("Additional debug info:\n%s\n"), debug);
739         }
740         g_error_free (gerror);
741         g_free (debug);
742         g_free (name);
743         break;
744       }
745       case GST_MESSAGE_ERROR:{
746         /* dump graph on error */
747         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
748             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.error");
750         print_error_message (message);
752         /* we have an error */
753         res = ELR_ERROR;
754         goto exit;
755       }
756       case GST_MESSAGE_STATE_CHANGED:{
757         GstState old, new, pending;
759         /* we only care about pipeline state change messages */
760         if (GST_MESSAGE_SRC (message) != GST_OBJECT_CAST (pipeline))
761           break;
763         /* ignore when we are buffering since then we mess with the states
764          * ourselves. */
765         if (buffering) {
766           PRINT (_("Prerolled, waiting for buffering to finish...\n"));
767           break;
768         }
770         gst_message_parse_state_changed (message, &old, &new, &pending);
772         /* if we reached the final target state, exit */
773         if (target_state == GST_STATE_PAUSED && new == target_state)
774           goto exit;
776         /* else not an interesting message */
777         break;
778       }
779       case GST_MESSAGE_BUFFERING:{
780         gint percent;
782         gst_message_parse_buffering (message, &percent);
783         PRINT ("%s %d%%  \r", _("buffering..."), percent);
785         /* no state management needed for live pipelines */
786         if (is_live)
787           break;
789         if (percent == 100) {
790           /* a 100% message means buffering is done */
791           buffering = FALSE;
792           /* if the desired state is playing, go back */
793           if (target_state == GST_STATE_PLAYING) {
794             PRINT (_("Done buffering, setting pipeline to PLAYING ...\n"));
795             gst_element_set_state (pipeline, GST_STATE_PLAYING);
796           } else
797             goto exit;
798         } else {
799           /* buffering busy */
800           if (buffering == FALSE && target_state == GST_STATE_PLAYING) {
801             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
802             PRINT (_("Buffering, setting pipeline to PAUSED ...\n"));
803             gst_element_set_state (pipeline, GST_STATE_PAUSED);
804           }
805           buffering = TRUE;
806         }
807         break;
808       }
809       case GST_MESSAGE_LATENCY:
810       {
811         PRINT (_("Redistribute latency...\n"));
812         gst_bin_recalculate_latency (GST_BIN (pipeline));
813         break;
814       }
815       case GST_MESSAGE_REQUEST_STATE:
816       {
817         GstState state;
818         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
820         gst_message_parse_request_state (message, &state);
822         PRINT (_("Setting state to %s as requested by %s...\n"),
823             gst_element_state_get_name (state), name);
825         gst_element_set_state (pipeline, state);
827         g_free (name);
828         break;
829       }
830       case GST_MESSAGE_APPLICATION:{
831         const GstStructure *s;
833         s = gst_message_get_structure (message);
835         if (gst_structure_has_name (s, "GstLaunchInterrupt")) {
836           /* this application message is posted when we caught an interrupt and
837            * we need to stop the pipeline. */
838           PRINT (_("Interrupt: Stopping pipeline ...\n"));
839           res = ELR_INTERRUPT;
840           goto exit;
841         }
842         break;
843       }
844       case GST_MESSAGE_ELEMENT:{
845         if (gst_is_missing_plugin_message (message)) {
846           const gchar *desc;
848           desc = gst_missing_plugin_message_get_description (message);
849           PRINT (_("Missing element: %s\n"), desc ? desc : "(no description)");
850         }
851         break;
852       }
853       default:
854         /* just be quiet by default */
855         break;
856     }
857     if (message)
858       gst_message_unref (message);
859   }
860   g_assert_not_reached ();
862 exit:
863   {
864     if (message)
865       gst_message_unref (message);
866     gst_object_unref (bus);
867 #ifndef DISABLE_FAULT_HANDLER
868     g_source_remove (timeout_id);
869 #endif
870     return res;
871   }
874 static GstBusSyncReply
875 bus_sync_handler (GstBus * bus, GstMessage * message, gpointer data)
877   GstElement *pipeline = (GstElement *) data;
879   switch (GST_MESSAGE_TYPE (message)) {
880     case GST_MESSAGE_STATE_CHANGED:
881       /* we only care about pipeline state change messages */
882       if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipeline)) {
883         GstState old, new, pending;
884         gchar *state_transition_name;
886         gst_message_parse_state_changed (message, &old, &new, &pending);
888         state_transition_name = g_strdup_printf ("%s_%s",
889             gst_element_state_get_name (old), gst_element_state_get_name (new));
891         /* dump graph for (some) pipeline state changes */
892         {
893           gchar *dump_name = g_strconcat ("gst-launch.", state_transition_name,
894               NULL);
895           GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
896               GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
897           g_free (dump_name);
898         }
900         /* place a marker into e.g. strace logs */
901         {
902           gchar *access_name = g_strconcat (g_get_tmp_dir (), G_DIR_SEPARATOR_S,
903               "gst-launch", G_DIR_SEPARATOR_S, state_transition_name, NULL);
904           g_file_test (access_name, G_FILE_TEST_EXISTS);
905           g_free (access_name);
906         }
908         g_free (state_transition_name);
909       }
910     default:
911       break;
912   }
913   return GST_BUS_PASS;
916 int
917 main (int argc, char *argv[])
919   /* options */
920   gboolean verbose = FALSE;
921   gboolean no_fault = FALSE;
922   gboolean no_sigusr_handler = FALSE;
923   gboolean trace = FALSE;
924   gboolean eos_on_shutdown = FALSE;
925   gboolean check_index = FALSE;
926   gboolean loop = FALSE;
927   gchar *savefile = NULL;
928   gchar *exclude_args = NULL;
929 #ifndef GST_DISABLE_OPTION_PARSING
930   GOptionEntry options[] = {
931     {"tags", 't', 0, G_OPTION_ARG_NONE, &tags,
932         N_("Output tags (also known as metadata)"), NULL},
933     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
934         N_("Output status information and property notifications"), NULL},
935     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
936         N_("Do not print any progress information"), NULL},
937     {"messages", 'm', 0, G_OPTION_ARG_NONE, &messages,
938         N_("Output messages"), NULL},
939     {"exclude", 'X', 0, G_OPTION_ARG_NONE, &exclude_args,
940         N_("Do not output status information of TYPE"), N_("TYPE1,TYPE2,...")},
941 #if !defined(GST_DISABLE_LOADSAVE) && !defined(GST_REMOVE_DEPRECATED)
942     {"output", 'o', 0, G_OPTION_ARG_STRING, &savefile,
943         N_("Save xml representation of pipeline to FILE and exit"), N_("FILE")},
944 #endif
945     {"no-fault", 'f', 0, G_OPTION_ARG_NONE, &no_fault,
946         N_("Do not install a fault handler"), NULL},
947     {"no-sigusr-handler", '\0', 0, G_OPTION_ARG_NONE, &no_sigusr_handler,
948         N_("Do not install signal handlers for SIGUSR1 and SIGUSR2"), NULL},
949     {"trace", 'T', 0, G_OPTION_ARG_NONE, &trace,
950         N_("Print alloc trace (if enabled at compile time)"), NULL},
951     {"eos-on-shutdown", 'e', 0, G_OPTION_ARG_NONE, &eos_on_shutdown,
952         N_("Force EOS on sources before shutting the pipeline down"), NULL},
953     {"index", 'i', 0, G_OPTION_ARG_NONE, &check_index,
954         N_("Gather and print index statistics"), NULL},
955     {"loop", 'l', 0, G_OPTION_ARG_NONE, &loop,
956         N_("Repeat clip in loop without rebuilding pipeline"), NULL},
957     GST_TOOLS_GOPTION_VERSION,
958     {NULL}
959   };
960   GOptionContext *ctx;
961   GError *err = NULL;
962 #endif
963   GstIndex *index;
964   GPtrArray *index_stats = NULL;
965   gchar **argvn;
966   GError *error = NULL;
967   gint res = 0;
969   free (malloc (8));            /* -lefence */
971 #ifdef ENABLE_NLS
972   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
973   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
974   textdomain (GETTEXT_PACKAGE);
975 #endif
977 #if !GLIB_CHECK_VERSION (2, 31, 0)
978   g_thread_init (NULL);
979 #endif
981   gst_tools_set_prgname ("gst-launch");
983 #ifndef GST_DISABLE_OPTION_PARSING
984   ctx = g_option_context_new ("PIPELINE-DESCRIPTION");
985   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
986   g_option_context_add_group (ctx, gst_init_get_option_group ());
987   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
988     if (err)
989       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
990     else
991       g_printerr ("Error initializing: Unknown error!\n");
992     exit (1);
993   }
994   g_option_context_free (ctx);
995 #else
996   gst_init (&argc, &argv);
997 #endif
999   gst_tools_print_version ("gst-launch");
1001 #ifndef DISABLE_FAULT_HANDLER
1002   if (!no_fault)
1003     fault_setup ();
1005   sigint_setup ();
1007   if (!no_sigusr_handler)
1008     play_signal_setup ();
1009 #endif
1011   if (trace) {
1012     if (!gst_alloc_trace_available ()) {
1013       g_warning ("Trace not available (recompile with trace enabled).");
1014     }
1015     gst_alloc_trace_set_flags_all (GST_ALLOC_TRACE_LIVE |
1016         GST_ALLOC_TRACE_MEM_LIVE);
1017     gst_alloc_trace_print_live ();
1018   }
1020   /* make a null-terminated version of argv */
1021   argvn = g_new0 (char *, argc);
1022   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
1023 #if !defined(GST_DISABLE_LOADSAVE) && !defined(GST_REMOVE_DEPRECATED)
1024   if (strstr (argv[0], "gst-xmllaunch")) {
1025     /* FIXME 0.11: remove xmllaunch entirely */
1026     g_warning ("gst-xmllaunch is deprecated and broken for all but the most "
1027         "simple pipelines. It will most likely be removed in future. Don't "
1028         "use it.\n");
1029     pipeline = xmllaunch_parse_cmdline ((const gchar **) argvn);
1030   } else
1031 #endif
1032   {
1033     pipeline =
1034         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
1035   }
1036   g_free (argvn);
1038   if (!pipeline) {
1039     if (error) {
1040       g_printerr (_("ERROR: pipeline could not be constructed: %s.\n"),
1041           GST_STR_NULL (error->message));
1042       g_error_free (error);
1043     } else {
1044       g_printerr (_("ERROR: pipeline could not be constructed.\n"));
1045     }
1046     return 1;
1047   } else if (error) {
1048     g_printerr (_("WARNING: erroneous pipeline: %s\n"),
1049         GST_STR_NULL (error->message));
1050     g_error_free (error);
1051     return 1;
1052   }
1054   if (verbose) {
1055     gchar **exclude_list =
1056         exclude_args ? g_strsplit (exclude_args, ",", 0) : NULL;
1057     g_signal_connect (pipeline, "deep-notify",
1058         G_CALLBACK (gst_object_default_deep_notify), exclude_list);
1059   }
1060 #if !defined(GST_DISABLE_LOADSAVE) && !defined(GST_REMOVE_DEPRECATED)
1061   if (savefile) {
1062     g_warning ("Pipeline serialization to XML is deprecated and broken for "
1063         "all but the most simple pipelines. It will most likely be removed "
1064         "in future. Don't use it.\n");
1066     gst_xml_write_file (GST_ELEMENT (pipeline), fopen (savefile, "w"));
1067   }
1068 #endif
1070   if (!savefile) {
1071     GstState state, pending;
1072     GstStateChangeReturn ret;
1073     GstBus *bus;
1075     /* If the top-level object is not a pipeline, place it in a pipeline. */
1076     if (!GST_IS_PIPELINE (pipeline)) {
1077       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
1079       if (real_pipeline == NULL) {
1080         g_printerr (_("ERROR: the 'pipeline' element wasn't found.\n"));
1081         return 1;
1082       }
1083       gst_bin_add (GST_BIN (real_pipeline), pipeline);
1084       pipeline = real_pipeline;
1085     }
1087     if (check_index) {
1088       /* gst_index_new() creates a null-index, it does not store anything, but
1089        * the entry-added signal works and this is what we use to build the
1090        * statistics */
1091       index = gst_index_new ();
1092       if (index) {
1093         index_stats = g_ptr_array_new ();
1094         g_signal_connect (G_OBJECT (index), "entry-added",
1095             G_CALLBACK (entry_added), index_stats);
1096         g_object_set (G_OBJECT (index), "resolver", GST_INDEX_RESOLVER_GTYPE,
1097             NULL);
1098         gst_element_set_index (pipeline, index);
1099       }
1100     }
1102     bus = gst_element_get_bus (pipeline);
1103     gst_bus_set_sync_handler (bus, bus_sync_handler, (gpointer) pipeline);
1104     gst_object_unref (bus);
1106     PRINT (_("Setting pipeline to PAUSED ...\n"));
1107     ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
1109     switch (ret) {
1110       case GST_STATE_CHANGE_FAILURE:
1111         g_printerr (_("ERROR: Pipeline doesn't want to pause.\n"));
1112         res = -1;
1113         event_loop (pipeline, FALSE, GST_STATE_VOID_PENDING);
1114         goto end;
1115       case GST_STATE_CHANGE_NO_PREROLL:
1116         PRINT (_("Pipeline is live and does not need PREROLL ...\n"));
1117         is_live = TRUE;
1118         break;
1119       case GST_STATE_CHANGE_ASYNC:
1120         PRINT (_("Pipeline is PREROLLING ...\n"));
1121         caught_error = event_loop (pipeline, TRUE, GST_STATE_PAUSED);
1122         if (caught_error) {
1123           g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1124           goto end;
1125         }
1126         state = GST_STATE_PAUSED;
1127         /* fallthrough */
1128       case GST_STATE_CHANGE_SUCCESS:
1129         PRINT (_("Pipeline is PREROLLED ...\n"));
1130         break;
1131     }
1133     caught_error = event_loop (pipeline, FALSE, GST_STATE_PLAYING);
1135     if (caught_error) {
1136       g_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
1137     } else {
1138       GstClockTime tfthen, tfnow;
1139       GstClockTimeDiff diff;
1141       PRINT (_("Setting pipeline to PLAYING ...\n"));
1143       if (gst_element_set_state (pipeline,
1144               GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
1145         GstMessage *err_msg;
1146         GstBus *bus;
1148         g_printerr (_("ERROR: pipeline doesn't want to play.\n"));
1149         bus = gst_element_get_bus (pipeline);
1150         if ((err_msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0))) {
1151           print_error_message (err_msg);
1152           gst_message_unref (err_msg);
1153         }
1154         gst_object_unref (bus);
1155         res = -1;
1156         goto end;
1157       }
1159       tfthen = gst_util_get_timestamp ();
1160       do {
1161         caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1162         if (loop && (caught_error == ELR_NO_ERROR)) {
1163           PRINT (_("Looping ...\n"));
1164           gst_element_seek (pipeline, 1.0,
1165               GST_FORMAT_TIME,
1166               GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT,
1167               GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
1168         } else {
1169           break;
1170         }
1171       } while (TRUE);
1172       if (eos_on_shutdown && caught_error == ELR_INTERRUPT) {
1173         PRINT (_("EOS on shutdown enabled -- Forcing EOS on the pipeline\n"));
1174         waiting_eos = TRUE;
1175         gst_element_send_event (pipeline, gst_event_new_eos ());
1176         PRINT (_("Waiting for EOS...\n"));
1177         caught_error = event_loop (pipeline, TRUE, GST_STATE_PLAYING);
1179         if (caught_error == ELR_NO_ERROR) {
1180           /* we got EOS */
1181           PRINT (_("EOS received - stopping pipeline...\n"));
1182         } else if (caught_error == ELR_ERROR) {
1183           PRINT (_("An error happened while waiting for EOS\n"));
1184         }
1185       }
1186       tfnow = gst_util_get_timestamp ();
1188       diff = GST_CLOCK_DIFF (tfthen, tfnow);
1190       PRINT (_("Execution ended after %" G_GUINT64_FORMAT " ns.\n"), diff);
1191     }
1193     PRINT (_("Setting pipeline to PAUSED ...\n"));
1194     gst_element_set_state (pipeline, GST_STATE_PAUSED);
1195     if (caught_error == ELR_NO_ERROR)
1196       gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1198     /* iterate mainloop to process pending stuff */
1199     while (g_main_context_iteration (NULL, FALSE));
1201     PRINT (_("Setting pipeline to READY ...\n"));
1202     gst_element_set_state (pipeline, GST_STATE_READY);
1203     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1205     if (check_index) {
1206       print_index_stats (index_stats);
1207       g_ptr_array_free (index_stats, TRUE);
1208     }
1210   end:
1211     PRINT (_("Setting pipeline to NULL ...\n"));
1212     gst_element_set_state (pipeline, GST_STATE_NULL);
1213     gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);
1214   }
1216   PRINT (_("Freeing pipeline ...\n"));
1217   gst_object_unref (pipeline);
1219   gst_deinit ();
1220   if (trace)
1221     gst_alloc_trace_print_live ();
1223   return res;