Snippets de Clutter: D-Bus, GStreamer y ClutterScript

Mis apuntes de Clutter: referencias, proyectos similares y pequeños snippets en python con D-Bus, GStreamer y ClutterScript.

Traducción del original en catalán. Léela en: CatalàEnglish

Parte 4 de 7Apuntes de Clutter
  1. Conceptos de Clutter
  2. Apuntes sobre Clutter
  3. Instalando Clutter con jhbuild
  4. Snippets de Clutter: D-Bus, GStreamer y ClutterScript
  5. Algunas notas sobre el desarrollo con Clutter
  6. Player en Clutter y DBUS
  7. Player en Clutter: integración contínua

Esta página estaba en el wiki de oriolrius.cat (2009–2012). La recupero aquí tal como era.

Referencias

Proyectos similares

Snippets

  • Clutter+DBUS: este snippet es un ejemplo de código en python que recibe señales DBUS usando las librerías de clutter y a gobject como reactor.
  • Clutter+GStreamer (simple player): se trata de un simple reproductor multimedia, los códecs que soporta dependen de los plugins de gstreamer que tengamos instalados. Se puede comprobar lo simple que es aplicar texturas en forma de vídeo sobre actores de Clutter.
  • CutterScript basic: pequeño snippet con python que carga un ClutterScript y lo muestra por pantalla.
  • Clutter 1.0+GStreamer: simple player que puede usar una webcam o un fichero de vídeo como fuente con efecto de rotación
  • Full Screen: código en C de la web de clutter que trabaja a pantalla completa

Clutter+DBUS

Emisor de señales DBUS

Código de ejemplo del dbus-python-0.83.0, se encuentra en: 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()

Receptor de señales DBUS usando 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)

*/!* No funciona con Clutter 1.0

Reproductor multimedia simple, programado usando clutter con gstreamer y a gobject como 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

¿Te estás volviendo loco cuando todos los pasos parecen correctos pero todo lo que ves es una pantalla negra (gst)?

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

ClutterScript loader en 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()

Script de ejemplo '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 que puede usar una webcam o un fichero de vídeo como fuente con efecto de rotación, basado en: http://luisbg.blogalia.com/historias/61951

Nota: Si obtienes una pantalla negra, prueba a ejecutar "gstreamer-properties" para poner la salida de vídeo a "x11", "xv" u otras, dependiendo de lo exigente que sea el driver de tu tarjeta de vídeo.

#!/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)

Proyectos