Пример #1
0
    def loginButtonClicked(self):
        
        from gobject import MainLoop
        from dbus.mainloop.glib import DBusGMainLoop
        from ubuntuone.platform.credentials import CredentialsManagementTool

        DBusGMainLoop(set_as_default=True)
        loop = MainLoop()

        def loginQuit(result):
            loop.quit()
            self.service['ubuntuOneInst'] = result
            self.service['auth'] = result != None
            if self.service['auth']:
                self.serviceModel.notifyAuthChanged()

        cd = CredentialsManagementTool()
        d = cd.login()
        d.addCallbacks(loginQuit)

        loop.run()

        isAuth = self.service['auth']
        self.ui.loginButton.setVisible(not isAuth)
        self.ui.successLabel.setVisible(isAuth)
        self.ui.volumeSettings.setVisible(isAuth)
        if isAuth:
            self.ui.volumeEdit.setFocus()
Пример #2
0
def log_in_or_out(login):
   
   MainLoop,DBusGMainLoop,CredentialsManagementTool = import_globals()

   global _login_success
   _login_success = False

   DBusGMainLoop(set_as_default=True)
   loop = MainLoop()
   
   def quit(result):
      global _login_success
      loop.quit()
      if result:
         _login_success = True

   cd = CredentialsManagementTool()
   if login:
      d = cd.login()
   else:
      d = cd.clear_credentials()
   d.addCallbacks(quit)
   loop.run()
   if not _login_success and login:
      sys.exit(1)
Пример #3
0
def main_pyneo():
	"""This is the function that will be used to launch pypimd for pyneo"""
	log_open('pypimd', LOG_NDELAY|LOG_PID|LOG_PERROR, LOG_DAEMON)
	
	DBusGMainLoop(set_as_default=True)
	
	# Claim the bus name
	# TODO Check for exceptions
	SystemBus().request_name(DBUS_BUS_NAME_PYNEO)
	
	# Workaround for relative imports of pyneod stuff, see
	# http://mail.python.org/pipermail/python-list/2007-May/438250.html
	sys.path.append('/usr/share/pyneod')
	
	from backend_manager import BackendManager
	from domain_manager import DomainManager

	# Load plugins
	DomainManager.init(os.getcwdu())
	BackendManager(os.getcwdu())
	
	# 3-2-1-Go!
	main_loop = MainLoop()
	main_loop.run()
	
	log_close()
	return 0
Пример #4
0
def main():
    # Se establece que D-Bus utilizará como ciclo de mensajes por defecto
    # al que provee Glib
    DBusGMainLoop(set_as_default=True)

    # Se instancia el objeto que procesará la señal proveniente de UDisks
    autoplayer = AutoPlayer()

    # Se instancia y pone a correr el ciclo de mensajes en espera de la emisión
    # de la señal de UDisks
    mainloop = MainLoop()
    mainloop.run()
Пример #5
0
def logout():
  from gobject import MainLoop
  from dbus.mainloop.glib import DBusGMainLoop
  from ubuntuone.platform.credentials import CredentialsManagementTool

  DBusGMainLoop(set_as_default=True)
  loop = MainLoop()

  def quit(result):
    loop.quit()

  cd = CredentialsManagementTool()
  d = cd.clear_credentials()
  d.addCallbacks(quit)
  loop.run()
Пример #6
0
class DBusThread(threading.Thread):
    """
    DBus server for testing will be ran in separate thread.
    """
    def run(self):
        # Start the main loop
        from dbus.mainloop.glib import DBusGMainLoop
        from gobject import MainLoop
        self.loop = DBusGMainLoop(set_as_default=True)
        dbus.set_default_main_loop(self.loop)
        self.obj = DBusTestObject()
        self.mainloop = MainLoop()
        self.mainloop.run()

    def stop(self):
        self.mainloop.quit()
Пример #7
0
def monitor(output='syslog'):
    bus = SystemBus()
    logger = DBusLogger(output)

    bus.add_match_string("")
    bus.add_message_filter(logger)

    loop = MainLoop()
    print "Press Ctrl-C to stop."
    try:
        loop.run()
    except:
        print " Loop exited"

    bus.remove_message_filter(logger)
    bus.remove_match_string("")
Пример #8
0
class DBusThread(threading.Thread):
    """
    DBus server for testing will be ran in separate thread.
    """
    def run(self):
        # Start the main loop
        from dbus.mainloop.glib import DBusGMainLoop
        from gobject import MainLoop
        self.loop = DBusGMainLoop(set_as_default=True)
        dbus.set_default_main_loop(self.loop)
        self.obj = DBusTestObject()
        self.mainloop = MainLoop()
        self.mainloop.run()

    def stop(self):
        self.mainloop.quit()
