/* GStreamer
 * Copyright (C) <2017> Víctor Jáquez <vjaquez@igalia.com>
 *
 * kms-videooverlay: demonstrate overlay handling using kmssink
 *
 * 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.
 */

/* compilation:
 * gcc `pkg-config --cflags --libs gstreamer-1.0 gstreamer-video-1.0.pc` \
 *   kms-videooverlay.c -o kms-videooverlay
 */

#include <gst/gst.h>
#include <gst/video/videooverlay.h>

#include <signal.h>

static GMainLoop *loop;

static void
signal_handler (int signum)
{
  gst_printerrln ("quitting…");
  g_main_loop_quit (loop);
}

static gboolean
change_position (gpointer data)
{
  gboolean ret;
  GstVideoOverlay *overlay = GST_VIDEO_OVERLAY (data);
  static guint i = 0, x = 0, y = 0;

  i++;
  x += 5;
  y += 5;

  if (i % 5 == 0)
    ret = gst_video_overlay_set_render_rectangle (overlay, x, y, -1, -1);
  else
    ret = gst_video_overlay_set_render_rectangle (overlay, x, y, 320, 240);
  if (ret)
    gst_video_overlay_expose (overlay);

  return ret;
}

int
main (int argc, char **argv)
{
  GstElement *pipeline, *src, *sink;
  GstStateChangeReturn sret;

  if (signal (SIGINT, signal_handler) == SIG_ERR)
    gst_printerrln ("can't catch SIGINT");

  gst_init (&argc, &argv);

  /* prepare the pipeline */
  pipeline = gst_pipeline_new ("xvoverlay");
  src = gst_element_factory_make ("videotestsrc", NULL);
  sink = gst_element_factory_make ("kmssink", NULL);

  if (sink == NULL)
    g_error ("Couldn't find a working video sink.");

  gst_bin_add_many (GST_BIN (pipeline), src, sink, NULL);
  gst_element_link (src, sink);

  /* run the pipeline */

  loop = g_main_loop_new (NULL, TRUE);

  sret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
  if (sret == GST_STATE_CHANGE_FAILURE) {
    gst_element_set_state (pipeline, GST_STATE_NULL);
  } else {
    g_timeout_add_seconds (1, change_position, sink);
    g_main_loop_run (loop);
  }

  gst_object_unref (pipeline);
  g_main_loop_unref (loop);
  return 0;
}
