gst-play.c 43.4 KB
Newer Older
1 2
/* GStreamer command line playback testing utility
 *
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 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

27 28
#include <locale.h>

29 30
#include <gst/gst.h>
#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 38 39
#include <stdio.h>
#include <string.h>

40 41
#include <glib/gprintf.h>

42
#include "gst-play-kb.h"
43

44 45
#define VOLUME_STEPS 20

46 47 48
GST_DEBUG_CATEGORY (play_debug);
#define GST_CAT_DEFAULT play_debug

49 50 51 52 53 54 55 56 57 58
typedef enum
{
  GST_PLAY_TRICK_MODE_NONE = 0,
  GST_PLAY_TRICK_MODE_DEFAULT,
  GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO,
  GST_PLAY_TRICK_MODE_KEY_UNITS,
  GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO,
  GST_PLAY_TRICK_MODE_LAST
} GstPlayTrickMode;

59 60 61 62 63 64 65 66
typedef enum
{
  GST_PLAY_TRACK_TYPE_INVALID = 0,
  GST_PLAY_TRACK_TYPE_AUDIO,
  GST_PLAY_TRACK_TYPE_VIDEO,
  GST_PLAY_TRACK_TYPE_SUBTITLE
} GstPlayTrackType;

67 68 69 70 71 72 73 74
typedef struct
{
  gchar **uris;
  guint num_uris;
  gint cur_idx;

  GstElement *playbin;

75 76 77 78 79 80 81 82
  /* playbin3 variables */
  gboolean is_playbin3;
  GstStreamCollection *collection;
  gchar *cur_audio_sid;
  gchar *cur_video_sid;
  gchar *cur_text_sid;
  GMutex selection_lock;

83 84 85 86 87 88 89 90 91
  GMainLoop *loop;
  guint bus_watch;
  guint timeout;

  /* missing plugin messages */
  GList *missing;

  gboolean buffering;
  gboolean is_live;
92

93 94
  GstState desired_state;       /* as per user interaction, PAUSED or PLAYING */

95 96
  gulong deep_notify_id;

97 98
  /* configuration */
  gboolean gapless;
99

100
  GstPlayTrickMode trick_mode;
101
  gdouble rate;
102 103
} GstPlay;

104 105
static gboolean quiet = FALSE;

106 107
static gboolean play_bus_msg (GstBus * bus, GstMessage * msg, gpointer data);
static gboolean play_next (GstPlay * play);
108
static gboolean play_prev (GstPlay * play);
109
static gboolean play_timeout (gpointer user_data);
110
static void play_about_to_finish (GstElement * playbin, gpointer user_data);
111
static void play_reset (GstPlay * play);
112
static void play_set_relative_volume (GstPlay * play, gdouble volume_step);
113 114
static gboolean play_do_seek (GstPlay * play, gint64 pos, gdouble rate,
    GstPlayTrickMode mode);
115

116 117 118 119
/* *INDENT-OFF* */
static void gst_play_printf (const gchar * format, ...) G_GNUC_PRINTF (1, 2);
/* *INDENT-ON* */

120 121 122
static void keyboard_cb (const gchar * key_input, gpointer user_data);
static void relative_seek (GstPlay * play, gdouble percent);

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
static void
gst_play_printf (const gchar * format, ...)
{
  gchar *str = NULL;
  va_list args;
  int len;

  if (quiet)
    return;

  va_start (args, format);

  len = g_vasprintf (&str, format, args);

  va_end (args);

  if (len > 0 && str != NULL)
    g_print ("%s", str);

  g_free (str);
}

#define g_print gst_play_printf

147
static GstPlay *
148
play_new (gchar ** uris, const gchar * audio_sink, const gchar * video_sink,
149
    gboolean gapless, gdouble initial_volume, gboolean verbose,
150
    const gchar * flags_string, gboolean use_playbin3)
151
{
152
  GstElement *sink, *playbin;
153 154
  GstPlay *play;

155 156 157 158 159 160 161

  if (use_playbin3) {
    playbin = gst_element_factory_make ("playbin3", "playbin");
  } else {
    playbin = gst_element_factory_make ("playbin", "playbin");
  }

162 163 164
  if (playbin == NULL)
    return NULL;

165 166 167 168 169 170
  play = g_new0 (GstPlay, 1);

  play->uris = uris;
  play->num_uris = g_strv_length (uris);
  play->cur_idx = -1;

171
  play->playbin = playbin;
172

173 174 175 176 177 178 179 180 181 182
  if (use_playbin3) {
    play->is_playbin3 = TRUE;
  } else {
    const gchar *env = g_getenv ("USE_PLAYBIN3");
    if (env && g_str_has_prefix (env, "1"))
      play->is_playbin3 = TRUE;
  }

  g_mutex_init (&play->selection_lock);

183
  if (audio_sink != NULL) {
184 185 186 187 188
    if (strchr (audio_sink, ' ') != NULL)
      sink = gst_parse_bin_from_description (audio_sink, TRUE, NULL);
    else
      sink = gst_element_factory_make (audio_sink, NULL);

189 190 191 192 193 194
    if (sink != NULL)
      g_object_set (play->playbin, "audio-sink", sink, NULL);
    else
      g_warning ("Couldn't create specified audio sink '%s'", audio_sink);
  }
  if (video_sink != NULL) {
195 196 197 198 199
    if (strchr (video_sink, ' ') != NULL)
      sink = gst_parse_bin_from_description (video_sink, TRUE, NULL);
    else
      sink = gst_element_factory_make (video_sink, NULL);

200 201 202 203 204 205
    if (sink != NULL)
      g_object_set (play->playbin, "video-sink", sink, NULL);
    else
      g_warning ("Couldn't create specified video sink '%s'", video_sink);
  }

206 207 208 209 210 211 212 213 214 215 216 217 218
  if (flags_string != NULL) {
    GParamSpec *pspec;
    GValue val = { 0, };

    pspec =
        g_object_class_find_property (G_OBJECT_GET_CLASS (playbin), "flags");
    g_value_init (&val, pspec->value_type);
    if (gst_value_deserialize (&val, flags_string))
      g_object_set_property (G_OBJECT (play->playbin), "flags", &val);
    else
      g_printerr ("Couldn't convert '%s' to playbin flags!\n", flags_string);
    g_value_unset (&val);
  }
219 220

  if (verbose) {
221 222
    play->deep_notify_id =
        gst_element_add_property_deep_notify_watch (play->playbin, NULL, TRUE);
223 224
  }

225 226 227 228 229 230 231 232 233 234 235 236
  play->loop = g_main_loop_new (NULL, FALSE);

  play->bus_watch = gst_bus_add_watch (GST_ELEMENT_BUS (play->playbin),
      play_bus_msg, play);

  /* FIXME: make configurable incl. 0 for disable */
  play->timeout = g_timeout_add (100, play_timeout, play);

  play->missing = NULL;
  play->buffering = FALSE;
  play->is_live = FALSE;

237 238
  play->desired_state = GST_STATE_PLAYING;

239 240 241 242 243 244
  play->gapless = gapless;
  if (gapless) {
    g_signal_connect (play->playbin, "about-to-finish",
        G_CALLBACK (play_about_to_finish), play);
  }

245 246
  if (initial_volume != -1)
    play_set_relative_volume (play, initial_volume - 1.0);
247

248
  play->rate = 1.0;
249
  play->trick_mode = GST_PLAY_TRICK_MODE_NONE;
250

251 252 253 254 255 256
  return play;
}

