Beispiel #1
0
    def __init__(self, caps=None, uri=None, *args, **kwargs):
        gst.Bin.__init__(self, *args, **kwargs)
        if not caps:
            caps = gst.caps_new_any()
        self.caps = caps
        self.typefind = gst.element_factory_make("typefind", "internal-typefind")
        self.add(self.typefind)

        self.uri = uri
        if self.uri and gst.uri_is_valid(self.uri):
            self.urisrc = gst.element_make_from_uri(gst.URI_SRC, uri, "urisrc")
            self.log("created urisrc %s / %r" % (self.urisrc.get_name(),
                                                 self.urisrc))
            self.add(self.urisrc)
            self.urisrc.link(self.typefind)
        else:
            self._sinkpad = gst.GhostPad("sink", self.typefind.get_pad("sink"))
            self._sinkpad.set_active(True)
            self.add_pad(self._sinkpad)

        self.typefind.connect("have_type", self._typefindHaveTypeCb)

        self._srcpad = None

        self._dynamics = []

        self._validelements = [] #added elements

        self._factories = self._getSortedFactoryList()
Beispiel #2
0
def main(args):
    if len(args) != 2:
        sys.stderr.write("usage: %s <media file or uri>\n" % args[0])
        sys.exit(1)
        
    playbin = gst.element_factory_make("playbin2", None)
    if not playbin:
        sys.stderr.write("'playbin2' gstreamer plugin missing\n")
        sys.exit(1)

    # take the commandline argument and ensure that it is a uri
    if gst.uri_is_valid(args[1]):
      uri = args[1]
    else:
      uri = gst.filename_to_uri(args[1])
    playbin.set_property('uri', uri)

    # create and event loop and feed gstreamer bus mesages to it
    loop = gobject.MainLoop()

    bus = playbin.get_bus()
    bus.add_watch(bus_call, loop)
    
    # start play back and listed to events
    playbin.set_state(gst.STATE_PLAYING)
    loop.run()
    
    # cleanup
    playbin.set_state(gst.STATE_NULL)
Beispiel #3
0
 def choose_next(self):
     """
     Skips the player to the next clip. 
     Schedules to be called again later.
     """
     self.load_clip_list()
     prev = -1
     if self.previous_clip_path in self.clips:
         prev = self.clips.index(self.previous_clip_path)
     if self.verbose:
         print("prev: %s" % (prev))
     next = prev + 1
     if len(self.clips) == 0:
         print("Error: Not clip to play.")
     elif len(self.clips) == 1:
         print("Warning: Only one clip to play.")
     else:
         if len(self.clips) == next:
             next = 0
         file_path = self.clips[next]
         self.previous_clip_path = file_path
         print "Playing next: (%s/%s) %s" % (next, len(self.clips), file_path)
         uri = "file://%s" % (file_path)
         if not gst.uri_is_valid(uri):
             msg = "Error: Invalid URI: %s\n" % (uri)
             raise RuntimeError(msg)
         else:
             self.player.set_location(uri)
             self.num_played_current_location = 1
             self.current_location = uri
Beispiel #4
0
 def check_uri(self):
     uri=self.player.get_property('uri')
     if uri and gst.uri_is_valid(uri):
         return True
     else:
         print "Invalid URI", str(uri)
         return False
Beispiel #5
0
def get_uri(source):
    """
    Check a media source as a valid file or uri and return the proper uri
    """

    import gst
    # Is this an valid URI source
    if gst.uri_is_valid(source):
        uri_protocol = gst.uri_get_protocol(source)
        if gst.uri_protocol_is_supported(gst.URI_SRC, uri_protocol):
            return source
        else:
            raise IOError('Invalid URI source for Gstreamer')

    # is this a file?
    import os.path
    if os.path.exists(source):
        # get the absolute path
        pathname = os.path.abspath(source)
        # and make a uri of it
        uri = path2uri(pathname)

        return get_uri(uri)
    else:
        raise IOError('Failed getting uri for path %s: not such file or directoy' % source)

    return uri
Beispiel #6
0
def main(args):
    if len(args) != 2:
        sys.stderr.write("usage: %s <media file or uri>\n" % args[0])
        sys.exit(1)

    playbin = gst.element_factory_make("playbin2", None)
    if not playbin:
        sys.stderr.write("'playbin2' gstreamer plugin missing\n")
        sys.exit(1)

    # take the commandline argument and ensure that it is a uri
    if gst.uri_is_valid(args[1]):
        uri = args[1]
    else:
        uri = gst.filename_to_uri(args[1])
    playbin.set_property('uri', uri)

    # create and event loop and feed gstreamer bus mesages to it
    loop = gobject.MainLoop()

    bus = playbin.get_bus()
    bus.add_watch(bus_call, loop)

    # start play back and listed to events
    playbin.set_state(gst.STATE_PLAYING)
    loop.run()

    # cleanup
    playbin.set_state(gst.STATE_NULL)