Пример #9
0
    def login(self):
	    from gobject import MainLoop
	    from dbus.mainloop.glib import DBusGMainLoop
	    from ubuntuone.platform.credentials import CredentialsManagementTool

	    self.login_success = False

	    DBusGMainLoop(set_as_default=True)
	    loop = MainLoop()

	    def quit(result):
		    loop.quit()
		    if result:
			    self.login_success = True

	    cd = CredentialsManagementTool()
	    d = cd.login()
	    d.addCallbacks(quit)
	    loop.run()
	    return self.login_success
Пример #10
0
def login():
  from gobject import MainLoop
  from dbus.mainloop.glib import DBusGMainLoop
  from ubuntuone.platform.credentials import CredentialsManagementTool
 
  global _login_success
  _login_success = False
 
  DBusGMainLoop(set_as_default=True)
  loop = MainLoop()
 
  def quit(result):
    global _login_success
    loop.quit()
    if result:
            _login_success = True
 
  cd = CredentialsManagementTool()
  d = cd.login()
  d.addCallbacks(quit)
  loop.run()
  if not _login_success:
    sys.exit(1)
Пример #11
0
def login():
    from gobject import MainLoop
    from dbus.mainloop.glib import DBusGMainLoop
    from ubuntuone.platform.credentials import CredentialsManagementTool

    global _login_success
    _login_success = False

    DBusGMainLoop(set_as_default=True)
    loop = MainLoop()

    def quit(result):
        global _login_success
        loop.quit()
        if result:
            _login_success = True

    cd = CredentialsManagementTool()
    d = cd.login()
    d.addCallbacks(quit)
    loop.run()
    if not _login_success:
        sys.exit(1)
Пример #12
0
    def export_share( self, share ):

        serviceName = "%s:%s" % ( self.hostname, share )
        serviceTXT = "%s%s" % ( serviceTXTPrefix, share )
        self.group.AddService( IF_UNSPEC, PROTO_INET, UInt32( 0 ), serviceName, serviceType, serviceDomain, self.hostname, UInt16( servicePort ), string_array_to_txt_array( [serviceTXT] ) )

# We are a Script, lets go!
if __name__ == '__main__':
    # prepare publish
    avahi = NfsAvahiPublish()
    avahi.export()

    # Start the MainLoop for Avahi
    main_loop = MainLoop()
    main_loop.run()#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#       nfsmount-exporter.py Version 0.2
#
#       Copyright 2008 Mario Bielert <*****@*****.**>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
Пример #13
0
                self._connection = dbus.ObjectPath(value)
            else:
                raise ValueError('Read-only or nonexistent property')

            props[prop] = self._account_props()[prop]
            self.AccountPropertyChanged(props)
        elif iface == ACCOUNT_IFACE_AVATAR_IFACE:
            if prop == 'Avatar':
                self._avatar = dbus.Struct(
                    (dbus.ByteArray(value[0]), unicode(value[1])),
                    signature='ays')
                self.AvatarChanged()
            else:
                raise ValueError('Nonexistent property')
        else:
            raise ValueError('No such interface')


if __name__ == '__main__':
    DBusGMainLoop(set_as_default=True)

    try:
        am = AccountManager()
    except dbus.NameExistsException:
        print >> sys.stderr, 'AccountManager already running'
        sys.exit(1)

    print "AccountManager running..."
    mainloop = MainLoop()
    mainloop.run()
Пример #14
0
# monitor zeitgeist and do stuff
from zeitgeist.client import ZeitgeistClient
from zeitgeist.datamodel import TimeRange, Event
from gobject import MainLoop

#import hamster.client
class e_handler:
   def handler(self, tr, ev):
      # because the mainloop appears to catch exceptions
      from traceback import print_exc
      from urlparse import urlparse
      try:
         # FIXME insert clever rules here
         app = urlparse(ev[0].actor).netloc
         #desk = open("/usr/share/applications/" + app)
         #comments = filter(lambda x: x.startswith("Comment[en_GB]="), desk)
         #comment = comments[0].split("=")[1].strip()
         #self.add_fact(comment + " - " + ev[0].subjects[0].text)
         print(ev[0].subjects[0].text)
      except:
         print_exc()

hh = e_handler()
ml = MainLoop()
ZeitgeistClient().install_monitor(
    TimeRange.from_now(),
    [Event()],
    hh.handler,
    hh.handler)
