First THREADED backport attempt, focusing on adding locks and making sure the API...
[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., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 /* FIXME: hack alert */
29 #ifdef _MSC_VER
30 #define DISABLE_FAULT_HANDLER
31 #endif
32
33 #include <string.h>
34 #include <stdlib.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 "gst/gst-i18n-app.h"
44
45 #include <gst/gst.h>
46
47 /* FIXME: This is just a temporary hack.  We should have a better
48  * check for siginfo handling. */
49 #ifdef SA_SIGINFO
50 #define USE_SIGINFO
51 #endif
52
53 extern volatile gboolean glib_on_error_halt;
54
55 #ifndef DISABLE_FAULT_HANDLER
56 static void fault_restore (void);
57 static void fault_spin (void);
58 static void sigint_restore (void);
59 #endif
60
61 static gint max_iterations = 0;
62 static guint64 iterations = 0;
63 static guint64 sum = 0;
64 static guint64 min = G_MAXINT64;
65 static guint64 max = 0;
66 static GstClock *s_clock;
67 static GstElement *pipeline;
68 static gboolean caught_intr = FALSE;
69 static gboolean caught_error = FALSE;
70 static gboolean need_new_state = FALSE;
71 static GstElementState new_state;
72 static GMainLoop *loop;
73
74 gboolean
75 idle_func (gpointer data)
76 {
77   gboolean busy;
78   GTimeVal tfthen, tfnow;
79   GstClockTimeDiff diff;
80
81   g_get_current_time (&tfthen);
82   busy = gst_bin_iterate (GST_BIN (data));
83   iterations++;
84   g_get_current_time (&tfnow);
85
86   diff = GST_TIMEVAL_TO_TIME (tfnow) - GST_TIMEVAL_TO_TIME (tfthen);
87
88   sum += diff;
89   min = MIN (min, diff);
90   max = MAX (max, diff);
91
92   if (need_new_state) {
93     gst_element_set_state (pipeline, new_state);
94     need_new_state = FALSE;
95   }
96
97   if (!busy || caught_intr || caught_error ||
98       (max_iterations > 0 && iterations >= max_iterations)) {
99     char *s_iterations;
100     char *s_sum;
101     char *s_ave;
102     char *s_min;
103     char *s_max;
104
105     g_main_loop_quit (loop);
106     g_main_loop_unref (loop);
107
108     /* We write these all to strings first because 
109      * G_GUINT64_FORMAT and gettext mix very poorly */
110     s_iterations = g_strdup_printf ("%" G_GUINT64_FORMAT, iterations);
111     s_sum = g_strdup_printf ("%" G_GUINT64_FORMAT, sum);
112     s_ave = g_strdup_printf ("%" G_GUINT64_FORMAT, sum / iterations);
113     s_min = g_strdup_printf ("%" G_GUINT64_FORMAT, min);
114     s_max = g_strdup_printf ("%" G_GUINT64_FORMAT, max);
115
116     g_print (_("Execution ended after %s iterations (sum %s ns, "
117             "average %s ns, min %s ns, max %s ns).\n"),
118         s_iterations, s_sum, s_ave, s_min, s_max);
119     g_free (s_iterations);
120     g_free (s_sum);
121     g_free (s_ave);
122     g_free (s_min);
123     g_free (s_max);
124   }
125
126   return busy;
127 }
128
129 #ifndef GST_DISABLE_LOADSAVE
130 static GstElement *
131 xmllaunch_parse_cmdline (const gchar ** argv)
132 {
133   GstElement *pipeline = NULL, *e;
134   GstXML *xml;
135   gboolean err;
136   const gchar *arg;
137   gchar *element, *property, *value;
138   GList *l;
139   gint i = 0;
140
141   if (!(arg = argv[0])) {
142     g_print (_
143         ("Usage: gst-xmllaunch <file.xml> [ element.property=value ... ]\n"));
144     exit (1);
145   }
146
147   xml = gst_xml_new ();
148   err = gst_xml_parse_file (xml, arg, NULL);
149
150   if (err != TRUE) {
151     fprintf (stderr, _("ERROR: parse of xml file '%s' failed.\n"), arg);
152     exit (1);
153   }
154
155   l = gst_xml_get_topelements (xml);
156   if (!l) {
157     fprintf (stderr, _("ERROR: no toplevel pipeline element in file '%s'.\n"),
158         arg);
159     exit (1);
160   }
161
162   if (l->next)
163     fprintf (stderr,
164         _("WARNING: only one toplevel element is supported at this time."));
165
166   pipeline = GST_ELEMENT (l->data);
167
168   while ((arg = argv[++i])) {
169     element = g_strdup (arg);
170     property = strchr (element, '.');
171     value = strchr (element, '=');
172
173     if (!(element < property && property < value)) {
174       fprintf (stderr,
175           _("ERROR: could not parse command line argument %d: %s.\n"), i,
176           element);
177       g_free (element);
178       exit (1);
179     }
180
181     *property++ = '\0';
182     *value++ = '\0';
183
184     e = gst_bin_get_by_name (GST_BIN (pipeline), element);
185     if (!e) {
186       fprintf (stderr, _("WARNING: element named '%s' not found.\n"), element);
187     } else {
188       gst_util_set_object_arg (G_OBJECT (e), property, value);
189     }
190     g_free (element);
191   }
192
193   if (!l)
194     return NULL;
195   else
196     return l->data;
197 }
198 #endif
199
200 #ifndef DISABLE_FAULT_HANDLER
201 #ifndef USE_SIGINFO
202 static void
203 fault_handler_sighandler (int signum)
204 {
205   fault_restore ();
206
207   /* printf is used instead of g_print(), since it's less likely to
208    * deadlock */
209   switch (signum) {
210     case SIGSEGV:
211       printf ("Caught SIGSEGV\n");
212       break;
213     case SIGQUIT:
214       printf ("Caught SIGQUIT\n");
215       break;
216     default:
217       printf ("signo:  %d\n", signum);
218       break;
219   }
220
221   fault_spin ();
222 }
223
224 #else
225
226 static void
227 fault_handler_sigaction (int signum, siginfo_t * si, void *misc)
228 {
229   fault_restore ();
230
231   /* printf is used instead of g_print(), since it's less likely to
232    * deadlock */
233   switch (si->si_signo) {
234     case SIGSEGV:
235       printf ("Caught SIGSEGV accessing address %p\n", si->si_addr);
236       break;
237     case SIGQUIT:
238       printf ("Caught SIGQUIT\n");
239       break;
240     default:
241       printf ("signo:  %d\n", si->si_signo);
242       printf ("errno:  %d\n", si->si_errno);
243       printf ("code:   %d\n", si->si_code);
244       break;
245   }
246
247   fault_spin ();
248 }
249 #endif
250
251 static void
252 fault_spin (void)
253 {
254   int spinning = TRUE;
255
256   glib_on_error_halt = FALSE;
257   g_on_error_stack_trace ("gst-launch");
258
259   wait (NULL);
260
261   /* FIXME how do we know if we were run by libtool? */
262   printf ("Spinning.  Please run 'gdb gst-launch %d' to continue debugging, "
263       "Ctrl-C to quit, or Ctrl-\\ to dump core.\n", (gint) getpid ());
264   while (spinning)
265     g_usleep (1000000);
266 }
267
268 static void
269 fault_restore (void)
270 {
271   struct sigaction action;
272
273   memset (&action, 0, sizeof (action));
274   action.sa_handler = SIG_DFL;
275
276   sigaction (SIGSEGV, &action, NULL);
277   sigaction (SIGQUIT, &action, NULL);
278 }
279
280 static void
281 fault_setup (void)
282 {
283   struct sigaction action;
284
285   memset (&action, 0, sizeof (action));
286 #ifdef USE_SIGINFO
287   action.sa_sigaction = fault_handler_sigaction;
288   action.sa_flags = SA_SIGINFO;
289 #else
290   action.sa_handler = fault_handler_sighandler;
291 #endif
292
293   sigaction (SIGSEGV, &action, NULL);
294   sigaction (SIGQUIT, &action, NULL);
295 }
296 #endif
297
298 static void
299 print_tag (const GstTagList * list, const gchar * tag, gpointer unused)
300 {
301   gint i, count;
302
303   count = gst_tag_list_get_tag_size (list, tag);
304
305   for (i = 0; i < count; i++) {
306     gchar *str;
307
308     if (gst_tag_get_type (tag) == G_TYPE_STRING) {
309       if (!gst_tag_list_get_string_index (list, tag, i, &str))
310         g_assert_not_reached ();
311     } else {
312       str =
313           g_strdup_value_contents (gst_tag_list_get_value_index (list, tag, i));
314     }
315
316     if (i == 0) {
317       g_print ("%15s: %s\n", gst_tag_get_nick (tag), str);
318     } else {
319       g_print ("               : %s\n", str);
320     }
321
322     g_free (str);
323   }
324 }
325
326 static void
327 found_tag (GObject * pipeline, GstElement * source, GstTagList * tags)
328 {
329   g_print (_("FOUND TAG      : found by element \"%s\".\n"),
330       GST_STR_NULL (GST_ELEMENT_NAME (source)));
331   gst_tag_list_foreach (tags, print_tag, NULL);
332 }
333
334 static void
335 error_cb (GObject * object, GstObject * source, GError * error, gchar * debug)
336 {
337   gst_element_default_error (object, source, error, debug);
338   caught_error = TRUE;
339 }
340
341 #ifndef DISABLE_FAULT_HANDLER
342 /* we only use sighandler here because the registers are not important */
343 static void
344 sigint_handler_sighandler (int signum)
345 {
346   sigint_restore ();
347
348   caught_intr = TRUE;
349 }
350
351 static void
352 sigint_setup (void)
353 {
354   struct sigaction action;
355
356   memset (&action, 0, sizeof (action));
357   action.sa_handler = sigint_handler_sighandler;
358
359   sigaction (SIGINT, &action, NULL);
360 }
361
362 static void
363 sigint_restore (void)
364 {
365   struct sigaction action;
366
367   memset (&action, 0, sizeof (action));
368   action.sa_handler = SIG_DFL;
369
370   sigaction (SIGINT, &action, NULL);
371 }
372
373 static void
374 play_handler (int signum)
375 {
376   switch (signum) {
377     case SIGUSR1:
378       new_state = GST_STATE_PLAYING;
379       need_new_state = TRUE;
380       break;
381     case SIGUSR2:
382       new_state = GST_STATE_NULL;
383       need_new_state = TRUE;
384       break;
385   }
386 }
387
388 static void
389 play_signal_setup (void)
390 {
391   struct sigaction action;
392
393   memset (&action, 0, sizeof (action));
394   action.sa_handler = play_handler;
395   sigaction (SIGUSR1, &action, NULL);
396   sigaction (SIGUSR2, &action, NULL);
397 }
398 #endif
399
400 int
401 main (int argc, char *argv[])
402 {
403   gint i, j;
404
405   /* options */
406   gboolean verbose = FALSE;
407   gboolean tags = FALSE;
408   gboolean no_fault = FALSE;
409   gboolean trace = FALSE;
410   gchar *savefile = NULL;
411   gchar *exclude_args = NULL;
412   struct poptOption options[] = {
413     {"tags", 't', POPT_ARG_NONE | POPT_ARGFLAG_STRIP, &tags, 0,
414         N_("Output tags (also known as metadata)"), NULL},
415     {"verbose", 'v', POPT_ARG_NONE | POPT_ARGFLAG_STRIP, &verbose, 0,
416         N_("Output status information and property notifications"), NULL},
417     {"exclude", 'X', POPT_ARG_STRING | POPT_ARGFLAG_STRIP, &exclude_args, 0,
418         N_("Do not output status information of TYPE"), N_("TYPE1,TYPE2,...")},
419 #ifndef GST_DISABLE_LOADSAVE
420     {"output", 'o', POPT_ARG_STRING | POPT_ARGFLAG_STRIP, &savefile, 0,
421         N_("Save xml representation of pipeline to FILE and exit"), N_("FILE")},
422 #endif
423     {"no-fault", 'f', POPT_ARG_NONE | POPT_ARGFLAG_STRIP, &no_fault, 0,
424         N_("Do not install a fault handler"), NULL},
425     {"trace", 'T', POPT_ARG_NONE | POPT_ARGFLAG_STRIP, &trace, 0,
426         N_("Print alloc trace (if enabled at compile time)"), NULL},
427     {"iterations", 'i', POPT_ARG_INT | POPT_ARGFLAG_STRIP, &max_iterations, 0,
428         N_("Number of times to iterate pipeline"), NULL},
429     POPT_TABLEEND
430   };
431
432   gchar **argvn;
433   GError *error = NULL;
434   gint res = 0;
435
436   free (malloc (8));            /* -lefence */
437
438 #ifdef GETTEXT_PACKAGE
439   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
440   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
441   textdomain (GETTEXT_PACKAGE);
442 #endif
443
444   gst_alloc_trace_set_flags_all (GST_ALLOC_TRACE_LIVE);
445
446   gst_init_with_popt_table (&argc, &argv, options);
447
448   /* FIXpopt: strip short args, too. We do it ourselves for now */
449   j = 1;
450   for (i = 1; i < argc; i++) {
451     if (*(argv[i]) == '-') {
452       if (strlen (argv[i]) == 2) {
453         gchar *c = argv[i];
454
455         c++;
456         if (*c == 'X' || *c == 'o') {
457           i++;
458         }
459       }
460     } else {
461       argv[j] = argv[i];
462       j++;
463     }
464   }
465   argc = j;
466
467 #ifndef DISABLE_FAULT_HANDLER
468   if (!no_fault)
469     fault_setup ();
470
471   sigint_setup ();
472   play_signal_setup ();
473 #endif
474
475   if (trace) {
476     if (!gst_alloc_trace_available ()) {
477       g_warning ("Trace not available (recompile with trace enabled).");
478     }
479     gst_alloc_trace_print_all ();
480   }
481
482   /* make a null-terminated version of argv */
483   argvn = g_new0 (char *, argc);
484   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
485 #ifndef GST_DISABLE_LOADSAVE
486   if (strstr (argv[0], "gst-xmllaunch")) {
487     pipeline = xmllaunch_parse_cmdline ((const gchar **) argvn);
488   } else
489 #endif
490   {
491     pipeline =
492         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
493   }
494   g_free (argvn);
495
496   if (!pipeline) {
497     if (error) {
498       fprintf (stderr, _("ERROR: pipeline could not be constructed: %s.\n"),
499           error->message);
500       g_error_free (error);
501     } else {
502       fprintf (stderr, _("ERROR: pipeline could not be constructed.\n"));
503     }
504     return 1;
505   } else if (error) {
506     fprintf (stderr, _("WARNING: erroneous pipeline: %s\n"), error->message);
507     fprintf (stderr, _("         Trying to run anyway.\n"));
508     g_error_free (error);
509   }
510
511   if (verbose) {
512     gchar **exclude_list =
513         exclude_args ? g_strsplit (exclude_args, ",", 0) : NULL;
514     g_signal_connect (pipeline, "deep_notify",
515         G_CALLBACK (gst_element_default_deep_notify), exclude_list);
516   }
517   if (tags) {
518     g_signal_connect (pipeline, "found-tag", G_CALLBACK (found_tag), NULL);
519   }
520   g_signal_connect (pipeline, "error", G_CALLBACK (error_cb), NULL);
521
522 #ifndef GST_DISABLE_LOADSAVE
523   if (savefile) {
524     gst_xml_write_file (GST_ELEMENT (pipeline), fopen (savefile, "w"));
525   }
526 #endif
527
528   if (!savefile) {
529
530     if (!GST_IS_BIN (pipeline)) {
531       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
532
533       if (real_pipeline == NULL) {
534         fprintf (stderr, _("ERROR: the 'pipeline' element wasn't found.\n"));
535         return 1;
536       }
537       gst_bin_add (GST_BIN (real_pipeline), pipeline);
538       pipeline = real_pipeline;
539     }
540
541     fprintf (stderr, _("RUNNING pipeline ...\n"));
542     if (gst_element_set_state (pipeline,
543             GST_STATE_PLAYING) == GST_STATE_FAILURE) {
544       fprintf (stderr, _("ERROR: pipeline doesn't want to play.\n"));
545       res = -1;
546       goto end;
547     }
548
549     s_clock = gst_element_get_clock (GST_ELEMENT (pipeline));
550
551     if (!GST_FLAG_IS_SET (GST_OBJECT (pipeline), GST_BIN_SELF_SCHEDULABLE)) {
552       g_idle_add (idle_func, pipeline);
553       loop = g_main_loop_new (NULL, FALSE);
554       g_main_loop_run (loop);
555     } else {
556       g_print ("Waiting for the state change... ");
557       gst_element_wait_state_change (pipeline);
558       g_print ("got the state change.\n");
559     }
560     if (caught_intr) {
561       g_print ("Caught interrupt.\n");
562       res = 2;
563     }
564     if (caught_error)
565       res = 3;
566
567     gst_element_set_state (pipeline, GST_STATE_NULL);
568   }
569
570 end:
571
572   gst_object_unref (GST_OBJECT (pipeline));
573
574   if (trace)
575     gst_alloc_trace_print_all ();
576
577   return res;
578 }