Clutter snippets: D-Bus, GStreamer and ClutterScript

My Clutter notes: references, similar projects and small python snippets with D-Bus, GStreamer and ClutterScript.

Translation of the original in Catalan. Read it in: CatalàCastellano

Part 4 of 7Clutter notes
  1. Clutter concepts
  2. Notes on Clutter
  3. Installing Clutter with jhbuild
  4. Clutter snippets: D-Bus, GStreamer and ClutterScript
  5. Some notes on Clutter development
  6. Player in Clutter and DBUS
  7. Player in Clutter: continuous integration

This page was on the oriolrius.cat wiki (2009–2012). I bring it back here as it was.

References

Similar projects

Snippets

  • Clutter+DBUS: this snippet is a sample python code that receives DBUS signals using the clutter libraries and gobject as the reactor.
  • Clutter+GStreamer (simple player): it is a simple multimedia player, the codecs it supports depend on the gstreamer plugins we have installed. You can see how simple it is to apply textures in the form of video onto Clutter actors.
  • CutterScript basic: small snippet with python that loads a ClutterScript and displays it on screen.
  • Clutter 1.0+GStreamer: simple player that can use webcam source or video file source with rotate effect
  • Full Screen: C code from the clutter website that works in fullscreen

Clutter+DBUS

DBUS signal emitter

Sample code from dbus-python-0.83.0, it is in: examples/example-signal-emitter.py

#!/usr/bin/env python

usage = """Usage:
python example-signal-emitter.py &
python example-signal-recipient.py
python example-signal-recipient.py --exit-service
"""

# Copyright (C) 2004-2006 Red Hat Inc. <http://www.redhat.com/>
# Copyright (C) 2005-2007 Collabora Ltd. <http://www.collabora.co.uk/>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy,
# modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import gobject

import dbus
import dbus.service
import dbus.mainloop.glib

class TestObject(dbus.service.Object):
    def __init__(self, conn, object_path='/com/example/TestService/object'):
        dbus.service.Object.__init__(self, conn, object_path)

    @dbus.service.signal('com.example.TestService')
    def HelloSignal(self, message):
        # The signal is emitted when this method exits
        # You can have code here if you wish
        pass

    @dbus.service.method('com.example.TestService')
    def emitHelloSignal(self):
        #you emit signals by calling the signal's skeleton method
        self.HelloSignal('Hello')
        return 'Signal emitted'

    @dbus.service.method("com.example.TestService",
                         in_signature='', out_signature='')
    def Exit(self):
        loop.quit()

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    session_bus = dbus.SessionBus()
    name = dbus.service.BusName('com.example.TestService', session_bus)
    object = TestObject(session_bus)

    loop = gobject.MainLoop()
    print "Running example signal emitter service."
    print usage
    loop.run()

DBUS signal receiver using Clutter

#!/usr/bin/env python

usage = """Usage:
python example-signal-emitter.py &
python example-signal-recipient.py
python example-signal-recipient.py --exit-service
"""

import sys
import traceback

import gobject
import clutter

import dbus
import dbus.mainloop.glib

def handle_reply(msg):
    print msg

def handle_error(e):
    print str(e)

def emit_signal():
   #call the emitHelloSignal method
   object.emitHelloSignal(dbus_interface="com.example.TestService")
   #reply_handler = handle_reply, error_handler = handle_error)
   # exit after waiting a short time for the signal
   gobject.timeout_add(2000, clutter.main_quit)

   if sys.argv[1:] == ['--exit-service']:
      object.Exit(dbus_interface='com.example.TestService')

   return False

def hello_signal_handler(hello_string):
    print ("Received signal (by connecting using remote object) and it says: " + hello_string)

def catchall_signal_handler(*args, **kwargs):
    print ("Caught signal (in catchall handler) " + kwargs['dbus_interface'] + "." + kwargs['member'])
    for arg in args:
        print " " + str(arg)

def catchall_hello_signals_handler(hello_string):
    print "Received a hello signal and it says " + hello_string