static void
play_free (GstPlay * play)
{
257 258 259 260
  /* No need to see all those pad caps going to NULL etc., it's just noise */
  if (play->deep_notify_id != 0)
    g_signal_handler_disconnect (play->playbin, play->deep_notify_id);

261 262 263 264 265 266 267 268 269 270
  play_reset (play);

  gst_element_set_state (play->playbin, GST_STATE_NULL);
  gst_object_unref (play->playbin);

  g_source_remove (play->bus_watch);
  g_source_remove (play->timeout);
  g_main_loop_unref (play->loop);

  g_strfreev (play->uris);
271 272 273 274 275 276 277 278 279

  if (play->collection)
    gst_object_unref (play->collection);
  g_free (play->cur_audio_sid);
  g_free (play->cur_video_sid);
  g_free (play->cur_text_sid);

  g_mutex_clear (&play->selection_lock);

280 281 282 283 284 285 286 287 288 289 290 291 292 293
  g_free (play);
}

/* reset for new file/stream */
static void
play_reset (GstPlay * play)
{
  g_list_foreach (play->missing, (GFunc) gst_message_unref, NULL);
  play->missing = NULL;

  play->buffering = FALSE;
  play->is_live = FALSE;
}

294 295 296 297 298 299
static void
play_set_relative_volume (GstPlay * play, gdouble volume_step)
{
  gdouble volume;

  volume = gst_stream_volume_get_volume (GST_STREAM_VOLUME (play->playbin),
300
      GST_STREAM_VOLUME_FORMAT_CUBIC);
301 302 303 304 305

  volume = round ((volume + volume_step) * VOLUME_STEPS) / VOLUME_STEPS;
  volume = CLAMP (volume, 0.0, 10.0);

  gst_stream_volume_set_volume (GST_STREAM_VOLUME (play->playbin),
306
      GST_STREAM_VOLUME_FORMAT_CUBIC, volume);
307

308 309
  g_print (_("Volume: %.0f%%"), volume * 100);
  g_print ("                  \n");
310 311
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
/* returns TRUE if something was installed and we should restart playback */
static gboolean
play_install_missing_plugins (GstPlay * play)
{
  /* FIXME: implement: try to install any missing plugins we haven't
   * tried to install before */
  return FALSE;
}

static gboolean
play_bus_msg (GstBus * bus, GstMessage * msg, gpointer user_data)
{
  GstPlay *play = user_data;

  switch (GST_MESSAGE_TYPE (msg)) {
    case GST_MESSAGE_ASYNC_DONE:
328 329 330 331 332

      /* dump graph on preroll */
      GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
          GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.async-done");

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
      g_print ("Prerolled.\r");
      if (play->missing != NULL && play_install_missing_plugins (play)) {
        g_print ("New plugins installed, trying again...\n");
        --play->cur_idx;
        play_next (play);
      }
      break;
    case GST_MESSAGE_BUFFERING:{
      gint percent;

      if (!play->buffering)
        g_print ("\n");

      gst_message_parse_buffering (msg, &percent);
      g_print ("%s %d%%  \r", _("Buffering..."), percent);

      if (percent == 100) {
        /* a 100% message means buffering is done */
        if (play->buffering) {
          play->buffering = FALSE;
353 354 355
          /* no state management needed for live pipelines */
          if (!play->is_live)
            gst_element_set_state (play->playbin, play->desired_state);
356 357 358 359
        }
      } else {
        /* buffering... */
        if (!play->buffering) {
360 361
          if (!play->is_live)
            gst_element_set_state (play->playbin, GST_STATE_PAUSED);
362 363 364 365 366
          play->buffering = TRUE;
        }
      }
      break;
    }
367 368 369 370 371 372
    case GST_MESSAGE_CLOCK_LOST:{
      g_print (_("Clock lost, selecting a new one\n"));
      gst_element_set_state (play->playbin, GST_STATE_PAUSED);
      gst_element_set_state (play->playbin, GST_STATE_PLAYING);
      break;
    }
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    case GST_MESSAGE_LATENCY:
      g_print ("Redistribute latency...\n");
      gst_bin_recalculate_latency (GST_BIN (play->playbin));
      break;
    case GST_MESSAGE_REQUEST_STATE:{
      GstState state;
      gchar *name;

      name = gst_object_get_path_string (GST_MESSAGE_SRC (msg));

      gst_message_parse_request_state (msg, &state);

      g_print ("Setting state to %s as requested by %s...\n",
          gst_element_state_get_name (state), name);

      gst_element_set_state (play->playbin, state);
      g_free (name);
      break;
    }
    case GST_MESSAGE_EOS:
      /* print final position at end */
      play_timeout (play);
      g_print ("\n");
      /* and switch to next item in list */
      if (!play_next (play)) {
398
        g_print ("%s\n", _("Reached end of play list."));
399 400 401 402 403 404 405
        g_main_loop_quit (play->loop);
      }
      break;
    case GST_MESSAGE_WARNING:{
      GError *err;
      gchar *dbg = NULL;

406 407 408 409
      /* dump graph on warning */
      GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
          GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.warning");

410 411 412 413
      gst_message_parse_warning (msg, &err, &dbg);
      g_printerr ("WARNING %s\n", err->message);
      if (dbg != NULL)
        g_printerr ("WARNING debug information: %s\n", dbg);
414
      g_clear_error (&err);
415 416 417 418 419 420 421
      g_free (dbg);
      break;
    }
    case GST_MESSAGE_ERROR:{
      GError *err;
      gchar *dbg;

422 423 424 425
      /* dump graph on error */
      GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (play->playbin),
          GST_DEBUG_GRAPH_SHOW_ALL, "gst-play.error");

426 427 428 429
      gst_message_parse_error (msg, &err, &dbg);
      g_printerr ("ERROR %s for %s\n", err->message, play->uris[play->cur_idx]);
      if (dbg != NULL)
        g_printerr ("ERROR debug information: %s\n", dbg);
430
      g_clear_error (&err);
431 432
      g_free (dbg);

433 434 435
      /* flush any other error messages from the bus and clean up */
      gst_element_set_state (play->playbin, GST_STATE_NULL);

436 437 438 439 440 441 442 443
      if (play->missing != NULL && play_install_missing_plugins (play)) {
        g_print ("New plugins installed, trying again...\n");
        --play->cur_idx;
        play_next (play);
        break;
      }
      /* try next item in list then */
      if (!play_next (play)) {
444
        g_print ("%s\n", _("Reached end of play list."));
445 446 447 448
        g_main_loop_quit (play->loop);
      }
      break;
    }
449 450 451 452
    case GST_MESSAGE_ELEMENT:
    {
      GstNavigationMessageType mtype = gst_navigation_message_get_type (msg);
      if (mtype == GST_NAVIGATION_MESSAGE_EVENT) {
Vineeth TM's avatar
Vineeth TM committed
453
        GstEvent *ev = NULL;
454

455 456 457 458 459 460
        if (gst_navigation_message_parse_event (msg, &ev)) {
          GstNavigationEventType e_type = gst_navigation_event_get_type (ev);
          switch (e_type) {
            case GST_NAVIGATION_EVENT_KEY_PRESS:
            {
              const gchar *key;
461

462
              if (gst_navigation_event_parse_key_event (ev, &key)) {
463 464
                GST_INFO ("Key press: %s", key);

465 466 467 468
                if (strcmp (key, "Left") == 0)
                  key = GST_PLAY_KB_ARROW_LEFT;
                else if (strcmp (key, "Right") == 0)
                  key = GST_PLAY_KB_ARROW_RIGHT;
469 470 471 472 473 474 475 476 477
                else if (strcmp (key, "Up") == 0)
                  key = GST_PLAY_KB_ARROW_UP;
                else if (strcmp (key, "Down") == 0)
                  key = GST_PLAY_KB_ARROW_DOWN;
                else if (strcmp (key, "space") == 0)
                  key = " ";
                else if (strlen (key) > 1)
                  break;

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
                keyboard_cb (key, user_data);
              }
              break;
            }
            case GST_NAVIGATION_EVENT_MOUSE_BUTTON_PRESS:
            {
              gint button;
              if (gst_navigation_event_parse_mouse_button_event (ev, &button,
                      NULL, NULL)) {
                if (button == 4) {
                  /* wheel up */
                  relative_seek (play, +0.08);
                } else if (button == 5) {
                  /* wheel down */
                  relative_seek (play, -0.01);
                }
              }
              break;
            }
            default:
              break;
          }
        }
Vineeth TM's avatar
Vineeth TM committed
501 502
        if (ev)
          gst_event_unref (ev);
503 504 505
      }
      break;
    }
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    case GST_MESSAGE_PROPERTY_NOTIFY:{
      const GValue *val;
      const gchar *name;
      GstObject *obj;
      gchar *val_str = NULL;
      gchar *obj_name;

      gst_message_parse_property_notify (msg, &obj, &name, &val);

      obj_name = gst_object_get_path_string (GST_OBJECT (obj));
      if (val != NULL) {
        if (G_VALUE_HOLDS_STRING (val))
          val_str = g_value_dup_string (val);
        else if (G_VALUE_TYPE (val) == GST_TYPE_CAPS)
          val_str = gst_caps_to_string (g_value_get_boxed (val));
        else if (G_VALUE_TYPE (val) == GST_TYPE_TAG_LIST)
          val_str = gst_tag_list_to_string (g_value_get_boxed (val));
        else
          val_str = gst_value_serialize (val);
      } else {
        val_str = g_strdup ("(no value)");
      }

      gst_play_printf ("%s: %s = %s\n", obj_name, name, val_str);
      g_free (obj_name);
      g_free (val_str);
      break;
    }
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    case GST_MESSAGE_STREAM_COLLECTION:
    {
      GstStreamCollection *collection = NULL;
      gst_message_parse_stream_collection (msg, &collection);

      if (collection) {
        g_mutex_lock (&play->selection_lock);
        gst_object_replace ((GstObject **) & play->collection,
            (GstObject *) collection);
        g_mutex_unlock (&play->selection_lock);
      }
      break;
    }
    case GST_MESSAGE_STREAMS_SELECTED:
    {
      GstStreamCollection *collection = NULL;
      guint i, len;

      gst_message_parse_streams_selected (msg, &collection);
      if (collection) {
        g_mutex_lock (&play->selection_lock);
        gst_object_replace ((GstObject **) & play->collection,
            (GstObject *) collection);

        /* Free all last stream-ids */
        g_free (play->cur_audio_sid);
        g_free (play->cur_video_sid);
        g_free (play->cur_text_sid);
        play->cur_audio_sid = NULL;
        play->cur_video_sid = NULL;
        play->cur_text_sid = NULL;

        len = gst_message_streams_selected_get_size (msg);
        for (i = 0; i < len; i++) {
          GstStream *stream = gst_message_streams_selected_get_stream (msg, i);
          if (stream) {
            GstStreamType type = gst_stream_get_stream_type (stream);
            const gchar *stream_id = gst_stream_get_stream_id (stream);

            if (type & GST_STREAM_TYPE_AUDIO) {
              play->cur_audio_sid = g_strdup (stream_id);
            } else if (type & GST_STREAM_TYPE_VIDEO) {
              play->cur_video_sid = g_strdup (stream_id);
            } else if (type & GST_STREAM_TYPE_TEXT) {
              play->cur_text_sid = g_strdup (stream_id);
            } else {
              g_print ("Unknown stream type with stream-id %s", stream_id);
            }
            gst_object_unref (stream);
          }
        }

        gst_object_unref (collection);
        g_mutex_unlock (&play->selection_lock);
      }
      break;
    }
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    default:
      if (gst_is_missing_plugin_message (msg)) {
        gchar *desc;

        desc = gst_missing_plugin_message_get_description (msg);
        g_print ("Missing plugin: %s\n", desc);
        g_free (desc);
        play->missing = g_list_append (play->missing, gst_message_ref (msg));
      }
      break;
  }

  return TRUE;
}