ml.run()
Пример #15
0
class RTSPclient:
    """
	GStreamer RTSP client.
	"""
    def __init__(self, conf, video):
        """
		**On init:** Some initialization code.
		
		:param dictionary conf: Parsed configuration file.
		:param string video: Path to the selected video.
		"""
        #: Dictionary of configuration options (see :attr:`VideoTester.core.Client.conf`).
        self.conf = conf
        #: Path to the selected video (see :attr:`VideoTester.core.Client.video`).
        self.video = video
        #: Video size: ``(width, height)``.
        self.size = None
        #: Dictionary of paths to the processed video files: ``{'original':[<compressed>, <yuv>], 'coded':[<compressed>, <yuv>], 'received':[<compressed>, <yuv>]}``.
        self.files = {'original': [], 'coded': [], 'received': []}
        #: Gstreamer pipeline.
        self.pipeline = None
        #: Gstreamer loop.
        self.loop = None
        #: Selected video URL.
        self.url = 'rtsp://' + self.conf['ip'] + ':' + self.conf[
            'rtspport'] + '/' + self.conf['video'] + '.' + self.conf['codec']
        self.encoder, self.depay, self.bitrate, self.__add = {
            'h263':
            ("ffenc_h263", "rtph263depay", self.conf['bitrate'] + '000', ''),
            'h264': ("x264enc", "rtph264depay", self.conf['bitrate'], ''),
            'mpeg4':
            ("ffenc_mpeg4", "rtpmp4vdepay", self.conf['bitrate'] + '000', ''),
            'theora': ("theoraenc", "rtptheoradepay ! theoraparse",
                       self.conf['bitrate'], ' ! matroskamux')
        }[self.conf['codec']]

    def __events(self, bus, msg):
        """
		Event handler.
		
		:param bus: Gstreamer bus object.
		:param msg: Gstreamer message object.
		
		:returns: True.
		:rtype: boolean
		"""
        t = msg.type
        if t == MESSAGE_EOS:
            self.pipeline.set_state(STATE_PAUSED)
            sleep(0.5)
            self.pipeline.set_state(STATE_READY)
            self.pipeline.set_state(STATE_NULL)
            VTLOG.debug("GStreamer: MESSAGE_EOS received")
            self.loop.quit()
        elif t == MESSAGE_ERROR:
            self.pipeline.set_state(STATE_PAUSED)
            sleep(0.5)
            self.pipeline.set_state(STATE_READY)
            self.pipeline.set_state(STATE_NULL)
            e, d = msg.parse_error()
            VTLOG.error("GStreamer: MESSAGE_ERROR received")
            VTLOG.error(e)
            self.loop.quit()
        return True

    def __play(self):
        """
		Attach event handler, set state to *playing* and run the loop (see :attr:`loop`).
		"""
        self.pipeline.get_bus().add_watch(self.__events)
        self.pipeline.set_state(STATE_PLAYING)
        self.loop = MainLoop()
        self.loop.run()
        VTLOG.debug("GStreamer: Loop stopped")

    def receiver(self):
        """
		Connect to the RTSP server and receive the selected video (see :attr:`video`).
		"""
        VTLOG.info("Starting GStreamer receiver...")
        self.pipeline = parse_launch(
            'rtspsrc name=source ! tee name=t ! queue ! ' + self.depay +
            self.__add + ' ! filesink name=sink1 t. ! queue \
				! decodebin ! videorate skip-to-first=True ! video/x-raw-yuv,framerate=' +
            self.conf['framerate'] + '/1 ! filesink name=sink2')
        source = self.pipeline.get_by_name('source')
        sink1 = self.pipeline.get_by_name('sink1')
        sink2 = self.pipeline.get_by_name('sink2')
        source.props.location = self.url
        source.props.protocols = self.conf['protocols']
        location = self.conf['tempdir'] + self.conf['num'] + '.' + self.conf[
            'codec']
        self.files['received'].append(location)
        sink1.props.location = location
        location = self.conf['tempdir'] + self.conf['num'] + '.yuv'
        self.files['received'].append(location)
        sink2.props.location = location
        pad = sink2.get_pad("sink")
        pad.connect("notify::caps", self.__notifyCaps)
        self.__play()
        VTLOG.info("GStreamer receiver stopped")

    def reference(self):
        """
		Make the reference videos.
		
		:returns: Paths to video files (see :attr:`files`) and video size (see :attr:`size`).
		:rtype: tuple
		"""
        VTLOG.info("Making reference...")
        self.pipeline = parse_launch(
            'filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate='
            + self.conf['framerate'] + '/1  ! filesink name=sink1')
        source = self.pipeline.get_by_name('source')
        sink1 = self.pipeline.get_by_name('sink1')
        location = self.video
        self.files['original'].append(location)
        source.props.location = location
        location = self.conf['tempdir'] + self.conf['num'] + '_ref_original.yuv'
        self.files['original'].append(location)
        sink1.props.location = location
        self.__play()
        self.pipeline = parse_launch('filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1  ! ' + self.encoder + ' bitrate=' + self.bitrate \
          + ' ! tee name=t ! queue' + self.__add + ' ! filesink name=sink2 t. ! queue ! decodebin ! filesink name=sink3')
        source = self.pipeline.get_by_name('source')
        sink2 = self.pipeline.get_by_name('sink2')
        sink3 = self.pipeline.get_by_name('sink3')
        location = self.video
        source.props.location = location
        location = self.conf['tempdir'] + self.conf[
            'num'] + '_ref.' + self.conf['codec']
        self.files['coded'].append(location)
        sink2.props.location = location
        location = self.conf['tempdir'] + self.conf['num'] + '_ref.yuv'
        self.files['coded'].append(location)
        sink3.props.location = location
        self.__play()
        VTLOG.info("Reference made")
        return self.files, self.size

    def __notifyCaps(self, pad, args):
        """
		Write caps to a file.
		
		:param pad: Gstreamer pad object.
		:param args: Other arguments.
		"""
        caps = pad.get_negotiated_caps()
        if caps:
            caps = caps.to_string()
            aux = caps.split(', ')
            for x in aux:
                if x.find('width') != -1:
                    width = int(x[11:len(x)])
                elif x.find('height') != -1:
                    height = int(x[12:len(x)])
            self.size = (width, height)
            f = open(self.conf['tempdir'] + self.conf['num'] + '_caps.txt',
                     "wb")
            f.write(caps)
            f.close()
