• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <io.h>
42 #ifndef STDOUT_FILENO
43 #define STDOUT_FILENO 1
44 #endif
45 #define isatty _isatty
46 #endif
47 #include <locale.h>             /* for LC_ALL */
48 #include "tools.h"
49 #ifdef HAVE_WINMM
50 #include <mmsystem.h>
51 #endif
52 
53 extern volatile gboolean glib_on_error_halt;
54 
55 #ifdef G_OS_UNIX
56 static void fault_restore (void);
57 static void fault_spin (void);
58 #endif
59 
60 /* exit codes */
61 typedef enum _LaunchExitCode
62 {
63   LEC_STATE_CHANGE_FAILURE = -1,
64   LEC_NO_ERROR = 0,
65   LEC_ERROR,
66   LEC_INTERRUPT
67 } LaunchExitCode;
68 
69 static GMainLoop *loop = NULL;
70 static GstElement *pipeline = NULL;
71 
72 /* options */
73 static gboolean quiet = FALSE;
74 static gboolean tags = FALSE;
75 static gboolean toc = FALSE;
76 static gboolean messages = FALSE;
77 static gboolean eos_on_shutdown = FALSE;
78 static gchar **exclude_args = NULL;
79 
80 /* pipeline status */
81 static gboolean is_live = FALSE;
82 static gboolean buffering = FALSE;
83 static LaunchExitCode last_launch_code = LEC_NO_ERROR;
84 static GstState target_state = GST_STATE_PAUSED;
85 static gboolean prerolled = FALSE;
86 static gboolean in_progress = FALSE;
87 static GstClockTime tfthen = GST_CLOCK_TIME_NONE;
88 static gboolean interrupting = FALSE;
89 static gboolean waiting_eos = FALSE;
90 
91 /* convenience macro so we don't have to litter the code with if(!quiet) */
92 #define PRINT if(!quiet)gst_print
93 
94 #ifdef G_OS_UNIX
95 static void
fault_handler_sighandler(int signum)96 fault_handler_sighandler (int signum)
97 {
98   fault_restore ();
99 
100   /* printf is used instead of gst_print(), since it's less likely to
101    * deadlock */
102   switch (signum) {
103     case SIGSEGV:
104       fprintf (stderr, "Caught SIGSEGV\n");
105       break;
106     case SIGQUIT:
107       if (!quiet)
108         printf ("Caught SIGQUIT\n");
109       break;
110     default:
111       fprintf (stderr, "signo:  %d\n", signum);
112       break;
113   }
114 
115   fault_spin ();
116 }
117 
118 static void
fault_spin(void)119 fault_spin (void)
120 {
121   int spinning = TRUE;
122 
123   glib_on_error_halt = FALSE;
124   g_on_error_stack_trace ("gst-launch-" GST_API_VERSION);
125 
126   wait (NULL);
127 
128   /* FIXME how do we know if we were run by libtool? */
129   fprintf (stderr,
130       "Spinning.  Please run 'gdb gst-launch-" GST_API_VERSION " %d' to "
131       "continue debugging, Ctrl-C to quit, or Ctrl-\\ to dump core.\n",
132       (gint) getpid ());
133   while (spinning)
134     g_usleep (1000000);
135 }
136 
137 static void
fault_restore(void)138 fault_restore (void)
139 {
140   struct sigaction action;
141 
142   memset (&action, 0, sizeof (action));
143   action.sa_handler = SIG_DFL;
144 
145   sigaction (SIGSEGV, &action, NULL);
146   sigaction (SIGQUIT, &action, NULL);
147 }
148 
149 static void
fault_setup(void)150 fault_setup (void)
151 {
152   struct sigaction action;
153 
154   memset (&action, 0, sizeof (action));
155   action.sa_handler = fault_handler_sighandler;
156 
157   sigaction (SIGSEGV, &action, NULL);
158   sigaction (SIGQUIT, &action, NULL);
159 }
160 #endif /* G_OS_UNIX */
161 
162 #if 0
163 typedef struct _GstIndexStats
164 {
165   gint id;
166   gchar *desc;
167 
168   guint num_frames;
169   guint num_keyframes;
170   guint num_dltframes;
171   GstClockTime last_keyframe;
172   GstClockTime last_dltframe;
173   GstClockTime min_keyframe_gap;
174   GstClockTime max_keyframe_gap;
175   GstClockTime avg_keyframe_gap;
176 } GstIndexStats;
177 
178 static void
179 entry_added (GstIndex * index, GstIndexEntry * entry, gpointer user_data)
180 {
181   GPtrArray *index_stats = (GPtrArray *) user_data;
182   GstIndexStats *s;
183 
184   switch (entry->type) {
185     case GST_INDEX_ENTRY_ID:
186       /* we have a new writer */
187       GST_DEBUG_OBJECT (index, "id %d: describes writer %s", entry->id,
188           GST_INDEX_ID_DESCRIPTION (entry));
189       if (entry->id >= index_stats->len) {
190         g_ptr_array_set_size (index_stats, entry->id + 1);
191       }
192       s = g_new (GstIndexStats, 1);
193       s->id = entry->id;
194       s->desc = g_strdup (GST_INDEX_ID_DESCRIPTION (entry));
195       s->num_frames = s->num_keyframes = s->num_dltframes = 0;
196       s->last_keyframe = s->last_dltframe = GST_CLOCK_TIME_NONE;
197       s->min_keyframe_gap = s->max_keyframe_gap = s->avg_keyframe_gap =
198           GST_CLOCK_TIME_NONE;
199       g_ptr_array_index (index_stats, entry->id) = s;
200       break;
201     case GST_INDEX_ENTRY_FORMAT:
202       /* have not found any code calling this */
203       GST_DEBUG_OBJECT (index, "id %d: registered format %d for %s\n",
204           entry->id, GST_INDEX_FORMAT_FORMAT (entry),
205           GST_INDEX_FORMAT_KEY (entry));
206       break;
207     case GST_INDEX_ENTRY_ASSOCIATION:
208     {
209       gint64 ts;
210       GstAssocFlags flags = GST_INDEX_ASSOC_FLAGS (entry);
211 
212       s = g_ptr_array_index (index_stats, entry->id);
213       gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
214 
215       if (flags & GST_ASSOCIATION_FLAG_KEY_UNIT) {
216         s->num_keyframes++;
217 
218         if (GST_CLOCK_TIME_IS_VALID (ts)) {
219           if (GST_CLOCK_TIME_IS_VALID (s->last_keyframe)) {
220             GstClockTimeDiff d = GST_CLOCK_DIFF (s->last_keyframe, ts);
221 
222             if (G_UNLIKELY (d < 0)) {
223               GST_WARNING ("received out-of-order keyframe at %"
224                   GST_TIME_FORMAT, GST_TIME_ARGS (ts));
225               /* FIXME: does it still make sense to use that for the statistics */
226               d = GST_CLOCK_DIFF (ts, s->last_keyframe);
227             }
228 
229             if (GST_CLOCK_TIME_IS_VALID (s->min_keyframe_gap)) {
230               if (d < s->min_keyframe_gap)
231                 s->min_keyframe_gap = d;
232             } else {
233               s->min_keyframe_gap = d;
234             }
235             if (GST_CLOCK_TIME_IS_VALID (s->max_keyframe_gap)) {
236               if (d > s->max_keyframe_gap)
237                 s->max_keyframe_gap = d;
238             } else {
239               s->max_keyframe_gap = d;
240             }
241             if (GST_CLOCK_TIME_IS_VALID (s->avg_keyframe_gap)) {
242               s->avg_keyframe_gap = (d + s->num_frames * s->avg_keyframe_gap) /
243                   (s->num_frames + 1);
244             } else {
245               s->avg_keyframe_gap = d;
246             }
247           }
248           s->last_keyframe = ts;
249         }
250       }
251       if (flags & GST_ASSOCIATION_FLAG_DELTA_UNIT) {
252         s->num_dltframes++;
253         if (GST_CLOCK_TIME_IS_VALID (ts)) {
254           s->last_dltframe = ts;
255         }
256       }
257       s->num_frames++;
258 
259       break;
260     }
261     default:
262       break;
263   }
264 }
265 
266 /* print statistics from the entry_added callback, free the entries */
267 static void
268 print_index_stats (GPtrArray * index_stats)
269 {
270   gint i;
271 
272   if (index_stats->len) {
273     gst_print ("%s:\n", _("Index statistics"));
274   }
275 
276   for (i = 0; i < index_stats->len; i++) {
277     GstIndexStats *s = g_ptr_array_index (index_stats, i);
278     if (s) {
279       gst_print ("id %d, %s\n", s->id, s->desc);
280       if (s->num_frames) {
281         GstClockTime last_frame = s->last_keyframe;
282 
283         if (GST_CLOCK_TIME_IS_VALID (s->last_dltframe)) {
284           if (!GST_CLOCK_TIME_IS_VALID (last_frame) ||
285               (s->last_dltframe > last_frame))
286             last_frame = s->last_dltframe;
287         }
288 
289         if (GST_CLOCK_TIME_IS_VALID (last_frame)) {
290           gst_print ("  total time               = %" GST_TIME_FORMAT "\n",
291               GST_TIME_ARGS (last_frame));
292         }
293         gst_print ("  frame/keyframe rate      = %u / %u = ", s->num_frames,
294             s->num_keyframes);
295         if (s->num_keyframes)
296           gst_print ("%lf\n", s->num_frames / (gdouble) s->num_keyframes);
297         else
298           gst_print ("-\n");
299         if (s->num_keyframes) {
300           gst_print ("  min/avg/max keyframe gap = %" GST_TIME_FORMAT ", %"
301               GST_TIME_FORMAT ", %" GST_TIME_FORMAT "\n",
302               GST_TIME_ARGS (s->min_keyframe_gap),
303               GST_TIME_ARGS (s->avg_keyframe_gap),
304               GST_TIME_ARGS (s->max_keyframe_gap));
305         }
306       } else {
307         gst_print ("  no stats\n");
308       }
309 
310       g_free (s->desc);
311       g_free (s);
312     }
313   }
314 }
315 #endif
316 
317 /* Kids, use the functions from libgstpbutils in gst-plugins-base in your
318  * own code (we can't do that here because it would introduce a circular
319  * dependency) */
320 static gboolean
gst_is_missing_plugin_message(GstMessage * msg)321 gst_is_missing_plugin_message (GstMessage * msg)
322 {
323   if (GST_MESSAGE_TYPE (msg) != GST_MESSAGE_ELEMENT
324       || gst_message_get_structure (msg) == NULL)
325     return FALSE;
326 
327   return gst_structure_has_name (gst_message_get_structure (msg),
328       "missing-plugin");
329 }
330 
331 static const gchar *
gst_missing_plugin_message_get_description(GstMessage * msg)332 gst_missing_plugin_message_get_description (GstMessage * msg)
333 {
334   return gst_structure_get_string (gst_message_get_structure (msg), "name");
335 }
336 
337 static void
print_error_message(GstMessage * msg)338 print_error_message (GstMessage * msg)
339 {
340   GError *err = NULL;
341   gchar *name, *debug = NULL;
342 
343   name = gst_object_get_path_string (msg->src);
344   gst_message_parse_error (msg, &err, &debug);
345 
346   gst_printerr (_("ERROR: from element %s: %s\n"), name, err->message);
347   if (debug != NULL)
348     gst_printerr (_("Additional debug info:\n%s\n"), debug);
349 
350   g_clear_error (&err);
351   g_free (debug);
352   g_free (name);
353 }
354 
355 static void
print_tag(const GstTagList * list,const gchar * tag,gpointer unused)356 print_tag (const GstTagList * list, const gchar * tag, gpointer unused)
357 {
358   gint i, count;
359 
360   count = gst_tag_list_get_tag_size (list, tag);
361 
362   for (i = 0; i < count; i++) {
363     gchar *str = NULL;
364 
365     if (gst_tag_get_type (tag) == G_TYPE_STRING) {
366       if (!gst_tag_list_get_string_index (list, tag, i, &str)) {
367         g_warning ("Couldn't fetch string for %s tag", tag);
368         g_assert_not_reached ();
369       }
370     } else if (gst_tag_get_type (tag) == GST_TYPE_SAMPLE) {
371       GstSample *sample = NULL;
372 
373       if (gst_tag_list_get_sample_index (list, tag, i, &sample)) {
374         GstBuffer *img = gst_sample_get_buffer (sample);
375         GstCaps *caps = gst_sample_get_caps (sample);
376 
377         if (img) {
378           if (caps) {
379             gchar *caps_str;
380 
381             caps_str = gst_caps_to_string (caps);
382             str = g_strdup_printf ("buffer of %" G_GSIZE_FORMAT " bytes, "
383                 "type: %s", gst_buffer_get_size (img), caps_str);
384             g_free (caps_str);
385           } else {
386             str = g_strdup_printf ("buffer of %" G_GSIZE_FORMAT " bytes",
387                 gst_buffer_get_size (img));
388           }
389         } else {
390           str = g_strdup ("NULL buffer");
391         }
392       } else {
393         g_warning ("Couldn't fetch sample for %s tag", tag);
394         g_assert_not_reached ();
395       }
396       gst_sample_unref (sample);
397     } else if (gst_tag_get_type (tag) == GST_TYPE_DATE_TIME) {
398       GstDateTime *dt = NULL;
399 
400       gst_tag_list_get_date_time_index (list, tag, i, &dt);
401       if (!gst_date_time_has_time (dt)) {
402         str = gst_date_time_to_iso8601_string (dt);
403       } else {
404         gdouble tz_offset = gst_date_time_get_time_zone_offset (dt);
405         gchar tz_str[32];
406 
407         if (tz_offset != 0.0) {
408           g_snprintf (tz_str, sizeof (tz_str), "(UTC %s%gh)",
409               (tz_offset > 0.0) ? "+" : "", tz_offset);
410         } else {
411           g_snprintf (tz_str, sizeof (tz_str), "(UTC)");
412         }
413 
414         str = g_strdup_printf ("%04u-%02u-%02u %02u:%02u:%02u %s",
415             gst_date_time_get_year (dt), gst_date_time_get_month (dt),
416             gst_date_time_get_day (dt), gst_date_time_get_hour (dt),
417             gst_date_time_get_minute (dt), gst_date_time_get_second (dt),
418             tz_str);
419       }
420       gst_date_time_unref (dt);
421     } else {
422       str =
423           g_strdup_value_contents (gst_tag_list_get_value_index (list, tag, i));
424     }
425 
426     if (str) {
427       PRINT ("%16s: %s\n", i == 0 ? gst_tag_get_nick (tag) : "", str);
428       g_free (str);
429     }
430   }
431 }
432 
433 static void
print_tag_foreach(const GstTagList * tags,const gchar * tag,gpointer user_data)434 print_tag_foreach (const GstTagList * tags, const gchar * tag,
435     gpointer user_data)
436 {
437   GValue val = { 0, };
438   gchar *str;
439   gint depth = GPOINTER_TO_INT (user_data);
440 
441   if (!gst_tag_list_copy_value (&val, tags, tag))
442     return;
443 
444   if (G_VALUE_HOLDS_STRING (&val))
445     str = g_value_dup_string (&val);
446   else
447     str = gst_value_serialize (&val);
448 
449   gst_print ("%*s%s: %s\n", 2 * depth, " ", gst_tag_get_nick (tag), str);
450   g_free (str);
451 
452   g_value_unset (&val);
453 }
454 
455 #define MAX_INDENT 40
456 
457 static void
print_toc_entry(gpointer data,gpointer user_data)458 print_toc_entry (gpointer data, gpointer user_data)
459 {
460   GstTocEntry *entry = (GstTocEntry *) data;
461   const gchar spc[MAX_INDENT + 1] = "                                        ";
462   guint indent = MIN (GPOINTER_TO_UINT (user_data), MAX_INDENT);
463   const GstTagList *tags;
464   GList *subentries;
465   gint64 start, stop;
466 
467   gst_toc_entry_get_start_stop_times (entry, &start, &stop);
468 
469   PRINT ("%s%s:", &spc[MAX_INDENT - indent],
470       gst_toc_entry_type_get_nick (gst_toc_entry_get_entry_type (entry)));
471   if (GST_CLOCK_TIME_IS_VALID (start)) {
472     PRINT (" start: %" GST_TIME_FORMAT, GST_TIME_ARGS (start));
473   }
474   if (GST_CLOCK_TIME_IS_VALID (stop)) {
475     PRINT (" stop: %" GST_TIME_FORMAT, GST_TIME_ARGS (stop));
476   }
477   PRINT ("\n");
478   indent += 2;
479 
480   /* print tags */
481   tags = gst_toc_entry_get_tags (entry);
482   if (tags)
483     gst_tag_list_foreach (tags, print_tag_foreach, GUINT_TO_POINTER (indent));
484 
485   /* loop over sub-toc entries */
486   subentries = gst_toc_entry_get_sub_entries (entry);
487   g_list_foreach (subentries, print_toc_entry, GUINT_TO_POINTER (indent));
488 }
489 
490 #ifdef G_OS_UNIX
491 static guint signal_watch_hup_id;
492 #endif
493 #if defined(G_OS_UNIX) || defined(G_OS_WIN32)
494 static guint signal_watch_intr_id;
495 #endif
496 
497 #if defined(G_OS_UNIX) || defined(G_OS_WIN32)
498 /* As the interrupt handler is dispatched from GMainContext as a GSourceFunc
499  * handler, we can react to this by posting a message. */
500 static gboolean
intr_handler(gpointer user_data)501 intr_handler (gpointer user_data)
502 {
503   GstElement *pipeline = (GstElement *) user_data;
504 
505   PRINT ("handling interrupt.\n");
506 
507   /* post an application specific message */
508   gst_element_post_message (GST_ELEMENT (pipeline),
509       gst_message_new_application (GST_OBJECT (pipeline),
510           gst_structure_new ("GstLaunchInterrupt",
511               "message", G_TYPE_STRING, "Pipeline interrupted", NULL)));
512 
513   /* remove signal handler */
514   signal_watch_intr_id = 0;
515   return G_SOURCE_REMOVE;
516 }
517 
518 #ifdef G_OS_UNIX
519 static gboolean
hup_handler(gpointer user_data)520 hup_handler (gpointer user_data)
521 {
522   GstElement *pipeline = (GstElement *) user_data;
523 
524   if (g_getenv ("GST_DEBUG_DUMP_DOT_DIR") != NULL) {
525     PRINT ("SIGHUP: dumping dot file snapshot ...\n");
526   } else {
527     PRINT ("SIGHUP: not dumping dot file snapshot, GST_DEBUG_DUMP_DOT_DIR "
528         "environment variable not set.\n");
529   }
530 
531   /* dump graph on hup */
532   GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
533       GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.snapshot");
534 
535   return G_SOURCE_CONTINUE;
536 }
537 #endif
538 
539 #if defined(G_OS_WIN32)         /* G_OS_UNIX */
540 static BOOL WINAPI
w32_intr_handler(DWORD dwCtrlType)541 w32_intr_handler (DWORD dwCtrlType)
542 {
543   if (pipeline)
544     intr_handler ((gpointer) pipeline);
545 
546   SetConsoleCtrlHandler (w32_intr_handler, FALSE);
547 
548   return TRUE;
549 }
550 #endif /* G_OS_WIN32 */
551 #endif /* G_OS_UNIX */
552 
553 static void
do_initial_play(GstElement * pipeline)554 do_initial_play (GstElement * pipeline)
555 {
556   PRINT (_("Setting pipeline to PLAYING ...\n"));
557 
558   tfthen = gst_util_get_timestamp ();
559 
560   if (gst_element_set_state (pipeline,
561           GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
562     gst_printerr (_("ERROR: pipeline doesn't want to play.\n"));
563     last_launch_code = LEC_STATE_CHANGE_FAILURE;
564 
565     /* error message will be posted later */
566     return;
567   }
568 
569   target_state = GST_STATE_PLAYING;
570 }
571 
572 static gboolean
bus_handler(GstBus * bus,GstMessage * message,gpointer data)573 bus_handler (GstBus * bus, GstMessage * message, gpointer data)
574 {
575   {
576     if (messages) {
577       GstObject *src_obj;
578       const GstStructure *s;
579       guint32 seqnum;
580 
581       seqnum = gst_message_get_seqnum (message);
582 
583       s = gst_message_get_structure (message);
584 
585       src_obj = GST_MESSAGE_SRC (message);
586 
587       if (GST_IS_ELEMENT (src_obj)) {
588         PRINT (_("Got message #%u from element \"%s\" (%s): "),
589             (guint) seqnum, GST_ELEMENT_NAME (src_obj),
590             GST_MESSAGE_TYPE_NAME (message));
591       } else if (GST_IS_PAD (src_obj)) {
592         PRINT (_("Got message #%u from pad \"%s:%s\" (%s): "),
593             (guint) seqnum, GST_DEBUG_PAD_NAME (src_obj),
594             GST_MESSAGE_TYPE_NAME (message));
595       } else if (GST_IS_OBJECT (src_obj)) {
596         PRINT (_("Got message #%u from object \"%s\" (%s): "),
597             (guint) seqnum, GST_OBJECT_NAME (src_obj),
598             GST_MESSAGE_TYPE_NAME (message));
599       } else {
600         PRINT (_("Got message #%u (%s): "), (guint) seqnum,
601             GST_MESSAGE_TYPE_NAME (message));
602       }
603 
604       if (s) {
605         gchar *sstr;
606 
607         sstr = gst_structure_to_string (s);
608         PRINT ("%s\n", sstr);
609         g_free (sstr);
610       } else {
611         PRINT ("no message details\n");
612       }
613     }
614 
615     switch (GST_MESSAGE_TYPE (message)) {
616       case GST_MESSAGE_NEW_CLOCK:
617       {
618         GstClock *clock;
619 
620         gst_message_parse_new_clock (message, &clock);
621 
622         PRINT ("New clock: %s\n", (clock ? GST_OBJECT_NAME (clock) : "NULL"));
623         break;
624       }
625       case GST_MESSAGE_CLOCK_LOST:
626         PRINT ("Clock lost, selecting a new one\n");
627         gst_element_set_state (pipeline, GST_STATE_PAUSED);
628         gst_element_set_state (pipeline, GST_STATE_PLAYING);
629         break;
630       case GST_MESSAGE_EOS:{
631         PRINT (_("Got EOS from element \"%s\".\n"),
632             GST_MESSAGE_SRC_NAME (message));
633 
634         if (eos_on_shutdown)
635           PRINT (_("EOS received - stopping pipeline...\n"));
636         g_main_loop_quit (loop);
637         break;
638       }
639       case GST_MESSAGE_TAG:
640         if (tags) {
641           GstTagList *tag_list;
642 
643           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
644             PRINT (_("FOUND TAG      : found by element \"%s\".\n"),
645                 GST_MESSAGE_SRC_NAME (message));
646           } else if (GST_IS_PAD (GST_MESSAGE_SRC (message))) {
647             PRINT (_("FOUND TAG      : found by pad \"%s:%s\".\n"),
648                 GST_DEBUG_PAD_NAME (GST_MESSAGE_SRC (message)));
649           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
650             PRINT (_("FOUND TAG      : found by object \"%s\".\n"),
651                 GST_MESSAGE_SRC_NAME (message));
652           } else {
653             PRINT (_("FOUND TAG\n"));
654           }
655 
656           gst_message_parse_tag (message, &tag_list);
657           gst_tag_list_foreach (tag_list, print_tag, NULL);
658           gst_tag_list_unref (tag_list);
659         }
660         break;
661       case GST_MESSAGE_TOC:
662         if (toc) {
663           GstToc *toc;
664           GList *entries;
665           gboolean updated;
666 
667           if (GST_IS_ELEMENT (GST_MESSAGE_SRC (message))) {
668             PRINT (_("FOUND TOC      : found by element \"%s\".\n"),
669                 GST_MESSAGE_SRC_NAME (message));
670           } else if (GST_IS_OBJECT (GST_MESSAGE_SRC (message))) {
671             PRINT (_("FOUND TOC      : found by object \"%s\".\n"),
672                 GST_MESSAGE_SRC_NAME (message));
673           } else {
674             PRINT (_("FOUND TOC\n"));
675           }
676 
677           gst_message_parse_toc (message, &toc, &updated);
678           /* recursively loop over toc entries */
679           entries = gst_toc_get_entries (toc);
680           g_list_foreach (entries, print_toc_entry, GUINT_TO_POINTER (0));
681           gst_toc_unref (toc);
682         }
683         break;
684       case GST_MESSAGE_INFO:{
685         GError *gerror;
686         gchar *debug;
687         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
688 
689         gst_message_parse_info (message, &gerror, &debug);
690         if (debug) {
691           PRINT (_("INFO:\n%s\n"), debug);
692         }
693         g_clear_error (&gerror);
694         g_free (debug);
695         g_free (name);
696         break;
697       }
698       case GST_MESSAGE_WARNING:{
699         GError *gerror;
700         gchar *debug;
701         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
702 
703         /* dump graph on warning */
704         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
705             GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.warning");
706 
707         gst_message_parse_warning (message, &gerror, &debug);
708         PRINT (_("WARNING: from element %s: %s\n"), name, gerror->message);
709         if (debug) {
710           PRINT (_("Additional debug info:\n%s\n"), debug);
711         }
712         g_clear_error (&gerror);
713         g_free (debug);
714         g_free (name);
715         break;
716       }
717       case GST_MESSAGE_STATE_CHANGED:{
718         GstState old, new, pending;
719 
720         /* we only care about pipeline state change messages */
721         if (GST_MESSAGE_SRC (message) != GST_OBJECT_CAST (pipeline))
722           break;
723 
724         gst_message_parse_state_changed (message, &old, &new, &pending);
725 
726         if (target_state == GST_STATE_PAUSED && new == target_state) {
727           prerolled = TRUE;
728 
729           PRINT (_("Pipeline is PREROLLED ...\n"));
730           /* ignore when we are buffering since then we mess with the states
731            * ourselves. */
732           if (buffering) {
733             PRINT (_("Prerolled, waiting for buffering to finish...\n"));
734             break;
735           }
736           if (in_progress) {
737             PRINT (_("Prerolled, waiting for progress to finish...\n"));
738             break;
739           }
740 
741           do_initial_play (pipeline);
742         }
743         /* else not an interesting message */
744         break;
745       }
746       case GST_MESSAGE_BUFFERING:{
747         gint percent;
748 
749         gst_message_parse_buffering (message, &percent);
750         PRINT ("%s %d%%  \r", _("buffering..."), percent);
751 
752         /* no state management needed for live pipelines */
753         if (is_live)
754           break;
755 
756         if (percent == 100) {
757           /* a 100% message means buffering is done */
758           buffering = FALSE;
759 
760           if (target_state == GST_STATE_PAUSED) {
761             do_initial_play (pipeline);
762             break;
763           }
764 
765           /* if the desired state is playing, go back */
766           if (target_state == GST_STATE_PLAYING) {
767             PRINT (_("Done buffering, setting pipeline to PLAYING ...\n"));
768             gst_element_set_state (pipeline, GST_STATE_PLAYING);
769           }
770         } else {
771           /* buffering busy */
772           if (!buffering && target_state == GST_STATE_PLAYING) {
773             /* we were not buffering but PLAYING, PAUSE  the pipeline. */
774             PRINT (_("Buffering, setting pipeline to PAUSED ...\n"));
775             gst_element_set_state (pipeline, GST_STATE_PAUSED);
776           }
777           buffering = TRUE;
778         }
779         break;
780       }
781       case GST_MESSAGE_LATENCY:
782       {
783         PRINT (_("Redistribute latency...\n"));
784         gst_bin_recalculate_latency (GST_BIN (pipeline));
785         break;
786       }
787       case GST_MESSAGE_REQUEST_STATE:
788       {
789         GstState state;
790         gchar *name = gst_object_get_path_string (GST_MESSAGE_SRC (message));
791 
792         gst_message_parse_request_state (message, &state);
793 
794         PRINT (_("Setting state to %s as requested by %s...\n"),
795             gst_element_state_get_name (state), name);
796 
797         gst_element_set_state (pipeline, state);
798 
799         g_free (name);
800         break;
801       }
802       case GST_MESSAGE_APPLICATION:{
803         const GstStructure *s;
804 
805         s = gst_message_get_structure (message);
806 
807         if (gst_structure_has_name (s, "GstLaunchInterrupt")) {
808           /* this application message is posted when we caught an interrupt and
809            * we need to stop the pipeline. */
810           PRINT (_("Interrupt: Stopping pipeline ...\n"));
811           interrupting = TRUE;
812 
813           if (eos_on_shutdown) {
814             if (waiting_eos) {
815               PRINT (_
816                   ("Interrupt while waiting for EOS - stopping pipeline...\n"));
817 
818               g_main_loop_quit (loop);
819             } else {
820               PRINT (_
821                   ("EOS on shutdown enabled -- Forcing EOS on the pipeline\n"));
822               gst_element_send_event (pipeline, gst_event_new_eos ());
823 
824               PRINT (_("Waiting for EOS...\n"));
825 
826               waiting_eos = TRUE;
827             }
828           } else {
829             g_main_loop_quit (loop);
830           }
831         }
832         break;
833       }
834       case GST_MESSAGE_PROGRESS:
835       {
836         GstProgressType type;
837         gchar *code, *text;
838 
839         gst_message_parse_progress (message, &type, &code, &text);
840 
841         switch (type) {
842           case GST_PROGRESS_TYPE_START:
843           case GST_PROGRESS_TYPE_CONTINUE:
844             in_progress = TRUE;
845             break;
846           case GST_PROGRESS_TYPE_COMPLETE:
847           case GST_PROGRESS_TYPE_CANCELED:
848           case GST_PROGRESS_TYPE_ERROR:
849             in_progress = FALSE;
850             break;
851           default:
852             break;
853         }
854         PRINT (_("Progress: (%s) %s\n"), code, text);
855         g_free (code);
856         g_free (text);
857 
858         if (!in_progress && prerolled && target_state == GST_STATE_PAUSED) {
859           do_initial_play (pipeline);
860         }
861         break;
862       }
863       case GST_MESSAGE_ELEMENT:{
864         if (gst_is_missing_plugin_message (message)) {
865           const gchar *desc;
866 
867           desc = gst_missing_plugin_message_get_description (message);
868           PRINT (_("Missing element: %s\n"), desc ? desc : "(no description)");
869         }
870         break;
871       }
872       case GST_MESSAGE_HAVE_CONTEXT:{
873         GstContext *context;
874         const gchar *context_type;
875         gchar *context_str;
876 
877         gst_message_parse_have_context (message, &context);
878 
879         context_type = gst_context_get_context_type (context);
880         context_str =
881             gst_structure_to_string (gst_context_get_structure (context));
882         PRINT (_("Got context from element '%s': %s=%s\n"),
883             GST_ELEMENT_NAME (GST_MESSAGE_SRC (message)), context_type,
884             context_str);
885         g_free (context_str);
886         gst_context_unref (context);
887         break;
888       }
889       case GST_MESSAGE_PROPERTY_NOTIFY:{
890         const GValue *val;
891         const gchar *name;
892         GstObject *obj;
893         gchar *val_str = NULL;
894         gchar **ex_prop, *obj_name;
895 
896         if (quiet)
897           break;
898 
899         gst_message_parse_property_notify (message, &obj, &name, &val);
900 
901         /* Let's not print anything for excluded properties... */
902         ex_prop = exclude_args;
903         while (ex_prop != NULL && *ex_prop != NULL) {
904           if (strcmp (name, *ex_prop) == 0)
905             break;
906           ex_prop++;
907         }
908         if (ex_prop != NULL && *ex_prop != NULL)
909           break;
910 
911         obj_name = gst_object_get_path_string (GST_OBJECT (obj));
912         if (val != NULL) {
913           if (G_VALUE_HOLDS_STRING (val))
914             val_str = g_value_dup_string (val);
915           else if (G_VALUE_TYPE (val) == GST_TYPE_CAPS)
916             val_str = gst_caps_to_string (g_value_get_boxed (val));
917           else if (G_VALUE_TYPE (val) == GST_TYPE_TAG_LIST)
918             val_str = gst_tag_list_to_string (g_value_get_boxed (val));
919           else if (G_VALUE_TYPE (val) == GST_TYPE_STRUCTURE)
920             val_str = gst_structure_to_string (g_value_get_boxed (val));
921           else
922             val_str = gst_value_serialize (val);
923         } else {
924           val_str = g_strdup ("(no value)");
925         }
926 
927         gst_print ("%s: %s = %s\n", obj_name, name, val_str);
928         g_free (obj_name);
929         g_free (val_str);
930         break;
931       }
932       default:
933         /* just be quiet by default */
934         break;
935     }
936   }
937 
938   return TRUE;
939 }
940 
941 static GstBusSyncReply
bus_sync_handler(GstBus * bus,GstMessage * message,gpointer data)942 bus_sync_handler (GstBus * bus, GstMessage * message, gpointer data)
943 {
944   GstElement *pipeline = (GstElement *) data;
945 
946   switch (GST_MESSAGE_TYPE (message)) {
947     case GST_MESSAGE_STATE_CHANGED:
948       /* we only care about pipeline state change messages */
949       if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipeline)) {
950         GstState old, new, pending;
951         gchar *state_transition_name;
952 
953         gst_message_parse_state_changed (message, &old, &new, &pending);
954 
955         state_transition_name = g_strdup_printf ("%s_%s",
956             gst_element_state_get_name (old), gst_element_state_get_name (new));
957 
958         /* dump graph for (some) pipeline state changes */
959         {
960           gchar *dump_name = g_strconcat ("gst-launch.", state_transition_name,
961               NULL);
962           GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
963               GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
964           g_free (dump_name);
965         }
966 
967         /* place a marker into e.g. strace logs */
968         {
969           gchar *access_name = g_strconcat (g_get_tmp_dir (), G_DIR_SEPARATOR_S,
970               "gst-launch", G_DIR_SEPARATOR_S, state_transition_name, NULL);
971           g_file_test (access_name, G_FILE_TEST_EXISTS);
972           g_free (access_name);
973         }
974 
975         g_free (state_transition_name);
976       }
977       break;
978     case GST_MESSAGE_ERROR:{
979       /* dump graph on error */
980       GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
981           GST_DEBUG_GRAPH_SHOW_ALL, "gst-launch.error");
982 
983       print_error_message (message);
984 
985       if (target_state == GST_STATE_PAUSED) {
986         gst_printerr (_("ERROR: pipeline doesn't want to preroll.\n"));
987       } else if (interrupting) {
988         PRINT (_("An error happened while waiting for EOS\n"));
989       }
990 
991       /* we have an error */
992       last_launch_code = LEC_ERROR;
993       g_main_loop_quit (loop);
994       break;
995     }
996     default:
997       break;
998   }
999   return GST_BUS_PASS;
1000 }
1001 
1002 static gboolean
query_pipeline_position(gpointer user_data)1003 query_pipeline_position (gpointer user_data)
1004 {
1005   gint64 pos = -1, dur = -1;
1006   gboolean output_is_tty = GPOINTER_TO_INT (user_data);
1007 
1008   if (buffering)
1009     return G_SOURCE_CONTINUE;
1010 
1011   gst_element_query_position (pipeline, GST_FORMAT_TIME, &pos);
1012   gst_element_query_duration (pipeline, GST_FORMAT_TIME, &dur);
1013 
1014   if (pos >= 0) {
1015     gchar dstr[32], pstr[32];
1016 
1017     /* FIXME: pretty print in nicer format */
1018     g_snprintf (pstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
1019     pstr[9] = '\0';
1020     g_snprintf (dstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
1021     dstr[9] = '\0';
1022 
1023     if (dur > 0 && dur >= pos) {
1024       gdouble percent;
1025       percent = 100 * (gdouble) (pos) / dur;
1026 
1027       gst_print ("%s / %s (%.1f %%)%c", pstr, dstr, percent,
1028           output_is_tty ? '\r' : '\n');
1029     } else
1030       gst_print ("%s / %s%c", pstr, dstr, output_is_tty ? '\r' : '\n');
1031   }
1032 
1033   return G_SOURCE_CONTINUE;
1034 }
1035 
1036 #ifdef HAVE_WINMM
1037 static guint
enable_winmm_timer_resolution(void)1038 enable_winmm_timer_resolution (void)
1039 {
1040   TIMECAPS time_caps;
1041   guint resolution = 0;
1042   MMRESULT res;
1043 
1044   res = timeGetDevCaps (&time_caps, sizeof (TIMECAPS));
1045   if (res != TIMERR_NOERROR) {
1046     g_warning ("timeGetDevCaps() returned non-zero code %d", res);
1047     return 0;
1048   }
1049 
1050   resolution = MIN (MAX (time_caps.wPeriodMin, 1), time_caps.wPeriodMax);
1051   res = timeBeginPeriod (resolution);
1052   if (res != TIMERR_NOERROR) {
1053     g_warning ("timeBeginPeriod() returned non-zero code %d", res);
1054     return 0;
1055   }
1056 
1057   PRINT (_("Use Windows high-resolution clock, precision: %u ms\n"),
1058       resolution);
1059 
1060   return resolution;
1061 }
1062 
1063 static void
clear_winmm_timer_resolution(guint resolution)1064 clear_winmm_timer_resolution (guint resolution)
1065 {
1066   if (resolution == 0)
1067     return;
1068 
1069   timeEndPeriod (resolution);
1070 }
1071 #endif
1072 
1073 int
main(int argc,char * argv[])1074 main (int argc, char *argv[])
1075 {
1076   /* options */
1077   gboolean verbose = FALSE;
1078   gboolean no_fault = FALSE;
1079 #if 0
1080   gboolean check_index = FALSE;
1081 #endif
1082   gchar *savefile = NULL;
1083   gboolean no_position = FALSE;
1084   gboolean force_position = FALSE;
1085 #ifndef GST_DISABLE_OPTION_PARSING
1086   GOptionEntry options[] = {
1087     {"tags", 't', 0, G_OPTION_ARG_NONE, &tags,
1088         N_("Output tags (also known as metadata)"), NULL},
1089     {"toc", 'c', 0, G_OPTION_ARG_NONE, &toc,
1090         N_("Output TOC (chapters and editions)"), NULL},
1091     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
1092         N_("Output status information and property notifications"), NULL},
1093     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
1094         N_("Do not print any progress information"), NULL},
1095     {"messages", 'm', 0, G_OPTION_ARG_NONE, &messages,
1096         N_("Output messages"), NULL},
1097     {"exclude", 'X', 0, G_OPTION_ARG_STRING_ARRAY, &exclude_args,
1098           N_("Do not output status information for the specified property "
1099               "if verbose output is enabled (can be used multiple times)"),
1100         N_("PROPERTY-NAME")},
1101     {"no-fault", 'f', 0, G_OPTION_ARG_NONE, &no_fault,
1102         N_("Do not install a fault handler"), NULL},
1103     {"eos-on-shutdown", 'e', 0, G_OPTION_ARG_NONE, &eos_on_shutdown,
1104         N_("Force EOS on sources before shutting the pipeline down"), NULL},
1105 #if 0
1106     {"index", 'i', 0, G_OPTION_ARG_NONE, &check_index,
1107         N_("Gather and print index statistics"), NULL},
1108 #endif
1109     GST_TOOLS_GOPTION_VERSION,
1110     {"no-position", '\0', 0, G_OPTION_ARG_NONE, &no_position,
1111         N_("Do not print current position of pipeline. "
1112               "If this option is unspecified, the position will be printed "
1113               "when stdout is a TTY. "
1114               "To enable printing position when stdout is not a TTY, "
1115               "use \"force-position\" option"), NULL},
1116     {"force-position", '\0', 0, G_OPTION_ARG_NONE, &force_position,
1117           N_("Allow printing current position of pipeline even if "
1118               "stdout is not a TTY. This option has no effect if "
1119               "the \"no-position\" option is specified"),
1120         NULL},
1121     {NULL}
1122   };
1123   GOptionContext *ctx;
1124   GError *err = NULL;
1125 #endif
1126 #if 0
1127   GstIndex *index;
1128   GPtrArray *index_stats = NULL;
1129 #endif
1130   gchar **argvn;
1131   GError *error = NULL;
1132   gulong deep_notify_id = 0;
1133   guint bus_watch_id = 0;
1134   GSource *position_source = NULL;
1135 #ifdef HAVE_WINMM
1136   guint winmm_timer_resolution = 0;
1137 #endif
1138 
1139   free (malloc (8));            /* -lefence */
1140 
1141   setlocale (LC_ALL, "");
1142 
1143 #ifdef ENABLE_NLS
1144   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
1145   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1146   textdomain (GETTEXT_PACKAGE);
1147 #endif
1148 
1149   g_set_prgname ("gst-launch-" GST_API_VERSION);
1150   /* Ensure XInitThreads() is called if/when needed */
1151   g_setenv ("GST_GL_XINITTHREADS", "1", TRUE);
1152 
1153 #ifndef GST_DISABLE_OPTION_PARSING
1154   ctx = g_option_context_new ("PIPELINE-DESCRIPTION");
1155   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
1156   g_option_context_add_group (ctx, gst_init_get_option_group ());
1157   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
1158     if (err)
1159       gst_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
1160     else
1161       gst_printerr ("Error initializing: Unknown error!\n");
1162     g_clear_error (&err);
1163     g_option_context_free (ctx);
1164     exit (1);
1165   }
1166   g_option_context_free (ctx);
1167 #else
1168   gst_init (&argc, &argv);
1169 #endif
1170 
1171   gst_tools_print_version ();
1172 
1173 #ifdef G_OS_UNIX
1174   if (!no_fault)
1175     fault_setup ();
1176 #endif
1177 
1178   /* make a null-terminated version of argv */
1179   argvn = g_new0 (char *, argc);
1180   memcpy (argvn, argv + 1, sizeof (char *) * (argc - 1));
1181   {
1182     pipeline =
1183         (GstElement *) gst_parse_launchv ((const gchar **) argvn, &error);
1184   }
1185   g_free (argvn);
1186 
1187   if (!pipeline) {
1188     if (error) {
1189       gst_printerr (_("ERROR: pipeline could not be constructed: %s.\n"),
1190           GST_STR_NULL (error->message));
1191       g_clear_error (&error);
1192     } else {
1193       gst_printerr (_("ERROR: pipeline could not be constructed.\n"));
1194     }
1195     return 1;
1196   } else if (error) {
1197     gst_printerr (_("WARNING: erroneous pipeline: %s\n"),
1198         GST_STR_NULL (error->message));
1199     g_clear_error (&error);
1200     return 1;
1201   }
1202 
1203   loop = g_main_loop_new (NULL, FALSE);
1204 
1205   if (!savefile) {
1206     GstStateChangeReturn ret;
1207     GstBus *bus;
1208 
1209     /* If the top-level object is not a pipeline, place it in a pipeline. */
1210     if (!GST_IS_PIPELINE (pipeline)) {
1211       GstElement *real_pipeline = gst_element_factory_make ("pipeline", NULL);
1212 
1213       if (real_pipeline == NULL) {
1214         gst_printerr (_("ERROR: the 'pipeline' element wasn't found.\n"));
1215         return 1;
1216       }
1217       gst_bin_add (GST_BIN (real_pipeline), pipeline);
1218       pipeline = real_pipeline;
1219     }
1220 #ifdef HAVE_WINMM
1221     /* Enable high-precision clock which will improve accuracy of various
1222      * Windows timer APIs (e.g., Sleep()), and it will increase the precision
1223      * of GstSystemClock as well
1224      */
1225 
1226     /* NOTE: Once timer resolution is updated via timeBeginPeriod(),
1227      * application should undo it by calling timeEndPeriod()
1228      *
1229      * Prior to Windows 10, version 2004, timeBeginPeriod() affects global
1230      * Windows setting (meaning that it will affect other processes),
1231      * but starting with Windows 10, version 2004, this function no longer
1232      * affects global timer resolution
1233      */
1234     winmm_timer_resolution = enable_winmm_timer_resolution ();
1235 #endif
1236 
1237     if (verbose) {
1238       deep_notify_id =
1239           gst_element_add_property_deep_notify_watch (pipeline, NULL, TRUE);
1240     }
1241 #if 0
1242     if (check_index) {
1243       /* gst_index_new() creates a null-index, it does not store anything, but
1244        * the entry-added signal works and this is what we use to build the
1245        * statistics */
1246       index = gst_index_new ();
1247       if (index) {
1248         index_stats = g_ptr_array_new ();
1249         g_signal_connect (G_OBJECT (index), "entry-added",
1250             G_CALLBACK (entry_added), index_stats);
1251         g_object_set (G_OBJECT (index), "resolver", GST_INDEX_RESOLVER_GTYPE,
1252             NULL);
1253         gst_element_set_index (pipeline, index);
1254       }
1255     }
1256 #endif
1257 
1258     bus = gst_element_get_bus (pipeline);
1259     gst_bus_set_sync_handler (bus, bus_sync_handler, (gpointer) pipeline, NULL);
1260     bus_watch_id = gst_bus_add_watch (bus, bus_handler, NULL);
1261     gst_object_unref (bus);
1262 
1263     PRINT (_("Setting pipeline to PAUSED ...\n"));
1264     ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
1265 
1266     switch (ret) {
1267       case GST_STATE_CHANGE_FAILURE:
1268         gst_printerr (_("Failed to set pipeline to PAUSED.\n"));
1269         last_launch_code = LEC_STATE_CHANGE_FAILURE;
1270         goto end;
1271       case GST_STATE_CHANGE_NO_PREROLL:
1272         PRINT (_("Pipeline is live and does not need PREROLL ...\n"));
1273         is_live = TRUE;
1274         break;
1275       case GST_STATE_CHANGE_ASYNC:
1276         PRINT (_("Pipeline is PREROLLING ...\n"));
1277         break;
1278       default:
1279         break;
1280     }
1281 
1282 #ifdef G_OS_UNIX
1283     signal_watch_intr_id =
1284         g_unix_signal_add (SIGINT, (GSourceFunc) intr_handler, pipeline);
1285     signal_watch_hup_id =
1286         g_unix_signal_add (SIGHUP, (GSourceFunc) hup_handler, pipeline);
1287 #elif defined(G_OS_WIN32)
1288     SetConsoleCtrlHandler (w32_intr_handler, TRUE);
1289 #endif
1290     if (!no_position) {
1291       gboolean output_is_tty = TRUE;
1292 
1293       if (!isatty (STDOUT_FILENO))
1294         output_is_tty = FALSE;
1295 
1296       if (output_is_tty || (!output_is_tty && force_position)) {
1297         position_source = g_timeout_source_new (100);
1298         g_source_set_callback (position_source, query_pipeline_position,
1299             GINT_TO_POINTER (output_is_tty), NULL);
1300         g_source_attach (position_source, NULL);
1301       }
1302     }
1303 
1304     /* playing state will be set on state-changed message handler */
1305     g_main_loop_run (loop);
1306 
1307     if (position_source) {
1308       g_source_destroy (position_source);
1309       g_source_unref (position_source);
1310     }
1311 
1312     {
1313       GstClockTime tfnow;
1314       GstClockTimeDiff diff;
1315 
1316       if (GST_CLOCK_TIME_IS_VALID (tfthen)) {
1317         tfnow = gst_util_get_timestamp ();
1318         diff = GST_CLOCK_DIFF (tfthen, tfnow);
1319 
1320         PRINT (_("Execution ended after %" GST_TIME_FORMAT "\n"),
1321             GST_TIME_ARGS (diff));
1322       }
1323     }
1324 
1325     /* No need to see all those pad caps going to NULL etc., it's just noise */
1326     if (deep_notify_id != 0)
1327       g_signal_handler_disconnect (pipeline, deep_notify_id);
1328 
1329 #if 0
1330     if (check_index) {
1331       print_index_stats (index_stats);
1332       g_ptr_array_free (index_stats, TRUE);
1333     }
1334 #endif
1335 
1336   end:
1337     PRINT (_("Setting pipeline to NULL ...\n"));
1338     gst_element_set_state (pipeline, GST_STATE_NULL);
1339 
1340 #ifdef G_OS_UNIX
1341     if (signal_watch_intr_id > 0)
1342       g_source_remove (signal_watch_intr_id);
1343     if (signal_watch_hup_id > 0)
1344       g_source_remove (signal_watch_hup_id);
1345 #endif
1346     g_source_remove (bus_watch_id);
1347     g_main_loop_unref (loop);
1348 
1349 #ifdef HAVE_WINMM
1350     /* Undo timeBeginPeriod() if required */
1351     clear_winmm_timer_resolution (winmm_timer_resolution);
1352 #endif
1353   }
1354 
1355   PRINT (_("Freeing pipeline ...\n"));
1356   gst_object_unref (pipeline);
1357 
1358   gst_deinit ();
1359 
1360   return last_launch_code;
1361 }
1362