Пример #1
0
    def __init__(self, **kwargs):
        super(DialogHandler, self).__init__(**kwargs)

        #self.cols = 1
        self.dialogList = []
        self.wId = -1
        self.sema = threading.Semaphore()
Пример #2
0
class Player():
    process = None
    _isPlaying = False
    path = None
    semaExec = threading.Semaphore()
    endHandler = []

    #Playback end event
    #
    def onPlayEnd(self, args):
        for func in self.endHandler:
            if func:
                func(args)

    def addEndHandler(self, handler):
        self.endHandler.append(handler)

    # Public functions of the player, each player class should have them
    #
    def stop(self):
        pass

    def pause(self):
        pass

    def play(self):
        pass

    def seek(self, time):
        pass

    def togglePause(self):
        pass

    def start(self, path, tSeek):
        self.path = path
        self._isPlaying = True

    def getRuntime(self):
        pass

    def getTotalTime(self):
        pass

    def getCurrentFile(self):
        if self._isPlaying:
            return self.path
        else:
            return None

    def isPaused(self):
        pass

    def isPlaying(self):
        return self._isPlaying
Пример #3
0
class Player():
    process = None
    _isPlaying = False
    path = None
    semaExec = threading.Semaphore()
    endHandler = []

    vlcPlayer = None
    vlcInst = None
    evManager = None
    cmdQueue = None

    #Playback end event
    #
    def onPlayEnd(self, args):
        for func in self.endHandler:
            if func:
                func(args)

    def addEndHandler(self, handler):
        self.endHandler.append(handler)

    # Public functions of the player, each player class should have them
    #
    def stop(self):
        self.vlcPlayer.stop()

    def pause(self):
        if not self.isPaused():
            self.vlcPlayer.pause()

    def play(self):
        self.vlcPlayer.play()

    def seek(self, tSeek):
        if self.vlcPlayer.is_seekable():
            self.vlcPlayer.set_time(tSeek*1000)


    def togglePause(self):
        self.vlcPlayer.pause()

    def start(self, path, tSeek):
        self.path = path
        self._isPlaying = True

        media = self.vlcInst.media_new(path)
        self.vlcPlayer.set_media(media)

        self.vlcPlayer.play()
        #self.vlcPlayer.set_fullscreen(True)

        #seek must come after file is started
        self.vlcPlayer.set_time(tSeek*1000)
        #self.vlcPlayer.toggle_fullscreen()


    def getRuntime(self):
        return int(self.vlcPlayer.get_time()/1000)

    def getTotalTime(self):
        return int(self.vlcPlayer.get_length()/1000)


    def getCurrentFile(self):
        if self._isPlaying:
            return self.path
        else:
            return None

    def isPaused(self):
        if self.vlcPlayer.is_playing() == 1:
            return False
        elif self.vlcPlayer.is_playing() == 0:
            return True

        return False


    def isPlaying(self):
        return self._isPlaying

    #
    # Private methods
    #
    def _mediaPlayerEnd(self, event):
        self.cmdQueue.put({'cmd':'mediaPlayerEnd'})

    def _worker(self):
        '''Worker thread that receives evenet manager signals'''
        while True:

            tmp = self.cmdQueue.get()
            cmd = tmp['cmd']

            #event manager callbacs cannot call vlc functions so this is why this...
            if cmd == "mediaPlayerEnd":
                self.onPlayEnd(None)
                self._isPlaying = False


    def __init__(self):
        #self.vlcInst = vlc.Instance()
        self.vlcInst = vlc.Instance(['-f'])
        self.vlcPlayer = self.vlcInst.media_player_new()

        self.evManager = self.vlcPlayer.event_manager()
        self.evManager.event_attach(vlc.EventType.MediaPlayerEndReached, self._mediaPlayerEnd)

        self.cmdQueue = queue.Queue()
        self.workThread = threading.Thread(target = self._worker)
        self.workThread.setDaemon(True)
        self.workThread.start()