Пример #16
0
class RTSPserver:
    """
	GStreamer RTSP server.
	"""
    def __init__(self, port, bitrate, framerate, path, videos):
        """
		**On init:** Some initialization code.
		
		:param port: RTSP server port.
		:type port: string or integer
		:param bitrate: The bitrate (in kbps).
		:type bitrate: string or integer
		:param framerate: The framerate (in fps).
		:type framerate: string or integer
		:param string path: Path to the video directory.
		:param list videos: List of available videos.
		"""
        #: The bitrate (in kbps).
        self.bitrate = bitrate
        #: The framerate (in fps).
        self.framerate = framerate
        #: Path to the video directory.
        self.path = path
        #: List of available videos.
        self.videos = videos
        #: GStreamer RTSP server instance.
        self.server = Server()
        #: Gstreamer loop.
        self.loop = None
        self.server.set_service(str(port))
        #: List of GStreamer RTSP factories.
        self.factory = []
        self.__addMedia()

    def __addMedia(self):
        """
		Add media to server.
		"""
        for i, video in enumerate(self.videos):
            for j in range(0, 4):
                launch = "filesrc location=" + self.path + "/" + video + " ! decodebin ! videorate ! video/x-raw-yuv,framerate=" + str(
                    self.framerate) + "/1 ! "
                launch += {
                    0:
                    "ffenc_h263 bitrate=" + str(self.bitrate) +
                    "000 ! rtph263pay name=pay0",
                    1:
                    "x264enc bitrate=" + str(self.bitrate) +
                    " ! rtph264pay name=pay0",
                    2:
                    "ffenc_mpeg4 bitrate=" + str(self.bitrate) +
                    "000 ! rtpmp4vpay name=pay0",
                    3:
                    "theoraenc bitrate=" + str(self.bitrate) +
                    " ! rtptheorapay name=pay0"
                }[j]
                mmap = self.server.get_media_mapping()
                self.factory.append(MediaFactory())
                self.factory[-1].set_launch(launch)
                self.factory[-1].set_shared(True)
                self.factory[-1].set_eos_shutdown(True)
                name = {
                    0: "/video" + str(i) + ".h263",
                    1: "/video" + str(i) + ".h264",
                    2: "/video" + str(i) + ".mpeg4",
                    3: "/video" + str(i) + ".theora"
                }[j]
                mmap.add_factory(name, self.factory[-1])
                self.server.set_media_mapping(mmap)

    def run(self):
        """
		Attach server and run the loop (see :attr:`loop`).
		"""
        if self.server.attach():
            self.loop = MainLoop()
            self.loop.run()