def catchall_testservice_interface_handler(hello_string, dbus_message):
    print "com.example.TestService interface says " + hello_string + " when it sent signal " + dbus_message.get_member()

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    bus = dbus.SessionBus()
    try:
        object = bus.get_object("com.example.TestService","/com/example/TestService/object")

        object.connect_to_signal("HelloSignal", hello_signal_handler, dbus_interface="com.example.TestService", arg0="Hello")
    except dbus.DBusException:
        traceback.print_exc()
        print usage
        sys.exit(1)

    #lets make a catchall
    bus.add_signal_receiver(catchall_signal_handler, interface_keyword='dbus_interface', member_keyword='member')

    bus.add_signal_receiver(catchall_hello_signals_handler, dbus_interface = "com.example.TestService", signal_name = "HelloSignal")

    bus.add_signal_receiver(catchall_testservice_interface_handler, dbus_interface = "com.example.TestService", message_keyword='dbus_message')

    # Tell the remote object to emit the signal after a short delay
    gobject.timeout_add(2000, emit_signal)

    #loop = gobject.MainLoop()
    #loop.run()
    clutter.main()

Clutter+GStreamer (Simple Player)

*/!* Does not work with Clutter 1.0

Simple multimedia player, programmed using clutter with gstreamer and gobject as the reactor.

# origin: http://lists.o-hand.com/clutter/0673.html
# Simple video player that outputs to a clutter texture
# For more funky control of the gst player like bus messages
# seeking and pausing, please see the gstreamer playbin document
# This has been tested with clutter trunk and not the stable branch
import gst
import cluttergst
import clutter
import gobject
import sys

class GstPlayer:
    def __init__(self, stage, vfile):
        self.stage = stage
        self.video_texture = cluttergst.VideoTexture()
        self.pipeline = gst.Pipeline("mypipe")
        self.playbin = self.video_texture.get_playbin()
        # Setup uri and sinks
        self.set_location(vfile)
        self.pipeline.add(self.playbin)
        # Finally add the video to the stage
        self.stage.add(self.video_texture)
        # play it
        self.pipeline.set_state(gst.STATE_PLAYING)

    def set_location(self, location):
        if not gst.uri_is_valid(location):
            location = "file://" + location
        self.playbin.set_property('uri', location)

def main():
    stage = clutter.stage_get_default()
    stage.set_size(1024,768)
    stage.set_color(clutter.color_parse('DarkSlateGrey'))
    stage.connect('key-press-event', clutter.main_quit)
    player = GstPlayer(stage, sys.argv[1])
    stage.show_all()
    loop = gobject.MainLoop()
    try:
        #loop.run() # This runs the gobject main loop via pythonbindings
        clutter.main() # This has the side effect of making telepathyunusable
    except KeyboardInterrupt:
        print 'interrupted'
    return 0

# the first command line argument is the name of the file or a URI
if __name__ == '__main__':
    main()

Debug PyGST

Getting mad when all steps look right but all you see is a black (gst) screen ?

GST_DEBUG=3,python:5,gnl*:5 python your_script.py

ClutterScript loader in python

import clutter

s = clutter.Script()
res = clutter.Script.load_from_file(s,'basic.json')
stage=s.get_object('main-stage')
stage.show_all()
clutter.init()
clutter.main()

Sample script 'basic.json':

{
  "My Scene" : {
    "id" : "main-stage",
    "type" : "ClutterStage",
    "title" : "ClutterScript test",
    "color" : "white",
    "children" : [
      {
        "id" : "rombo-roig",
        "type" : "ClutterRectangle",
        "color" : "#ff0000ff",
        "x" : 150, "y" : 200, "width" : 200, "height" : 200
      }
    ]
  }
}

Simple Player: Clutter 1.0 + GStreamer

simple player that can use webcam source or video file source with rotate effect, base on: http://luisbg.blogalia.com/historias/61951

Note: If you get a blackscreen, try running "gstreamer-properties" to set video output to "x11", "xv" or others, depending on how picky is your video driver.

#!/usr/bin/env python

import os, sys, optparse
import clutter
import gtk
import gst
import cluttergst
import gobject

gobject.threads_init()