Beispiel #7
0
    def __init__(self, caps=None, uri=None, stream=None, *args, **kwargs):
        gst.Bin.__init__(self, *args, **kwargs)

        if not caps:
            caps = gst.caps_new_any()
        self.caps = caps
        self.stream = stream
        self.typefind = gst.element_factory_make("typefind",
            "internal-typefind")
        self.add(self.typefind)

        self.uri = uri
        if self.uri and gst.uri_is_valid(self.uri):
            self.urisrc = gst.element_make_from_uri(gst.URI_SRC, uri, "urisrc")
            self.log("created urisrc %s / %r" % (self.urisrc.get_name(),
                                                 self.urisrc))
            self.add(self.urisrc)
            self.urisrc.link(self.typefind)
        else:
            self._sinkpad = gst.GhostPad("sink", self.typefind.get_pad("sink"))
            self._sinkpad.set_active(True)
            self.add_pad(self._sinkpad)

        self.typefind.connect("have_type", self._typefindHaveTypeCb)

        self._srcpad = None

        self._dynamics = []

        self._validelements = [] #added elements

        self._factories = self._getSortedFactoryList()
 def load(self, uri):
     print "JAMediaGrabador:", uri
     if gst.uri_is_valid(uri):
         self.archivo.set_property("location", self.patharchivo)
         self.uri = uri
         self.player.set_property("uri", self.uri)
     else:
         print "JAMediaGrabador: uri inválida:", uri
         self.emit("endfile")
     return False
Beispiel #9
0
def uri_is_valid(uri):
    """Checks if the given uri is a valid uri (of type file://)

    Will also check if the size is valid (> 0).

    @param uri: The location to check
    @type uri: C{URI}
    """
    return (gst.uri_is_valid(uri) and gst.uri_get_protocol(uri) == "file"
            and len(os.path.basename(gst.uri_get_location(uri))) > 0)
 def load(self, uri):
     print "JAMediaGrabador:", uri
     if gst.uri_is_valid(uri):
         self.archivo.set_property("location", self.patharchivo)
         self.uri = uri
         self.player.set_property("uri", self.uri)
     else:
         print "JAMediaGrabador: uri inválida:", uri
         self.emit("endfile")
     return False
Beispiel #11
0
 def load(self, uri):
     if not uri:
         return False
     if os.path.exists(uri):
         #direccion = gst.filename_to_uri(uri)
         direccion = "file://" + uri
         self.player.set_property("uri", direccion)
     else:
         if gst.uri_is_valid(uri):
             self.player.set_property("uri", uri)
     return False
Beispiel #12
0
def uri_is_valid(uri):
    """Checks if the given uri is a valid uri (of type file://)

    Will also check if the size is valid (> 0).

    @param uri: The location to check
    @type uri: C{URI}
    """
    return (gst.uri_is_valid(uri) and
            gst.uri_get_protocol(uri) == "file" and
            len(os.path.basename(gst.uri_get_location(uri))) > 0)
    def __load(self, uri):

        if os.path.exists(uri):
            direccion = "file://" + uri
            self.player.set_property("uri", direccion)
            self.__play()

        else:
            # FIXME: Funciona con la radio pero no con la Tv
            if gst.uri_is_valid(uri):
                self.player.set_property("uri", uri)
                self.__play()
Beispiel #14
0
 def play(self, uri=None, seek=None):
     if uri:
         if not gst.uri_is_valid(uri):
             uri = 'file://' + uri
         logger.debug(uri)
         self.player.set_state(gst.STATE_NULL)
         self.player.set_property('uri', uri)
         self.player.set_state(gst.STATE_PLAYING)
     if seek is not None:
         # 由于 gstreamer 的 seek , query_position 和 query_duration
         # 都是异步的,是通过消息来通信的,刚刚设置好就操作,
         # 很可能会失败,所以休息 0.1 秒
         time.sleep(0.1)
         self.seek(seek)
     if gst.STATE_PAUSED == self.player.get_state()[1]:
         self.player.set_state(gst.STATE_PLAYING)
Beispiel #15
0
 def play(self, uri=None, seek=None):
     if uri:
         if not gst.uri_is_valid(uri):
             uri = 'file://' + uri
         logger.debug(uri)
         self.player.set_state(gst.STATE_NULL)
         self.player.set_property('uri', uri)
         self.player.set_state(gst.STATE_PLAYING)
     if seek is not None:
         # 由于 gstreamer 的 seek , query_position 和 query_duration 
         # 都是异步的,是通过消息来通信的,刚刚设置好就操作,
         # 很可能会失败,所以休息 0.1 秒
         time.sleep(0.1)
         self.seek(seek)
     if gst.STATE_PAUSED == self.player.get_state()[1]:
         self.player.set_state(gst.STATE_PLAYING)