Пример #17
0
class RTSPserver:
	"""
	GStreamer RTSP server.
	"""
	def __init__(self, port, bitrate, framerate):
		"""
		**On init:** Some initialization code.
		
		:param integer port: RTSP server port.
		:param integer bitrate: Video bitrate.
		:param integer framerate: Video framerate.
		"""
		self.bitrate = bitrate
		self.framerate = framerate
		self.server = Server()
		self.loop = None
		self.server.set_service(str(port))
		self.factory = []
		self.__addMedia()
	
	def __addFactory(self,url,factory):
		mmap = self.server.get_media_mapping()
		self.factory.append(factory)
		mmap.add_factory(url,factory)
		self.server.set_media_mapping(mmap)
		print "Add Service rtsp://"+socket.gethostname()+":" + self.server.get_service() + url

	def __addMedia(self):
		"""
		videotest
		"""                                
		launch = "videotestsrc pattern=ball ! timeoverlay halign=right valign=top ! clockoverlay halign=left valign=top time-format=\"%Y/%m/%d %H:%M:%S\" ! "
		launch += "x264enc bitrate="+str(self.bitrate)+" ! rtph264pay name=pay0"                
		mfactory = MediaFactory()
		mfactory.set_launch(launch)
		mfactory.set_shared(True)
		mfactory.set_eos_shutdown(True)
		self.__addFactory("/videotest.h264", mfactory)

		"""
		webcam
		"""
		launch = "v4l2src ! video/x-raw-yuv,width=320,height=240,depth=32,framerate="+str(self.framerate)+"/1 ! timeoverlay halign=right valign=top ! clockoverlay halign=left valign=top time-format=\"%Y/%m/%d %H:%M:%S\" ! queue ! "
		launch += "x264enc bitrate="+str(self.bitrate)+" ! rtph264pay name=pay0"                
		mfactory = MediaFactory()
		mfactory.set_launch(launch)
		mfactory.set_shared(True)
		mfactory.set_eos_shutdown(True)
		self.__addFactory("/v4l2.h264", mfactory)
		
	
	def run(self):
		"""
		Attach server and run the loop (see :attr:`loop`).
		"""
		if self.server.attach():
			self.loop = MainLoop()
			self.loop.run()
	
	def stop(self):
		self.loop.quit()
Пример #18
0
from clipboardms.server import ClipboardMediaServer
from dbus.mainloop.glib import DBusGMainLoop
from gobject import MainLoop

DBusGMainLoop(set_as_default=True)

server = ClipboardMediaServer()

loop = MainLoop()
loop.run()
Пример #19
0
            elif prop == 'Connection':
                self._connection = dbus.ObjectPath(value)
            else:
                raise ValueError('Read-only or nonexistent property')

            props[prop] = self._account_props()[prop]
            self.AccountPropertyChanged(props)
        elif iface == ACCOUNT_IFACE_AVATAR_IFACE:
            if prop == 'Avatar':
                self._avatar = dbus.Struct(
                        (dbus.ByteArray(value[0]), unicode(value[1])),
                        signature='ays')
                self.AvatarChanged()
            else:
                raise ValueError('Nonexistent property')
        else:
            raise ValueError('No such interface')

if __name__ == '__main__':
    DBusGMainLoop(set_as_default=True)

    try:
        am = AccountManager()
    except dbus.NameExistsException:
        print >> sys.stderr, 'AccountManager already running'
        sys.exit(1)

    print "AccountManager running..."
    mainloop = MainLoop()
    mainloop.run()
Пример #20
0
 def listen(self):
     from gobject import MainLoop
     loop = MainLoop()
     loop.run()