static gboolean
play_timeout (gpointer user_data)
{
  GstPlay *play = user_data;
  gint64 pos = -1, dur = -1;
611 612
  const gchar *paused = _("Paused");
  gchar *status;
613 614 615 616 617 618 619

  if (play->buffering)
    return TRUE;

  gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos);
  gst_element_query_duration (play->playbin, GST_FORMAT_TIME, &dur);

620 621 622 623 624 625 626 627
  if (play->desired_state == GST_STATE_PAUSED) {
    status = (gchar *) paused;
  } else {
    gint len = g_utf8_strlen (paused, -1);
    status = g_newa (gchar, len + 1);
    memset (status, ' ', len);
    status[len] = '\0';
  }
628

629 630 631 632 633 634 635 636
  if (pos >= 0 && dur > 0) {
    gchar dstr[32], pstr[32];

    /* FIXME: pretty print in nicer format */
    g_snprintf (pstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
    pstr[9] = '\0';
    g_snprintf (dstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
    dstr[9] = '\0';
637
    g_print ("%s / %s %s\r", pstr, dstr, status);
638 639 640 641 642
  }

  return TRUE;
}

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
static gchar *
play_uri_get_display_name (GstPlay * play, const gchar * uri)
{
  gchar *loc;

  if (gst_uri_has_protocol (uri, "file")) {
    loc = g_filename_from_uri (uri, NULL, NULL);
  } else if (gst_uri_has_protocol (uri, "pushfile")) {
    loc = g_filename_from_uri (uri + 4, NULL, NULL);
  } else {
    loc = g_strdup (uri);
  }

  /* Maybe additionally use glib's filename to display name function */
  return loc;
}

660 661
static void
play_uri (GstPlay * play, const gchar * next_uri)
662 663 664 665 666 667
{
  gchar *loc;

  gst_element_set_state (play->playbin, GST_STATE_READY);
  play_reset (play);

668
  loc = play_uri_get_display_name (play, next_uri);
669
  g_print (_("Now playing %s\n"), loc);
670 671 672 673
  g_free (loc);

  g_object_set (play->playbin, "uri", next_uri, NULL);

674
  switch (gst_element_set_state (play->playbin, GST_STATE_PAUSED)) {
675 676 677 678 679 680 681 682 683 684 685 686 687
    case GST_STATE_CHANGE_FAILURE:
      /* ignore, we should get an error message posted on the bus */
      break;
    case GST_STATE_CHANGE_NO_PREROLL:
      g_print ("Pipeline is live.\n");
      play->is_live = TRUE;
      break;
    case GST_STATE_CHANGE_ASYNC:
      g_print ("Prerolling...\r");
      break;
    default:
      break;
  }
688

689
  if (play->desired_state != GST_STATE_PAUSED)
690
    gst_element_set_state (play->playbin, play->desired_state);
691 692 693 694 695 696 697 698
}

/* returns FALSE if we have reached the end of the playlist */
static gboolean
play_next (GstPlay * play)
{
  if ((play->cur_idx + 1) >= play->num_uris)
    return FALSE;
699

700 701 702 703 704 705 706 707 708 709 710 711
  play_uri (play, play->uris[++play->cur_idx]);
  return TRUE;
}

/* returns FALSE if we have reached the beginning of the playlist */
static gboolean
play_prev (GstPlay * play)
{
  if (play->cur_idx == 0 || play->num_uris <= 1)
    return FALSE;

  play_uri (play, play->uris[--play->cur_idx]);
712 713 714
  return TRUE;
}

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
static void
play_about_to_finish (GstElement * playbin, gpointer user_data)
{
  GstPlay *play = user_data;
  const gchar *next_uri;
  gchar *loc;
  guint next_idx;

  if (!play->gapless)
    return;

  next_idx = play->cur_idx + 1;
  if (next_idx >= play->num_uris)
    return;

  next_uri = play->uris[next_idx];
  loc = play_uri_get_display_name (play, next_uri);
732 733
  g_print (_("About to finish, preparing next title: %s"), loc);
  g_print ("\n");
734 735 736
  g_free (loc);

  g_object_set (play->playbin, "uri", next_uri, NULL);
737
  play->cur_idx = next_idx;
738 739
}

740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
static void
do_play (GstPlay * play)
{
  gint i;

  /* dump playlist */
  for (i = 0; i < play->num_uris; ++i)
    GST_INFO ("%4u : %s", i, play->uris[i]);

  if (!play_next (play))
    return;

  g_main_loop_run (play->loop);
}

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
static gint
compare (gconstpointer a, gconstpointer b)
{
  gchar *a1, *b1;
  gint ret;

  a1 = g_utf8_collate_key_for_filename ((gchar *) a, -1);
  b1 = g_utf8_collate_key_for_filename ((gchar *) b, -1);
  ret = strcmp (a1, b1);
  g_free (a1);
  g_free (b1);

  return ret;
}

770 771 772 773 774 775 776 777 778 779 780 781 782
static void
add_to_playlist (GPtrArray * playlist, const gchar * filename)
{
  GDir *dir;
  gchar *uri;

  if (gst_uri_is_valid (filename)) {
    g_ptr_array_add (playlist, g_strdup (filename));
    return;
  }

  if ((dir = g_dir_open (filename, 0, NULL))) {
    const gchar *entry;
783
    GList *l, *files = NULL;
784 785 786 787

    while ((entry = g_dir_read_name (dir))) {
      gchar *path;

788
      path = g_build_filename (filename, entry, NULL);
789
      files = g_list_insert_sorted (files, path, compare);
790 791 792
    }

    g_dir_close (dir);
793 794 795 796 797 798 799 800

    for (l = files; l != NULL; l = l->next) {
      gchar *path = (gchar *) l->data;

      add_to_playlist (playlist, path);
      g_free (path);
    }
    g_list_free (files);
801 802 803 804 805 806 807 808 809 810
    return;
  }

  uri = gst_filename_to_uri (filename, NULL);
  if (uri != NULL)
    g_ptr_array_add (playlist, uri);
  else
    g_warning ("Could not make URI out of filename '%s'", filename);
}

811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
static void
shuffle_uris (gchar ** uris, guint num)
{
  gchar *tmp;
  guint i, j;

  if (num < 2)
    return;

  for (i = 0; i < num; i++) {
    /* gets equally distributed random number in 0..num-1 [0;num[ */
    j = g_random_int_range (0, num);
    tmp = uris[j];
    uris[j] = uris[i];
    uris[i] = tmp;
  }
}

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
static void
restore_terminal (void)
{
  gst_play_kb_set_key_handler (NULL, NULL);
}

static void
toggle_paused (GstPlay * play)
{
  if (play->desired_state == GST_STATE_PLAYING)
    play->desired_state = GST_STATE_PAUSED;
  else
    play->desired_state = GST_STATE_PLAYING;

  if (!play->buffering) {
    gst_element_set_state (play->playbin, play->desired_state);
  } else if (play->desired_state == GST_STATE_PLAYING) {
    g_print ("\nWill play as soon as buffering finishes)\n");
  }
}

850 851 852 853 854
static void
relative_seek (GstPlay * play, gdouble percent)
{
  GstQuery *query;
  gboolean seekable = FALSE;
855
  gint64 dur = -1, pos = -1, step;
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873

  g_return_if_fail (percent >= -1.0 && percent <= 1.0);

  if (!gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos))
    goto seek_failed;

  query = gst_query_new_seeking (GST_FORMAT_TIME);
  if (!gst_element_query (play->playbin, query)) {
    gst_query_unref (query);
    goto seek_failed;
  }

  gst_query_parse_seeking (query, NULL, &seekable, NULL, &dur);
  gst_query_unref (query);

  if (!seekable || dur <= 0)
    goto seek_failed;

874 875 876 877 878
  step = dur * percent;
  if (ABS (step) < GST_SECOND)
    step = (percent < 0) ? -GST_SECOND : GST_SECOND;

  pos = pos + step;
879 880
  if (pos > dur) {
    if (!play_next (play)) {
881
      g_print ("\n%s\n", _("Reached end of play list."));
882 883 884 885 886
      g_main_loop_quit (play->loop);
    }
  } else {
    if (pos < 0)
      pos = 0;
887 888

    play_do_seek (play, pos, play->rate, play->trick_mode);
889 890 891 892 893 894 895 896 897 898
  }

  return;

seek_failed:
  {
    g_print ("\nCould not seek.\n");
  }
}