Beispiel #16
0
def main(args):

    # Need to register our derived widget types for implicit event
    # handlers to get called.
    gobject.type_register(ScannerUI)
    gobject.type_register(VideoWidget)

    s = Scanner()

    if len(args) == 2:
        if gst.uri_is_valid(args[1]):
            s.set_uri(args[1])
        else:
            sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
            sys.exit(1)

    gtk.main()
Beispiel #17
0
def main(args):

    # Need to register our derived widget types for implicit event
    # handlers to get called.
    gobject.type_register(ScannerUI)
    gobject.type_register(VideoWidget)

    s = Scanner();

    if len(args) == 2:
        if gst.uri_is_valid(args[1]):
            s.set_uri(args[1])
        else:
            sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
            sys.exit(1)

    gtk.main()
 def load(self, uri):
     if not uri:
         return False
     self.duracion = 0.0
     self.posicion = 0.0
     self.emit("newposicion", self.posicion)
     self.emit("loading-buffer", 100)
     if os.path.exists(uri):
         #direccion = gst.filename_to_uri(uri)
         direccion = "file://" + uri
         self.player.set_property("uri", direccion)
         self.progressbar = True
     else:
         if gst.uri_is_valid(uri):
             self.player.set_property("uri", uri)
             self.progressbar = False
     return False
    def load(self, uri):
        if not uri:
            return

        if os.path.exists(uri):
            #direccion = gst.filename_to_uri(uri)
            direccion = "file://" + uri
            self.player.set_property("uri", direccion)
            self.progressbar = True
            self.__play()

        else:
            if gst.uri_is_valid(uri):
                self.player.set_property("uri", uri)
                self.progressbar = False
                self.__play()

        return False
Beispiel #20
0
def main(args):

    # Need to register our derived widget types for implicit event
    # handlers to get called.
    gobject.type_register(PlayerWindow)
    gobject.type_register(VideoWidget)

    w = PlayerWindow()

    if len(args) == 2:
        if not gst.uri_is_valid(args[1]):
            sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
            sys.exit(1)
        w.load_file(args[1])

    w.show_all()

    gtk.main()
Beispiel #21
0
    def load(self, uri):
        """
        Carga un archivo o stream en el pipe de gst.
        """

        if os.path.exists(uri):
            #direccion = gst.filename_to_uri(uri)
            direccion = "file://" + uri
            self.player.set_property("uri", direccion)
            self.progressbar = True
            self.__play()

        else:
            if gst.uri_is_valid(uri):
                self.player.set_property("uri", uri)
                self.progressbar = False
                self.__play()

        return False
Beispiel #22
0
    def __init__(self, path, filter_caps, *args, **kwargs):
        gst.Bin.__init__(self, *args, **kwargs)
        uri = 'file://%s' % path
        if uri and gst.uri_is_valid(uri):


            urisrc = gst.element_make_from_uri(gst.URI_SRC, uri, "urisrc")
            self.add(urisrc)

            jpegdec = gst.element_factory_make('jpegdec','pic-jpegdec')
            self.add(jpegdec)

            queue = gst.element_factory_make('queue', "pic-queue")
            self.add(queue)

            csp = gst.element_factory_make('ffmpegcolorspace', 'pic-colorspace')
            self.add(csp)

            videoscale = gst.element_factory_make('videoscale', 'pic-scale')
            videoscale.set_property("add-borders", False)
            self.add(videoscale)

            freeze = gst.element_factory_make('imagefreeze', 'pic-freeze')
            self.add(freeze)

            capsfilter = gst.element_factory_make("capsfilter", "pic-capsfilter")
            caps = gst.Caps(filter_caps)
            capsfilter.set_property("caps", caps)
            self.add(capsfilter)

            # link elements
            gst.element_link_many(
                    urisrc,
                    jpegdec,
                    videoscale,
                    queue,
                    csp,
                    capsfilter,
                    freeze
                    )

            self.add_pad(gst.GhostPad('src', freeze.get_pad('src')))
Beispiel #23
0
def main(args):
    def usage():
        sys.stderr.write("usage: %s [URI-OF-MEDIA-FILE]\n" % args[0])
        return 1

    w = PlayerWindow()
    w.show()

    if len(args) == 1:
        if not w.do_choose_file():
            return 1
    elif len(args) == 2:
        if not gst.uri_is_valid(args[1]):
            sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
            return 1
        w.load_file(args[1])
    else:
        return usage()

    gtk.main()
