#!/usr/bin/env python

from gi.repository import GObject, Gst, GstApp

GObject.threads_init()
Gst.init(None)

print Gst.version_string()

pipeline=Gst.ElementFactory.make('pipeline',None)
src=Gst.ElementFactory.make('videotestsrc',None)
src.set_property('num-buffers',1)
sink=Gst.ElementFactory.make('appsink',None)
pipeline.add(src)
pipeline.add(sink)
src.link(sink)

pipeline.set_state(Gst.State.PLAYING)

bus=pipeline.get_bus()

# still a little problem with the annotation for this
# msg=bus.timed_pop_filtered(Gst.CLOCK_TIME_NONE,Gst.MessageType.EOS | Gst.MessageType.ERROR)
# ValueError: -1 not in range 0 to 18446744073709551615
GST_CLOCK_TIME_NONE=18446744073709551615

# wait for preroll or error
msg=bus.timed_pop_filtered(GST_CLOCK_TIME_NONE, Gst.MessageType.ASYNC_DONE | Gst.MessageType.ERROR)

if msg.type == Gst.MessageType.ASYNC_DONE:
  ret, dur = pipeline.query_duration(Gst.Format.TIME)
  print "Duration: %u seconds" % (dur / Gst.SECOND)

  sample = sink.pull_sample()
  print sample
  buf = sample.get_buffer()
  print buf
  print buf.get_size()
  ret, info = buf.map_range(0,-1,Gst.MapFlags.READ)
  print info
  print len(info.data)
  print info.size
  try:
      print info.data[info.size]
  except IndexError as msg:
      print "Index Error: ",msg 
 
  # wait for EOS or error
  msg=bus.timed_pop_filtered(GST_CLOCK_TIME_NONE, Gst.MessageType.EOS | Gst.MessageType.ERROR)

if msg.type == Gst.MessageType.ERROR:
  gerror, dbg_msg = msg.parse_error()
  print "Error         : ", gerror.message
  print "Debug details : ", dbg_msg

#pipeline.set_state(Gst.State.NULL)