899 900 901
static gboolean
play_set_rate_and_trick_mode (GstPlay * play, gdouble rate,
    GstPlayTrickMode mode)
902 903 904
{
  gint64 pos = -1;

905
  g_return_val_if_fail (rate != 0, FALSE);
906 907

  if (!gst_element_query_position (play->playbin, GST_FORMAT_TIME, &pos))
908
    return FALSE;
909

910 911 912 913 914 915 916 917 918 919 920
  return play_do_seek (play, pos, rate, mode);
}

static gboolean
play_do_seek (GstPlay * play, gint64 pos, gdouble rate, GstPlayTrickMode mode)
{
  GstSeekFlags seek_flags;
  GstQuery *query;
  GstEvent *seek;
  gboolean seekable = FALSE;

921 922 923
  query = gst_query_new_seeking (GST_FORMAT_TIME);
  if (!gst_element_query (play->playbin, query)) {
    gst_query_unref (query);
924
    return FALSE;
925 926 927 928 929 930
  }

  gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
  gst_query_unref (query);

  if (!seekable)
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    return FALSE;

  seek_flags = GST_SEEK_FLAG_FLUSH;

  switch (mode) {
    case GST_PLAY_TRICK_MODE_DEFAULT:
      seek_flags |= GST_SEEK_FLAG_TRICKMODE;
      break;
    case GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO:
      seek_flags |= GST_SEEK_FLAG_TRICKMODE | GST_SEEK_FLAG_TRICKMODE_NO_AUDIO;
      break;
    case GST_PLAY_TRICK_MODE_KEY_UNITS:
      seek_flags |= GST_SEEK_FLAG_TRICKMODE_KEY_UNITS;
      break;
    case GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO:
      seek_flags |=
          GST_SEEK_FLAG_TRICKMODE_KEY_UNITS | GST_SEEK_FLAG_TRICKMODE_NO_AUDIO;
      break;
    case GST_PLAY_TRICK_MODE_NONE:
    default:
      break;
  }
953

954
  if (rate >= 0)
955
    seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
956
        seek_flags | GST_SEEK_FLAG_ACCURATE,
957
        /* start */ GST_SEEK_TYPE_SET, pos,
958
        /* stop */ GST_SEEK_TYPE_SET, GST_CLOCK_TIME_NONE);