Beispiel #24
0
def get_uri(source):
    """
    Check a media source as a valid file or uri and return the proper uri
    """

    import gst

    src_info = source_info(source)

    if src_info['is_file']:  # Is this a file?
        return get_uri(src_info['uri'])

    elif gst.uri_is_valid(source):  # Is this a valid URI source for Gstreamer
        uri_protocol = gst.uri_get_protocol(source)
        if gst.uri_protocol_is_supported(gst.URI_SRC, uri_protocol):
            return source
        else:
            raise IOError('Invalid URI source for Gstreamer')
    else:
        raise IOError('Failed getting uri for path %s: no such file' % source)
Beispiel #25
0
def get_uri(source):
    """
    Check a media source as a valid file or uri and return the proper uri
    """

    import gst

    src_info = source_info(source)

    if src_info['is_file']:  # Is this a file?
        return get_uri(src_info['uri'])

    elif gst.uri_is_valid(source):  # Is this a valid URI source for Gstreamer
        uri_protocol = gst.uri_get_protocol(source)
        if gst.uri_protocol_is_supported(gst.URI_SRC, uri_protocol):
            return source
        else:
            raise IOError('Invalid URI source for Gstreamer')
    else:
        raise IOError('Failed getting uri for path %s: no such file' % source)
Beispiel #26
0
def main(args):
    def usage():
        sys.stderr.write("usage: %s [URI-OF-MEDIA-FILE]\n" % args[0])
        return 1

    w = PlayerWindow()
    w.show()

    if len(args) == 1:
        if not w.do_choose_file():
            return 1
    elif len(args) == 2:
        if not gst.uri_is_valid(args[1]):
            sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
            return 1
        w.load_file(args[1])
    else:
        return usage()

    gtk.main()
 def load(self, uri):
     if not uri:
         return False
     self.duracion = 0.0
     self.posicion = 0.0
     self.emit("newposicion", self.posicion)
     self.emit("loading-buffer", 100)
     if os.path.exists(uri):
         direccion = "file://" + uri
         self.player.set_property("uri", direccion)
         # FIXME: Quitado por consideraciones de rendimiento en la XO
         #suburi = os.path.join(os.path.dirname(uri), "subtitulos.srt")
         #if os.path.exists(suburi):
         #    self.player.set_property("suburi", "file://" + suburi)
         #    self.player.set_property("subtitle-font-desc", "sans bold 18")
         self.progressbar = True
     else:
         if gst.uri_is_valid(uri):
             self.player.set_property("uri", uri)
             self.progressbar = False
     return False
Beispiel #28
0
    def createPipeline(self):
        # uri source
        uri = self.arguments["uri"]
        if not gst.uri_is_valid(uri):
            self.validateStep("is-valid-uri-format", False)
            return None

        self.validateStep("is-valid-uri-format")
        src = gst.element_make_from_uri(gst.URI_SRC, uri, "uri-src")

        typefind = gst.element_factory_make("typefind")
        fakesink = gst.element_factory_make("fakesink")

        p = gst.Pipeline()
        p.add(src, typefind, fakesink)
        gst.element_link_many(src,typefind,fakesink)
        # connect signals

        typefind.connect("have-type", self._typefindHaveTypeCb)

        return p
Beispiel #29
0
    def live_pipeline(self, w=None):

        if self.player:
            self.player.set_state(gst.STATE_NULL)

        uri = self.uri.get_text()

        if uri != None :

            if gst.uri_is_valid (uri) is False:
                self.status.set_label("Invalid URI. Please verify.")
                gst.debug("Invalid URI")
                return
            if gst.uri_protocol_is_supported(gst.URI_SRC,
                                             uri.split('://')[0]):
                self.setSinks(uri)
                self.player.set_state(gst.STATE_PLAYING)
                self.status.push(self.status_id, "")
            else:
                self.status.set_label("Unsupported Protocol. Please verify the URI.")
                gst.debug("Unsupported Protocol")
Beispiel #30
0
 def load(self, uri):
     if not uri:
         return False
     self.duracion = 0.0
     self.posicion = 0.0
     self.emit("newposicion", self.posicion)
     self.emit("loading-buffer", 100)
     if os.path.exists(uri):
         direccion = "file://" + uri
         self.player.set_property("uri", direccion)
         # FIXME: Quitado por consideraciones de rendimiento en la XO
         #suburi = os.path.join(os.path.dirname(uri), "subtitulos.srt")
         #if os.path.exists(suburi):
         #    self.player.set_property("suburi", "file://" + suburi)
         #    self.player.set_property("subtitle-font-desc", "sans bold 18")
         self.progressbar = True
     else:
         if gst.uri_is_valid(uri):
             self.player.set_property("uri", uri)
             self.progressbar = False
     return False
    def live_pipeline(self, w=None):

        if self.player:
            self.player.set_state(gst.STATE_NULL)

        uri = self.uri.get_text()

        if uri != None :

            if gst.uri_is_valid (uri) is False:
                self.status.set_label("Invalid URI. Please verify.")
                gst.debug("Invalid URI")
                return
            if gst.uri_protocol_is_supported(gst.URI_SRC,
                                             uri.split('://')[0]):
                self.setSinks(uri)
                self.player.set_state(gst.STATE_PLAYING)
                self.status.push(self.status_id, "")
            else:
                self.status.set_label("Unsupported Protocol. Please verify the URI.")
                gst.debug("Unsupported Protocol")
    def __init__(self, uri, archivo):

        gobject.GObject.__init__(self)

        self.patharchivo = archivo
        self.actualizador = False
        self.info = ""
        self.uri = uri

        self.player = None
        self.archivo = None
        self.bus = None

        self.__reset()

        # FIXME: Funciona con la radio pero no con la Tv
        if gst.uri_is_valid(uri):
            self.archivo.set_property("location", archivo)
            self.player.set_property("uri", uri)
            self.__play()
            self.__new_handle(True)
