tools: gst-play: add 'n' and 'b' as additional shortcuts for next/previous item
[platform/upstream/gst-plugins-base.git] / 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 <gst/gst-i18n-app.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 #include "gst-play-kb.h"
43
44 #define VOLUME_STEPS 20
45
46 GST_DEBUG_CATEGORY (play_debug);
47 #define GST_CAT_DEFAULT play_debug
48
49 typedef enum
50 {
51   GST_PLAY_TRICK_MODE_NONE = 0,
52   GST_PLAY_TRICK_MODE_DEFAULT,
53   GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO,
54   GST_PLAY_TRICK_MODE_KEY_UNITS,
55   GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO,
56   GST_PLAY_TRICK_MODE_LAST
57 } GstPlayTrickMode;
58
59 typedef enum
60 {
61   GST_PLAY_TRACK_TYPE_INVALID = 0,
62   GST_PLAY_TRACK_TYPE_AUDIO,
63   GST_PLAY_TRACK_TYPE_VIDEO,
64   GST_PLAY_TRACK_TYPE_SUBTITLE
65 } GstPlayTrackType;
66
67 typedef struct
68 {
69   gchar **uris;
70   guint num_uris;
71   gint cur_idx;
72
73   GstElement *playbin;
74
75   GMainLoop *loop;
76   guint bus_watch;
77   guint timeout;
78
79   /* missing plugin messages */
80   GList *missing;
81
82   gboolean buffering;
83   gboolean is_live;
84
85   GstState desired_state;       /* as per user interaction, PAUSED or PLAYING */
86
87   gulong deep_notify_id;
88
89   /* configuration */
90   gboolean gapless;
91
92   GstPlayTrickMode trick_mode;
93   gdouble rate;
94 } GstPlay;
95
96 static gboolean quiet = FALSE;
97
98 static gboolean play_bus_msg (GstBus * bus, GstMessage * msg, gpointer data);
99 static gboolean play_next (GstPlay * play);
100 static gboolean play_prev (GstPlay * play);
101 static gboolean play_timeout (gpointer user_data);
102 static void play_about_to_finish (GstElement * playbin, gpointer user_data);
103 static void play_reset (GstPlay * play);
104 static void play_set_relative_volume (GstPlay * play, gdouble volume_step);
105 static gboolean play_do_seek (GstPlay * play, gint64 pos, gdouble rate,
106     GstPlayTrickMode mode);
107
108 /* *INDENT-OFF* */
109 static void gst_play_printf (const gchar * format, ...) G_GNUC_PRINTF (1, 2);
110 /* *INDENT-ON* */
111
112 static void keyboard_cb (const gchar * key_input, gpointer user_data);
113 static void relative_seek (GstPlay * play, gdouble percent);
114
115 static void
116 gst_play_printf (const gchar * format, ...)
117 {
118   gchar *str = NULL;
119   va_list args;
120   int len;
121
122   if (quiet)
123     return;
124
125   va_start (args, format);
126
127   len = g_vasprintf (&str, format, args);
128
129   va_end (args);
130
131   if (len > 0 && str != NULL)
132     g_print ("%s", str);
133
134   g_free (str);
135 }
136
137 #define g_print gst_play_printf
138
139 static GstPlay *
140 play_new (gchar ** uris, const gchar * audio_sink, const gchar * video_sink,
141     gboolean gapless, gdouble initial_volume, gboolean verbose,
142     const gchar * flags_string)
143 {
144   GstElement *sink, *playbin;
145   GstPlay *play;
146
147   playbin = gst_element_factory_make ("playbin", "playbin");
148   if (playbin == NULL)
149     return NULL;
150
151   play = g_new0 (GstPlay, 1);
152
153   play->uris = uris;
154   play->num_uris = g_strv_length (uris);
155   play->cur_idx = -1;
156
157   play->playbin = playbin;
158
159   if (audio_sink != NULL) {
160     if (strchr (audio_sink, ' ') != NULL)
161       sink = gst_parse_bin_from_description (audio_sink, TRUE, NULL);
162     else
163       sink = gst_element_factory_make (audio_sink, NULL);
164
165     if (sink != NULL)
166       g_object_set (play->playbin, "audio-sink", sink, NULL);
167     else
168       g_warning ("Couldn't create specified audio sink '%s'", audio_sink);
169   }
170   if (video_sink != NULL) {
171     if (strchr (video_sink, ' ') != NULL)
172       sink = gst_parse_bin_from_description (video_sink, TRUE, NULL);
173     else
174       sink = gst_element_factory_make (video_sink, NULL);
175
176     if (sink != NULL)
177       g_object_set (play->playbin, "video-sink", sink, NULL);
178     else
179       g_warning ("Couldn't create specified video sink '%s'", video_sink);
180   }
181
182   if (flags_string != NULL) {
183     GParamSpec *pspec;
184     GValue val = { 0, };
185
186     pspec =
187         g_object_class_find_property (G_OBJECT_GET_CLASS (playbin), "flags");
188     g_value_init (&val, pspec->value_type);
189     if (gst_value_deserialize (&val, flags_string))
190       g_object_set_property (G_OBJECT (play->playbin), "flags", &val);
191     else
192       g_printerr ("Couldn't convert '%s' to playbin flags!\n", flags_string);
193     g_value_unset (&val);
194   }
195
196   if (verbose) {
197     play->deep_notify_id = g_signal_connect (play->playbin, "deep-notify",
198         G_CALLBACK (gst_object_default_deep_notify), NULL);
199   }
200
201   play->loop = g_main_loop_new (NULL, FALSE);
202
203   play->bus_watch = gst_bus_add_watch (GST_ELEMENT_BUS (play->playbin),
204       play_bus_msg, play);
205
206   /* FIXME: make configurable incl. 0 for disable */
207   play->timeout = g_timeout_add (100, play_timeout, play);
208
209   play->missing = NULL;
210   play->buffering = FALSE;
211   play->is_live = FALSE;
212
213   play->desired_state = GST_STATE_PLAYING;
214
215   play->gapless = gapless;
216   if (gapless) {
217     g_signal_connect (play->playbin, "about-to-finish",
218         G_CALLBACK (play_about_to_finish), play);
219   }
220
221   if (initial_volume != -1)
222     play_set_relative_volume (play, initial_volume - 1.0);
223
224   play->rate = 1.0;
225   play->trick_mode = GST_PLAY_TRICK_MODE_NONE;
226
227   return play;
228 }
229
230 static void
231 play_free (GstPlay * play)
232 {
233   /* No need to see all those pad caps going to NULL etc., it's just noise */
234   if (play->deep_notify_id != 0)
235     g_signal_handler_disconnect (play->playbin, play->deep_notify_id);
236
237   play_reset (play);
238
239   gst_element_set_state (play->playbin, GST_STATE_NULL);
240   gst_object_unref (play->playbin);
241
242   g_source_remove (play->bus_watch);
243   g_source_remove (play->timeout);
244   g_main_loop_unref (play->loop);
245
246   g_strfreev (play->uris);
247   g_free (play);
248 }
249
250 /* reset for new file/stream */
251 static void
252 play_reset (GstPlay * play)
253 {
254   g_list_foreach (play->missing, (GFunc) gst_message_unref, NULL);
255   play->missing = NULL;
256
257   play->buffering = FALSE;
258   play->is_live = FALSE;
259 }
260
261 static void
262 play_set_relative_volume (GstPlay * play, gdouble volume_step)
263 {
264   gdouble volume;
265
266   volume = gst_stream_volume_get_volume (GST_STREAM_VOLUME (play->playbin),
267       GST_STREAM_VOLUME_FORMAT_CUBIC);
268
269   volume = round ((volume + volume_step) * VOLUME_STEPS) / VOLUME_STEPS;
270   volume = CLAMP (volume, 0.0, 10.0);
271
272   gst_stream_volume_set_volume (GST_STREAM_VOLUME (play->playbin),
273       GST_STREAM_VOLUME_FORMAT_CUBIC, volume);
274
275   g_print (_("Volume: %.0f%%"), volume * 100);
276   g_print ("                  \n");
277 }
278
279 /* returns TRUE if something was installed and we should restart playback */
280 static gboolean
281 play_install_missing_plugins (GstPlay * play)
282 {
283   /* FIXME: implement: try to install any missing plugins we haven't
284    * tried to install before */
285   return FALSE;
286 }
287
288 static gboolean
289 play_bus_msg (GstBus * bus, GstMessage * msg, gpointer user_data)
290 {
291   GstPlay *play = user_data;
292
293   switch (GST_MESSAGE_TYPE (msg)) {
294     case GST_MESSAGE_ASYNC_DONE:
295
296       /* dump graph on preroll */
297       GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
298           GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.async-done");
299
300       g_print ("Prerolled.\r");
301       if (play->missing != NULL && play_install_missing_plugins (play)) {
302         g_print ("New plugins installed, trying again...\n");
303         --play->cur_idx;
304         play_next (play);
305       }
306       break;
307     case GST_MESSAGE_BUFFERING:{
308       gint percent;
309
310       if (!play->buffering)
311         g_print ("\n");
312
313       gst_message_parse_buffering (msg, &percent);
314       g_print ("%s %d%%  \r", _("Buffering..."), percent);
315
316       if (percent == 100) {
317         /* a 100% message means buffering is done */
318         if (play->buffering) {
319           play->buffering = FALSE;
320           /* no state management needed for live pipelines */
321           if (!play->is_live)
322             gst_element_set_state (play->playbin, play->desired_state);
323         }
324       } else {
325         /* buffering... */
326         if (!play->buffering) {
327           if (!play->is_live)
328             gst_element_set_state (play->playbin, GST_STATE_PAUSED);
329           play->buffering = TRUE;
330         }
331       }
332       break;
333     }
334     case GST_MESSAGE_CLOCK_LOST:{
335       g_print (_("Clock lost, selecting a new one\n"));
336       gst_element_set_state (play->playbin, GST_STATE_PAUSED);
337       gst_element_set_state (play->playbin, GST_STATE_PLAYING);
338       break;
339     }
340     case GST_MESSAGE_LATENCY:
341       g_print ("Redistribute latency...\n");
342       gst_bin_recalculate_latency (GST_BIN (play->playbin));
343       break;
344     case GST_MESSAGE_REQUEST_STATE:{
345       GstState state;
346       gchar *name;
347
348       name = gst_object_get_path_string (GST_MESSAGE_SRC (msg));
349
350       gst_message_parse_request_state (msg, &state);
351
352       g_print ("Setting state to %s as requested by %s...\n",
353           gst_element_state_get_name (state), name);
354
355       gst_element_set_state (play->playbin, state);
356       g_free (name);
357       break;
358     }
359     case GST_MESSAGE_EOS:
360       /* print final position at end */
361       play_timeout (play);
362       g_print ("\n");
363       /* and switch to next item in list */
364       if (!play_next (play)) {
365         g_print ("%s\n", _("Reached end of play list."));
366         g_main_loop_quit (play->loop);
367       }
368       break;
369     case GST_MESSAGE_WARNING:{
370       GError *err;
371       gchar *dbg = NULL;
372
373       /* dump graph on warning */
374       GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
375           GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.warning");
376
377       gst_message_parse_warning (msg, &err, &dbg);
378       g_printerr ("WARNING %s\n", err->message);
379       if (dbg != NULL)
380         g_printerr ("WARNING debug information: %s\n", dbg);
381       g_clear_error (&err);
382       g_free (dbg);
383       break;
384     }
385     case GST_MESSAGE_ERROR:{
386       GError *err;
387       gchar *dbg;
388
389       /* dump graph on error */
390       GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
391           GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.error");
392
393       gst_message_parse_error (msg, &err, &dbg);
394       g_printerr ("ERROR %s for %s\n", err->message, play->uris[play->cur_idx]);
395       if (dbg != NULL)
396         g_printerr ("ERROR debug information: %s\n", dbg);
397       g_clear_error (&err);
398       g_free (dbg);
399
400       /* flush any other error messages from the bus and clean up */
401       gst_element_set_state (play->playbin, GST_STATE_NULL);
402
403       if (play->missing != NULL && play_install_missing_plugins (play)) {
404         g_print ("New plugins installed, trying again...\n");
405         --play->cur_idx;
406         play_next (play);
407         break;
408       }
409       /* try next item in list then */
410       if (!play_next (play)) {
411         g_print ("%s\n", _("Reached end of play list."));
412         g_main_loop_quit (play->loop);
413       }
414       break;
415     }
416     case GST_MESSAGE_ELEMENT:
417     {
418       GstNavigationMessageType mtype = gst_navigation_message_get_type (msg);
419       if (mtype == GST_NAVIGATION_MESSAGE_EVENT) {
420         GstEvent *ev = NULL;
421
422         if (gst_navigation_message_parse_event (msg, &ev)) {
423           GstNavigationEventType e_type = gst_navigation_event_get_type (ev);
424           switch (e_type) {
425             case GST_NAVIGATION_EVENT_KEY_PRESS:
426             {
427               const gchar *key;
428
429               if (gst_navigation_event_parse_key_event (ev, &key)) {
430                 GST_INFO ("Key press: %s", key);
431
432                 if (strcmp (key, "Left") == 0)
433                   key = GST_PLAY_KB_ARROW_LEFT;
434                 else if (strcmp (key, "Right") == 0)
435                   key = GST_PLAY_KB_ARROW_RIGHT;
436                 else if (strcmp (key, "Up") == 0)
437                   key = GST_PLAY_KB_ARROW_UP;
438                 else if (strcmp (key, "Down") == 0)
439                   key = GST_PLAY_KB_ARROW_DOWN;
440                 else if (strcmp (key, "space") == 0)
441                   key = " ";
442                 else if (strlen (key) > 1)
443                   break;
444
445                 keyboard_cb (key, user_data);
446               }
447               break;
448             }
449             case GST_NAVIGATION_EVENT_MOUSE_BUTTON_PRESS:
450             {
451               gint button;
452               if (gst_navigation_event_parse_mouse_button_event (ev, &button,
453                       NULL, NULL)) {
454                 if (button == 4) {
455                   /* wheel up */
456                   relative_seek (play, +0.08);
457                 } else if (button == 5) {
458                   /* wheel down */
459                   relative_seek (play, -0.01);
460                 }
461               }
462               break;
463             }
464             default:
465               break;
466           }
467         }
468         if (ev)
469           gst_event_unref (ev);
470       }
471       break;
472     }
473     default:
474       if (gst_is_missing_plugin_message (msg)) {
475         gchar *desc;
476
477         desc = gst_missing_plugin_message_get_description (msg);
478         g_print ("Missing plugin: %s\n", desc);
479         g_free (desc);
480         play->missing = g_list_append (play->missing, gst_message_ref (msg));
481       }
482       break;
483   }
484
485   return TRUE;
486 }
487
488 static gboolean
489 play_timeout (gpointer user_data)
490 {
491   GstPlay *play = user_data;
492   gint64 pos = -1, dur = -1;
493   const gchar *paused = _("Paused");
494   gchar *status;
495
496   if (play->buffering)
497     return TRUE;
498
499   gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos);
500   gst_element_query_duration (play->playbin, GST_FORMAT_TIME, &dur);
501
502   if (play->desired_state == GST_STATE_PAUSED) {
503     status = (gchar *) paused;
504   } else {
505     gint len = g_utf8_strlen (paused, -1);
506     status = g_newa (gchar, len + 1);
507     memset (status, ' ', len);
508     status[len] = '\0';
509   }
510
511   if (pos >= 0 && dur > 0) {
512     gchar dstr[32], pstr[32];
513
514     /* FIXME: pretty print in nicer format */
515     g_snprintf (pstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
516     pstr[9] = '\0';
517     g_snprintf (dstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
518     dstr[9] = '\0';
519     g_print ("%s / %s %s\r", pstr, dstr, status);
520   }
521
522   return TRUE;
523 }
524
525 static gchar *
526 play_uri_get_display_name (GstPlay * play, const gchar * uri)
527 {
528   gchar *loc;
529
530   if (gst_uri_has_protocol (uri, "file")) {
531     loc = g_filename_from_uri (uri, NULL, NULL);
532   } else if (gst_uri_has_protocol (uri, "pushfile")) {
533     loc = g_filename_from_uri (uri + 4, NULL, NULL);
534   } else {
535     loc = g_strdup (uri);
536   }
537
538   /* Maybe additionally use glib's filename to display name function */
539   return loc;
540 }
541
542 static void
543 play_uri (GstPlay * play, const gchar * next_uri)
544 {
545   gchar *loc;
546
547   gst_element_set_state (play->playbin, GST_STATE_READY);
548   play_reset (play);
549
550   loc = play_uri_get_display_name (play, next_uri);
551   g_print (_("Now playing %s\n"), loc);
552   g_free (loc);
553
554   g_object_set (play->playbin, "uri", next_uri, NULL);
555
556   switch (gst_element_set_state (play->playbin, GST_STATE_PAUSED)) {
557     case GST_STATE_CHANGE_FAILURE:
558       /* ignore, we should get an error message posted on the bus */
559       break;
560     case GST_STATE_CHANGE_NO_PREROLL:
561       g_print ("Pipeline is live.\n");
562       play->is_live = TRUE;
563       break;
564     case GST_STATE_CHANGE_ASYNC:
565       g_print ("Prerolling...\r");
566       break;
567     default:
568       break;
569   }
570
571   if (play->desired_state != GST_STATE_PAUSED)
572     gst_element_set_state (play->playbin, play->desired_state);
573 }
574
575 /* returns FALSE if we have reached the end of the playlist */
576 static gboolean
577 play_next (GstPlay * play)
578 {
579   if ((play->cur_idx + 1) >= play->num_uris)
580     return FALSE;
581
582   play_uri (play, play->uris[++play->cur_idx]);
583   return TRUE;
584 }
585
586 /* returns FALSE if we have reached the beginning of the playlist */
587 static gboolean
588 play_prev (GstPlay * play)
589 {
590   if (play->cur_idx == 0 || play->num_uris <= 1)
591     return FALSE;
592
593   play_uri (play, play->uris[--play->cur_idx]);
594   return TRUE;
595 }
596
597 static void
598 play_about_to_finish (GstElement * playbin, gpointer user_data)
599 {
600   GstPlay *play = user_data;
601   const gchar *next_uri;
602   gchar *loc;
603   guint next_idx;
604
605   if (!play->gapless)
606     return;
607
608   next_idx = play->cur_idx + 1;
609   if (next_idx >= play->num_uris)
610     return;
611
612   next_uri = play->uris[next_idx];
613   loc = play_uri_get_display_name (play, next_uri);
614   g_print (_("About to finish, preparing next title: %s"), loc);
615   g_print ("\n");
616   g_free (loc);
617
618   g_object_set (play->playbin, "uri", next_uri, NULL);
619   play->cur_idx = next_idx;
620
621   g_object_set (play->playbin, "-v", NULL);
622 }
623
624 static void
625 do_play (GstPlay * play)
626 {
627   gint i;
628
629   /* dump playlist */
630   for (i = 0; i < play->num_uris; ++i)
631     GST_INFO ("%4u : %s", i, play->uris[i]);
632
633   if (!play_next (play))
634     return;
635
636   g_main_loop_run (play->loop);
637 }
638
639 static gint
640 compare (gconstpointer a, gconstpointer b)
641 {
642   gchar *a1, *b1;
643   gint ret;
644
645   a1 = g_utf8_collate_key_for_filename ((gchar *) a, -1);
646   b1 = g_utf8_collate_key_for_filename ((gchar *) b, -1);
647   ret = strcmp (a1, b1);
648   g_free (a1);
649   g_free (b1);
650
651   return ret;
652 }
653
654 static void
655 add_to_playlist (GPtrArray * playlist, const gchar * filename)
656 {
657   GDir *dir;
658   gchar *uri;
659
660   if (gst_uri_is_valid (filename)) {
661     g_ptr_array_add (playlist, g_strdup (filename));
662     return;
663   }
664
665   if ((dir = g_dir_open (filename, 0, NULL))) {
666     const gchar *entry;
667     GList *l, *files = NULL;
668
669     while ((entry = g_dir_read_name (dir))) {
670       gchar *path;
671
672       path = g_build_filename (filename, entry, NULL);
673       files = g_list_insert_sorted (files, path, compare);
674     }
675
676     g_dir_close (dir);
677
678     for (l = files; l != NULL; l = l->next) {
679       gchar *path = (gchar *) l->data;
680
681       add_to_playlist (playlist, path);
682       g_free (path);
683     }
684     g_list_free (files);
685     return;
686   }
687
688   uri = gst_filename_to_uri (filename, NULL);
689   if (uri != NULL)
690     g_ptr_array_add (playlist, uri);
691   else
692     g_warning ("Could not make URI out of filename '%s'", filename);
693 }
694
695 static void
696 shuffle_uris (gchar ** uris, guint num)
697 {
698   gchar *tmp;
699   guint i, j;
700
701   if (num < 2)
702     return;
703
704   for (i = 0; i < num; i++) {
705     /* gets equally distributed random number in 0..num-1 [0;num[ */
706     j = g_random_int_range (0, num);
707     tmp = uris[j];
708     uris[j] = uris[i];
709     uris[i] = tmp;
710   }
711 }
712
713 static void
714 restore_terminal (void)
715 {
716   gst_play_kb_set_key_handler (NULL, NULL);
717 }
718
719 static void
720 toggle_paused (GstPlay * play)
721 {
722   if (play->desired_state == GST_STATE_PLAYING)
723     play->desired_state = GST_STATE_PAUSED;
724   else
725     play->desired_state = GST_STATE_PLAYING;
726
727   if (!play->buffering) {
728     gst_element_set_state (play->playbin, play->desired_state);
729   } else if (play->desired_state == GST_STATE_PLAYING) {
730     g_print ("\nWill play as soon as buffering finishes)\n");
731   }
732 }
733
734 static void
735 relative_seek (GstPlay * play, gdouble percent)
736 {
737   GstQuery *query;
738   gboolean seekable = FALSE;
739   gint64 dur = -1, pos = -1, step;
740
741   g_return_if_fail (percent >= -1.0 && percent <= 1.0);
742
743   if (!gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos))
744     goto seek_failed;
745
746   query = gst_query_new_seeking (GST_FORMAT_TIME);
747   if (!gst_element_query (play->playbin, query)) {
748     gst_query_unref (query);
749     goto seek_failed;
750   }
751
752   gst_query_parse_seeking (query, NULL, &seekable, NULL, &dur);
753   gst_query_unref (query);
754
755   if (!seekable || dur <= 0)
756     goto seek_failed;
757
758   step = dur * percent;
759   if (ABS (step) < GST_SECOND)
760     step = (percent < 0) ? -GST_SECOND : GST_SECOND;
761
762   pos = pos + step;
763   if (pos > dur) {
764     if (!play_next (play)) {
765       g_print ("\n%s\n", _("Reached end of play list."));
766       g_main_loop_quit (play->loop);
767     }
768   } else {
769     if (pos < 0)
770       pos = 0;
771
772     play_do_seek (play, pos, play->rate, play->trick_mode);
773   }
774
775   return;
776
777 seek_failed:
778   {
779     g_print ("\nCould not seek.\n");
780   }
781 }
782
783 static gboolean
784 play_set_rate_and_trick_mode (GstPlay * play, gdouble rate,
785     GstPlayTrickMode mode)
786 {
787   gint64 pos = -1;
788
789   g_return_val_if_fail (rate != 0, FALSE);
790
791   if (!gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos))
792     return FALSE;
793
794   return play_do_seek (play, pos, rate, mode);
795 }
796
797 static gboolean
798 play_do_seek (GstPlay * play, gint64 pos, gdouble rate, GstPlayTrickMode mode)
799 {
800   GstSeekFlags seek_flags;
801   GstQuery *query;
802   GstEvent *seek;
803   gboolean seekable = FALSE;
804
805   query = gst_query_new_seeking (GST_FORMAT_TIME);
806   if (!gst_element_query (play->playbin, query)) {
807     gst_query_unref (query);
808     return FALSE;
809   }
810
811   gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
812   gst_query_unref (query);
813
814   if (!seekable)
815     return FALSE;
816
817   seek_flags = GST_SEEK_FLAG_FLUSH;
818
819   switch (mode) {
820     case GST_PLAY_TRICK_MODE_DEFAULT:
821       seek_flags |= GST_SEEK_FLAG_TRICKMODE;
822       break;
823     case GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO:
824       seek_flags |= GST_SEEK_FLAG_TRICKMODE | GST_SEEK_FLAG_TRICKMODE_NO_AUDIO;
825       break;
826     case GST_PLAY_TRICK_MODE_KEY_UNITS:
827       seek_flags |= GST_SEEK_FLAG_TRICKMODE_KEY_UNITS;
828       break;
829     case GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO:
830       seek_flags |=
831           GST_SEEK_FLAG_TRICKMODE_KEY_UNITS | GST_SEEK_FLAG_TRICKMODE_NO_AUDIO;
832       break;
833     case GST_PLAY_TRICK_MODE_NONE:
834     default:
835       break;
836   }
837
838   if (rate >= 0)
839     seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
840         seek_flags | GST_SEEK_FLAG_ACCURATE,
841         /* start */ GST_SEEK_TYPE_SET, pos,
842         /* stop */ GST_SEEK_TYPE_SET, GST_CLOCK_TIME_NONE);
843   else
844     seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
845         seek_flags | GST_SEEK_FLAG_ACCURATE,
846         /* start */ GST_SEEK_TYPE_SET, 0,
847         /* stop */ GST_SEEK_TYPE_SET, pos);
848
849   if (!gst_element_send_event (play->playbin, seek))
850     return FALSE;
851
852   play->rate = rate;
853   play->trick_mode = mode;
854   return TRUE;
855 }
856
857 static void
858 play_set_playback_rate (GstPlay * play, gdouble rate)
859 {
860   if (play_set_rate_and_trick_mode (play, rate, play->trick_mode)) {
861     g_print (_("Playback rate: %.2f"), rate);
862     g_print ("                               \n");
863   } else {
864     g_print ("\n");
865     g_print (_("Could not change playback rate to %.2f"), rate);
866     g_print (".\n");
867   }
868 }
869
870 static void
871 play_set_relative_playback_rate (GstPlay * play, gdouble rate_step,
872     gboolean reverse_direction)
873 {
874   gdouble new_rate = play->rate + rate_step;
875
876   if (reverse_direction)
877     new_rate *= -1.0;
878
879   play_set_playback_rate (play, new_rate);
880 }
881
882 static const gchar *
883 trick_mode_get_description (GstPlayTrickMode mode)
884 {
885   switch (mode) {
886     case GST_PLAY_TRICK_MODE_NONE:
887       return "normal playback, trick modes disabled";
888     case GST_PLAY_TRICK_MODE_DEFAULT:
889       return "trick mode: default";
890     case GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO:
891       return "trick mode: default, no audio";
892     case GST_PLAY_TRICK_MODE_KEY_UNITS:
893       return "trick mode: key frames only";
894     case GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO:
895       return "trick mode: key frames only, no audio";
896     default:
897       break;
898   }
899   return "unknown trick mode";
900 }
901
902 static void
903 play_switch_trick_mode (GstPlay * play)
904 {
905   GstPlayTrickMode new_mode = ++play->trick_mode;
906   const gchar *mode_desc;
907
908   if (new_mode == GST_PLAY_TRICK_MODE_LAST)
909     new_mode = GST_PLAY_TRICK_MODE_NONE;
910
911   mode_desc = trick_mode_get_description (new_mode);
912
913   if (play_set_rate_and_trick_mode (play, play->rate, new_mode)) {
914     g_print ("Rate: %.2f (%s)                      \n", play->rate, mode_desc);
915   } else {
916     g_print ("\nCould not change trick mode to %s.\n", mode_desc);
917   }
918 }
919
920 static void
921 play_cycle_track_selection (GstPlay * play, GstPlayTrackType track_type)
922 {
923   const gchar *prop_cur, *prop_n, *prop_get, *name;
924   gint cur = -1, n = -1;
925
926   switch (track_type) {
927     case GST_PLAY_TRACK_TYPE_AUDIO:
928       prop_get = "get-audio-tags";
929       prop_cur = "current-audio";
930       prop_n = "n-audio";
931       name = "audio";
932       break;
933     case GST_PLAY_TRACK_TYPE_VIDEO:
934       prop_get = "get-video-tags";
935       prop_cur = "current-video";
936       prop_n = "n-video";
937       name = "video";
938       break;
939     case GST_PLAY_TRACK_TYPE_SUBTITLE:
940       prop_get = "get-text-tags";
941       prop_cur = "current-text";
942       prop_n = "n-text";
943       name = "subtitle";
944       break;
945     default:
946       return;
947   }
948
949   g_object_get (play->playbin, prop_cur, &cur, prop_n, &n, NULL);
950
951   if (n < 1) {
952     g_print ("No %s tracks.\n", name);
953   } else if (n == 1) {
954     g_print ("No other %s tracks to switch to.\n", name);
955   } else {
956     gchar *lcode = NULL, *lname = NULL;
957     const gchar *lang = NULL;
958     GstTagList *tags = NULL;
959
960     cur = (cur + 1) % n;
961     g_signal_emit_by_name (play->playbin, prop_get, cur, &tags);
962     if (tags != NULL) {
963       if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &lcode))
964         lang = gst_tag_get_language_name (lcode);
965       else if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_NAME, &lname))
966         lang = lname;
967       gst_tag_list_unref (tags);
968     }
969     if (lang != NULL)
970       g_print ("Switching to %s track %d of %d (%s).\n", name, cur + 1, n,
971           lang);
972     else
973       g_print ("Switching to %s track %d of %d.\n", name, cur + 1, n);
974     g_object_set (play->playbin, prop_cur, cur, NULL);
975     g_free (lcode);
976     g_free (lname);
977   }
978 }
979
980 static void
981 print_keyboard_help (void)
982 {
983   static struct
984   {
985     const gchar *key_desc;
986     const gchar *key_help;
987   } key_controls[] = {
988     {
989     N_("space"), N_("pause/unpause")}, {
990     N_("q or ESC"), N_("quit")}, {
991     N_("> or n"), N_("play next")}, {
992     N_("< or b"), N_("play previous")}, {
993     "\342\206\222", N_("seek forward")}, {
994     "\342\206\220", N_("seek backward")}, {
995     "\342\206\221", N_("volume up")}, {
996     "\342\206\223", N_("volume down")}, {
997     "+", N_("increase playback rate")}, {
998     "-", N_("decrease playback rate")}, {
999     "d", N_("change playback direction")}, {
1000     "t", N_("enable/disable trick modes")}, {
1001     "a", N_("change audio track")}, {
1002     "v", N_("change video track")}, {
1003     "s", N_("change subtitle track")}, {
1004     "0", N_("seek to beginning")}, {
1005   "k", N_("show keyboard shortcuts")},};
1006   guint i, chars_to_pad, desc_len, max_desc_len = 0;
1007
1008   g_print ("\n\n%s\n\n", _("Interactive mode - keyboard controls:"));
1009
1010   for (i = 0; i < G_N_ELEMENTS (key_controls); ++i) {
1011     desc_len = g_utf8_strlen (key_controls[i].key_desc, -1);
1012     max_desc_len = MAX (max_desc_len, desc_len);
1013   }
1014   ++max_desc_len;
1015
1016   for (i = 0; i < G_N_ELEMENTS (key_controls); ++i) {
1017     chars_to_pad = max_desc_len - g_utf8_strlen (key_controls[i].key_desc, -1);
1018     g_print ("\t%s", key_controls[i].key_desc);
1019     g_print ("%-*s: ", chars_to_pad, "");
1020     g_print ("%s\n", key_controls[i].key_help);
1021   }
1022   g_print ("\n");
1023 }
1024
1025 static void
1026 keyboard_cb (const gchar * key_input, gpointer user_data)
1027 {
1028   GstPlay *play = (GstPlay *) user_data;
1029   gchar key = '\0';
1030
1031   /* only want to switch/case on single char, not first char of string */
1032   if (key_input[0] != '\0' && key_input[1] == '\0')
1033     key = g_ascii_tolower (key_input[0]);
1034
1035   switch (key) {
1036     case 'k':
1037       print_keyboard_help ();
1038       break;
1039     case ' ':
1040       toggle_paused (play);
1041       break;
1042     case 'q':
1043     case 'Q':
1044       g_main_loop_quit (play->loop);
1045       break;
1046     case 'n':
1047     case '>':
1048       if (!play_next (play)) {
1049         g_print ("\n%s\n", _("Reached end of play list."));
1050         g_main_loop_quit (play->loop);
1051       }
1052       break;
1053     case 'b':
1054     case '<':
1055       play_prev (play);
1056       break;
1057     case '+':
1058       if (play->rate > -0.2 && play->rate < 0.0)
1059         play_set_relative_playback_rate (play, 0.0, TRUE);
1060       else if (ABS (play->rate) < 2.0)
1061         play_set_relative_playback_rate (play, 0.1, FALSE);
1062       else if (ABS (play->rate) < 4.0)
1063         play_set_relative_playback_rate (play, 0.5, FALSE);
1064       else
1065         play_set_relative_playback_rate (play, 1.0, FALSE);
1066       break;
1067     case '-':
1068       if (play->rate > 0.0 && play->rate < 0.20)
1069         play_set_relative_playback_rate (play, 0.0, TRUE);
1070       else if (ABS (play->rate) <= 2.0)
1071         play_set_relative_playback_rate (play, -0.1, FALSE);
1072       else if (ABS (play->rate) <= 4.0)
1073         play_set_relative_playback_rate (play, -0.5, FALSE);
1074       else
1075         play_set_relative_playback_rate (play, -1.0, FALSE);
1076       break;
1077     case 'd':
1078       play_set_relative_playback_rate (play, 0.0, TRUE);
1079       break;
1080     case 't':
1081       play_switch_trick_mode (play);
1082       break;
1083     case 27:                   /* ESC */
1084       if (key_input[1] == '\0') {
1085         g_main_loop_quit (play->loop);
1086         break;
1087       }
1088     case 'a':
1089       play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_AUDIO);
1090       break;
1091     case 'v':
1092       play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_VIDEO);
1093       break;
1094     case 's':
1095       play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_SUBTITLE);
1096       break;
1097     case '0':
1098       play_do_seek (play, 0, play->rate, play->trick_mode);
1099       break;
1100     default:
1101       if (strcmp (key_input, GST_PLAY_KB_ARROW_RIGHT) == 0) {
1102         relative_seek (play, +0.08);
1103       } else if (strcmp (key_input, GST_PLAY_KB_ARROW_LEFT) == 0) {
1104         relative_seek (play, -0.01);
1105       } else if (strcmp (key_input, GST_PLAY_KB_ARROW_UP) == 0) {
1106         play_set_relative_volume (play, +1.0 / VOLUME_STEPS);
1107       } else if (strcmp (key_input, GST_PLAY_KB_ARROW_DOWN) == 0) {
1108         play_set_relative_volume (play, -1.0 / VOLUME_STEPS);
1109       } else {
1110         GST_INFO ("keyboard input:");
1111         for (; *key_input != '\0'; ++key_input)
1112           GST_INFO ("  code %3d", *key_input);
1113       }
1114       break;
1115   }
1116 }
1117
1118 int
1119 main (int argc, char **argv)
1120 {
1121   GstPlay *play;
1122   GPtrArray *playlist;
1123   gboolean verbose = FALSE;
1124   gboolean print_version = FALSE;
1125   gboolean interactive = TRUE;
1126   gboolean gapless = FALSE;
1127   gboolean shuffle = FALSE;
1128   gdouble volume = -1;
1129   gchar **filenames = NULL;
1130   gchar *audio_sink = NULL;
1131   gchar *video_sink = NULL;
1132   gchar **uris;
1133   gchar *flags = NULL;
1134   guint num, i;
1135   GError *err = NULL;
1136   GOptionContext *ctx;
1137   gchar *playlist_file = NULL;
1138   GOptionEntry options[] = {
1139     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
1140         N_("Output status information and property notifications"), NULL},
1141     {"flags", 0, 0, G_OPTION_ARG_STRING, &flags,
1142           N_("Control playback behaviour setting playbin 'flags' property"),
1143         NULL},
1144     {"version", 0, 0, G_OPTION_ARG_NONE, &print_version,
1145         N_("Print version information and exit"), NULL},
1146     {"videosink", 0, 0, G_OPTION_ARG_STRING, &video_sink,
1147         N_("Video sink to use (default is autovideosink)"), NULL},
1148     {"audiosink", 0, 0, G_OPTION_ARG_STRING, &audio_sink,
1149         N_("Audio sink to use (default is autoaudiosink)"), NULL},
1150     {"gapless", 0, 0, G_OPTION_ARG_NONE, &gapless,
1151         N_("Enable gapless playback"), NULL},
1152     {"shuffle", 0, 0, G_OPTION_ARG_NONE, &shuffle,
1153         N_("Shuffle playlist"), NULL},
1154     {"no-interactive", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE,
1155           &interactive,
1156         N_("Disable interactive control via the keyboard"), NULL},
1157     {"volume", 0, 0, G_OPTION_ARG_DOUBLE, &volume,
1158         N_("Volume"), NULL},
1159     {"playlist", 0, 0, G_OPTION_ARG_FILENAME, &playlist_file,
1160         N_("Playlist file containing input media files"), NULL},
1161     {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
1162         N_("Do not print any output (apart from errors)"), NULL},
1163     {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &filenames, NULL},
1164     {NULL}
1165   };
1166
1167   setlocale (LC_ALL, "");
1168
1169 #ifdef ENABLE_NLS
1170   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
1171   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1172   textdomain (GETTEXT_PACKAGE);
1173 #endif
1174
1175   g_set_prgname ("gst-play-" GST_API_VERSION);
1176
1177   ctx = g_option_context_new ("FILE1|URI1 [FILE2|URI2] [FILE3|URI3] ...");
1178   g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
1179   g_option_context_add_group (ctx, gst_init_get_option_group ());
1180   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
1181     g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
1182     g_option_context_free (ctx);
1183     g_clear_error (&err);
1184     return 1;
1185   }
1186   g_option_context_free (ctx);
1187
1188   GST_DEBUG_CATEGORY_INIT (play_debug, "play", 0, "gst-play");
1189
1190   if (print_version) {
1191     gchar *version_str;
1192
1193     version_str = gst_version_string ();
1194     g_print ("%s version %s\n", g_get_prgname (), PACKAGE_VERSION);
1195     g_print ("%s\n", version_str);
1196     g_print ("%s\n", GST_PACKAGE_ORIGIN);
1197     g_free (version_str);
1198
1199     g_free (audio_sink);
1200     g_free (video_sink);
1201     g_free (playlist_file);
1202
1203     return 0;
1204   }
1205
1206   playlist = g_ptr_array_new ();
1207
1208   if (playlist_file != NULL) {
1209     gchar *playlist_contents = NULL;
1210     gchar **lines = NULL;
1211
1212     if (g_file_get_contents (playlist_file, &playlist_contents, NULL, &err)) {
1213       lines = g_strsplit (playlist_contents, "\n", 0);
1214       num = g_strv_length (lines);
1215
1216       for (i = 0; i < num; i++) {
1217         if (lines[i][0] != '\0') {
1218           GST_LOG ("Playlist[%d]: %s", i + 1, lines[i]);
1219           add_to_playlist (playlist, lines[i]);
1220         }
1221       }
1222       g_strfreev (lines);
1223       g_free (playlist_contents);
1224     } else {
1225       g_printerr ("Could not read playlist: %s\n", err->message);
1226       g_clear_error (&err);
1227     }
1228     g_free (playlist_file);
1229     playlist_file = NULL;
1230   }
1231
1232   if (playlist->len == 0 && (filenames == NULL || *filenames == NULL)) {
1233     g_printerr (_("Usage: %s FILE1|URI1 [FILE2|URI2] [FILE3|URI3] ..."),
1234         "gst-play-" GST_API_VERSION);
1235     g_printerr ("\n\n"),
1236         g_printerr ("%s\n\n",
1237         _("You must provide at least one filename or URI to play."));
1238     /* No input provided. Free array */
1239     g_ptr_array_free (playlist, TRUE);
1240
1241     g_free (audio_sink);
1242     g_free (video_sink);
1243
1244     return 1;
1245   }
1246
1247   /* fill playlist */
1248   if (filenames != NULL && *filenames != NULL) {
1249     num = g_strv_length (filenames);
1250     for (i = 0; i < num; ++i) {
1251       GST_LOG ("command line argument: %s", filenames[i]);
1252       add_to_playlist (playlist, filenames[i]);
1253     }
1254     g_strfreev (filenames);
1255   }
1256
1257   num = playlist->len;
1258   g_ptr_array_add (playlist, NULL);
1259
1260   uris = (gchar **) g_ptr_array_free (playlist, FALSE);
1261
1262   if (shuffle)
1263     shuffle_uris (uris, num);
1264
1265   /* prepare */
1266   play =
1267       play_new (uris, audio_sink, video_sink, gapless, volume, verbose, flags);
1268
1269   if (play == NULL) {
1270     g_printerr
1271         ("Failed to create 'playbin' element. Check your GStreamer installation.\n");
1272     return EXIT_FAILURE;
1273   }
1274
1275   if (interactive) {
1276     if (gst_play_kb_set_key_handler (keyboard_cb, play)) {
1277       g_print (_("Press 'k' to see a list of keyboard shortcuts.\n"));
1278       atexit (restore_terminal);
1279     } else {
1280       g_print ("Interactive keyboard handling in terminal not available.\n");
1281     }
1282   }
1283
1284   /* play */
1285   do_play (play);
1286
1287   /* clean up */
1288   play_free (play);
1289
1290   g_free (audio_sink);
1291   g_free (video_sink);
1292
1293   g_print ("\n");
1294   return 0;
1295 }