Пример #4
0
class Player():
    process = None
    _isPlaying = False
    path = None
    semaExec = threading.Semaphore()
    endHandler = []

    #Playback end event
    #
    def onPlayEnd(self, args):
        for func in self.endHandler:
            if func:
                func(args)

    def addEndHandler(self, handler):
        self.endHandler.append(handler)

    #Methods that need to be assigned from outside
    #
    def _onUpdateRunTime(self, val):
        '''User must overrid this'''
        pass

    def _onUpdateTotaltime(self, val):
        '''User must overrid this'''
        pass


    # Public functions of the player, each player class should have them
    #
    def stop(self):
        self.killPlayer()


    def pause(self):
        self._execute({'command': ["set_property", "pause", True]})

    def play(self):
        self._execute({'command': ["set_property", "pause", False]})

    def seek(self, time):
        self._execute({'command': ["seek", str(time), "absolute"]})

    def togglePause(self):
        val = self.isPaused()
        if val is not None:
            self._execute({'command': ["set_property", "pause", not val]})

    def start(self, path, tSeek):
        logging.error("thomas - ß?????????????????????????????:  yes yes yes")
        self.path = path
        self._isPlaying = True

        mpvParam = mpvParams(tSeek, path, includes.config)
        self.process = Popen(mpvParam)

        self.playThread = threading.Thread(target = self._playWorkThread)
        self.playThread.setDaemon(True)
        self.playThread.start()

    def getRuntime(self):
        ret = self._execute({'command': ["get_property", "time-pos"]})

        if ret is None:
            return 0

        try:
            if 'data' in ret:
                return int(ret['data'])

        except json.decoder.JSONDecodeError as e:
            logging.error("Player: {}".format(e))
            return 0

    def getTotalTime(self):
        ret = self._execute({'command': ["get_property", "duration"]})

        if ret is None:
            return 0

        try:
            if 'data' in ret:
                return int(ret['data'])

        except json.decoder.JSONDecodeError as e:
            logging.error("Player: {}".format(e))
            return 0

    def getCurrentFile(self):
        if self._isPlaying:
            return self.path
        else:
            return None

    def isPaused(self):
        ret = self._execute({'command': ["get_property", "pause"]})
        if ret is None:
            return False

        if 'data' in ret:
            return ret['data']
        else:
            return None

    def isPlaying(self):
        return self._isPlaying

    #
    # Private methods
    #
    socket = None
    sockPath = None
    def _conectToSocket(self, path):
        #wait for socket file to be created
        while not os.path.exists(path):
            time.sleep(0.1)

        self.sockPath = path
        self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            self.socket.connect(path)
            return True
        except:
            return False


    def _execute(self, command):
        self.semaExec.acquire()
        data = json.dumps(command) + "\r\n"
        data = bytes(data, encoding='utf-8')
        try:
            if self.socket:
                self.socket.send(data)
                buf = self.socket.recv(1024)

                if "error" not in str(buf):#we got event see read again... retry
                     buf = self.socket.recv(1024)

                tmp = buf.decode("utf-8").split("\n")

                for line in tmp:
                    result = json.loads(line)

                    if not 'error' in result:
                        continue

                    status = result['error']
                    if status == 'success':
                        self.semaExec.release()
                        return result

                self.semaExec.release()
                return None

            else:
                self.semaExec.release()
                return None
        except Exception as e:
            logging.error(f"MpvPlayerV0: _execute: exception in socket communication = {e}")

            self.semaExec.release()
            return None



        logging.error("Player: error value returned from player...")
        self.semaExec.release()
        return None

    def _command(self, command, *args):
        return self._execute({'command': [command, *args]})

    def close(self):
        self.socket.close()


    def _playWorkThread(self):

        while True:
            if self._conectToSocket(os.path.join(includes.config['tmpdir'],"socket")):
                break

        self._isPlaying = True
        if self.process == None:
            self._isPlaying = False
            self.onPlayEnd(None)
            return

        while self.process.poll() == None:
            time.sleep(1)


        #-------------- End of playback ------------
        self.onPlayEnd(None)
        self._isPlaying = False


    def killPlayer(self):

        if self.process:
            self.process.kill()

        #wait for process to finish
        while self.process is not None and self.process.poll() is None:
            time.sleep(0.25)