Beispiel #33
0
    def __init__(self, caps=None, uri=None, stream=None, *args, **kwargs):
        gst.Bin.__init__(self, *args, **kwargs)
        if not caps:
            caps = gst.caps_new_any()
        self.caps = caps
        self.stream = stream
        self.typefind = gst.element_factory_make("typefind",
                                                 "internal-typefind")
        self.add(self.typefind)

        self.uri = uri
        if self.uri and gst.uri_is_valid(self.uri):
            self.urisrc = gst.element_make_from_uri(gst.URI_SRC, uri, "urisrc")
            self.log("created urisrc %s / %r" %
                     (self.urisrc.get_name(), self.urisrc))
            self.add(self.urisrc)
            # Set the blocksize to 512kbytes, this will only matter for push-based sources
            if hasattr(self.urisrc.props, "blocksize"):
                self.urisrc.props.blocksize = 524288
            self.urisrc.link_pads_full("src", self.typefind, "sink",
                                       gst.PAD_LINK_CHECK_NOTHING)
        else:
            self._sinkpad = gst.GhostPad("sink", self.typefind.get_pad("sink"))
            self._sinkpad.set_active(True)
            self.add_pad(self._sinkpad)

        self.typefind.connect("have_type", self._typefindHaveTypeCb)

        self._srcpad = None

        self._dynamics = []

        self._validelements = []  # added elements

        self.debug("stream:%r" % self.stream)

        self.pending_newsegment = None
        self.eventProbeId = None
Beispiel #34
0
def main(args):
    def usage():
        sys.stderr.write("usage: %s URI-OF-MEDIA-FILE\n" % args[0])
        sys.exit(1)

    # Need to register our derived widget types for implicit event
    # handlers to get called.
    gobject.type_register(PlayerWindow)
    gobject.type_register(VideoWidget)

    w = PlayerWindow()

    if len(args) != 2:
        usage()

    if not gst.uri_is_valid(args[1]):
        sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
        sys.exit(1)

    w.load_file(args[1])
    w.show_all()

    gtk.main()
    def __init__(self, caps=None, uri=None, stream=None, *args, **kwargs):
        gst.Bin.__init__(self, *args, **kwargs)
        if not caps:
            caps = gst.caps_new_any()
        self.caps = caps
        self.stream = stream
        self.typefind = gst.element_factory_make("typefind", "internal-typefind")
        self.add(self.typefind)

        self.uri = uri
        if self.uri and gst.uri_is_valid(self.uri):
            self.urisrc = gst.element_make_from_uri(gst.URI_SRC, uri, "urisrc")
            self.log("created urisrc %s / %r" % (self.urisrc.get_name(),
                                                 self.urisrc))
            self.add(self.urisrc)
            # Set the blocksize to 512kbytes, this will only matter for push-based sources
            if hasattr(self.urisrc.props, "blocksize"):
                self.urisrc.props.blocksize = 524288
            self.urisrc.link_pads_full("src", self.typefind, "sink",
                                       gst.PAD_LINK_CHECK_NOTHING)
        else:
            self._sinkpad = gst.GhostPad("sink", self.typefind.get_pad("sink"))
            self._sinkpad.set_active(True)
            self.add_pad(self._sinkpad)

        self.typefind.connect("have_type", self._typefindHaveTypeCb)

        self._srcpad = None

        self._dynamics = []

        self._validelements = [] #added elements

        self.debug("stream:%r" % self.stream)

        self.pending_newsegment = None
        self.eventProbeId = None