Пример #21
0
class HTTPServer(SoupServer):
    def __init__(self,
                 address='',
                 port=8080,
                 access_log=None,
                 pid_file=None,
                 profile=None):
        SoupServer.__init__(self, address=address, port=port)

        # Keep arguments
        self.address = address
        self.port = port
        self.access_log = access_log
        self.pid_file = pid_file
        self.profile = profile

        # Main Loop
        self.main_loop = MainLoop()

        # Open log files
        if access_log is not None:
            self.access_log_file = open(access_log, 'a+')

    #######################################################################
    # Logging
    #######################################################################
    def log_access(self, line):
        # Default: stdout
        if self.access_log is None:
            stdout.write(line)
            return

        # File
        log = self.access_log_file
        if fstat(log.fileno())[3] == 0:
            log = open(self.access_log, 'a+')
            self.access_log_file = log
        log.write(line)
        log.flush()

    #######################################################################
    # Start & Stop
    #######################################################################
    def start(self):
        # Language negotiation
        from itools.web import select_language
        init_language_selector(select_language)

        # Graceful stop
        signal(SIGINT, self.stop_gracefully)
        signal(SIGTERM, self.zap)
        if self.pid_file:
            pid = getpid()
            open(self.pid_file, 'w').write(str(pid))

        # Run
        SoupServer.start(self)
        print 'Listen %s:%d' % (self.address, self.port)
        if self.profile:
            runctx("self.main_loop.run()", globals(), locals(), self.profile)
        else:
            self.main_loop.run()

    def stop_gracefully(self, signum, frame):
        """Inmediately stop accepting new connections, and quit once there
        are not more ongoing requests.
        """
        # TODO Implement the graceful part

        # Quit
        print 'Shutting down the server (gracefully)...'
        self.stop()

    def zap(self, signum, frame):
        print 'Shutting down the server...'
        self.stop()

    def stop(self):
        SoupServer.stop(self)
        self.main_loop.quit()
        if self.pid_file:
            remove_file(self.pid_file)
        if self.access_log:
            self.access_log_file.close()

    #######################################################################
    # Callbacks
    #######################################################################
    known_methods = [
        'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'LOCK', 'UNLOCK'
    ]

    def star_callback(self, soup_message, path):
        """This method is called for the special "*" request URI, which means
        the request concerns the server itself, and not any particular
        resource.

        Currently this feature is only supported for the OPTIONS request
        method:

          OPTIONS * HTTP/1.1
        """
        method = soup_message.get_method()
        if method != 'OPTIONS':
            soup_message.set_status(405)
            soup_message.set_header('Allow', 'OPTIONS')
            return

        methods = self.known_methods
        soup_message.set_status(200)
        soup_message.set_header('Allow', ','.join(methods))

    def path_callback(self, soup_message, path):
        raise NotImplementedError
Пример #22
0
 def listen(self):
     from gobject import MainLoop
     loop = MainLoop()
     loop.run()
Пример #23
0
def dbus_loop(actor):
    threads_init()
    mainloop = MainLoop()
    actor.set_event_loop(mainloop)
    actor.start()
    mainloop.run()