959 960
  else
    seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
961
        seek_flags | GST_SEEK_FLAG_ACCURATE,
962 963 964 965
        /* start */ GST_SEEK_TYPE_SET, 0,
        /* stop */ GST_SEEK_TYPE_SET, pos);

  if (!gst_element_send_event (play->playbin, seek))
966
    return FALSE;
967

968 969 970 971
  play->rate = rate;
  play->trick_mode = mode;
  return TRUE;
}
972

973 974 975 976
static void
play_set_playback_rate (GstPlay * play, gdouble rate)
{
  if (play_set_rate_and_trick_mode (play, rate, play->trick_mode)) {
977 978
    g_print (_("Playback rate: %.2f"), rate);
    g_print ("                               \n");
979
  } else {
980 981 982
    g_print ("\n");
    g_print (_("Could not change playback rate to %.2f"), rate);
    g_print (".\n");
983 984 985
  }
}

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
static void
play_set_relative_playback_rate (GstPlay * play, gdouble rate_step,
    gboolean reverse_direction)
{
  gdouble new_rate = play->rate + rate_step;

  if (reverse_direction)
    new_rate *= -1.0;

  play_set_playback_rate (play, new_rate);
}

static const gchar *
trick_mode_get_description (GstPlayTrickMode mode)
{
  switch (mode) {
    case GST_PLAY_TRICK_MODE_NONE:
      return "normal playback, trick modes disabled";
    case GST_PLAY_TRICK_MODE_DEFAULT:
      return "trick mode: default";
    case GST_PLAY_TRICK_MODE_DEFAULT_NO_AUDIO:
      return "trick mode: default, no audio";
    case GST_PLAY_TRICK_MODE_KEY_UNITS:
      return "trick mode: key frames only";
    case GST_PLAY_TRICK_MODE_KEY_UNITS_NO_AUDIO:
      return "trick mode: key frames only, no audio";
    default:
      break;
  }
  return "unknown trick mode";
}

static void
play_switch_trick_mode (GstPlay * play)
{
  GstPlayTrickMode new_mode = ++play->trick_mode;
  const gchar *mode_desc;

  if (new_mode == GST_PLAY_TRICK_MODE_LAST)
    new_mode = GST_PLAY_TRICK_MODE_NONE;

  mode_desc = trick_mode_get_description (new_mode);

  if (play_set_rate_and_trick_mode (play, play->rate, new_mode)) {
    g_print ("Rate: %.2f (%s)                      \n", play->rate, mode_desc);
  } else {
    g_print ("\nCould not change trick mode to %s.\n", mode_desc);
  }
}

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
static GstStream *
play_get_nth_stream_in_collection (GstPlay * play, guint index,
    GstPlayTrackType track_type)
{
  guint len, i, n_streams = 0;
  GstStreamType target_type;

  switch (track_type) {
    case GST_PLAY_TRACK_TYPE_AUDIO:
      target_type = GST_STREAM_TYPE_AUDIO;
      break;
    case GST_PLAY_TRACK_TYPE_VIDEO:
      target_type = GST_STREAM_TYPE_VIDEO;
      break;
    case GST_PLAY_TRACK_TYPE_SUBTITLE:
      target_type = GST_STREAM_TYPE_TEXT;
      break;
    default:
      return NULL;
  }

  len = gst_stream_collection_get_size (play->collection);

  for (i = 0; i < len; i++) {
    GstStream *stream = gst_stream_collection_get_stream (play->collection, i);
    GstStreamType type = gst_stream_get_stream_type (stream);

    if (type & target_type) {
      if (index == n_streams)
        return stream;

      n_streams++;
    }
  }

  return NULL;
}