Beispiel #36
0
    def __init__(self, location, matrix, visualize=None, mainloop=None):
        # The pipeline

        self.visualize = visualize
        self.seek_to = None
        self.start_pipeline = False

        self.pipeline = gst.Pipeline()
        self.pipeline.auto_clock()

        # Create bus and connect several handlers
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect('message::eos', self.on_eos)
        self.bus.connect('message::tag', self.on_tag)
        self.bus.connect('message::error', self.on_error)

        # Create elements
        self.src = gst.element_factory_make('filesrc')
        self.player = player = gst.element_factory_make('playbin2')
        self.player.set_property("volume", 2)
        self.player.set_property(
            "flags",
            0x00000001 | 0x00000002 | 0x00000008 | 0x00000010 | 0x00000200)

        self.sink = gst.Bin()  #gst.element_factory_make('alsasink')
        self.led = LedVideoSink(matrix)  #gst.element_factory_make('alsasink')
        self.color = gst.element_factory_make('ffmpegcolorspace')
        self.rate = gst.element_factory_make('videorate')
        self.scale = gst.element_factory_make('ffvideoscale')
        self.scale.set_property("method", 5)

        self.sink.add(self.color, self.rate, self.scale, self.led)
        ghostpad = gst.GhostPad("sink", self.color.get_pad("sink"))
        self.sink.add_pad(ghostpad)
        gst.element_link_many(self.color, self.rate, self.scale, self.led)
        if self.visualize:
            self.vis = gst.element_factory_make(self.visualize)
            player.set_property("vis-plugin", self.vis)

        player.set_property("video-sink", self.sink)
        player.connect("about-to-finish", self.on_finish)
        #player.connect("state-change", self.on_state_change)

        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.enable_sync_message_emission()
        #bus.connect("message", self.on_message)
        bus.connect("sync-message::element", self.on_sync_message)
        bus.connect("message", self.on_message)

        # Set 'location' property on filesrc
        player.set_property(
            'uri',
            gst.uri_is_valid(location) and location or "file://" + location)

        # Connect handler for 'new-decoded-pad' signal
        #self.dec.connect('new-decoded-pad', self.on_new_decoded_pad)

        # Add elements to pipeline
        self.pipeline.add(player)

        # The MainLoop
        self.mainloop = mainloop or gobject.MainLoop()

        # And off we go!
        self.pipeline.set_state(gst.STATE_PLAYING)
Beispiel #37
0
def parse_urilist(data):
    for line in data.readlines():
        if not line.startswith('#') and gst.uri_is_valid(line.strip()):
            yield line
Beispiel #38
0
def parse_urilist(data):
    for line in data.readlines():
        if not line.startswith('#') and gst.uri_is_valid(line.strip()):
            yield line
Beispiel #39
0
def main(args):
    global w
    global imgdir
    global spotter
    global httpd
    global httpdt

    def usage():
        sys.stderr.write("usage: %s videofile imgdir [algorithm=surf] [minscore=30]\n" % args[0])
        sys.exit(1)

    # Need to register our derived widget types for implicit event
    # handlers to get called.
    gobject.type_register(PlayerWindow)
    gobject.type_register(VideoWidget)

    if len(args) < 3:
        usage()

    imgdir = args[2]

    if len(args) >= 4 : 
       algorithm=args[3]
    else :
       algorithm = 'surf'

    if len(args) == 5 :
       minscore=args[4]
    else :
       minscore = "30"

    uri = "file://"+os.getcwd()+"/"+args[1]

    if not gst.uri_is_valid(uri):
        sys.stderr.write("Error: Invalid URI: %s\n" % uri)
        sys.exit(1)

    w = PlayerWindow()

    w.load_file(uri)

    bin = gst.Bin("my-bin")
    ffmpegcolorspace = gst.element_factory_make("ffmpegcolorspace")
    bin.add(ffmpegcolorspace)
    pad = ffmpegcolorspace.get_pad("sink")
    ghostpad = gst.GhostPad("sink", pad)
    bin.add_pad(ghostpad)
    spotter = gst.element_factory_make("imgspot")
    spotter.set_property("width", 320 );
    spotter.set_property("height", 240 );
    spotter.set_property("output", "bus" );
    spotter.set_property("algorithm", algorithm );
    spotter.set_property("imgdir", imgdir );
    spotter.set_property("minscore", int(minscore) );
    bin.add(spotter)
    ffmpegcolorspace2 = gst.element_factory_make("ffmpegcolorspace")
    bin.add(ffmpegcolorspace2)
    videosink = gst.element_factory_make("autovideosink")
    bin.add(videosink)
    gst.element_link_many(ffmpegcolorspace, spotter, ffmpegcolorspace2, videosink)
    w.player.set_property("video-sink", bin)

    w.show_all()

    # start http command handler
    httpd = HTTPServer((HOST, PORT), jsCommandsHandler)

    httpdt = HTTPServerThread()
    httpdt.setDaemon(True)
    httpdt.start()

    gtk.main()
Beispiel #40
0
            tags.update(utils.convert_taglist(taglist))

        timeout -= clock.get_time() - start

    raise exceptions.ScannerError('Timeout after %dms' % timeout_ms)


