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