#!/usr/bin/env python

from gi.repository import GObject, Gst, GstApp


def cb_have_data(pad, pinfo, udata):
    # how to make pinfo.data (gpointer) into a Gst.Buffer ? 
    if not pinfo.type & Gst.PadProbeType.BUFFER:
        print "not buffer type"
        return Gst.PadProbeReturn.OK
    buffer = pinfo.get_buffer()
    ret, info = buffer.map(Gst.MapFlags.WRITE)

    print  id(info)
    print  id(info.data)
    print  type(info.data)
    print 'before =%s' % info.data[0]
    print 'size =%ld' % info.size
    i = 0
    for y in xrange (0,288):
         for x in xrange(0,192):
              #t = info.data[i + 384 - 1 - x]
              info.data[i + 384 - 1 - x] = b'\x99' #info.data[i + x]
              info.data[i + x] = b'\x99'
         i += 384
    print 'after =%s' % info.data[0]

    buffer.unmap(info)
    return Gst.PadProbeReturn.OK





GObject.threads_init()
Gst.init(None)
loop = GObject.MainLoop(None, False)

print Gst.version_string()

pipeline=Gst.ElementFactory.make('pipeline',None)
src=Gst.ElementFactory.make('videotestsrc',None)
capsfilter=Gst.ElementFactory.make('capsfilter',None)
sink=Gst.ElementFactory.make('xvimagesink',None)
pipeline.add(src)
pipeline.add(capsfilter)
pipeline.add(sink)
src.link(capsfilter)
capsfilter.link(sink)

filtercaps = Gst.Caps.from_string("video/x-raw,width=384,height=288,framerate=25/1,bpp=16,depth=16,endianness=1234")
capsfilter.set_property('caps', filtercaps)


capsfilter.get_static_pad('src').add_probe(Gst.PadProbeType.BUFFER , cb_have_data, None)


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.ERROR:
  gerror, dbg_msg = msg.parse_error()
  print "Error         : ", gerror.message
  print "Debug details : ", dbg_msg
  exit(1)

print 'running'
loop.run()

pipeline.set_state(Gst.State.NULL)
exit(0)