if __name__ == '__main__':
    import os
    import sys

    import gobject

    from mopidy.internal import path

    gobject.threads_init()

    scanner = Scanner(5000)
    for uri in sys.argv[1:]:
        if not gst.uri_is_valid(uri):
            uri = path.path_to_uri(os.path.abspath(uri))
        try:
            result = scanner.scan(uri)
            for key in ('uri', 'mime', 'duration', 'playable', 'seekable'):
                print('%-20s   %s' % (key, getattr(result, key)))
            print('tags')
            for tag, value in result.tags.items():
                print('%-20s   %s' % (tag, value))
        except exceptions.ScannerError as error:
            print('%s: %s' % (uri, error))
Beispiel #41
0
            tags.update(utils.convert_taglist(taglist))

        timeout -= clock.get_time() - start

    raise exceptions.ScannerError("Timeout after %dms" % timeout_ms)


if __name__ == "__main__":
    import os
    import sys

    import gobject

    from mopidy.utils import path

    gobject.threads_init()

    scanner = Scanner(5000)
    for uri in sys.argv[1:]:
        if not gst.uri_is_valid(uri):
            uri = path.path_to_uri(os.path.abspath(uri))
        try:
            result = scanner.scan(uri)
            for key in ("uri", "mime", "duration", "playable", "seekable"):
                print("%-20s   %s" % (key, getattr(result, key)))
            print("tags")
            for tag, value in result.tags.items():
                print("%-20s   %s" % (tag, value))
        except exceptions.ScannerError as error:
            print("%s: %s" % (uri, error))
Beispiel #42
0
    def queue_add(self, location):
        """
        Adds location to the play queue.

        NOTES:
          - location must be a valid URI
          - If self.verify_on_load==True, then location
          can be a directory. All .mp3 files from the
          directory will be loaded.

        Return values:
          - If successful: [200]
          - else: [err_code,[err_msg]].
        """
        ans = [200]
        is_dir = False
        is_ascii = True
        # ignore non-ascii stuff
        try:
            unicode(location)
        except UnicodeDecodeError as e:
            is_ascii = False
            gst.warning('Ignoring %s, not ascii' % location)
            ans = [406]
            ans.append(e.__str__())
        if not is_ascii or not gst.uri_is_valid(location):
            if is_ascii:
                gst.error("Error: Invalid URI: %s\nExpected uri"
                      "like file:///home/foo/bar.mp3\nIgnoring...\n" % location)
                ans = [403]
        else:
            # if(self.player.status()):
            #     self.queued = True
            gst.debug('URI is valid: %s' % location)
            err_msg = []
            code = 0
            msg  = ''
            if self.verify_on_load:
                gst.debug('Attempting to verify %s' % location)
                if location[0:4] == 'file':
                    path = location[7:]
                    try:
                        with open(path) as f: pass
                    except IOError as e:
                        if e.errno == 21:
                            is_dir = True
                            loaded = []
                            try:
                                # is directory, load content
                                os.chdir(path)
                                for f in os.listdir('.'):
                                    if f.endswith('.mp3'):
                                        full_path = location+'/'+f
                                        res = self.queue_add(full_path)
                                        if res[0] == 200:
                                            loaded.append(full_path)
                                ans.append(loaded)
                            except IOError as e:
                                err_msg = 'Error parsing directory, will'\
                                    'stop loading, exception:%s' % e.__str__()
                                gst.error(err_msg)
                                ans = [404]
                                ans.append(err_msg)
                        else:
                            err_msg = 'Will not load, exception when opening'\
                                '%s: %s' % (path,e.__str__())
                            gst.error(err_msg)
                            ans = [404]
                            ans.append(err_msg)
                elif location[0:4] == 'http':
                    try:
                        urlopen_ans  = urlopen(location)
                        code = urlopen_ans.code
                        msg  = urlopen_ans.msg
                        if code >= 400:
                            err_msg = 'urlopen failed with %d: %s' % (code,msg)
                    except:
                        err_msg = 'urlopen() failed'
                    if err_msg:
                        ans = [400]
                        ans.append(err_msg)
                if not err_msg:
                    gst.debug('Verification succeeded!')
            if err_msg:
                gst.warning(err_msg)
            elif not is_dir:
                gst.debug('Setting location to %s' % location)
                try:
                    if location in self.queue:
                        gst.info('Duplicate entry %s' % location)
                    self.queue.append({'uri':location,'tags':{}})
                    try:
                        gst.debug('will prepare tag getter: get_tags(%s)' % location)
                        tgt = threading.Thread(target=tagget.get_tags,
                                               args=[self.queue[-1]['tags'],
                                                     location])
                        gst.debug('will start tag getter')
                        tgt.start()

                    except Exception as e:
                        err_msg = 'Problem near tag get thread. Exception:%s' % e.__str__()
                        gst.warning(err_msg)
                    # call to print current queue
                    self.queue_get()
                    if self.queue_pos == -1:
                        gst.debug('New queue, will next()')
                        ans_n = self.queue_next()
                        if ans_n[0] == 200:
                            gst.debug('New queue play success!')
                        else:
                            ans = [400]
                            ans.append('Failed to set initial queue position')
                except Exception as e:
                    print e
                    ans = [400]
                    gst.error('Problem near queue.append()')
        return ans
