#include <QApplication>
#include <QWidget>
#include <gst/gst.h>

#if GST_VERSION_MAJOR == 1
  #include <gst/video/videooverlay.h>
#else
  #include <gst/interfaces/xoverlay.h>
#endif

static ulong winId;

static GstBusSyncReply
create_window (GstBus * bus, GstMessage * message, GstPipeline * pipeline)
{
  // ignore anything but 'prepare-window-handle' element messages
  if (!gst_is_video_overlay_prepare_window_handle_message (message))
    return GST_BUS_PASS;

  //XSetWindowBackgroundPixmap (disp, win, None);
  //XMapRaised (disp, win);
  //XSync (disp, FALSE);
  gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (GST_MESSAGE_SRC (message)),
      winId);
  gst_message_unref (message);

  return GST_BUS_DROP;
}


void startGst(void /*ulong winId*/) {
  GError* err = NULL;
  GstElement* gstPipe = gst_parse_launch("videotestsrc is-live=true ! "
					 "xvimagesink name=sink handle-events=true", &err);
  if(gstPipe == NULL)
    qFatal("pipe failed\n");

  GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (gstPipe));
  gst_bus_set_sync_handler (bus, (GstBusSyncHandler) create_window, gstPipe,
        NULL);

#if 0
#if GST_VERSION_MAJOR == 1
  GstVideoOverlay* overlay = GST_VIDEO_OVERLAY(gst_bin_get_by_name(GST_BIN(gstPipe), "sink"));
  gst_video_overlay_set_window_handle(overlay, winId);
  gst_object_unref(overlay);
#else
  GstXOverlay* overlay = GST_X_OVERLAY(gst_bin_get_by_name(GST_BIN(gstPipe), "sink"));
  gst_x_overlay_set_window_handle(overlay, winId);
  gst_object_unref(overlay);
#endif
#endif

  gst_element_set_state(gstPipe, GST_STATE_PLAYING);
}


int main(int argc, char *argv[])
{
  gst_init(&argc, &argv);
  QApplication a(argc, argv);
  QWidget widget;
  widget.setAttribute(Qt::WA_PaintOnScreen);
  widget.setAttribute(Qt::WA_OpaquePaintEvent);
  widget.resize(640, 480);
  widget.show();
  winId = widget.winId();
  startGst();
  return a.exec();
}