1074 1075 1076 1077 1078
static void
play_cycle_track_selection (GstPlay * play, GstPlayTrackType track_type)
{
  const gchar *prop_cur, *prop_n, *prop_get, *name;
  gint cur = -1, n = -1;
1079
  guint flag, cur_flags;
1080

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
  /* playbin3 variables */
  GList *selected_streams = NULL;
  gint cur_audio_idx = -1, cur_video_idx = -1, cur_text_idx = -1;
  gint nb_audio = 0, nb_video = 0, nb_text = 0;
  guint len, i;

  g_mutex_lock (&play->selection_lock);
  if (play->is_playbin3) {
    if (!play->collection) {
      g_print ("No stream-collection\n");
      g_mutex_unlock (&play->selection_lock);
      return;
    }

    /* Check the total number of streams of each type */
    len = gst_stream_collection_get_size (play->collection);
    for (i = 0; i < len; i++) {
      GstStream *stream =
          gst_stream_collection_get_stream (play->collection, i);
      if (stream) {
        GstStreamType type = gst_stream_get_stream_type (stream);
        const gchar *sid = gst_stream_get_stream_id (stream);

        if (type & GST_STREAM_TYPE_AUDIO) {
          if (play->cur_audio_sid && !g_strcmp0 (play->cur_audio_sid, sid))
            cur_audio_idx = nb_audio;
          nb_audio++;
        } else if (type & GST_STREAM_TYPE_VIDEO) {
          if (play->cur_video_sid && !g_strcmp0 (play->cur_video_sid, sid))
            cur_video_idx = nb_video;
          nb_video++;
        } else if (type & GST_STREAM_TYPE_TEXT) {
          if (play->cur_text_sid && !g_strcmp0 (play->cur_text_sid, sid))
            cur_text_idx = nb_text;
          nb_text++;
        } else {
          g_print ("Unknown stream type with stream-id %s", sid);
        }
      }
    }
  }

1123 1124 1125 1126 1127 1128
  switch (track_type) {
    case GST_PLAY_TRACK_TYPE_AUDIO:
      prop_get = "get-audio-tags";
      prop_cur = "current-audio";
      prop_n = "n-audio";
      name = "audio";
1129
      flag = 0x2;
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
      if (play->is_playbin3) {
        n = nb_audio;
        cur = cur_audio_idx;
        if (play->cur_video_sid) {
          selected_streams =
              g_list_append (selected_streams, play->cur_video_sid);
        }
        if (play->cur_text_sid) {
          selected_streams =
              g_list_append (selected_streams, play->cur_text_sid);
        }
      }
1142 1143 1144 1145 1146 1147
      break;
    case GST_PLAY_TRACK_TYPE_VIDEO:
      prop_get = "get-video-tags";
      prop_cur = "current-video";
      prop_n = "n-video";
      name = "video";
1148
      flag = 0x1;
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
      if (play->is_playbin3) {
        n = nb_video;
        cur = cur_video_idx;
        if (play->cur_audio_sid) {
          selected_streams =
              g_list_append (selected_streams, play->cur_audio_sid);
        }
        if (play->cur_text_sid) {
          selected_streams =
              g_list_append (selected_streams, play->cur_text_sid);
        }
      }
1161 1162 1163 1164 1165 1166
      break;
    case GST_PLAY_TRACK_TYPE_SUBTITLE:
      prop_get = "get-text-tags";
      prop_cur = "current-text";
      prop_n = "n-text";
      name = "subtitle";
1167
      flag = 0x4;
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
      if (play->is_playbin3) {
        n = nb_text;
        cur = cur_text_idx;
        if (play->cur_audio_sid) {
          selected_streams =
              g_list_append (selected_streams, play->cur_audio_sid);
        }
        if (play->cur_video_sid) {
          selected_streams =
              g_list_append (selected_streams, play->cur_video_sid);
        }
      }
1180 1181 1182 1183 1184
      break;
    default:
      return;
  }

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
  if (play->is_playbin3) {
    if (n > 0) {
      if (cur < 0)
        cur = 0;
      else
        cur = (cur + 1) % (n + 1);
    }
  } else {
    g_object_get (play->playbin, prop_cur, &cur, prop_n, &n, "flags",
        &cur_flags, NULL);

    if (!(cur_flags & flag))
      cur = 0;
    else
      cur = (cur + 1) % (n + 1);
  }
1201 1202 1203

  if (n < 1) {
    g_print ("No %s tracks.\n", name);
1204
    g_mutex_unlock (&play->selection_lock);
1205 1206 1207 1208 1209
  } else {
    gchar *lcode = NULL, *lname = NULL;
    const gchar *lang = NULL;
    GstTagList *tags = NULL;

1210
    if (cur >= n && track_type != GST_PLAY_TRACK_TYPE_VIDEO) {
1211 1212
      cur = -1;
      g_print ("Disabling %s.           \n", name);
1213 1214 1215
      if (play->is_playbin3) {
        /* Just make it empty for the track type */
      } else if (cur_flags & flag) {
1216 1217 1218 1219
        cur_flags &= ~flag;
        g_object_set (play->playbin, "flags", cur_flags, NULL);
      }
    } else {
1220 1221 1222
      /* For video we only want to switch between streams, not disable it altogether */
      if (cur >= n)
        cur = 0;
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241

      if (play->is_playbin3) {
        GstStream *stream;

        stream = play_get_nth_stream_in_collection (play, cur, track_type);
        if (stream) {
          selected_streams = g_list_append (selected_streams,
              (gchar *) gst_stream_get_stream_id (stream));
          tags = gst_stream_get_tags (stream);
        } else {
          g_print ("Collection has no stream for track %d of %d.\n",
              cur + 1, n);
        }
      } else {
        if (!(cur_flags & flag) && track_type != GST_PLAY_TRACK_TYPE_VIDEO) {
          cur_flags |= flag;
          g_object_set (play->playbin, "flags", cur_flags, NULL);
        }
        g_signal_emit_by_name (play->playbin, prop_get, cur, &tags);
1242
      }
1243

1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
      if (tags != NULL) {
        if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &lcode))
          lang = gst_tag_get_language_name (lcode);
        else if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_NAME, &lname))
          lang = lname;
        gst_tag_list_unref (tags);
      }
      if (lang != NULL)
        g_print ("Switching to %s track %d of %d (%s).\n", name, cur + 1, n,
            lang);
      else
        g_print ("Switching to %s track %d of %d.\n", name, cur + 1, n);
    }
1257 1258
    g_free (lcode);
    g_free (lname);