Пример #24
0
class HTTPServer(SoupServer):

    def __init__(self, address='', port=8080, access_log=None, pid_file=None,
                 profile=None):
        SoupServer.__init__(self, address=address, port=port)

        # Keep arguments
        self.address = address
        self.port = port
        self.access_log = access_log
        self.pid_file = pid_file
        self.profile = profile

        # Main Loop
        self.main_loop = MainLoop()

        # Open log files
        if access_log is not None:
            self.access_log_file = open(access_log, 'a+')


    #######################################################################
    # Logging
    #######################################################################
    def log_access(self, line):
        # Default: stdout
        if self.access_log is None:
            stdout.write(line)
            return

        # File
        log = self.access_log_file
        if fstat(log.fileno())[3] == 0:
            log = open(self.access_log, 'a+')
            self.access_log_file = log
        log.write(line)
        log.flush()


    #######################################################################
    # Start & Stop
    #######################################################################
    def start(self):
        # Language negotiation
        from itools.web import select_language
        init_language_selector(select_language)

        # Graceful stop
        signal(SIGINT, self.stop_gracefully)
        signal(SIGTERM, self.zap)
        if self.pid_file:
            pid = getpid()
            open(self.pid_file, 'w').write(str(pid))

        # Run
        SoupServer.start(self)
        print 'Listen %s:%d' % (self.address, self.port)
        if self.profile:
            runctx("self.main_loop.run()", globals(), locals(), self.profile)
        else:
            self.main_loop.run()


    def stop_gracefully(self, signum, frame):
        """Inmediately stop accepting new connections, and quit once there
        are not more ongoing requests.
        """
        # TODO Implement the graceful part

        # Quit
        print 'Shutting down the server (gracefully)...'
        self.stop()


    def zap(self, signum, frame):
        print 'Shutting down the server...'
        self.stop()


    def stop(self):
        SoupServer.stop(self)
        self.main_loop.quit()
        if self.pid_file:
            remove_file(self.pid_file)
        if self.access_log:
            self.access_log_file.close()


    #######################################################################
    # Callbacks
    #######################################################################
    known_methods = [
        'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'LOCK', 'UNLOCK']


    def star_callback(self, soup_message, path):
        """This method is called for the special "*" request URI, which means
        the request concerns the server itself, and not any particular
        resource.

        Currently this feature is only supported for the OPTIONS request
        method:

          OPTIONS * HTTP/1.1
        """
        method = soup_message.get_method()
        if method != 'OPTIONS':
            soup_message.set_status(405)
            soup_message.set_header('Allow', 'OPTIONS')
            return

        methods = self.known_methods
        soup_message.set_status(200)
        soup_message.set_header('Allow', ','.join(methods))


    def path_callback(self, soup_message, path):
        raise NotImplementedError
Пример #25
0
class RTSPclient:
	"""
	GStreamer RTSP client.
	"""
	def __init__(self, conf, video):
		"""
		**On init:** Some initialization code.
		
		:param dictionary conf: Parsed configuration file.
		:param string video: Path to the selected video.
		"""
		#: Dictionary of configuration options (see :attr:`VideoTester.core.Client.conf`).
		self.conf = conf
		#: Path to the selected video (see :attr:`VideoTester.core.Client.video`).
		self.video = video
		#: Video size: ``(width, height)``.
		self.size = None
		#: Dictionary of paths to the processed video files: ``{'original':[<compressed>, <yuv>], 'coded':[<compressed>, <yuv>], 'received':[<compressed>, <yuv>]}``.
		self.files = {'original':[], 'coded':[], 'received':[]}
		#: Gstreamer pipeline.
		self.pipeline = None
		#: Gstreamer loop.
		self.loop = None
		#: Selected video URL.
		self.url = 'rtsp://' + self.conf['ip'] + ':' + self.conf['rtspport'] + '/' + self.conf['video'] + '.' + self.conf['codec']
		self.encoder, self.depay, self.bitrate, self.__add = {
			'h263': ("ffenc_h263", "rtph263depay", self.conf['bitrate'] + '000', ''),
			'h264': ("x264enc", "rtph264depay", self.conf['bitrate'], ''),
			'mpeg4': ("ffenc_mpeg4", "rtpmp4vdepay", self.conf['bitrate'] + '000', ''),
			'theora': ("theoraenc", "rtptheoradepay ! theoraparse", self.conf['bitrate'], ' ! matroskamux')
		}[self.conf['codec']]
	
	def __events(self, bus, msg):
		"""
		Event handler.
		
		:param bus: Gstreamer bus object.
		:param msg: Gstreamer message object.
		
		:returns: True.
		:rtype: boolean
		"""
		t = msg.type
		if t == MESSAGE_EOS:
			self.pipeline.set_state(STATE_PAUSED)
			sleep(0.5)
			self.pipeline.set_state(STATE_READY)
			self.pipeline.set_state(STATE_NULL)
			VTLOG.debug("GStreamer: MESSAGE_EOS received")
			self.loop.quit()
		elif t == MESSAGE_ERROR:
			self.pipeline.set_state(STATE_PAUSED)
			sleep(0.5)
			self.pipeline.set_state(STATE_READY)
			self.pipeline.set_state(STATE_NULL)
			e, d = msg.parse_error()
			VTLOG.error("GStreamer: MESSAGE_ERROR received")
			VTLOG.error(e)
			self.loop.quit()
		return True
	
	def __play(self):
		"""
		Attach event handler, set state to *playing* and run the loop (see :attr:`loop`).
		"""
		self.pipeline.get_bus().add_watch(self.__events)
		self.pipeline.set_state(STATE_PLAYING)
		self.loop = MainLoop()
		self.loop.run()
		VTLOG.debug("GStreamer: Loop stopped")
	
	def receiver(self):
		"""
		Connect to the RTSP server and receive the selected video (see :attr:`video`).
		"""
		VTLOG.info("Starting GStreamer receiver...")
		self.pipeline = parse_launch('rtspsrc name=source ! tee name=t ! queue ! ' + self.depay + self.__add + ' ! filesink name=sink1 t. ! queue \
				! decodebin ! videorate skip-to-first=True ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1 ! filesink name=sink2')
		source = self.pipeline.get_by_name('source')
		sink1 = self.pipeline.get_by_name('sink1')
		sink2 = self.pipeline.get_by_name('sink2')
		source.props.location = self.url
		source.props.protocols = self.conf['protocols']
		location = self.conf['tempdir'] + self.conf['num'] + '.' + self.conf['codec']
		self.files['received'].append(location)
		sink1.props.location = location
		location = self.conf['tempdir'] + self.conf['num'] + '.yuv'
		self.files['received'].append(location)
		sink2.props.location = location
		pad = sink2.get_pad("sink")
		pad.connect("notify::caps", self.__notifyCaps)
		self.__play()
		VTLOG.info("GStreamer receiver stopped")
	
	def reference(self):
		"""
		Make the reference videos.
		
		:returns: Paths to video files (see :attr:`files`) and video size (see :attr:`size`).
		:rtype: tuple
		"""
		VTLOG.info("Making reference...")
		self.pipeline = parse_launch('filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1  ! filesink name=sink1')
		source = self.pipeline.get_by_name('source')
		sink1 = self.pipeline.get_by_name('sink1')
		location = self.video
		self.files['original'].append(location)
		source.props.location = location
		location = self.conf['tempdir'] + self.conf['num'] + '_ref_original.yuv'
		self.files['original'].append(location)
		sink1.props.location = location
		self.__play()
		self.pipeline = parse_launch('filesrc name=source ! decodebin ! videorate ! video/x-raw-yuv,framerate=' + self.conf['framerate'] + '/1  ! ' + self.encoder + ' bitrate=' + self.bitrate \
				+ ' ! tee name=t ! queue' + self.__add + ' ! filesink name=sink2 t. ! queue ! decodebin ! filesink name=sink3')
		source = self.pipeline.get_by_name('source')
		sink2 = self.pipeline.get_by_name('sink2')
		sink3 = self.pipeline.get_by_name('sink3')
		location = self.video
		source.props.location = location
		location = self.conf['tempdir'] + self.conf['num'] + '_ref.' + self.conf['codec']
		self.files['coded'].append(location)
		sink2.props.location = location
		location = self.conf['tempdir'] + self.conf['num'] + '_ref.yuv'
		self.files['coded'].append(location)
		sink3.props.location = location
		self.__play()
		VTLOG.info("Reference made")
		return self.files, self.size
	
	def __notifyCaps(self, pad, args):
		"""
		Write caps to a file.
		
		:param pad: Gstreamer pad object.
		:param args: Other arguments.
		"""
		caps = pad.get_negotiated_caps()
		if caps:
			caps = caps.to_string()
			aux = caps.split(', ')
			for x in aux:
				if x.find('width') != -1:
					width = int(x[11:len(x)])
				elif x.find('height') != -1:
					height = int(x[12:len(x)])
			self.size = (width, height)
			f = open(self.conf['tempdir'] + self.conf['num'] + '_caps.txt', "wb")
			f.write(caps)
			f.close()
Пример #26
0
class RTSPserver:
	"""
	GStreamer RTSP server.
	"""
	def __init__(self, port, bitrate, framerate, path, videos):
		"""
		**On init:** Some initialization code.
		
		:param port: RTSP server port.
		:type port: string or integer
		:param bitrate: The bitrate (in kbps).
		:type bitrate: string or integer
		:param framerate: The framerate (in fps).
		:type framerate: string or integer
		:param string path: Path to the video directory.
		:param list videos: List of available videos.
		"""
		#: The bitrate (in kbps).
		self.bitrate = bitrate
		#: The framerate (in fps).
		self.framerate = framerate
		#: Path to the video directory.
		self.path = path
		#: List of available videos.
		self.videos = videos
		#: GStreamer RTSP server instance.
		self.server = Server()
		#: Gstreamer loop.
		self.loop = None
		self.server.set_service(str(port))
		#: List of GStreamer RTSP factories.
		self.factory = []
		self.__addMedia()
	
	def __addMedia(self):
		"""
		Add media to server.
		"""
		for i, video in enumerate(self.videos):
			for j in range(0, 4):
				launch = "filesrc location="+self.path+"/"+video+" ! decodebin ! videorate ! video/x-raw-yuv,framerate="+str(self.framerate)+"/1 ! "
				launch += {
					0: "ffenc_h263 bitrate="+str(self.bitrate)+"000 ! rtph263pay name=pay0",
					1: "x264enc bitrate="+str(self.bitrate)+" ! rtph264pay name=pay0",
					2: "ffenc_mpeg4 bitrate="+str(self.bitrate)+"000 ! rtpmp4vpay name=pay0",
					3: "theoraenc bitrate="+str(self.bitrate)+" ! rtptheorapay name=pay0"
				}[j]
				mmap = self.server.get_media_mapping()
				self.factory.append(MediaFactory())
				self.factory[-1].set_launch(launch)
				self.factory[-1].set_shared(True)
				self.factory[-1].set_eos_shutdown(True)
				name = {
					0: "/video"+str(i)+".h263",
					1: "/video"+str(i)+".h264",
					2: "/video"+str(i)+".mpeg4",
					3: "/video"+str(i)+".theora"
				}[j]
				mmap.add_factory(name, self.factory[-1])
				self.server.set_media_mapping(mmap)
	
	def run(self):
		"""
		Attach server and run the loop (see :attr:`loop`).
		"""
		if self.server.attach():
			self.loop = MainLoop()
			self.loop.run()