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