696f481110289cddee0db323d4b01f6bb5a51a4e
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / tools / gst-play.c
1 /* GStreamer command line playback testing utility
2  *
3  * Copyright (C) 2013-2014 Tim-Philipp Müller <tim centricular net>
4  * Copyright (C) 2013 Collabora Ltd.
5  * Copyright (C) 2015 Centricular Ltd
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <locale.h>
28
29 #include <gst/gst.h>
30 #include <glib/gi18n.h>
31 #include <gst/audio/audio.h>
32 #include <gst/video/video.h>
33 #include <gst/pbutils/pbutils.h>
34 #include <gst/tag/tag.h>
35 #include <gst/math-compat.h>
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <string.h>
39
40 #include <glib/gprintf.h>
41
42 #ifdef HAVE_WINMM
43 #define WIN32_LEAN_AND_MEAN
44 #include <windows.h>
45 #include <mmsystem.h>
46 #endif
47
48 #ifdef __APPLE__
49 #include <TargetConditionals.h>
50 #endif
51
52 #include "gst-play-kb.h"
53
54 #define VOLUME_STEPS 20
55
56 static gboolean wait_on_eos = FALSE;
57
58 GST_DEBUG_CATEGORY (play_debug);
59 #define GST_CAT_DEFAULT play_debug
60
61 typedef enum
62 {
63   GST_PLAY_TRICK_MODE_NONE = 0,
64   GST_PLAY_TRICK_MODE_DEFAULT,
65   GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO,
66   GST_PLAY_TRICK_MODE_KEY_UNITS,
67   GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO,
68   GST_PLAY_TRICK_MODE_LAST,
69
70   /* The instant-rate setting is a flag,
71    * applied on top of the trick-mode enum value.
72    * It needs to have a 2^n value bigger than 
73    * any of the enum values so setting it
74    * won't affect the trickmode value */
75   GST_PLAY_TRICK_MODE_INSTANT_RATE = (1 << 3)
76 } GstPlayTrickMode;
77
78 typedef enum
79 {
80   GST_PLAY_TRACK_TYPE_INVALID = 0,
81   GST_PLAY_TRACK_TYPE_AUDIO,
82   GST_PLAY_TRACK_TYPE_VIDEO,
83   GST_PLAY_TRACK_TYPE_SUBTITLE
84 } GstPlayTrackType;
85
86 typedef struct
87 {
88   gchar **uris;
89   guint num_uris;
90   gint cur_idx;
91
92   GstElement *playbin;
93
94   /* playbin3 variables */
95   gboolean is_playbin3;
96   GstStreamCollection *collection;
97   gchar *cur_audio_sid;
98   gchar *cur_video_sid;
99   gchar *cur_text_sid;
100   GMutex selection_lock;
101
102   GMainLoop *loop;
103   guint bus_watch;
104   guint timeout;
105
106   /* missing plugin messages */
107   GList *missing;
108
109   gboolean buffering;
110   gboolean is_live;
111   gboolean initial_file;
112
113   GstState desired_state;       /* as per user interaction, PAUSED or PLAYING */
114
115   gulong deep_notify_id;
116
117   /* configuration */
118   gboolean gapless;
119   gboolean instant_uri;
120
121   GstPlayTrickMode trick_mode;
122   gdouble rate;
123   gdouble start_position;
124
125   /* keyboard state tracking */
126   gboolean shift_pressed;
127 } GstPlay;
128
129 static gboolean quiet = FALSE;
130 static gboolean instant_rate_changes = FALSE;
131
132 static gboolean play_bus_msg (GstBus * bus, GstMessage * msg, gpointer data);
133 static gboolean play_next (GstPlay * play);
134 static gboolean play_prev (GstPlay * play);
135 static gboolean play_timeout (gpointer user_data);
136 static void play_about_to_finish (GstElement * playbin, gpointer user_data);
137 static void play_reset (GstPlay * play);
138 static void play_set_relative_volume (GstPlay * play, gdouble volume_step);
139 static gboolean play_do_seek (GstPlay * play, gint64 pos, gdouble rate,
140     GstPlayTrickMode mode);
141
142 /* *INDENT-OFF* */
143 static void gst_play_printf (const gchar * format, ...) G_GNUC_PRINTF (1, 2);
144 /* *INDENT-ON* */
145
146 static void keyboard_cb (const gchar * key_input, gpointer user_data);
147 static void relative_seek (GstPlay * play, gdouble percent);
148
149 static void
150 gst_play_printf (const gchar * format, ...)
151 {
152   gchar *str = NULL;
153   va_list args;
154   int len;
155
156   if (quiet)
157     return;
158
159   va_start (args, format);
160
161   len = g_vasprintf (&str, format, args);
162
163   va_end (args);
164
165   if (len > 0 && str != NULL)
166     gst_print ("%s", str);
167
168   g_free (str);
169 }
170
171 #define gst_print gst_play_printf
172
173 static GstPlay *
174 play_new (gchar ** uris, const gchar * audio_sink, const gchar * video_sink,
175     gboolean gapless, gboolean instant_uri, gdouble initial_volume,
176     gboolean verbose, const gchar * flags_string, gboolean use_playbin3,
177     gdouble start_position, gboolean no_position)
178 {
179   GstElement *sink, *playbin;
180   GstPlay *play;
181
182
183   if (use_playbin3) {
184     playbin = gst_element_factory_make ("playbin3", "playbin");
185   } else {
186     playbin = gst_element_factory_make ("playbin", "playbin");
187   }
188
189   if (playbin == NULL)
190     return NULL;
191
192   play = g_new0 (GstPlay, 1);
193
194   play->uris = uris;
195   play->num_uris = g_strv_length (uris);
196   play->cur_idx = -1;
197
198   play->playbin = playbin;
199
200   if (use_playbin3) {
201     play->is_playbin3 = TRUE;
202   } else {
203     const gchar *env = g_getenv ("USE_PLAYBIN3");
204     if (env && g_str_has_prefix (env, "1"))
205       play->is_playbin3 = TRUE;
206   }
207
208   g_mutex_init (&play->selection_lock);
209
210   if (audio_sink != NULL) {
211     if (strchr (audio_sink, ' ') != NULL)
212       sink = gst_parse_bin_from_description (audio_sink, TRUE, NULL);
213     else
214       sink = gst_element_factory_make (audio_sink, NULL);
215
216     if (sink != NULL)
217       g_object_set (play->playbin, "audio-sink", sink, NULL);
218     else
219       g_warning ("Couldn't create specified audio sink '%s'", audio_sink);
220   }
221   if (video_sink != NULL) {
222     if (strchr (video_sink, ' ') != NULL)
223       sink = gst_parse_bin_from_description (video_sink, TRUE, NULL);
224     else
225       sink = gst_element_factory_make (video_sink, NULL);
226
227     if (sink != NULL)
228       g_object_set (play->playbin, "video-sink", sink, NULL);
229     else
230       g_warning ("Couldn't create specified video sink '%s'", video_sink);
231   }
232
233   if (flags_string != NULL) {
234     GParamSpec *pspec;
235     GValue val = { 0, };
236
237     pspec =
238         g_object_class_find_property (G_OBJECT_GET_CLASS (playbin), "flags");
239     g_value_init (&val, pspec->value_type);
240     if (gst_value_deserialize (&val, flags_string))
241       g_object_set_property (G_OBJECT (play->playbin), "flags", &val);
242     else
243       gst_printerr ("Couldn't convert '%s' to playbin flags!\n", flags_string);
244     g_value_unset (&val);
245   }
246
247   if (verbose) {
248     play->deep_notify_id =
249         gst_element_add_property_deep_notify_watch (play->playbin, NULL, TRUE);
250   }
251
252   play->loop = g_main_loop_new (NULL, FALSE);
253
254   play->bus_watch = gst_bus_add_watch (GST_ELEMENT_BUS (play->playbin),
255       play_bus_msg, play);
256
257   if (!no_position) {
258     play->timeout = g_timeout_add (100, play_timeout, play);
259   }
260
261   play->missing = NULL;
262   play->buffering = FALSE;
263   play->is_live = FALSE;
264
265   play->desired_state = GST_STATE_PLAYING;
266
267   play->gapless = gapless;
268   if (gapless) {
269     g_signal_connect (play->playbin, "about-to-finish",
270         G_CALLBACK (play_about_to_finish), play);
271   }
272
273   play->initial_file = TRUE;
274   if (use_playbin3) {
275     play->instant_uri = instant_uri;
276     g_object_set (G_OBJECT (play->playbin), "instant-uri", instant_uri, NULL);
277   }
278   if (initial_volume != -1)
279     play_set_relative_volume (play, initial_volume - 1.0);
280
281   play->rate = 1.0;
282   play->trick_mode = GST_PLAY_TRICK_MODE_NONE;
283   play->start_position = start_position;
284   return play;
285 }
286
287 static void
288 play_free (GstPlay * play)
289 {
290   /* No need to see all those pad caps going to NULL etc., it's just noise */
291   if (play->deep_notify_id != 0)
292     g_signal_handler_disconnect (play->playbin, play->deep_notify_id);
293
294   play_reset (play);
295
296   gst_element_set_state (play->playbin, GST_STATE_NULL);
297   gst_object_unref (play->playbin);
298
299   g_source_remove (play->bus_watch);
300   if (play->timeout != 0)
301     g_source_remove (play->timeout);
302   g_main_loop_unref (play->loop);
303
304   g_strfreev (play->uris);
305
306   if (play->collection)
307     gst_object_unref (play->collection);
308   g_free (play->cur_audio_sid);
309   g_free (play->cur_video_sid);
310   g_free (play->cur_text_sid);
311
312   g_mutex_clear (&play->selection_lock);
313
314   g_free (play);
315 }
316
317 /* reset for new file/stream */
318 static void
319 play_reset (GstPlay * play)
320 {
321   g_list_foreach (play->missing, (GFunc) gst_message_unref, NULL);
322   play->missing = NULL;
323
324   play->buffering = FALSE;
325   play->is_live = FALSE;
326 }
327
328 static void
329 play_set_relative_volume (GstPlay * play, gdouble volume_step)
330 {
331   gdouble volume;
332
333   volume = gst_stream_volume_get_volume (GST_STREAM_VOLUME (play->playbin),
334       GST_STREAM_VOLUME_FORMAT_CUBIC);
335
336   volume = round ((volume + volume_step) * VOLUME_STEPS) / VOLUME_STEPS;
337   volume = CLAMP (volume, 0.0, 10.0);
338
339   gst_stream_volume_set_volume (GST_STREAM_VOLUME (play->playbin),
340       GST_STREAM_VOLUME_FORMAT_CUBIC, volume);
341
342   gst_print (_("Volume: %.0f%%"), volume * 100);
343   gst_print ("                  \n");
344 }
345
346 static void
347 play_toggle_audio_mute (GstPlay * play)
348 {
349   gboolean mute;
350
351   mute = gst_stream_volume_get_mute (GST_STREAM_VOLUME (play->playbin));
352
353   mute = !mute;
354   gst_stream_volume_set_mute (GST_STREAM_VOLUME (play->playbin), mute);
355
356   if (mute)
357     gst_print (_("Mute: on"));
358   else
359     gst_print (_("Mute: off"));
360   gst_print ("                  \n");
361 }
362
363 /* returns TRUE if something was installed and we should restart playback */
364 static gboolean
365 play_install_missing_plugins (GstPlay * play)
366 {
367   /* FIXME: implement: try to install any missing plugins we haven't
368    * tried to install before */
369   return FALSE;
370 }
371
372 static gboolean
373 play_bus_msg (GstBus * bus, GstMessage * msg, gpointer user_data)
374 {
375   GstPlay *play = user_data;
376
377   switch (GST_MESSAGE_TYPE (msg)) {
378     case GST_MESSAGE_ASYNC_DONE:
379
380       /* dump graph on preroll */
381       GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
382           GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.async-done");
383
384       gst_print ("Prerolled.\r");
385       if (play->missing != NULL && play_install_missing_plugins (play)) {
386         gst_print ("New plugins installed, trying again...\n");
387         --play->cur_idx;
388         play_next (play);
389       }
390       if (play->start_position > 0.0) {
391         play_do_seek (play, play->start_position * GST_SECOND,
392             play->rate, play->trick_mode);
393         play->start_position = 0;
394       }
395       break;
396     case GST_MESSAGE_BUFFERING:{
397       gint percent;
398
399       if (!play->buffering)
400         gst_print ("\n");
401
402       gst_message_parse_buffering (msg, &percent);
403       gst_print ("%s %d%%  \r", _("Buffering..."), percent);
404
405       if (percent == 100) {
406         /* a 100% message means buffering is done */
407         if (play->buffering) {
408           play->buffering = FALSE;
409           /* no state management needed for live pipelines */
410           if (!play->is_live)
411             gst_element_set_state (play->playbin, play->desired_state);
412         }
413       } else {
414         /* buffering... */
415         if (!play->buffering) {
416           if (!play->is_live)
417             gst_element_set_state (play->playbin, GST_STATE_PAUSED);
418           play->buffering = TRUE;
419         }
420       }
421       break;
422     }
423     case GST_MESSAGE_CLOCK_LOST:{
424       gst_print (_("Clock lost, selecting a new one\n"));
425       gst_element_set_state (play->playbin, GST_STATE_PAUSED);
426       gst_element_set_state (play->playbin, GST_STATE_PLAYING);
427       break;
428     }
429     case GST_MESSAGE_LATENCY:
430       gst_print ("Redistribute latency...\n");
431       gst_bin_recalculate_latency (GST_BIN (play->playbin));
432       break;
433     case GST_MESSAGE_REQUEST_STATE:{
434       GstState state;
435       gchar *name;
436
437       name = gst_object_get_path_string (GST_MESSAGE_SRC (msg));
438
439       gst_message_parse_request_state (msg, &state);
440
441       gst_print ("Setting state to %s as requested by %s...\n",
442           gst_element_state_get_name (state), name);
443
444       gst_element_set_state (play->playbin, state);
445       g_free (name);
446       break;
447     }
448     case GST_MESSAGE_EOS:
449       /* print final position at end */
450       play_timeout (play);
451       gst_print ("\n");
452       /* and switch to next item in list */
453       if (!wait_on_eos && !play_next (play)) {
454         gst_print ("%s\n", _("Reached end of play list."));
455         g_main_loop_quit (play->loop);
456       }
457       break;
458     case GST_MESSAGE_WARNING:{
459       GError *err;
460       gchar *dbg = NULL;
461
462       /* dump graph on warning */
463       GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
464           GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.warning");
465
466       gst_message_parse_warning (msg, &err, &dbg);
467       gst_printerr ("WARNING %s\n", err->message);
468       if (dbg != NULL)
469         gst_printerr ("WARNING debug information: %s\n", dbg);
470       g_clear_error (&err);
471       g_free (dbg);
472       break;
473     }
474     case GST_MESSAGE_ERROR:{
475       GError *err;
476       gchar *dbg;
477
478       /* dump graph on error */
479       GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
480           GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.error");
481
482       gst_message_parse_error (msg, &err, &dbg);
483       gst_printerr ("ERROR %s for %s\n", err->message,
484           play->uris[play->cur_idx]);
485       if (dbg != NULL)
486         gst_printerr ("ERROR debug information: %s\n", dbg);
487       g_clear_error (&err);
488       g_free (dbg);
489
490       /* flush any other error messages from the bus and clean up */
491       gst_element_set_state (play->playbin, GST_STATE_NULL);
492
493       if (play->missing != NULL && play_install_missing_plugins (play)) {
494         gst_print ("New plugins installed, trying again...\n");
495         --play->cur_idx;
496         play_next (play);
497         break;
498       }
499       /* try next item in list then */
500       if (!play_next (play)) {
501         gst_print ("%s\n", _("Reached end of play list."));
502         g_main_loop_quit (play->loop);
503       }
504       break;
505     }
506     case GST_MESSAGE_ELEMENT:
507     {
508       GstNavigationMessageType mtype = gst_navigation_message_get_type (msg);
509       if (mtype == GST_NAVIGATION_MESSAGE_EVENT) {
510         GstEvent *ev = NULL;
511
512         if (gst_navigation_message_parse_event (msg, &ev)) {
513           GstNavigationEventType e_type = gst_navigation_event_get_type (ev);
514           switch (e_type) {
515             case GST_NAVIGATION_EVENT_KEY_PRESS:
516             {
517               const gchar *key;
518               const gchar *key_input;
519               gchar key_adjusted[2];
520
521               if (gst_navigation_event_parse_key_event (ev, &key)) {
522                 GST_INFO ("Key press: %s", key);
523
524                 if (strcmp (key, "Left") == 0)
525                   key = GST_PLAY_KB_ARROW_LEFT;
526                 else if (strcmp (key, "Right") == 0)
527                   key = GST_PLAY_KB_ARROW_RIGHT;
528                 else if (strcmp (key, "Up") == 0)
529                   key = GST_PLAY_KB_ARROW_UP;
530                 else if (strcmp (key, "Down") == 0)
531                   key = GST_PLAY_KB_ARROW_DOWN;
532                 else if (strncmp (key, "Shift", 5) == 0) {
533                   play->shift_pressed = TRUE;
534                   break;
535                 } else if (strcmp (key, "space") == 0 ||
536                     strcmp (key, "Space") == 0) {
537                   key = " ";
538                 } else if (strcmp (key, "minus") == 0) {
539                   key = "-";
540                 } else if (strcmp (key, "plus") == 0
541                     /* TODO: That's not universally correct at all, but still handy */
542                     || (strcmp (key, "equal") == 0 && play->shift_pressed)) {
543                   key = "+";
544                 } else if (strlen (key) > 1) {
545                   break;
546                 }
547
548                 /* In the case of a simple single-char input,
549                  * make it lower or upper as needed, and
550                  * send that instead */
551                 if (key[0] != '\0' && key[1] == '\0') {
552                   if (play->shift_pressed)
553                     key_adjusted[0] = g_ascii_toupper (key[0]);
554                   else
555                     key_adjusted[0] = g_ascii_tolower (key[0]);
556                   key_adjusted[1] = '\0';
557                   key_input = key_adjusted;
558                 } else {
559                   key_input = key;
560                 }
561
562                 keyboard_cb (key_input, user_data);
563               }
564               break;
565             }
566             case GST_NAVIGATION_EVENT_KEY_RELEASE:
567             {
568               const gchar *key;
569
570               if (gst_navigation_event_parse_key_event (ev, &key)) {
571                 GST_INFO ("Key release: %s", key);
572                 if (strncmp (key, "Shift", 5) == 0) {
573                   play->shift_pressed = FALSE;
574                 }
575               }
576               break;
577             }
578             case GST_NAVIGATION_EVENT_MOUSE_BUTTON_PRESS:
579             {
580               gint button;
581               if (gst_navigation_event_parse_mouse_button_event (ev, &button,
582                       NULL, NULL)) {
583                 if (button == 4) {
584                   /* wheel up */
585                   relative_seek (play, +0.08);
586                 } else if (button == 5) {
587                   /* wheel down */
588                   relative_seek (play, -0.01);
589                 }
590               }
591               break;
592             }
593             default:
594               break;
595           }
596         }
597         if (ev)
598           gst_event_unref (ev);
599       }
600       break;
601     }
602     case GST_MESSAGE_PROPERTY_NOTIFY:{
603       const GValue *val;
604       const gchar *name;
605       GstObject *obj;
606       gchar *val_str = NULL;
607       gchar *obj_name;
608
609       gst_message_parse_property_notify (msg, &obj, &name, &val);
610
611       obj_name = gst_object_get_path_string (GST_OBJECT (obj));
612       if (val != NULL) {
613         if (G_VALUE_HOLDS_STRING (val))
614           val_str = g_value_dup_string (val);
615         else if (G_VALUE_TYPE (val) == GST_TYPE_CAPS)
616           val_str = gst_caps_to_string (g_value_get_boxed (val));
617         else if (G_VALUE_TYPE (val) == GST_TYPE_TAG_LIST)
618           val_str = gst_tag_list_to_string (g_value_get_boxed (val));
619         else
620           val_str = gst_value_serialize (val);
621       } else {
622         val_str = g_strdup ("(no value)");
623       }
624
625       gst_play_printf ("%s: %s = %s\n", obj_name, name, val_str);
626       g_free (obj_name);
627       g_free (val_str);
628       break;
629     }
630     case GST_MESSAGE_STREAM_COLLECTION:
631     {
632       GstStreamCollection *collection = NULL;
633       gst_message_parse_stream_collection (msg, &collection);
634
635       if (collection) {
636         g_mutex_lock (&play->selection_lock);
637         if (play->collection)
638           gst_object_unref (play->collection);
639         play->collection = collection;
640         g_mutex_unlock (&play->selection_lock);
641       }
642       break;
643     }
644     case GST_MESSAGE_STREAMS_SELECTED:
645     {
646       GstStreamCollection *collection = NULL;
647       guint i, len;
648
649       gst_message_parse_streams_selected (msg, &collection);
650       if (collection) {
651         g_mutex_lock (&play->selection_lock);
652         gst_object_replace ((GstObject **) & play->collection,
653             (GstObject *) collection);
654
655         /* Free all last stream-ids */
656         g_free (play->cur_audio_sid);
657         g_free (play->cur_video_sid);
658         g_free (play->cur_text_sid);
659         play->cur_audio_sid = NULL;
660         play->cur_video_sid = NULL;
661         play->cur_text_sid = NULL;
662
663         len = gst_message_streams_selected_get_size (msg);
664         for (i = 0; i < len; i++) {
665           GstStream *stream = gst_message_streams_selected_get_stream (msg, i);
666           if (stream) {
667             GstStreamType type = gst_stream_get_stream_type (stream);
668             const gchar *stream_id = gst_stream_get_stream_id (stream);
669
670             if (type & GST_STREAM_TYPE_AUDIO) {
671               play->cur_audio_sid = g_strdup (stream_id);
672             } else if (type & GST_STREAM_TYPE_VIDEO) {
673               play->cur_video_sid = g_strdup (stream_id);
674             } else if (type & GST_STREAM_TYPE_TEXT) {
675               play->cur_text_sid = g_strdup (stream_id);
676             } else {
677               gst_print ("Unknown stream type with stream-id %s\n", stream_id);
678             }
679             gst_object_unref (stream);
680           }
681         }
682
683         gst_object_unref (collection);
684         g_mutex_unlock (&play->selection_lock);
685       }
686       break;
687     }
688     default:
689       if (gst_is_missing_plugin_message (msg)) {
690         gchar *desc;
691
692         desc = gst_missing_plugin_message_get_description (msg);
693         gst_print ("Missing plugin: %s\n", desc);
694         g_free (desc);
695         play->missing = g_list_append (play->missing, gst_message_ref (msg));
696       }
697       break;
698   }
699
700   return TRUE;
701 }
702
703 static gboolean
704 play_timeout (gpointer user_data)
705 {
706   GstPlay *play = user_data;
707   gint64 pos = -1, dur = -1;
708   const gchar *paused = _("Paused");
709   gchar *status;
710
711   if (play->buffering)
712     return TRUE;
713
714   gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos);
715   gst_element_query_duration (play->playbin, GST_FORMAT_TIME, &dur);
716
717   if (play->desired_state == GST_STATE_PAUSED) {
718     status = (gchar *) paused;
719   } else {
720     gint len = g_utf8_strlen (paused, -1);
721     status = g_newa (gchar, len + 1);
722     memset (status, ' ', len);
723     status[len] = '\0';
724   }
725
726   if (pos >= 0) {
727     gchar dstr[32], pstr[32];
728
729     /* FIXME: pretty print in nicer format */
730     g_snprintf (pstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
731     pstr[9] = '\0';
732     g_snprintf (dstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
733     dstr[9] = '\0';
734     gst_print ("%s / %s %s\r", pstr, dstr, status);
735   }
736
737   return TRUE;
738 }
739
740 static gchar *
741 play_uri_get_display_name (GstPlay * play, const gchar * uri)
742 {
743   gchar *loc;
744
745   if (gst_uri_has_protocol (uri, "file")) {
746     loc = g_filename_from_uri (uri, NULL, NULL);
747   } else if (gst_uri_has_protocol (uri, "pushfile")) {
748     loc = g_filename_from_uri (uri + 4, NULL, NULL);
749   } else {
750     loc = g_strdup (uri);
751   }
752
753   /* Maybe additionally use glib's filename to display name function */
754   return loc;
755 }
756
757 static void
758 play_uri (GstPlay * play, const gchar * next_uri)
759 {
760   gchar *loc;
761
762   if (!play->instant_uri || play->initial_file)
763     gst_element_set_state (play->playbin, GST_STATE_READY);
764   play_reset (play);
765
766   loc = play_uri_get_display_name (play, next_uri);
767   gst_print (_("Now playing %s\n"), loc);
768   g_free (loc);
769
770   g_object_set (play->playbin, "uri", next_uri, NULL);
771
772   if (!play->instant_uri || play->initial_file) {
773     switch (gst_element_set_state (play->playbin, GST_STATE_PAUSED)) {
774       case GST_STATE_CHANGE_FAILURE:
775         /* ignore, we should get an error message posted on the bus */
776         break;
777       case GST_STATE_CHANGE_NO_PREROLL:
778         gst_print ("Pipeline is live.\n");
779         play->is_live = TRUE;
780         break;
781       case GST_STATE_CHANGE_ASYNC:
782         gst_print ("Prerolling...\r");
783         break;
784       default:
785         break;
786     }
787
788     if (play->desired_state != GST_STATE_PAUSED)
789       gst_element_set_state (play->playbin, play->desired_state);
790   }
791   play->initial_file = FALSE;
792 }
793
794 /* returns FALSE if we have reached the end of the playlist */
795 static gboolean
796 play_next (GstPlay * play)
797 {
798   if ((play->cur_idx + 1) >= play->num_uris)
799     return FALSE;
800
801   play_uri (play, play->uris[++play->cur_idx]);
802   return TRUE;
803 }
804
805 /* returns FALSE if we have reached the beginning of the playlist */
806 static gboolean
807 play_prev (GstPlay * play)
808 {
809   if (play->cur_idx == 0 || play->num_uris <= 1)
810     return FALSE;
811
812   play_uri (play, play->uris[--play->cur_idx]);
813   return TRUE;
814 }
815
816 static void
817 play_about_to_finish (GstElement * playbin, gpointer user_data)
818 {
819   GstPlay *play = user_data;
820   const gchar *next_uri;
821   gchar *loc;
822   guint next_idx;
823
824   if (!play->gapless)
825     return;
826
827   next_idx = play->cur_idx + 1;
828   if (next_idx >= play->num_uris)
829     return;
830
831   next_uri = play->uris[next_idx];
832   loc = play_uri_get_display_name (play, next_uri);
833   gst_print (_("About to finish, preparing next title: %s"), loc);
834   gst_print ("\n");
835   g_free (loc);
836
837   g_object_set (play->playbin, "uri", next_uri, NULL);
838   play->cur_idx = next_idx;
839 }
840
841 static void
842 do_play (GstPlay * play)
843 {
844   gint i;
845
846   /* dump playlist */
847   for (i = 0; i < play->num_uris; ++i)
848     GST_INFO ("%4u : %s", i, play->uris[i]);
849
850   if (!play_next (play))
851     return;
852
853   g_main_loop_run (play->loop);
854 }
855
856 static gint
857 compare (gconstpointer a, gconstpointer b)
858 {
859   gchar *a1, *b1;
860   gint ret;
861
862   a1 = g_utf8_collate_key_for_filename ((gchar *) a, -1);
863   b1 = g_utf8_collate_key_for_filename ((gchar *) b, -1);
864   ret = strcmp (a1, b1);
865   g_free (a1);
866   g_free (b1);
867
868   return ret;
869 }
870
871 static void
872 add_to_playlist (GPtrArray * playlist, const gchar * filename)
873 {
874   GDir *dir;
875   gchar *uri;
876
877   if (gst_uri_is_valid (filename)) {
878     g_ptr_array_add (playlist, g_strdup (filename));
879     return;
880   }
881
882   if ((dir = g_dir_open (filename, 0, NULL))) {
883     const gchar *entry;
884     GList *l, *files = NULL;
885
886     while ((entry = g_dir_read_name (dir))) {
887       gchar *path;
888
889       path = g_build_filename (filename, entry, NULL);
890       files = g_list_insert_sorted (files, path, compare);
891     }
892
893     g_dir_close (dir);
894
895     for (l = files; l != NULL; l = l->next) {
896       gchar *path = (gchar *) l->data;
897
898       add_to_playlist (playlist, path);
899       g_free (path);
900     }
901     g_list_free (files);
902     return;
903   }
904
905   uri = gst_filename_to_uri (filename, NULL);
906   if (uri != NULL)
907     g_ptr_array_add (playlist, uri);
908   else
909     g_warning ("Could not make URI out of filename '%s'", filename);
910 }
911
912 static void
913 shuffle_uris (gchar ** uris, guint num)
914 {
915   gchar *tmp;
916   guint i, j;
917
918   if (num < 2)
919     return;
920
921   for (i = num - 1; i >= 1; i--) {
922     /* +1 because number returned will be in range [a;b[ so excl. stop */
923     j = g_random_int_range (0, i + 1);
924     tmp = uris[j];
925     uris[j] = uris[i];
926     uris[i] = tmp;
927   }
928 }
929
930 static void
931 restore_terminal (void)
932 {
933   gst_play_kb_set_key_handler (NULL, NULL);
934 }
935
936 static void
937 toggle_paused (GstPlay * play)
938 {
939   if (play->desired_state == GST_STATE_PLAYING)
940     play->desired_state = GST_STATE_PAUSED;
941   else
942     play->desired_state = GST_STATE_PLAYING;
943
944   if (!play->buffering) {
945     gst_element_set_state (play->playbin, play->desired_state);
946   } else if (play->desired_state == GST_STATE_PLAYING) {
947     gst_print ("\nWill play as soon as buffering finishes)\n");
948   }
949 }
950
951 static void
952 relative_seek (GstPlay * play, gdouble percent)
953 {
954   GstQuery *query;
955   gboolean seekable = FALSE;
956   gint64 dur = -1, pos = -1, step;
957
958   g_return_if_fail (percent >= -1.0 && percent <= 1.0);
959
960   if (!gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos))
961     goto seek_failed;
962
963   query = gst_query_new_seeking (GST_FORMAT_TIME);
964   if (!gst_element_query (play->playbin, query)) {
965     gst_query_unref (query);
966     goto seek_failed;
967   }
968
969   gst_query_parse_seeking (query, NULL, &seekable, NULL, &dur);
970   gst_query_unref (query);
971
972   if (!seekable || dur <= 0)
973     goto seek_failed;
974
975   step = dur * percent;
976   if (ABS (step) < GST_SECOND)
977     step = (percent < 0) ? -GST_SECOND : GST_SECOND;
978
979   pos = pos + step;
980   if (pos > dur) {
981     if (!play_next (play)) {
982       gst_print ("\n%s\n", _("Reached end of play list."));
983       g_main_loop_quit (play->loop);
984     }
985   } else {
986     if (pos < 0)
987       pos = 0;
988
989     play_do_seek (play, pos, play->rate, play->trick_mode);
990   }
991
992   return;
993
994 seek_failed:
995   {
996     gst_print ("\nCould not seek.\n");
997   }
998 }
999
1000 static gboolean
1001 play_set_rate_and_trick_mode (GstPlay * play, gdouble rate,
1002     GstPlayTrickMode mode)
1003 {
1004   gint64 pos = -1;
1005
1006   g_return_val_if_fail (rate != 0, FALSE);
1007
1008   if (!gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos))
1009     return FALSE;
1010
1011   return play_do_seek (play, pos, rate, mode);
1012 }
1013
1014 static gboolean
1015 play_do_seek (GstPlay * play, gint64 pos, gdouble rate, GstPlayTrickMode mode)
1016 {
1017   GstSeekFlags seek_flags;
1018   GstQuery *query;
1019   GstEvent *seek;
1020   gboolean seekable = FALSE;
1021
1022   query = gst_query_new_seeking (GST_FORMAT_TIME);
1023   if (!gst_element_query (play->playbin, query)) {
1024     gst_query_unref (query);
1025     return FALSE;
1026   }
1027
1028   gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
1029   gst_query_unref (query);
1030
1031   if (!seekable)
1032     return FALSE;
1033
1034   seek_flags = 0;
1035
1036   switch (mode) {
1037     case GST_PLAY_TRICK_MODE_DEFAULT:
1038       seek_flags |= GST_SEEK_FLAG_TRICKMODE;
1039       break;
1040     case GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO:
1041       seek_flags |= GST_SEEK_FLAG_TRICKMODE | GST_SEEK_FLAG_TRICKMODE_NO_AUDIO;
1042       break;
1043     case GST_PLAY_TRICK_MODE_KEY_UNITS:
1044       seek_flags |= GST_SEEK_FLAG_TRICKMODE_KEY_UNITS;
1045       break;
1046     case GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO:
1047       seek_flags |=
1048           GST_SEEK_FLAG_TRICKMODE_KEY_UNITS | GST_SEEK_FLAG_TRICKMODE_NO_AUDIO;
1049       break;
1050     case GST_PLAY_TRICK_MODE_NONE:
1051     default:
1052       break;
1053   }
1054
1055   /* See if we can do an instant rate change (not changing dir) */
1056   if (mode & GST_PLAY_TRICK_MODE_INSTANT_RATE && rate * play->rate > 0) {
1057     seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
1058         seek_flags | GST_SEEK_FLAG_INSTANT_RATE_CHANGE,
1059         GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE,
1060         GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
1061     if (gst_element_send_event (play->playbin, seek)) {
1062       goto done;
1063     }
1064   }
1065
1066   /* No instant rate change, need to do a flushing seek */
1067   seek_flags |= GST_SEEK_FLAG_FLUSH;
1068   if (rate >= 0)
1069     seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
1070         seek_flags | GST_SEEK_FLAG_ACCURATE,
1071         /* start */ GST_SEEK_TYPE_SET, pos,
1072         /* stop */ GST_SEEK_TYPE_SET, GST_CLOCK_TIME_NONE);
1073   else
1074     seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
1075         seek_flags | GST_SEEK_FLAG_ACCURATE,
1076         /* start */ GST_SEEK_TYPE_SET, 0,
1077         /* stop */ GST_SEEK_TYPE_SET, pos);
1078
1079   if (!gst_element_send_event (play->playbin, seek))
1080     return FALSE;
1081
1082 done:
1083   play->rate = rate;
1084   play->trick_mode = mode & ~GST_PLAY_TRICK_MODE_INSTANT_RATE;
1085   return TRUE;
1086 }
1087
1088 static void
1089 play_set_playback_rate (GstPlay * play, gdouble rate)
1090 {
1091   GstPlayTrickMode mode = play->trick_mode;
1092
1093   if (instant_rate_changes)
1094     mode |= GST_PLAY_TRICK_MODE_INSTANT_RATE;
1095
1096   if (play_set_rate_and_trick_mode (play, rate, mode)) {
1097     gst_print (_("Playback rate: %.2f"), rate);
1098     gst_print ("                               \n");
1099   } else {
1100     gst_print ("\n");
1101     gst_print (_("Could not change playback rate to %.2f"), rate);
1102     gst_print (".\n");
1103   }
1104 }
1105
1106 static void
1107 play_set_relative_playback_rate (GstPlay * play, gdouble rate_step,
1108     gboolean reverse_direction)
1109 {
1110   gdouble new_rate = play->rate + rate_step;
1111
1112   if (reverse_direction)
1113     new_rate *= -1.0;
1114
1115   play_set_playback_rate (play, new_rate);
1116 }
1117
1118 static const gchar *
1119 trick_mode_get_description (GstPlayTrickMode mode)
1120 {
1121   switch (mode) {
1122     case GST_PLAY_TRICK_MODE_NONE:
1123       return "normal playback, trick modes disabled";
1124     case GST_PLAY_TRICK_MODE_DEFAULT:
1125       return "trick mode: default";
1126     case GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO:
1127       return "trick mode: default, no audio";
1128     case GST_PLAY_TRICK_MODE_KEY_UNITS:
1129       return "trick mode: key frames only";
1130     case GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO:
1131       return "trick mode: key frames only, no audio";
1132     default:
1133       break;
1134   }
1135   return "unknown trick mode";
1136 }
1137
1138 static void
1139 play_switch_trick_mode (GstPlay * play)
1140 {
1141   GstPlayTrickMode new_mode = ++play->trick_mode;
1142   const gchar *mode_desc;
1143
1144   if (new_mode == GST_PLAY_TRICK_MODE_LAST)
1145     new_mode = GST_PLAY_TRICK_MODE_NONE;
1146
1147   mode_desc = trick_mode_get_description (new_mode);
1148
1149   if (play_set_rate_and_trick_mode (play, play->rate, new_mode)) {
1150     gst_print ("Rate: %.2f (%s)                      \n", play->rate,
1151         mode_desc);
1152   } else {
1153     gst_print ("\nCould not change trick mode to %s.\n", mode_desc);
1154   }
1155 }
1156
1157 static GstStream *
1158 play_get_nth_stream_in_collection (GstPlay * play, guint index,
1159     GstPlayTrackType track_type)
1160 {
1161   guint len, i, n_streams = 0;
1162   GstStreamType target_type;
1163
1164   switch (track_type) {
1165     case GST_PLAY_TRACK_TYPE_AUDIO:
1166       target_type = GST_STREAM_TYPE_AUDIO;
1167       break;
1168     case GST_PLAY_TRACK_TYPE_VIDEO:
1169       target_type = GST_STREAM_TYPE_VIDEO;
1170       break;
1171     case GST_PLAY_TRACK_TYPE_SUBTITLE:
1172       target_type = GST_STREAM_TYPE_TEXT;
1173       break;
1174     default:
1175       return NULL;
1176   }
1177
1178   len = gst_stream_collection_get_size (play->collection);
1179
1180   for (i = 0; i < len; i++) {
1181     GstStream *stream = gst_stream_collection_get_stream (play->collection, i);
1182     GstStreamType type = gst_stream_get_stream_type (stream);
1183
1184     if (type & target_type) {
1185       if (index == n_streams)
1186         return stream;
1187
1188       n_streams++;
1189     }
1190   }
1191
1192   return NULL;
1193 }
1194
1195 static void
1196 play_cycle_track_selection (GstPlay * play, GstPlayTrackType track_type,
1197     gboolean forward)
1198 {
1199   const gchar *prop_cur, *prop_n, *prop_get, *name;
1200   gint cur = -1, n = -1;
1201   guint flag, cur_flags;
1202
1203   /* playbin3 variables */
1204   GList *selected_streams = NULL;
1205   gint cur_audio_idx = -1, cur_video_idx = -1, cur_text_idx = -1;
1206   gint nb_audio = 0, nb_video = 0, nb_text = 0;
1207   guint len, i;
1208
1209   g_mutex_lock (&play->selection_lock);
1210   if (play->is_playbin3) {
1211     if (!play->collection) {
1212       gst_print ("No stream-collection\n");
1213       g_mutex_unlock (&play->selection_lock);
1214       return;
1215     }
1216
1217     /* Check the total number of streams of each type */
1218     len = gst_stream_collection_get_size (play->collection);
1219     for (i = 0; i < len; i++) {
1220       GstStream *stream =
1221           gst_stream_collection_get_stream (play->collection, i);
1222       if (stream) {
1223         GstStreamType type = gst_stream_get_stream_type (stream);
1224         const gchar *sid = gst_stream_get_stream_id (stream);
1225
1226         if (type & GST_STREAM_TYPE_AUDIO) {
1227           if (play->cur_audio_sid && !g_strcmp0 (play->cur_audio_sid, sid))
1228             cur_audio_idx = nb_audio;
1229           nb_audio++;
1230         } else if (type & GST_STREAM_TYPE_VIDEO) {
1231           if (play->cur_video_sid && !g_strcmp0 (play->cur_video_sid, sid))
1232             cur_video_idx = nb_video;
1233           nb_video++;
1234         } else if (type & GST_STREAM_TYPE_TEXT) {
1235           if (play->cur_text_sid && !g_strcmp0 (play->cur_text_sid, sid))
1236             cur_text_idx = nb_text;
1237           nb_text++;
1238         } else {
1239           gst_print ("Unknown stream type with stream-id %s", sid);
1240         }
1241       }
1242     }
1243   }
1244
1245   switch (track_type) {
1246     case GST_PLAY_TRACK_TYPE_AUDIO:
1247       prop_get = "get-audio-tags";
1248       prop_cur = "current-audio";
1249       prop_n = "n-audio";
1250       name = "audio";
1251       flag = 0x2;
1252       if (play->is_playbin3) {
1253         n = nb_audio;
1254         cur = cur_audio_idx;
1255         if (play->cur_video_sid) {
1256           selected_streams =
1257               g_list_append (selected_streams, play->cur_video_sid);
1258         }
1259         if (play->cur_text_sid) {
1260           selected_streams =
1261               g_list_append (selected_streams, play->cur_text_sid);
1262         }
1263       }
1264       break;
1265     case GST_PLAY_TRACK_TYPE_VIDEO:
1266       prop_get = "get-video-tags";
1267       prop_cur = "current-video";
1268       prop_n = "n-video";
1269       name = "video";
1270       flag = 0x1;
1271       if (play->is_playbin3) {
1272         n = nb_video;
1273         cur = cur_video_idx;
1274         if (play->cur_audio_sid) {
1275           selected_streams =
1276               g_list_append (selected_streams, play->cur_audio_sid);
1277         }
1278         if (play->cur_text_sid) {
1279           selected_streams =
1280               g_list_append (selected_streams, play->cur_text_sid);
1281         }
1282       }
1283       break;
1284     case GST_PLAY_TRACK_TYPE_SUBTITLE:
1285       prop_get = "get-text-tags";
1286       prop_cur = "current-text";
1287       prop_n = "n-text";
1288       name = "subtitle";
1289       flag = 0x4;
1290       if (play->is_playbin3) {
1291         n = nb_text;
1292         cur = cur_text_idx;
1293         if (play->cur_audio_sid) {
1294           selected_streams =
1295               g_list_append (selected_streams, play->cur_audio_sid);
1296         }
1297         if (play->cur_video_sid) {
1298           selected_streams =
1299               g_list_append (selected_streams, play->cur_video_sid);
1300         }
1301       }
1302       break;
1303     default:
1304       return;
1305   }
1306
1307   if (play->is_playbin3) {
1308     if (n > 0) {
1309       if (forward) {
1310         if (cur < 0)
1311           cur = 0;
1312         else
1313           cur = (cur + 1) % (n + 1);
1314       } else {
1315         if (cur <= 0)
1316           cur = n;
1317         else
1318           cur = (cur - 1) % (n + 1);
1319       }
1320     }
1321   } else {
1322     g_object_get (play->playbin, prop_cur, &cur, prop_n, &n, "flags",
1323         &cur_flags, NULL);
1324
1325     if (forward) {
1326       if (!(cur_flags & flag))
1327         cur = 0;
1328       else
1329         cur = (cur + 1) % (n + 1);
1330
1331     } else {
1332       if (cur <= 0)
1333         cur = n;
1334       else
1335         cur = (cur - 1) % (n + 1);
1336     }
1337   }
1338
1339   if (n < 1) {
1340     gst_print ("No %s tracks.\n", name);
1341     g_mutex_unlock (&play->selection_lock);
1342   } else {
1343     gchar *lcode = NULL, *lname = NULL;
1344     const gchar *lang = NULL;
1345     GstTagList *tags = NULL;
1346
1347     if (cur >= n && track_type != GST_PLAY_TRACK_TYPE_VIDEO) {
1348       cur = -1;
1349       gst_print ("Disabling %s.           \n", name);
1350       if (play->is_playbin3) {
1351         /* Just make it empty for the track type */
1352       } else if (cur_flags & flag) {
1353         cur_flags &= ~flag;
1354         g_object_set (play->playbin, "flags", cur_flags, NULL);
1355       }
1356     } else {
1357       /* For video we only want to switch between streams, not disable it altogether */
1358       if (cur >= n)
1359         cur = 0;
1360
1361       if (play->is_playbin3) {
1362         GstStream *stream;
1363
1364         stream = play_get_nth_stream_in_collection (play, cur, track_type);
1365         if (stream) {
1366           selected_streams = g_list_append (selected_streams,
1367               (gchar *) gst_stream_get_stream_id (stream));
1368           tags = gst_stream_get_tags (stream);
1369         } else {
1370           gst_print ("Collection has no stream for track %d of %d.\n",
1371               cur + 1, n);
1372         }
1373       } else {
1374         if (!(cur_flags & flag) && track_type != GST_PLAY_TRACK_TYPE_VIDEO) {
1375           cur_flags |= flag;
1376           g_object_set (play->playbin, "flags", cur_flags, NULL);
1377         }
1378         g_signal_emit_by_name (play->playbin, prop_get, cur, &tags);
1379       }
1380
1381       if (tags != NULL) {
1382         if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &lcode))
1383           lang = gst_tag_get_language_name (lcode);
1384         else if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_NAME, &lname))
1385           lang = lname;
1386         gst_tag_list_unref (tags);
1387       }
1388       if (lang != NULL)
1389         gst_print ("Switching to %s track %d of %d (%s).\n", name, cur + 1, n,
1390             lang);
1391       else
1392         gst_print ("Switching to %s track %d of %d.\n", name, cur + 1, n);
1393     }
1394     g_free (lcode);
1395     g_free (lname);
1396     g_mutex_unlock (&play->selection_lock);
1397
1398     if (play->is_playbin3) {
1399       if (selected_streams)
1400         gst_element_send_event (play->playbin,
1401             gst_event_new_select_streams (selected_streams));
1402       else
1403         gst_print ("Can't disable all streams !\n");
1404     } else {
1405       g_object_set (play->playbin, prop_cur, cur, NULL);
1406     }
1407   }
1408
1409   if (selected_streams)
1410     g_list_free (selected_streams);
1411 }
1412
1413 static void
1414 print_keyboard_help (void)
1415 {
1416   /* *INDENT-OFF* */
1417   static struct
1418   {
1419     const gchar *key_desc;
1420     const gchar *key_help;
1421   } key_controls[] = {
1422     {
1423     N_("space"), N_("pause/unpause")}, {
1424     N_("q or ESC"), N_("quit")}, {
1425     N_("> or n"), N_("play next")}, {
1426     N_("< or b"), N_("play previous")}, {
1427     "\342\206\222", N_("seek forward")}, {
1428     "\342\206\220", N_("seek backward")}, {
1429     "\342\206\221", N_("volume up")}, {
1430     "\342\206\223", N_("volume down")}, {
1431     "m", N_("toggle audio mute on/off")}, {
1432     "+", N_("increase playback rate")}, {
1433     "-", N_("decrease playback rate")}, {
1434     "d", N_("change playback direction")}, {
1435     "t", N_("enable/disable trick modes")}, {
1436     "A/a", N_("change to previous/next audio track")}, {
1437     "V/v", N_("change to previous/next video track")}, {
1438     "S/s", N_("change to previous/next subtitle track")}, {
1439     "0", N_("seek to beginning")}, {
1440   "k", N_("show keyboard shortcuts")},};
1441   /* *INDENT-ON* */
1442   guint i, chars_to_pad, desc_len, max_desc_len = 0;
1443
1444   gst_print ("\n\n%s\n\n", _("Interactive mode - keyboard controls:"));
1445
1446   for (i = 0; i < G_N_ELEMENTS (key_controls); ++i) {
1447     desc_len = g_utf8_strlen (key_controls[i].key_desc, -1);
1448     max_desc_len = MAX (max_desc_len, desc_len);
1449   }
1450   ++max_desc_len;
1451
1452   for (i = 0; i < G_N_ELEMENTS (key_controls); ++i) {
1453     chars_to_pad = max_desc_len - g_utf8_strlen (key_controls[i].key_desc, -1);
1454     gst_print ("\t%s", key_controls[i].key_desc);
1455     gst_print ("%-*s: ", chars_to_pad, "");
1456     gst_print ("%s\n", key_controls[i].key_help);
1457   }
1458   gst_print ("\n");
1459 }
1460
1461 static void
1462 keyboard_cb (const gchar * key_input, gpointer user_data)
1463 {
1464   GstPlay *play = (GstPlay *) user_data;
1465   gchar key = '\0';
1466
1467   /* Switch on the first char for single char inputs,
1468    * otherwise leave key = '\0' to fall through to
1469    * the default case below */
1470   if (key_input[0] != '\0' && key_input[1] == '\0') {
1471     key = key_input[0];
1472   }
1473
1474   switch (key) {
1475     case 'k':
1476       print_keyboard_help ();
1477       break;
1478     case ' ':
1479       toggle_paused (play);
1480       break;
1481     case 'q':
1482     case 'Q':
1483       g_main_loop_quit (play->loop);
1484       break;
1485     case 'n':
1486     case '>':
1487       if (!play_next (play)) {
1488         gst_print ("\n%s\n", _("Reached end of play list."));
1489         g_main_loop_quit (play->loop);
1490       }
1491       break;
1492     case 'b':
1493     case '<':
1494       play_prev (play);
1495       break;
1496     case '+':
1497       if (play->rate > -0.2 && play->rate < 0.0)
1498         play_set_relative_playback_rate (play, 0.0, TRUE);
1499       else if (ABS (play->rate) < 2.0)
1500         play_set_relative_playback_rate (play, 0.1, FALSE);
1501       else if (ABS (play->rate) < 4.0)
1502         play_set_relative_playback_rate (play, 0.5, FALSE);
1503       else
1504         play_set_relative_playback_rate (play, 1.0, FALSE);
1505       break;
1506     case '-':
1507       if (play->rate > 0.0 && play->rate < 0.20)
1508         play_set_relative_playback_rate (play, 0.0, TRUE);
1509       else if (ABS (play->rate) <= 2.0)
1510         play_set_relative_playback_rate (play, -0.1, FALSE);
1511       else if (ABS (play->rate) <= 4.0)
1512         play_set_relative_playback_rate (play, -0.5, FALSE);
1513       else
1514         play_set_relative_playback_rate (play, -1.0, FALSE);
1515       break;
1516     case 'd':
1517       play_set_relative_playback_rate (play, 0.0, TRUE);
1518       break;
1519     case 't':
1520       play_switch_trick_mode (play);
1521       break;
1522     case 27:                   /* ESC */
1523       if (key_input[1] == '\0') {
1524         g_main_loop_quit (play->loop);
1525         break;
1526       }
1527     case 'a':
1528     case 'A':
1529       play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_AUDIO, key == 'a');
1530       break;
1531     case 'v':
1532     case 'V':
1533       play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_VIDEO, key == 'v');
1534       break;
1535     case 's':
1536     case 'S':
1537       play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_SUBTITLE,
1538           key == 's');
1539       break;
1540     case '0':
1541       play_do_seek (play, 0, play->rate, play->trick_mode);
1542       break;
1543     case 'm':
1544       play_toggle_audio_mute (play);
1545       break;
1546     default:
1547       if (strcmp (key_input, GST_PLAY_KB_ARROW_RIGHT) == 0) {
1548         relative_seek (play, +0.08);
1549       } else if (strcmp (key_input, GST_PLAY_KB_ARROW_LEFT) == 0) {
1550         relative_seek (play, -0.01);
1551       } else if (strcmp (key_input, GST_PLAY_KB_ARROW_UP) == 0) {
1552         play_set_relative_volume (play, +1.0 / VOLUME_STEPS);
1553       } else if (strcmp (key_input, GST_PLAY_KB_ARROW_DOWN) == 0) {
1554         play_set_relative_volume (play, -1.0 / VOLUME_STEPS);
1555       } else {
1556         GST_INFO ("keyboard input:");
1557         for (; *key_input != '\0'; ++key_input)
1558           GST_INFO ("  code %3d", *key_input);
1559       }
1560       break;
1561   }
1562 }
1563
1564 #ifdef HAVE_WINMM
1565 static guint
1566 enable_winmm_timer_resolution (void)
1567 {
1568   TIMECAPS time_caps;
1569   guint resolution = 0;
1570   MMRESULT res;
1571
1572   res = timeGetDevCaps (&time_caps, sizeof (TIMECAPS));
1573   if (res != TIMERR_NOERROR) {
1574     g_warning ("timeGetDevCaps() returned non-zero code %d", res);
1575     return 0;
1576   }
1577
1578   resolution = MIN (MAX (time_caps.wPeriodMin, 1), time_caps.wPeriodMax);
1579   res = timeBeginPeriod (resolution);
1580   if (res != TIMERR_NOERROR) {
1581     g_warning ("timeBeginPeriod() returned non-zero code %d", res);
1582     return 0;
1583   }
1584
1585   gst_println (_("Use Windows high-resolution clock, precision: %u ms\n"),
1586       resolution);
1587
1588   return resolution;
1589 }
1590
1591 static void
1592 clear_winmm_timer_resolution (guint resolution)
1593 {
1594   if (resolution == 0)
1595     return;
1596
1597   timeEndPeriod (resolution);
1598 }
1599 #endif
1600
1601 static int
1602 real_main (int argc, char **argv)
1603 {
1604   GstPlay *play;
1605   GPtrArray *playlist;
1606   gboolean verbose = FALSE;
1607   gboolean print_version = FALSE;
1608   gboolean interactive = TRUE;
1609   gboolean gapless = FALSE;
1610   gboolean instant_uri = FALSE;
1611   gboolean shuffle = FALSE;
1612   gdouble volume = -1;
1613   gdouble start_position = 0;
1614   gchar **filenames = NULL;
1615   gchar *audio_sink = NULL;
1616   gchar *video_sink = NULL;
1617   gchar **uris;
1618   gchar *flags = NULL;
1619   guint num, i;
1620   GError *err = NULL;
1621   GOptionContext *ctx;
1622   gchar *playlist_file = NULL;
1623   gboolean use_playbin3 = FALSE;
1624   gboolean no_position = FALSE;
1625 #ifdef HAVE_WINMM
1626   guint winmm_timer_resolution = 0;
1627 #endif
1628   GOptionEntry options[] = {
1629     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
1630         N_("Output status information and property notifications"), NULL},
1631     {"flags", 0, 0, G_OPTION_ARG_STRING, &flags,
1632           N_("Control playback behaviour setting playbin 'flags' property"),
1633         NULL},
1634     {"version", 0, 0, G_OPTION_ARG_NONE, &print_version,
1635         N_("Print version information and exit"), NULL},
1636     {"videosink", 0, 0, G_OPTION_ARG_STRING, &video_sink,
1637         N_("Video sink to use (default is autovideosink)"), NULL},
1638     {"audiosink", 0, 0, G_OPTION_ARG_STRING, &audio_sink,
1639         N_("Audio sink to use (default is autoaudiosink)"), NULL},
1640     {"gapless", 0, 0, G_OPTION_ARG_NONE, &gapless,
1641         N_("Enable gapless playback"), NULL},
1642     {"instant-uri", 0, 0, G_OPTION_ARG_NONE, &instant_uri,
1643         N_("Enable instantaneous uri changes (only with playbin3)"), NULL},
1644     {"shuffle", 0, 0, G_OPTION_ARG_NONE, &shuffle,
1645         N_("Shuffle playlist"), NULL},
1646     {"no-interactive", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE,
1647           &interactive,
1648         N_("Disable interactive control via the keyboard"), NULL},
1649     {"volume", 0, 0, G_OPTION_ARG_DOUBLE, &volume,
1650         N_("Volume"), NULL},
1651     {"start-position", 's', 0, G_OPTION_ARG_DOUBLE, &start_position,
1652         N_("Start position in seconds."), NULL},
1653     {"playlist", 0, 0, G_OPTION_ARG_FILENAME, &playlist_file,
1654         N_("Playlist file containing input media files"), NULL},
1655     {"instant-rate-changes", 'i', 0, G_OPTION_ARG_NONE, &instant_rate_changes,
1656           N_
1657           ("Use the experimental instant-rate-change flag when changing rate"),
1658         NULL},
1659     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
1660         N_("Do not print any output (apart from errors)"), NULL},
1661     {"use-playbin3", 0, 0, G_OPTION_ARG_NONE, &use_playbin3,
1662           N_("Use playbin3 pipeline "
1663               "(default varies depending on 'USE_PLAYBIN' env variable)"),
1664         NULL},
1665     {"wait-on-eos", 0, 0, G_OPTION_ARG_NONE, &wait_on_eos,
1666           N_
1667           ("Keep showing the last frame on EOS until quit or playlist change command "
1668               "(gapless is ignored)"),
1669         NULL},
1670     {"no-position", 0, 0, G_OPTION_ARG_NONE, &no_position,
1671           N_("Do not print current position of pipeline"),
1672         NULL},
1673     {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &filenames, NULL},
1674     {NULL}
1675   };
1676
1677   setlocale (LC_ALL, "");
1678
1679 #ifdef ENABLE_NLS
1680   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
1681   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1682   textdomain (GETTEXT_PACKAGE);
1683 #endif
1684
1685   g_set_prgname ("gst-play-" GST_API_VERSION);
1686   /* Ensure XInitThreads() is called if/when needed */
1687   g_setenv ("GST_GL_XINITTHREADS", "1", TRUE);
1688   g_setenv ("GST_XINITTHREADS", "1", TRUE);
1689
1690   ctx = g_option_context_new ("FILE1|URI1 [FILE2|URI2] [FILE3|URI3] ...");
1691   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
1692   g_option_context_add_group (ctx, gst_init_get_option_group ());
1693   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
1694     gst_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
1695     g_option_context_free (ctx);
1696     g_clear_error (&err);
1697     return 1;
1698   }
1699   g_option_context_free (ctx);
1700
1701   GST_DEBUG_CATEGORY_INIT (play_debug, "play", 0, "gst-play");
1702
1703   if (print_version) {
1704     gchar *version_str;
1705
1706     version_str = gst_version_string ();
1707     gst_print ("%s version %s\n", g_get_prgname (), PACKAGE_VERSION);
1708     gst_print ("%s\n", version_str);
1709     gst_print ("%s\n", GST_PACKAGE_ORIGIN);
1710     g_free (version_str);
1711
1712     g_free (audio_sink);
1713     g_free (video_sink);
1714     g_free (playlist_file);
1715
1716     return 0;
1717   }
1718
1719   if (wait_on_eos)
1720     gapless = FALSE;
1721
1722   playlist = g_ptr_array_new ();
1723
1724   if (playlist_file != NULL) {
1725     gchar *playlist_contents = NULL;
1726     gchar **lines = NULL;
1727
1728     if (g_file_get_contents (playlist_file, &playlist_contents, NULL, &err)) {
1729       lines = g_strsplit (playlist_contents, "\n", 0);
1730       num = g_strv_length (lines);
1731
1732       for (i = 0; i < num; i++) {
1733         if (lines[i][0] != '\0') {
1734           GST_LOG ("Playlist[%d]: %s", i + 1, lines[i]);
1735           add_to_playlist (playlist, lines[i]);
1736         }
1737       }
1738       g_strfreev (lines);
1739       g_free (playlist_contents);
1740     } else {
1741       gst_printerr ("Could not read playlist: %s\n", err->message);
1742       g_clear_error (&err);
1743     }
1744     g_free (playlist_file);
1745     playlist_file = NULL;
1746   }
1747
1748   if (playlist->len == 0 && (filenames == NULL || *filenames == NULL)) {
1749     gst_printerr (_("Usage: %s FILE1|URI1 [FILE2|URI2] [FILE3|URI3] ..."),
1750         "gst-play-" GST_API_VERSION);
1751     gst_printerr ("\n\n"),
1752         gst_printerr ("%s\n\n",
1753         _("You must provide at least one filename or URI to play."));
1754     /* No input provided. Free array */
1755     g_ptr_array_free (playlist, TRUE);
1756
1757     g_free (audio_sink);
1758     g_free (video_sink);
1759
1760     return 1;
1761   }
1762
1763   /* fill playlist */
1764   if (filenames != NULL && *filenames != NULL) {
1765     num = g_strv_length (filenames);
1766     for (i = 0; i < num; ++i) {
1767       GST_LOG ("command line argument: %s", filenames[i]);
1768       add_to_playlist (playlist, filenames[i]);
1769     }
1770     g_strfreev (filenames);
1771   }
1772
1773   num = playlist->len;
1774   g_ptr_array_add (playlist, NULL);
1775
1776   uris = (gchar **) g_ptr_array_free (playlist, FALSE);
1777
1778   if (shuffle)
1779     shuffle_uris (uris, num);
1780
1781   /* prepare */
1782   play =
1783       play_new (uris, audio_sink, video_sink, gapless, instant_uri, volume,
1784       verbose, flags, use_playbin3, start_position, no_position);
1785
1786   if (play == NULL) {
1787     gst_printerr
1788         ("Failed to create 'playbin' element. Check your GStreamer installation.\n");
1789     return EXIT_FAILURE;
1790   }
1791 #ifdef HAVE_WINMM
1792   /* Enable high-precision clock which will improve accuracy of various
1793    * Windows timer APIs (e.g., Sleep()), and it will increase the precision
1794    * of GstSystemClock as well
1795    */
1796
1797   /* NOTE: Once timer resolution is updated via timeBeginPeriod(),
1798    * application should undo it by calling timeEndPeriod()
1799    *
1800    * Prior to Windows 10, version 2004, timeBeginPeriod() affects global
1801    * Windows setting (meaning that it will affect other processes),
1802    * but starting with Windows 10, version 2004, this function no longer
1803    * affects global timer resolution
1804    */
1805   winmm_timer_resolution = enable_winmm_timer_resolution ();
1806 #endif
1807
1808   if (interactive) {
1809     if (gst_play_kb_set_key_handler (keyboard_cb, play)) {
1810       gst_print (_("Press 'k' to see a list of keyboard shortcuts.\n"));
1811       atexit (restore_terminal);
1812     } else {
1813       gst_print ("Interactive keyboard handling in terminal not available.\n");
1814     }
1815   }
1816
1817   /* play */
1818   do_play (play);
1819
1820 #ifdef HAVE_WINMM
1821   /* Undo timeBeginPeriod() if required */
1822   clear_winmm_timer_resolution (winmm_timer_resolution);
1823 #endif
1824
1825   /* clean up */
1826   play_free (play);
1827
1828   g_free (audio_sink);
1829   g_free (video_sink);
1830
1831   gst_print ("\n");
1832   gst_deinit ();
1833   return 0;
1834 }
1835
1836 int
1837 main (int argc, char *argv[])
1838 {
1839 #if defined(__APPLE__) && TARGET_OS_MAC && !TARGET_OS_IPHONE
1840   return gst_macos_main ((GstMainFunc) real_main, argc, argv, NULL);
1841 #else
1842   return real_main (argc, argv);
1843 #endif
1844 }