#!/usr/bin/env python3
#
# get gst-python version from intern downstream memoryview-buffer branch
# mkdir -p $HOME/.gstreamer-1.0/plugins/python
# cp numpye.py $HOME/.gstreamer-1.0/plugins/python
# gst-launch-1.0 videotestsrc pattern=snow ! videoconvert ! numpye ! videoconvert ! xvimagesink
#

import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstBase', '1.0')

from gi.repository import Gst, GObject, GstBase
Gst.init(None)

import ctypes
import numpy as np

FIXED_CAPS = Gst.Caps.from_string('video/x-raw,format=GRAY8,width=480,height=240')

#
# Simple Numpy element created entirely in python
#
class Numpye(GstBase.BaseTransform):
    __gstmetadata__ = ('Numpy Python','Transform', \
                      'Simple numpy element written in python', 'omgomgomg')

    __gsttemplates__ = (Gst.PadTemplate.new("src",
                                           Gst.PadDirection.SRC,
                                           Gst.PadPresence.ALWAYS,
                                           FIXED_CAPS),
                       Gst.PadTemplate.new("sink",
                                           Gst.PadDirection.SINK,
                                           Gst.PadPresence.ALWAYS,
                                           FIXED_CAPS))

    def do_transform_ip(self, buffer):
        Gst.info("timestamp(buffer):%s" % (Gst.TIME_ARGS(buffer.pts)))
        
        (ok, info) = buffer.map(Gst.MapFlags.READ | Gst.MapFlags.WRITE)

            # Now create a NumPy ndarray from the memoryview and modify it:
        width = 480
        height = 240

        A = np.ndarray(shape = (height, width), dtype = np.int8, buffer = info.data)
        A.setflags(write = True)
        A[20,:] = 0

        buffer.unmap(info)

        return Gst.FlowReturn.OK

GObject.type_register(Numpye)
__gstelementfactory__ = ("numpye", Gst.Rank.NONE, Numpye)
