python: Add a Gst.init_python function to be called from plugins
[platform/upstream/gstreamer.git] / subprojects / gst-python / examples / plugins / python / exampleTransform.py
1 #!/usr/bin/python3
2 # exampleTransform.py
3 # 2019 Daniel Klamt <graphics@pengutronix.de>
4
5 # Inverts a grayscale image in place, requires numpy.
6 #
7 # gst-launch-1.0 videotestsrc ! ExampleTransform ! videoconvert ! xvimagesink
8
9 import gi
10 gi.require_version('Gst', '1.0')
11 gi.require_version('GstBase', '1.0')
12 gi.require_version('GstVideo', '1.0')
13
14 from gi.repository import Gst, GObject, GstBase, GstVideo
15
16 import numpy as np
17
18 Gst.init_python()
19 FIXED_CAPS = Gst.Caps.from_string('video/x-raw,format=GRAY8,width=[1,2147483647],height=[1,2147483647]')
20
21 class ExampleTransform(GstBase.BaseTransform):
22     __gstmetadata__ = ('ExampleTransform Python','Transform',
23                       'example gst-python element that can modify the buffer gst-launch-1.0 videotestsrc ! ExampleTransform ! videoconvert ! xvimagesink', 'dkl')
24
25     __gsttemplates__ = (Gst.PadTemplate.new("src",
26                                            Gst.PadDirection.SRC,
27                                            Gst.PadPresence.ALWAYS,
28                                            FIXED_CAPS),
29                        Gst.PadTemplate.new("sink",
30                                            Gst.PadDirection.SINK,
31                                            Gst.PadPresence.ALWAYS,
32                                            FIXED_CAPS))
33
34     def do_set_caps(self, incaps, outcaps):
35         struct = incaps.get_structure(0)
36         self.width = struct.get_int("width").value
37         self.height = struct.get_int("height").value
38         return True
39
40     def do_transform_ip(self, buf):
41         try:
42             with buf.map(Gst.MapFlags.READ | Gst.MapFlags.WRITE) as info:
43                 # Create a NumPy ndarray from the memoryview and modify it in place:
44                 A = np.ndarray(shape = (self.height, self.width), dtype = np.uint8, buffer = info.data)
45                 A[:] = np.invert(A)
46
47                 return Gst.FlowReturn.OK
48         except Gst.MapError as e:
49             Gst.error("Mapping error: %s" % e)
50             return Gst.FlowReturn.ERROR
51
52 GObject.type_register(ExampleTransform)
53 __gstelementfactory__ = ("ExampleTransform", Gst.Rank.NONE, ExampleTransform)