1259 1260 1261
    g_mutex_unlock (&play->selection_lock);

    if (play->is_playbin3) {
1262 1263 1264 1265 1266
      if (selected_streams)
        gst_element_send_event (play->playbin,
            gst_event_new_select_streams (selected_streams));
      else
        g_print ("Can't disable all streams !\n");
1267 1268 1269
    } else {
      g_object_set (play->playbin, prop_cur, cur, NULL);
    }
1270
  }
1271 1272 1273

  if (selected_streams)
    g_list_free (selected_streams);
1274 1275
}

1276 1277 1278
static void
print_keyboard_help (void)
{
1279 1280 1281 1282 1283 1284 1285 1286
  static struct
  {
    const gchar *key_desc;
    const gchar *key_help;
  } key_controls[] = {
    {
    N_("space"), N_("pause/unpause")}, {
    N_("q or ESC"), N_("quit")}, {
1287 1288
    N_("> or n"), N_("play next")}, {
    N_("< or b"), N_("play previous")}, {
1289 1290 1291 1292 1293 1294 1295 1296
    "\342\206\222", N_("seek forward")}, {
    "\342\206\220", N_("seek backward")}, {
    "\342\206\221", N_("volume up")}, {
    "\342\206\223", N_("volume down")}, {
    "+", N_("increase playback rate")}, {
    "-", N_("decrease playback rate")}, {
    "d", N_("change playback direction")}, {
    "t", N_("enable/disable trick modes")}, {
1297 1298 1299
    "a", N_("change audio track")}, {
    "v", N_("change video track")}, {
    "s", N_("change subtitle track")}, {
1300
    "0", N_("seek to beginning")}, {
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
  "k", N_("show keyboard shortcuts")},};
  guint i, chars_to_pad, desc_len, max_desc_len = 0;

  g_print ("\n\n%s\n\n", _("Interactive mode - keyboard controls:"));

  for (i = 0; i < G_N_ELEMENTS (key_controls); ++i) {
    desc_len = g_utf8_strlen (key_controls[i].key_desc, -1);
    max_desc_len = MAX (max_desc_len, desc_len);
  }
  ++max_desc_len;

  for (i = 0; i < G_N_ELEMENTS (key_controls); ++i) {
    chars_to_pad = max_desc_len - g_utf8_strlen (key_controls[i].key_desc, -1);
    g_print ("\t%s", key_controls[i].key_desc);
    g_print ("%-*s: ", chars_to_pad, "");
    g_print ("%s\n", key_controls[i].key_help);
  }
  g_print ("\n");
1319 1320
}

1321 1322 1323 1324
static void
keyboard_cb (const gchar * key_input, gpointer user_data)
{
  GstPlay *play = (GstPlay *) user_data;
1325 1326 1327 1328 1329
  gchar key = '\0';

  /* only want to switch/case on single char, not first char of string */
  if (key_input[0] != '\0' && key_input[1] == '\0')
    key = g_ascii_tolower (key_input[0]);
1330

1331
  switch (key) {
1332 1333 1334
    case 'k':
      print_keyboard_help ();
      break;
1335 1336 1337
    case ' ':
      toggle_paused (play);
      break;
1338 1339 1340 1341
    case 'q':
    case 'Q':
      g_main_loop_quit (play->loop);
      break;
1342
    case 'n':
1343 1344
    case '>':
      if (!play_next (play)) {
1345
        g_print ("\n%s\n", _("Reached end of play list."));
1346 1347 1348
        g_main_loop_quit (play->loop);
      }
      break;
1349
    case 'b':
1350 1351 1352
    case '<':
      play_prev (play);
      break;
1353
    case '+':
1354
      if (play->rate > -0.2 && play->rate < 0.0)
1355
        play_set_relative_playback_rate (play, 0.0, TRUE);
1356
      else if (ABS (play->rate) < 2.0)
1357
        play_set_relative_playback_rate (play, 0.1, FALSE);
1358
      else if (ABS (play->rate) < 4.0)
1359
        play_set_relative_playback_rate (play, 0.5, FALSE);
1360
      else
1361
        play_set_relative_playback_rate (play, 1.0, FALSE);
1362 1363
      break;
    case '-':
1364 1365 1366 1367
      if (play->rate > 0.0 && play->rate < 0.20)
        play_set_relative_playback_rate (play, 0.0, TRUE);
      else if (ABS (play->rate) <= 2.0)
        play_set_relative_playback_rate (play, -0.1, FALSE);
1368
      else if (ABS (play->rate) <= 4.0)
1369
        play_set_relative_playback_rate (play, -0.5, FALSE);
1370
      else
1371
        play_set_relative_playback_rate (play, -1.0, FALSE);
1372 1373
      break;
    case 'd':
1374 1375 1376 1377
      play_set_relative_playback_rate (play, 0.0, TRUE);
      break;
    case 't':
      play_switch_trick_mode (play);
1378
      break;
1379
    case 27:                   /* ESC */
1380 1381 1382 1383
      if (key_input[1] == '\0') {
        g_main_loop_quit (play->loop);
        break;
      }
1384 1385 1386 1387 1388 1389 1390 1391 1392
    case 'a':
      play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_AUDIO);
      break;
    case 'v':
      play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_VIDEO);
      break;
    case 's':
      play_cycle_track_selection (play, GST_PLAY_TRACK_TYPE_SUBTITLE);
      break;
1393 1394 1395
    case '0':
      play_do_seek (play, 0, play->rate, play->trick_mode);
      break;
1396
    default:
1397 1398 1399 1400
      if (strcmp (key_input, GST_PLAY_KB_ARROW_RIGHT) == 0) {
        relative_seek (play, +0.08);
      } else if (strcmp (key_input, GST_PLAY_KB_ARROW_LEFT) == 0) {
        relative_seek (play, -0.01);
1401 1402 1403 1404
      } else if (strcmp (key_input, GST_PLAY_KB_ARROW_UP) == 0) {
        play_set_relative_volume (play, +1.0 / VOLUME_STEPS);
      } else if (strcmp (key_input, GST_PLAY_KB_ARROW_DOWN) == 0) {
        play_set_relative_volume (play, -1.0 / VOLUME_STEPS);
1405 1406 1407 1408 1409
      } else {
        GST_INFO ("keyboard input:");
        for (; *key_input != '\0'; ++key_input)
          GST_INFO ("  code %3d", *key_input);
      }
1410 1411 1412 1413
      break;
  }
}