Пример #5
0
class Player():
    exec = None
    process = None
    screensaver = None
    screenManager = None
    isPlaying = False
    isPaused = False
    path = None
    runtime = 0
    vlcPl = None
    semaExec = threading.Semaphore()

    #
    # Playback functions the user need to set up if needed
    #
    def onPlayEnd(self):
        '''Callbakc function called when playback finished'''
        return

    #
    # Public functions of the player, each player class should have them
    #
    def stop(self):
        self._execute({'command': ["quit"]})

    def _getRunTime(self):
        ret = self._execute({'command': ["get_property", "time-pos"]})
        if ret is None:
            return

        try:
            tmp = json.loads(ret[0])
            if 'data' in tmp:
                self.runtime = int(tmp['data'])

        except json.decoder.JSONDecodeError as e:
            logging.error("Player: {}".format(e))

    def pause(self):
        # from random import randint as random
        # cmd = 'echo \'{ "command": ["cycle", "pause"], "request_id": %s }\'' % str(random(0,100))
        # cmd = cmd + "| socat - " + includes.config['tmpdir'] + "/socket"
        # logging.error(cmd)
        # os.system(cmd)
        self._execute({'command': ["set_property", "pause", True]})

    def play(self):
        # from random import randint as random
        # cmd = 'echo \'{ "command": ["set_property", "pause", false], "request_id": %s }\'' % str(random(100,200))
        # cmd = cmd + "| socat - " + includes.config['tmpdir'] + "/socket"
        # os.system(cmd)
        self._execute({'command': ["set_property", "pause", False]})

    def isPaused(self):
        ret = self._execute({'command': ["get_property", "pause"]})
        if ret is None:
            return

        #logging.error("Ret= {}".format(ret))
        tmp = json.loads(ret[0])

        if 'data' in tmp:
            return tmp['data']
        else:
            return None

    def togglePause(self):

        #self.isPaused = True
        val = self.isPaused()
        if value is not None:
            self._execute({'command': ["set_property", "pause", not val]})

    #
    # Private methods
    #
    socket = None
    sockPath = None

    def _conectToSocket(self, path):

        while not os.path.exists(path):
            time.sleep(0.5)

        self.sockPath = path
        self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            self.socket.connect(path)
        except OSError as e:
            self.socket = None
            #raise SocketError from e
            logging.error("SockerError")

    def _execute(self, command):
        self.semaExec.acquire()
        data = json.dumps(command) + "\r\n"
        data = bytes(data, encoding='utf-8')

        try:
            if self.socket:
                self.socket.send(data)
                buf = self.socket.recv(1024)
                if "error" not in str(
                        buf):  #we got event see read again... retry
                    buf = self.socket.recv(1024)
            else:
                logging.error("No socket in commmand")
                self.semaExec.release()
                return None
        except:
            logging.error("Problems in socket....")
            self.semaExec.release()
            return None

        tmp = buf.decode('utf-8').split('\n')

        for item in tmp:
            result = json.loads(item)
            if not 'error' in result:
                self.semaExec.release()
                return None

            status = result['error']
            if status == 'success':
                self.semaExec.release()
                return tmp

        logging.error("Player: error value returned from player...")
        self.semaExec.release()

    def _command(self, command, *args):
        return self._execute({'command': [command, *args]})

    def close(self):
        self.socket.close()

    def _onUpdateRunTime(self, val):
        pass

    def _playWorkThread(self, mode):
        logging.debug("Thread mode = {}.....".format(mode))
        time.sleep(2)
        self._conectToSocket(os.path.join(includes.config['tmpdir'], "socket"))

        self.isPlaying = True
        if self.process == None:
            self.isPlaying = False
            self.onPlayEnd()
            return

        while self.process.poll() == None:
            time.sleep(1)
            self._getRunTime()
            self._onUpdateRunTime(
                time.strftime('%H:%M:%S', time.gmtime(self.runtime)))

            if self.runtime % includes.config['settings'][
                    'runtimeInterval'] == 0:
                includes.db['runtime'] = self.runtime
                includes.db['mediaPath'] = self.path
                includes.writeDb()

        #-------------- End of playback ------------
        self.isPlaying = False
        includes.db['runtime'] = 0
        includes.db['mediaPath'] = ""
        includes.writeDb()

        self.onPlayEnd(None)

    def start(self, path, tSeek):
        logging.info("Player: start playing file... path = {}".format(path))
        self.path = path

        if not os.path.isfile(path):
            logging.error("Player: file not found [{}]".format(path))
            return

        videoFormats = tuple(includes.config['video']['types'].split(','))
        audioFormats = tuple(includes.config['audio']['types'].split(','))

        logging.debug("Player: videoFormats = {} / audioFormats = {}".format(
            videoFormats, audioFormats))
        mode = "nothing"
        if path.lower().endswith(videoFormats):
            mode = "video"
            mediaInfo = MediaInfo.parse(path)

            videoWidth, videoHeight = 0, 0
            for track in mediaInfo.tracks:
                if track.track_type == 'Video':
                    videoWidth, videoHeight = track.width, track.height

            osdHeight = 50
            playerHeight = Window.height - (2 * osdHeight
                                            )  #videoHeight - osdHeight
            playerWidth = int(playerHeight * (videoWidth / videoHeight))

            posx = int((Window.width - playerWidth) / 2)
            posy = int((Window.height - playerHeight) / 2)

            logging.error(
                "Player: playerWidth: {} / playerHeight: {} / videoWidth: {} / videoHeight: {} / posx: {} / posy: {}"
                .format(playerWidth, playerHeight, videoWidth, videoHeight,
                        posx, posy))

            self.isPlaying = True
            self.runtime = tSeek

            self.process = Popen([
                "mpv", "--geometry={}+{}+{}".format(playerWidth, posx, posy),
                "--start=+{}".format(tSeek), "--no-border",
                "--no-input-default-bindings", path, "--really-quiet",
                "--no-osc", "--no-input-terminal",
                "--input-ipc-server={}".format(
                    os.path.join(includes.config['tmpdir'], "socket"))
            ])

        elif path.lower().endswith(audioFormats):
            self.isPlaying = True
            mode = "audio"
            logging.debug("Player: start playing audio")

            self.isPlaying = True
            self.process = Popen([
                "mpv", "--start=+{}".format(tSeek), "--no-border",
                "--no-input-default-bindings", path, "--really-quiet",
                "--no-osc", "--no-input-terminal",
                "--input-ipc-server={}".format(
                    os.path.join(includes.config['tmpdir'], "socket"))
            ])
        else:
            logging.debug("Player: no video nor audio file... {}".format(path))

        # Start player thread

        self.playThread = threading.Thread(target=self._playWorkThread,
                                           args=(mode, ))
        self.playThread.setDaemon(True)
        self.playThread.start()

    def killPlayer(self):

        if self.process:
            self.process.kill()

        #wait for process to finish
        while self.process.poll() == None:
            time.sleep(0.25)

        #reset the runtime value
        self.runtime = 0
        self._onUpdateRunTime(
            time.strftime('%H:%M:%S', time.gmtime(self.runtime)))