class Awesome:
    def OnDynamicPad(self, dbin, pad, islast):
        pad.link(self.colorspace.get_pad("sink"))

    def __init__(self, video_file):
        # Controls depth
        self.foward = True

        def bus_handler(unused_bus, message):
            if message.type == gst.MESSAGE_ERROR:
                pass
            return gst.BUS_PASS

        self.stage = clutter.Stage(default=True)
        self.stage.set_color(clutter.Color(0))
        self.stage.set_title("Awesome")
        self.stage.connect('destroy', clutter.main_quit)
        self.stage.connect('key-press-event', clutter.main_quit)

        # Creates a gstreamer texture
        self.video_texture = clutter.Texture()

        self.pipeline = gst.Pipeline()
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect("message", bus_handler)

        if video_file == 'none':
            self.src = gst.element_factory_make("v4l2src", "src")
        else:
            self.src = gst.element_factory_make("filesrc", "filesrc")
            self.src.set_property("location", video_file)
        self.decode = gst.element_factory_make("decodebin", "decode")
        self.colorspace = gst.element_factory_make("ffmpegcolorspace", "colorspace")

        # Attaches the output texture to gstreamer sink
        self.sink = cluttergst.VideoSink(self.video_texture)

        self.pipeline.add(self.src, self.decode, self.colorspace, self.sink)

        self.decode.connect("new-decoded-pad", self.OnDynamicPad)
        gst.element_link_many(self.src, self.decode)
        gst.element_link_many(self.colorspace, self.sink)
        self.pipeline.set_state(gst.STATE_PLAYING)

        self.timeline = clutter.Timeline(500)
        self.timeline.set_loop(True)
        self.timeline.connect("completed", self.timeline_completed)

        alpha = clutter.Alpha(self.timeline, clutter.sine_half_func)
        self.behaviour_scale = clutter.BehaviourScale(alpha=alpha, \
            x_scale_start=1.0, x_scale_end=1.5, \
            y_scale_start=1.0, y_scale_end=1.6)
        self.behaviour_rotate_y = clutter.BehaviourRotate(alpha=alpha, \
            angle_start=30.0, angle_end=5.0, axis=clutter.Y_AXIS, \
            direction = "ccw")
        self.behaviour_rotate_z = clutter.BehaviourRotate(alpha=alpha, \
            angle_start=3.0, angle_end=0.0, axis=clutter.Z_AXIS, \
            direction = "ccw")

        self.behaviour_scale.apply(self.video_texture)
        self.behaviour_rotate_y.apply(self.video_texture)
        self.behaviour_rotate_z.apply(self.video_texture)

        self.stage.add(self.video_texture)
        self.stage.set_size(800, 600)
        self.stage.show_all()

        self.timeline.start()
        clutter.main()

  # Change the direction
    def timeline_completed(self,data):
        if self.foward:
            self.x_scale_start = 2.0
            self.x_scale_end = 1.0
            self.y_scale_start = 2.2
            self.y_scale_end = 1.0
            self.foward = False
        else:
            self.x_scale_start = 2.0
            self.x_scale_end = 1.0
            self.y_scale_start = 2.2
            self.y_scale_end = 1.0
            self.foward = True

        self.behaviour_scale.set_property("x_scale_start",self.x_scale_start)
        self.behaviour_scale.set_property("x_scale_end",self.x_scale_end)
        self.behaviour_scale.set_property("y_scale_start",self.y_scale_start)
        self.behaviour_scale.set_property("y_scale_end",self.y_scale_end)
        self.timeline.rewind()
        self.timeline.start()


if __name__ == "__main__":
    usage = """ pudovkin -i [file] """

    parser = optparse.OptionParser(usage=usage)
    parser.add_option("-i", "--input", action="store", type="string", \
        dest="video_file", help="Input video file", default="")
    (options, args) = parser.parse_args()

    if options.video_file:
        video_file = options.video_file
        if not os.path.exists(options.video_file):
            print "%s was not found" % options.video_file
            os._exit(2)
    else:
        video_file = 'none'

    awesome = Awesome(video_file)

Projects