1414 1415 1416 1417 1418
int
main (int argc, char **argv)
{
  GstPlay *play;
  GPtrArray *playlist;
1419
  gboolean verbose = FALSE;
1420
  gboolean print_version = FALSE;
1421
  gboolean interactive = TRUE;
1422
  gboolean gapless = FALSE;
1423
  gboolean shuffle = FALSE;
1424
  gdouble volume = -1;
1425 1426 1427 1428
  gchar **filenames = NULL;
  gchar *audio_sink = NULL;
  gchar *video_sink = NULL;
  gchar **uris;
1429
  gchar *flags = NULL;
1430 1431 1432
  guint num, i;
  GError *err = NULL;
  GOptionContext *ctx;
1433
  gchar *playlist_file = NULL;
1434
  gboolean use_playbin3 = FALSE;
1435
  GOptionEntry options[] = {
1436 1437
    {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
        N_("Output status information and property notifications"), NULL},
1438
    {"flags", 0, 0, G_OPTION_ARG_STRING, &flags,
1439 1440
          N_("Control playback behaviour setting playbin 'flags' property"),
        NULL},
1441 1442 1443 1444 1445 1446
    {"version", 0, 0, G_OPTION_ARG_NONE, &print_version,
        N_("Print version information and exit"), NULL},
    {"videosink", 0, 0, G_OPTION_ARG_STRING, &video_sink,
        N_("Video sink to use (default is autovideosink)"), NULL},
    {"audiosink", 0, 0, G_OPTION_ARG_STRING, &audio_sink,
        N_("Audio sink to use (default is autoaudiosink)"), NULL},
1447 1448
    {"gapless", 0, 0, G_OPTION_ARG_NONE, &gapless,
        N_("Enable gapless playback"), NULL},
1449 1450
    {"shuffle", 0, 0, G_OPTION_ARG_NONE, &shuffle,
        N_("Shuffle playlist"), NULL},
1451 1452 1453
    {"no-interactive", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE,
          &interactive,
        N_("Disable interactive control via the keyboard"), NULL},
1454 1455
    {"volume", 0, 0, G_OPTION_ARG_DOUBLE, &volume,
        N_("Volume"), NULL},
1456 1457
    {"playlist", 0, 0, G_OPTION_ARG_FILENAME, &playlist_file,
        N_("Playlist file containing input media files"), NULL},
1458 1459
    {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet,
        N_("Do not print any output (apart from errors)"), NULL},
1460 1461 1462 1463
    {"use-playbin3", 0, 0, G_OPTION_ARG_NONE, &use_playbin3,
          N_("Use playbin3 pipeline")
          N_("(default varies depending on 'USE_PLAYBIN' env variable)"),
        NULL},
1464 1465 1466 1467
    {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &filenames, NULL},
    {NULL}
  };

1468 1469
  setlocale (LC_ALL, "");

1470 1471 1472 1473 1474 1475 1476
#ifdef ENABLE_NLS
  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);
#endif

  g_set_prgname ("gst-play-" GST_API_VERSION);
1477 1478
  /* Ensure XInitThreads() is called if/when needed */
  g_setenv ("GST_GL_XINITTHREADS", "1", TRUE);
1479 1480 1481 1482 1483 1484

  ctx = g_option_context_new ("FILE1|URI1 [FILE2|URI2] [FILE3|URI3] ...");
  g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
  g_option_context_add_group (ctx, gst_init_get_option_group ());
  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
1485 1486
    g_option_context_free (ctx);
    g_clear_error (&err);
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
    return 1;
  }
  g_option_context_free (ctx);

  GST_DEBUG_CATEGORY_INIT (play_debug, "play", 0, "gst-play");

  if (print_version) {
    gchar *version_str;

    version_str = gst_version_string ();
    g_print ("%s version %s\n", g_get_prgname (), PACKAGE_VERSION);
    g_print ("%s\n", version_str);
    g_print ("%s\n", GST_PACKAGE_ORIGIN);
    g_free (version_str);
1501 1502 1503

    g_free (audio_sink);
    g_free (video_sink);
1504
    g_free (playlist_file);
1505

1506 1507 1508
    return 0;
  }

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
  playlist = g_ptr_array_new ();

  if (playlist_file != NULL) {
    gchar *playlist_contents = NULL;
    gchar **lines = NULL;

    if (g_file_get_contents (playlist_file, &playlist_contents, NULL, &err)) {
      lines = g_strsplit (playlist_contents, "\n", 0);
      num = g_strv_length (lines);

      for (i = 0; i < num; i++) {
        if (lines[i][0] != '\0') {
          GST_LOG ("Playlist[%d]: %s", i + 1, lines[i]);
          add_to_playlist (playlist, lines[i]);
        }
      }
      g_strfreev (lines);
      g_free (playlist_contents);
    } else {
      g_printerr ("Could not read playlist: %s\n", err->message);
      g_clear_error (&err);
    }
    g_free (playlist_file);
1532
    playlist_file = NULL;
1533 1534 1535
  }

  if (playlist->len == 0 && (filenames == NULL || *filenames == NULL)) {
1536 1537 1538 1539 1540
    g_printerr (_("Usage: %s FILE1|URI1 [FILE2|URI2] [FILE3|URI3] ..."),
        "gst-play-" GST_API_VERSION);
    g_printerr ("\n\n"),
        g_printerr ("%s\n\n",
        _("You must provide at least one filename or URI to play."));
1541 1542
    /* No input provided. Free array */
    g_ptr_array_free (playlist, TRUE);
1543 1544 1545 1546

    g_free (audio_sink);
    g_free (video_sink);

1547 1548 1549 1550
    return 1;
  }

  /* fill playlist */
1551 1552 1553 1554 1555 1556 1557
  if (filenames != NULL && *filenames != NULL) {
    num = g_strv_length (filenames);
    for (i = 0; i < num; ++i) {
      GST_LOG ("command line argument: %s", filenames[i]);
      add_to_playlist (playlist, filenames[i]);
    }
    g_strfreev (filenames);
1558 1559
  }

1560
  num = playlist->len;
1561 1562 1563
  g_ptr_array_add (playlist, NULL);

  uris = (gchar **) g_ptr_array_free (playlist, FALSE);
1564 1565 1566 1567

  if (shuffle)
    shuffle_uris (uris, num);

1568
  /* prepare */
1569 1570
  play = play_new (uris, audio_sink, video_sink, gapless, volume, verbose,
      flags, use_playbin3);
1571

1572 1573 1574 1575 1576 1577
  if (play == NULL) {
    g_printerr
        ("Failed to create 'playbin' element. Check your GStreamer installation.\n");
    return EXIT_FAILURE;
  }

1578 1579
  if (interactive) {
    if (gst_play_kb_set_key_handler (keyboard_cb, play)) {
1580
      g_print (_("Press 'k' to see a list of keyboard shortcuts.\n"));
1581 1582 1583 1584 1585 1586 1587
      atexit (restore_terminal);
    } else {
      g_print ("Interactive keyboard handling in terminal not available.\n");
    }
  }

  /* play */
1588 1589 1590 1591 1592
  do_play (play);

  /* clean up */
  play_free (play);

1593 1594 1595
  g_free (audio_sink);
  g_free (video_sink);

1596
  g_print ("\n");
1597
  gst_deinit ();
1598 1599
  return 0;
}