Beispiel #43
0
  def __init__(self, location, matrix, visualize=None, mainloop=None):
    # The pipeline

    self.visualize = visualize
    self.seek_to = None
    self.start_pipeline = False

    self.pipeline = gst.Pipeline()
    self.pipeline.auto_clock()

    # Create bus and connect several handlers
    self.bus = self.pipeline.get_bus()
    self.bus.add_signal_watch()
    self.bus.connect('message::eos', self.on_eos)
    self.bus.connect('message::tag', self.on_tag)
    self.bus.connect('message::error', self.on_error)

    # Create elements
    self.src = gst.element_factory_make('filesrc')
    self.player = player = gst.element_factory_make('playbin2')
    self.player.set_property("volume", 2)
    self.player.set_property("flags", 0x00000001 | 0x00000002 | 0x00000008 | 0x00000010 | 0x00000200)

    self.sink = gst.Bin() #gst.element_factory_make('alsasink')
    self.led = LedVideoSink(matrix) #gst.element_factory_make('alsasink')
    self.color = gst.element_factory_make('ffmpegcolorspace')
    self.rate = gst.element_factory_make('videorate')
    self.scale = gst.element_factory_make('ffvideoscale')
    self.scale.set_property("method", 5)

    self.sink.add(self.color, self.rate, self.scale, self.led)
    ghostpad = gst.GhostPad("sink", self.color.get_pad("sink"))
    self.sink.add_pad(ghostpad)
    gst.element_link_many(self.color, self.rate, self.scale, self.led)
    if self.visualize:    
        self.vis = gst.element_factory_make(self.visualize)
        player.set_property("vis-plugin", self.vis)

    player.set_property("video-sink", self.sink)
    player.connect("about-to-finish", self.on_finish)
    #player.connect("state-change", self.on_state_change)

    bus = self.pipeline.get_bus()
    bus.add_signal_watch()
    bus.enable_sync_message_emission()
    #bus.connect("message", self.on_message)
    bus.connect("sync-message::element", self.on_sync_message)
    bus.connect("message", self.on_message)

    # Set 'location' property on filesrc
    player.set_property('uri', gst.uri_is_valid(location) and location or "file://" + location)

    # Connect handler for 'new-decoded-pad' signal 
    #self.dec.connect('new-decoded-pad', self.on_new_decoded_pad)

    # Add elements to pipeline
    self.pipeline.add(player)

    # The MainLoop
    self.mainloop = mainloop or gobject.MainLoop()

    # And off we go!
    self.pipeline.set_state(gst.STATE_PLAYING)
Beispiel #44
0
        self.end_button.set_sensitive(False)
        self.sound_player.set_state(gst.STATE_NULL)
        self.audio_adjustment.value = 0

    def quit(self, *args):
        gtk.main_quit(*args)


# "MAIN" CODE STARTS HERE

# set window icon
gtk.window_set_default_icon_from_file("abx-comparator.svg")

a, b = None, None
# if we have at least 2 arguments, go ahead and set file A
if 2 < len(sys.argv) <= 3:
    a = sys.argv[1]
    if not gst.uri_is_valid(a):
        a = "file://" + os.path.abspath(a)

# and if we have 3, set file B as well
if len(sys.argv) == 3:
    b = sys.argv[2]
    if not gst.uri_is_valid(b):
        b = "file://" + os.path.abspath(b)

# define the app class
app = AbxComparator(a, b)
# launch the window
gtk.main()
Beispiel #45
0
        self.begin_button.set_sensitive(False)
        self.end_button.set_sensitive(False)
        self.sound_player.set_state(gst.STATE_NULL)
        self.audio_adjustment.value = 0
    
    def quit(self, *args):
        gtk.main_quit(*args)

# "MAIN" CODE STARTS HERE

# set window icon
gtk.window_set_default_icon_from_file("abx-comparator.svg")

a, b = None, None
# if we have at least 2 arguments, go ahead and set file A
if 2 < len(sys.argv) <= 3:
    a = sys.argv[1]
    if not gst.uri_is_valid(a):
        a = "file://" + os.path.abspath(a)

# and if we have 3, set file B as well
if len(sys.argv) == 3:
    b = sys.argv[2]
    if not gst.uri_is_valid(b):
        b = "file://" + os.path.abspath(b)

# define the app class
app = AbxComparator(a, b)
# launch the window
gtk.main()