Exemplo n.º 1
0
class Video_Player:
    def __init__(self, player_id, video_path):
        self.player_id = player_id
        self.video_path = video_path
        self.player = OMXPlayer(video_path,
                                args=['--loop'],
                                dbus_name="org.mpris.MediaPlayer2.player" +
                                player_id)
        sleep(2)

    #

    def load(self, video_path):
        self.player.hide_video()
        self.video_path = video_path
        self.player.load(video_path)

    def play(self):
        self.player.play()
        self.player.show_video()

    def pause(self):
        self.player.hide_video()
        self.player.pause()

    def stop(self):
        self.player.stop()
Exemplo n.º 2
0
def play_film(filename="demo.mp4", duration=0, position=0):
    debug("\nfilename:", filename)
    debug("  position:", position)
    debug("  duration:", duration)
    trim_from_end = 0.5
    #trim_from_end = 0
    player = OMXPlayer(filename)
    player.set_position(0.0)
    debug("  pre-play pos:", player.position())
    player.play()
    # check and set position
    full_length = player.duration()
    # if the position is imposible, set it to 0
    if position <= 0 or position > full_length:
        position = 0.0
    player.set_position(position)
    # check and set duration
    length_to_end = player.duration()
    # if duration is imposible, set it to the length_to_end
    if duration == 0 or duration > length_to_end:
        wait = length_to_end - trim_from_end
    else:
        wait = duration
    if wait < 0:
        wait = 0
    debug("  full length: ", full_length)
    debug("  length to end: ", length_to_end)
    debug("  wait: ", wait)
    sleep(wait)
    debug("  post sleep pos:", player.position())
    player.pause()
    player.quit()
    debug("  post pause pos:", player.position())
    return True
Exemplo n.º 3
0
def single_video_player_looper(video_clip_path, sleep_minutes, test_mode):
    """
    Loops a single video.

    Arguments
        video_clip_path     string
                            The path of the video clip being played.

        sleep_minutes       integer or float
                            Length of time to pause between loops.

        test_mode           boolean
                            True of False. If test_mode is True, clip is not
                            played in full screen mode.
    """

    test_mode_length = "720"
    test_mode_width = "360"
    play_message = "{} - Playing {}".format(current_time(), video_clip_path)
    if test_mode is True:
        player = OMXPlayer(video_clip_path,
                           args=[
                               "--no-osd", "--loop", "--win",
                               "0, 0, {0}, {1}".format(test_mode_length,
                                                       test_mode_width)
                           ])
        play_message = "{} in test mode".format(play_message)
    else:
        player = OMXPlayer(video_clip_path,
                           args=[
                               "--no-osd", "--loop", "--orientation", "180",
                               "--aspect-mode", "fill"
                           ])

    print(play_message)
    print("{} - {} minute(s) pause between each play".format(
        current_time(), sleep_minutes))

    try:
        player.pause()

        while True:
            print(play_message)
            player.play()
            sleep(player.duration())
            player.pause()
            player.set_position(0.0)
            if sleep_minutes > 0:
                if sleep_minutes < 1:
                    sleep_message = "{} seconds".format(
                        int(60.0 * sleep_minutes))
                else:
                    sleep_message = "{} minute(s)".format(sleep_minutes)
                print("{} - Sleeping {} before starting again".format(
                    current_time(), sleep_message))
                sleep(60 * sleep_minutes)
    except KeyboardInterrupt:
        print("{} - Exiting".format(current_time()))
        player.quit()
        sys.exit()
Exemplo n.º 4
0
def play_film(filename="demo.mp4", duration=0, position=0):
    debug("\nfilename:", filename)
    debug("  position:", position)
    debug("  duration:", duration)
    trim_from_end = 0.5
    #trim_from_end = 0
    player = OMXPlayer(filename)
    player.set_position(0.0)
    debug("  pre-play pos:", player.position())
    player.play()
    # check and set position
    full_length = player.duration()
    # if the position is imposible, set it to 0
    if position <= 0 or position > full_length:
        position = 0.0
    player.set_position(position)
    # check and set duration
    length_to_end = player.duration()
    # if duration is imposible, set it to the length_to_end
    if duration == 0 or duration > length_to_end:
        wait = length_to_end - trim_from_end
    else:
        wait = duration
    if wait < 0:
        wait = 0
    debug("  full length: ", full_length)
    debug("  length to end: ", length_to_end)
    debug("  wait: ", wait)
    sleep(wait)
    debug("  post sleep pos:", player.position())
    player.pause()
    player.quit()
    debug("  post pause pos:", player.position())
    return True
Exemplo n.º 5
0
def playBGVideo(video, startPos):
    video_path = VIDEO_PATH + video
    player_log = logging.getLogger("Stone Player - BG")

    try:

        bgPlayer = OMXPlayer(video_path,
                             args=['--loop'],
                             dbus_name='org.mpris.MediaPlayer2.omxplayer0')

        if bgPlayer.playback_status() == "Playing":
            return

        bgPlayer.playEvent += lambda _: player_log.info("Play")
        bgPlayer.pauseEvent += lambda _: player_log.info("Pause")
        bgPlayer.stopEvent += lambda _: player_log.info("Stop")

        # global playbackStatus
        # playbackStatus = player.playback_status()

        sleep(5)
        bgPlayer.set_position(startPos)  #seconds from the start of the video
        # player.pause()

        # sleep(2)

        # player.set_aspect_mode('stretch')
        # player.set_video_pos(0, 0, 200, 200)
        bgPlayer.play()
        bgPlayer.quit()

    except Exception as err:
        print("bgPlayer ERROR:", str(err))
Exemplo n.º 6
0
def play_video(video):
    VIDEO_PATH = Path(video)

    player = None
    try:
        arguments = "--no-osd -o alsa --aspect-mode fill"
        if DEV_MODE:
            arguments = arguments + " --win '0 0 400 300'"

        player = OMXPlayer(VIDEO_PATH, args=arguments)

        # App is real slow to boot and start playing video
        time.sleep(1)

        player.play()

    except SystemError:
        print "OMXPlayer failed to start, maybe"
        print "Sleeping for 60 seconds in case it didn't actually fail..."
        time.sleep(60)

    except OMXPlayerDeadError:
        print "OMXPlayer appeared to close, video likely ended!"

    except DBusException:
        print "OMXPlayer not replying, video likely ended!"

    finally:
        return player
Exemplo n.º 7
0
def playVideo(video, player_log):

    if Path(video.path).is_file():

        player = OMXPlayer(video.path, dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=['--loop'])

        player.playEvent += lambda _: player_log.info("Play")
        player.pauseEvent += lambda _: player_log.info("Pause")
        player.stopEvent += lambda _: player_log.info("Stop")

        player.hide_video()

        player.set_position(video.start)
        player.set_volume(video.volume)

        if video.crop != None:
            player.set_video_crop(video.crop[0], video.crop[1], video.crop[2], video.crop[3])

        player.set_aspect_mode(video.aspect)

        player.show_video()
        player.play()

        return player

    else:

        return None
Exemplo n.º 8
0
def playMedia(path="../tests/media/test_media_1.mp4", duration=0, position=0):
    player = OMXPlayer(path, args=["--no-osd"])
    player.set_aspect_mode("fill")
    if position > 0:
            player.set_position(position)
    #player.duration() # this only works if this line is here
    if duration == 0:
            duration = player.duration() - position
    player.play()
    time.sleep(duration)
    player.quit()
Exemplo n.º 9
0
def playMedia(path="../tests/media/test_media_1.mp4", duration=0, position=0):
    player = OMXPlayer(path, args=["--no-osd"])
    player.set_aspect_mode("fill")
    if position > 0:
        player.set_position(position)
    #player.duration() # this only works if this line is here
    if duration == 0:
        duration = player.duration() - position
    player.play()
    time.sleep(duration)
    player.quit()
Exemplo n.º 10
0
def play_video():
    player = OMXPlayer('video.mp4',
                       dbus_name='org.mpris.MediaPlayer2.omxplayer1',
                       args=['--loop', '--no-osd'])
    sleep(2.5)
    player.set_position(5)
    player.pause()
    sleep(2)
    player.set_aspect_mode('stretch')
    #player.set_fullscreen()
    # player.set_video_pos(0, 0, 200, 200)
    player.play()
    return player
Exemplo n.º 11
0
class Player:
    def __init__(self, url):
        self.url = url
        self.player = None
        self.state = True
        self.playlist = False
        self._play = True

    def start(self):
        if isinstance(self.url, string_types):
            cmd = 'youtube-dl -g -f best {0}'.format(self.url)
            yt_dl = subprocess.Popen(cmd,
                                     shell=True,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
            (url, err) = yt_dl.communicate()
            if yt_dl.returncode != 0:
                sys.stderr.write(err)
                print('error')
            yurl = url.decode('UTF-8').strip()
            self.player = OMXPlayer(yurl, args=['-o', 'hdmi'])
            return self.player.duration()

    def stop(self):
        self.player.stop()
        self._play = False
        self.player = None
        return False

    def skip(self):
        if self.playlist == True:
            self.player.stop()
            return True
        else:
            self.player.stop()
            return False

    def toggle(self):
        #false = not playing // true = playing
        if self.state == True:
            self.state = False
            self.player.pause()
        elif self.state == False:
            self.state = True
            self.player.play()
        else:
            return False

    def is_play(self):
        return self.player.can_control()
Exemplo n.º 12
0
  def run(self):
    omxplayer = OMXPlayer(Path("./video/Slàinte.mp4"))
    time_remaining = omxplayer.duration()
    omxplayer_sleep = 1 # one second sleep sessions below for video to run in loop
    omxplayer.play()
    while self.running:
        time_remaining = time_remaining - omxplayer_sleep
        if time_remaining > 0:
            sleep(omxplayer_sleep)
        print('Can Control = '+str(omxplayer.can_control())) 
        # If can_control() = True, pressing Kivy Stop button will make self.running = False and allow
        # me to take control of this loop and terminate the thread.

    omxplayer.quit()
Exemplo n.º 13
0
def playVideos(vN):

    global playing
    global player
    global player1
    global first

    print("Dentro funcion video >> " + str(vN))
    vid = "/home/pi/Desktop/videocoto/videos/" + str(vN) + ".mp4"
    print("Toca reproducir ahora: " + vid)

    if playing == 0:
        print("Not Playing: " + str(playing))

        VIDEO_PATH = Path(vid)
        if slave == False:
            player = OMXPlayer(VIDEO_PATH, args=omx_arg, dbus_name=bus[0])

        if slave == True:
            player = OMXPlayer(VIDEO_PATH,
                               args=omx_arg_pasive,
                               dbus_name=bus[0])

        player.seek(0)
        player.play()

        if first == 1:
            player1.stop()

        first = 1
        playing = 1

    elif playing == 1:
        print("Is Playing: " + str(playing))

        VIDEO_PATH = Path(vid)
        if slave == False:
            player1 = OMXPlayer(VIDEO_PATH, args=omx_arg, dbus_name=bus[1])

        if slave == True:
            player1 = OMXPlayer(VIDEO_PATH,
                                args=omx_arg_pasive,
                                dbus_name=bus[1])

        player1.seek(0)
        player1.play()

        player.stop()
        playing = 0
class videoPlayer:
    def __init__(self, videoPath):
        self.videoPath = videoPath
        self.classPlayer = OMXPlayer(self.videoPath)
        sleep(0.2)
        self.classPlayer.pause()

    def playVideo(self):
        self.classPlayer.play()

    def end(self):
        return self.classPlayer.is_playing()

    def length(self):
        return self.classPlayer.duration()

    def freeze(self):
        self.classPlayer.quit()
Exemplo n.º 15
0
	def __init__(self):
		#loading settings from setup.config
		settings = sl_settings.Settings()
		if not settings.load():
			error(1)

		ip_setup = dynamic_ip()
		ip_setup.set(settings.get("ip_address"))
	
		plr = OMXPlayer(settings.get("file_name"),["--blank","--no-osd"])

		if settings.get("ismaster") == "True":
			if ip_setup.waitForConnections(settings.get("num_clients")):
				ip_setup.sendStartSignal()
		else:
			ip_setup.connectToServer()
			ip_setup.waitForStartSignal()
			print "this function is not ready yet"
			### TODO: error check 
		#loop_time = plr.duration() - float(settings.get("load_time"))
		plr.play()
	
		while True:
			try:
				if settings.get("ismaster") == "False":
					ip_setup.waitForStartSignal()
					plr.set_position(0)
				elif settings.get("ismaster") == "True":
					sleep(plr.duration() - 1.0)
					#sleep(6)
					ip_setup.sendStartSignal()
					plr.set_position(0)
			except KeyboardInterrupt:
				print "interrupted!"
				ip_setup.closeConnection()
				ip_setup.setOldIp()
				plr.stop()
				plr.quit()
				break
		#plr.stop()

		ip_setup.setOldIp()
Exemplo n.º 16
0
class VideoPlayer:
    def __init__(self, root, message_handler, data, name):
        self.root = root
        self.message_handler = message_handler
        self.data = data
        self.omx_player = None
        self.name = name
        self.omx_running = False
        self.status = 'EMPTY'
        self.total_length = 0.0
        self.bankslot_number = '*-*'
        self.start = -1.0
        self.end = -1.0
        self.rate = 1
        self.crop_length = 0.0
        self.location = ''
        self.load_attempts = 0
        self.alpha = 0

    def try_load(self, layer):
        load_attempts = 0
        while (load_attempts < 2):
            load_attempts = load_attempts + 1
            if self.load(layer):
                print('load success')
                return True
            else:
                print('load failed')
        self.message_handler.set_message('ERROR', 'failed to load')
        self.status = 'ERROR'
        return False

    def load(self, layer):
        #try:
        self.get_context_for_player()
        is_dev_mode, first_screen_arg, second_screen_arg = self.set_screen_size_for_dev_mode(
        )
        arguments = [
            '--no-osd', '--layer',
            str(layer), '--adev', 'local', '--alpha', '0', first_screen_arg,
            second_screen_arg
        ]
        if not is_dev_mode:
            arguments.append('--blank=0x{}'.format(
                self.data.get_background_colour()))
        self.status = 'LOADING'
        print('the location is {}'.format(self.location))
        if self.location == '':
            self.status = 'EMPTY'
            return True
        self.omx_player = OMXPlayer(self.location,
                                    args=arguments,
                                    dbus_name=self.name)
        self.omx_running = True
        self.total_length = self.omx_player.duration(
        )  # <-- uneeded once self.duration stores float
        if (self.end is -1):
            self.end = self.total_length
        if (self.start is -1):
            self.start = 0
        self.crop_length = self.end - self.start
        print('{}: the duration is {}'.format(self.name, self.total_length))
        if self.start > 0.9:
            self.set_position(self.start - 0.9)
        if 'show' in self.data.settings['sampler']['ON_LOAD']['value']:
            self.set_alpha_value(255)
        else:
            self.set_alpha_value(0)
        self.pause_at_start()
        return True
        #except (ValueError, SystemError) as e:
        #  print(e)
        #self.message_handler.set_message('ERROR', 'load attempt fail')
        #return False

    def pause_at_start(self):
        position = self.get_position()
        start_threshold = round(self.start - 0.02, 2)
        if position > start_threshold:
            if self.status == 'LOADING':
                self.status = 'LOADED'
                self.omx_player.pause()
        elif self.omx_running:
            self.root.after(5, self.pause_at_start)

    def start_video(self):
        if 'show' in self.data.settings['sampler']['ON_START']['value']:
            self.set_alpha_value(255)
        else:
            self.set_alpha_value(0)
        if 'play' in self.data.settings['sampler']['ON_START']['value']:
            self.status = 'PLAYING'
            self.omx_player.play()
        else:
            self.status = 'START'
        self.pause_at_end()

    def pause_at_end(self):
        position = self.get_position()
        end_threshold = self.end - 0.2
        if (position > end_threshold):
            self.status = 'FINISHED'
            self.omx_player.pause()

            print('its paused at end!')
        elif (self.omx_running):
            self.root.after(5, self.pause_at_end)

    def reload(self, layer):
        self.exit()
        self.omx_running = False
        self.try_load(layer)

    def is_loaded(self):
        return self.status is 'LOADED'

    def is_finished(self):
        return self.status is 'FINISHED'

    def get_position(self):
        try:
            return self.omx_player.position()
        except:
            print('{}: error get_position'.format(self.name))
            return -1

    def get_context_for_player(self):
        next_context = self.data.get_next_context()
        self.location = next_context['location']
        #self.total_length = next_context['length']
        self.start = next_context['start']
        self.end = next_context['end']
        self.bankslot_number = next_context['bankslot_number']
        self.rate = next_context['rate']

    def toggle_pause(self):
        self.omx_player.play_pause()
        self.status = self.omx_player.playback_status().upper()

    def toggle_show(self):
        if self.alpha > 127:
            self.show_toggle_on = False
            self.set_alpha_value(0)
        else:
            self.show_toggle_on = True
            self.set_alpha_value(255)

    def set_alpha_value(self, amount):
        self.omx_player.set_alpha(amount)
        self.alpha = amount

    def seek(self, amount):
        position = self.get_position()
        after_seek_position = position + amount
        if after_seek_position > self.start and after_seek_position < self.end:
            self.set_position(after_seek_position)
            #self.player.seek(amount)
        else:
            self.message_handler.set_message('INFO',
                                             'can not seek outside range')

    def change_rate(self, amount):
        new_rate = self.rate + amount
        if (new_rate > self.omx_player.minimum_rate()
                and new_rate < self.omx_player.maximum_rate()):
            updated_speed = self.omx_player.set_rate(new_rate)
            self.rate = new_rate
            print('max rate {} , min rate {} '.format(
                self.omx_player.maximum_rate(),
                self.omx_player.minimum_rate()))
            return new_rate
        else:
            self.message_handler.set_message(
                'INFO', 'can not set speed outside of range')
            return self.rate

    def set_position(self, position):
        self.omx_player.set_position(position)

    def exit(self):
        try:
            self.omx_player.quit()
            self.status = 'EMPTY'
            self.omx_running = False
        except:
            pass

    def set_screen_size_for_dev_mode(self):
        ## only dev mode is needed now that auto handles all modes... can be removed probably ...
        if self.data.settings['other']['DEV_MODE_RESET']['value'] == 'on':
            return True, '--win', '50,350,550,750'
        else:
            aspect_mode = self.data.settings['video']['SCREEN_MODE']['value']
            return False, '--aspect-mode', aspect_mode
Exemplo n.º 17
0
#        ,dbus_name='org.mpris.MediaPlayer2.omxplayer1')
#player1.playEvent += lambda _: print("Play event triggered") #player_log.info("Play")
#player1.pauseEvent += lambda _: print("Pause event triggered") #player_log.info("Pause")
#player1.stopEvent += lambda _: print("Stop event triggered") #player_log.info("Stop")

player2.playEvent += lambda _: print("Play event triggered for 2"
                                     )  #player_log.info("Play")
player2.pauseEvent += lambda _: print("Pause event triggered for 2"
                                      )  #player_log.info("Pause")
player2.stopEvent += lambda _: print("Stop event triggered for 2"
                                     )  #player_log.info("Stop")

time.sleep(2.5)

player2.play()
# it takes about this long for omxplayer to warm up and start displaying a picture on a rpi3
time.sleep(15.5)

player2.set_position(20)
player2.pause()

time.sleep(2)

#player.set_aspect_mode('stretch')
#player.set_video_pos(0, 0, 200, 200)
player2.play()

time.sleep(5)
player2.pause()
player2.load(VIDEO_1_PATH)
Exemplo n.º 18
0
class ScreenController:
    video_playlist = []
    player1 = None
    player2 = None
    index = None
    number_of_cycles = 0
    currentIndex = None
    nextIndex = None
    layer = 10
    baseUrl = "http://10.0.0.111:8080/video/"
    fadeTime = 2
    fadeStep = 5
    lowerAlpha = 50
    upperAlpha = 250

    def __init__(self):
        self.index = 0
        self.currentIndex = 0
        self.nextIndex = self.currentIndex + 1
        self.player_log = logging.getLogger("Player")

    def setup_player_one(self):
        self.player1 = OMXPlayer(self.baseUrl +
                                 self.video_playlist[self.currentIndex],
                                 args='--win 0,0,1920,1080 --layer 2',
                                 dbus_name='orb.mpris.MediaPlayer2.omxplayer1',
                                 pause=True)
        self.player1.playEvent += lambda _: self.player_log.info(" 1 Play")
        self.player1.pauseEvent += lambda _: self.player_log.info("1 Pause")
        self.player1.stopEvent += lambda _: self.player_log.info("1 Stop")

    def setup_player_two(self):
        self.player2 = OMXPlayer(self.baseUrl +
                                 self.video_playlist[self.nextIndex],
                                 args='--win 0,0,1920,1080 --layer 1',
                                 dbus_name='orb.mpris.MediaPlayer2.omxplayer2',
                                 pause=True)
        self.player2.playEvent += lambda _: self.player_log.info(" 2 Play")
        self.player2.pauseEvent += lambda _: self.player_log.info("2 Pause")
        self.player2.stopEvent += lambda _: self.player_log.info("2 Stop")

    def start_playlist(self, videos):
        self.layer = len(videos) + 1
        videos.sort(reverse=False, key=self.sort_videos)
        for x in videos:
            self.video_playlist.append(x['id'])

        self.setup_player_one()
        self.setup_player_two()
        self.play_videos(True)

    def start_stream(self, stream_id):
        videos = json.load(open('videos.json', 'r'))
        video = next((item for item in videos if item["id"] == stream_id),
                     None)
        url = video.uri
        self.player1 = OMXPlayer(url,
                                 args='--win 0,0,1920,1080',
                                 dbus_name='orb.mpris.MediaPlayer2.omxplayer1')

    def stop_stream(self):
        self.player1.quit()

    def play_single_video(self, video_id):
        # videos = json.load(open('videos.json', 'r'))
        # video = next((item for item in videos if item["id"] == video_id), None)
        url = self.baseUrl + video_id
        # check if player is already playing
        # if it is playing then fade out player 1
        # start player 2 with new video fading in
        # quit player 1
        # do the same for player 2
        if self.player1 == None:
            self.player1 = OMXPlayer(
                url,
                args='--win 0,0,1920,1080 --layer 2',
                dbus_name='orb.mpris.MediaPlayer2.omxplayer1')
            self.player2 = None
        else:
            self.player2 = OMXPlayer(
                url,
                args='--win 0,0,1920,1080 --layer 1',
                dbus_name='orb.mpris.MediaPlayer2.omxplayer2')
            self.player1 = None

    def play_videos(self, init=False):
        # Load players with appropiate indexes
        if init == False:
            self.player1.load(self.baseUrl +
                              self.video_playlist[self.currentIndex],
                              pause=True)
            self.player2.load(self.baseUrl +
                              self.video_playlist[self.nextIndex],
                              pause=True)

    #	else:
    #	self.player1.set_alpha(255)
    #	self.player2.set_alpha(255)

    # Play video on player one
        self.player1.play()
        print("first video started")
        #self.fade_player_in(self.player1)

        # Sleep for video duration - 2 * self.fadeTime seconds because there are two following fades which sleep for fadeTime seconds each
        sleep(self.player1.duration() - (2 * self.fadeTime))
        self.player2.play()
        print("second video started")
        #  Start fading player one out and player two in for fadeTime seconds each
        self.fade_player_out(self.player1)
        self.fade_player_in(self.player2)

        # Stop Video One
        print("first video quit start")
        self.player1.quit()
        print("first video quit finished")

        # Play for total duration - 1 second
        sleep(self.player2.duration() - self.fadeTime)

        # Fade player
        #	self.fade_player_out(self.player2)
        self.player2.quit()

        # Set new current and next index
        self.reset_indexes()

        # Recursively call play videos
        self.number_of_cycles = self.number_of_cycles + 1
        if (self.number_of_cycles < 3):
            #if(self.layer > 1):
            #self.layer = self.layer - 2
            self.play_videos(False)

    def reset_indexes(self):
        if self.nextIndex + 1 >= len(self.video_playlist):
            self.currentIndex = 0
        else:
            self.currentIndex = self.nextIndex + 1

        if self.currentIndex + 1 >= len(self.video_playlist):
            self.nextIndex = 0
        else:
            self.nextIndex = self.currentIndex + 1

        print('----AFTER CURRENT----')
        print(self.currentIndex)
        print('----AFTER NEXT----')
        print(self.nextIndex)

    def fade_player_out(self, player):
        print('----fade_player_out START----')
        alpha = self.upperAlpha
        no_of_steps = (self.upperAlpha - self.lowerAlpha) / self.fadeTime
        fadeSleep = self.fadeTime / no_of_steps
        for x in range(no_of_steps):
            sleep(fadeSleep)
            alpha = alpha - ((self.upperAlpha - self.lowerAlpha) / no_of_steps)
            player.set_alpha(alpha)
        print('----fade_player_out END----')

    def fade_player_in(self, player):
        alpha = self.lowerAlpha
        no_of_steps = (self.upperAlpha - self.lowerAlpha) / self.fadeTime
        fadeSleep = self.fadeTime / no_of_steps
        for x in range(no_of_steps):
            sleep(fadeSleep)
            alpha = alpha + ((self.upperAlpha - self.lowerAlpha) / no_of_steps)
            player.set_alpha(alpha)

    def get_remaining_seconds(self, player):
        remaining_seconds = player.duration() - player.position()
        return remaining_seconds

    def sort_videos(self, video):
        return video['order']

    def is_nearly_finished(self, player):
        amountPlayed = 0
        if player.position() > 0:
            amountPlayed = player.position()
        percentPlayed = amountPlayed / player.duration()
        print(percentPlayed)
        if (percentPlayed > 0.9):
            return True
        else:
            return False
from time import sleep
import logging
logging.basicConfig(level=logging.INFO)


VIDEO_1_PATH = "../tests/media/test_media_1.mp4"
player_log = logging.getLogger("Player 1")

player = OMXPlayer(VIDEO_1_PATH, 
        dbus_name='org.mpris.MediaPlayer2.omxplayer1')
player.playEvent += lambda _: player_log.info("Play")
player.pauseEvent += lambda _: player_log.info("Pause")
player.stopEvent += lambda _: player_log.info("Stop")

# it takes about this long for omxplayer to warm up and start displaying a picture on a rpi3
sleep(2.5)

player.set_position(5)
player.pause()


sleep(2)

player.set_aspect_mode('stretch')
player.set_video_pos(0, 0, 200, 200)
player.play()

sleep(5)

player.quit()
Exemplo n.º 20
0
from omxplayer.player import OMXPlayer
from pathlib import Path
from time import sleep

VIDEO_PATH_OPENING = Path("./assets/opening.mp4")
VIDEO_PATH_BATTLE = Path("./assets/battle-test.mp4")

player_opening = OMXPlayer(VIDEO_PATH_OPENING, args=['--no-osd'], pause=True)

#player_battle = OMXPlayer(VIDEO_PATH_BATTLE)
#player_battle.pause()

sleep(5)

player_opening.play()

sleep(3)

player_opening.stop()
player_opening.quit()
print("quit opening player")

#sleep(3)

#print("creating new player instance for the battle")

#player_battle = OMXPlayer(VIDEO_PATH_BATTLE)

#sleep(5)
Exemplo n.º 21
0
class ScreenController:
    video_playlist = []
    player1 = None
    player2 = None
    index = None
    index = None

    def __init__(self):
        self.video_playlist = [
            VideoFile(1, "/media/pi/TOSHIBA1/Apocalyptic.mp4"),
            VideoFile(2, "/media/pi/TOSHIBA1/ledtime.mp4")
        ]
        self.index = 0
        self.player_log = logging.getLogger("Player")

    def setup_player_one(self):
        self.player1 = OMXPlayer(self.video_playlist[self.index].path,
                                 args='--win 0,0,1920,1080 --layer 2',
                                 bus_address_finder=None,
                                 Connection=None,
                                 dbus_name='orb.mpris.MediaPlayer2.omxplayer1',
                                 pause=True)
        self.player1.playEvent += lambda _: self.player_log.info(" 1 Play")
        self.player1.pauseEvent += lambda _: self.player_log.info("1 Pause")
        self.player1.stopEvent += lambda _: self.player_log.info("1 Stop")

    def setup_player_two(self):
        self.player2 = OMXPlayer(self.video_playlist[self.index + 1].path,
                                 args='--win 0,0,1920,1080 --layer 3',
                                 bus_address_finder=None,
                                 Connection=None,
                                 dbus_name='orb.mpris.MediaPlayer2.omxplayer2',
                                 pause=True)
        self.player2.playEvent += lambda _: self.player_log.info(" 2 Play")
        self.player2.pauseEvent += lambda _: self.player_log.info("2 Pause")
        self.player2.stopEvent += lambda _: self.player_log.info("2 Stop")

    def start_playlist(self):
        self.setup_player_one()
        self.setup_player_two()
        self.play_videos()

    def play_videos(self):
        alpha1 = 255
        self.player1.load(self.video_playlist[self.index].path, True)
        self.player2.load(self.video_playlist[self.index + 1].path, True)

        self.player1.play()
        while self.is_nearly_finished(self.player1) == False:
            sleep(1)

        #while self.is_nearly_finished(self.player1) == True and alpha1 > 0:
        #reductionRate = self.get_remaining_seconds(self.player1)
        #alpha1 = alpha1 - reductionRate
        #self.player1.set_alpha(alpha1)
        #sleep(1)

        self.player2.play()
        self.player1.stop()

        while self.is_nearly_finished(self.player2) == False:
            sleep(1)
        self.player2.stop()

    def get_remaining_seconds(self, player):
        remaining_seconds = player.duration() - player.position()
        return remaining_seconds

    def is_nearly_finished(self, player):
        amountPlayed = 0
        if player.position() > 0:
            amountPlayed = player.position()
        percentPlayed = amountPlayed / player.duration()
        print(percentPlayed)
        if (percentPlayed > 0.9):
            return True
        else:
            return False
class ScreenController:
	video_playlist = []
	player1 = None
	player2 = None
	index = None
	number_of_cycles = 0
	currentIndex = None
	nextIndex = None
	
	def __init__(self):
		self.video_playlist = [VideoFile(1, "/media/pi/TOSHIBA1/Apocalyptic.mp4"), VideoFile(2, "/media/pi/TOSHIBA1/ledtime.mp4"), VideoFile(3, "/media/pi/TOSHIBA1/DiscoLightsVidevo.mov")]
		self.index = 0
		self.currentIndex = 0
		self.nextIndex = self.currentIndex+1
		self.player_log = logging.getLogger("Player")	
	
	def setup_player_one(self):
		self.player1 = OMXPlayer(self.video_playlist[self.index].path, args='--win 0,0,1920,1080 --layer 2', dbus_name='orb.mpris.MediaPlayer2.omxplayer1', pause = True)
		self.player1.playEvent += lambda _: self.player_log.info(" 1 Play")
		self.player1.pauseEvent += lambda _: self.player_log.info("1 Pause")
		self.player1.stopEvent += lambda _: self.player_log.info("1 Stop")
		
	def setup_player_two(self):
		self.player2 = OMXPlayer(self.video_playlist[self.index + 1].path,  args='--win 0,0,1920,1080 --layer 1', dbus_name='orb.mpris.MediaPlayer2.omxplayer2', pause = True)
		self.player2.playEvent += lambda _: self.player_log.info(" 2 Play")
		self.player2.pauseEvent += lambda _: self.player_log.info("2 Pause")
		self.player2.stopEvent += lambda _: self.player_log.info("2 Stop")
	
	def start_playlist(self):
		self.setup_player_one();
		self.setup_player_two();
		self.play_videos(True);
	
	def play_videos(self, init = False):
		# Load players with appropiate indexes	
		self.player1.load(self.video_playlist[self.currentIndex].path, True)
		self.player2.load(self.video_playlist[self.nextIndex].path, True)
		
		self.player1.set_alpha(255)
		self.player2.set_alpha(255)
		# Play for total duration - 1 second	
		self.player1.play()
		sleep(self.player1.duration()-1)
		
		# Fade player 
		self.fade_player_out(self.player1)
		
		# Play for total duration - 1 second	
		self.player2.play()
		sleep(self.player2.duration()-1)
		
		# Set new current and next index 
		self.reset_indexes()
		
		# Recursively call play videos
		self.number_of_cycles = self.number_of_cycles + 1
		if(self.number_of_cycles < 2):
			self.play_videos(False)
			
		# Fade player
		self.fade_player_out(self.player2)



		

	
	def reset_indexes(self): 

		
		if self.nextIndex + 1 >= len(self.video_playlist):
			self.currentIndex = 0
		else :
			self.currentIndex = self.nextIndex + 1
			
		if self.currentIndex + 1 >= len(self.video_playlist):
			self.nextIndex = 0
		else:
			self.nextIndex = self.currentIndex + 1
		
		print('AFTER CURRENT')
		print(self.currentIndex)
		print('AFTER NEXT')
		print(self.nextIndex)
		
	def fade_player_out(self, player):
		alpha = 200
		for x in range(6):
			sleep(0.1)
			alpha = alpha - 20
			player.set_alpha(alpha)
			
		alpha = 200
	
	def get_remaining_seconds(self, player):
		remaining_seconds = player.duration() - player.position()
		return remaining_seconds
             
	def is_nearly_finished(self, player):
		amountPlayed = 0
		if player.position() > 0:
			amountPlayed = player.position();
		percentPlayed = amountPlayed/player.duration()
		print(percentPlayed)
		if(percentPlayed > 0.9):
			return True;
		else:
			return False;
Exemplo n.º 23
0
class VideoPlayer:
    def __init__(self,
                 VIDEO_NAME,
                 IMAGE_WIDTH,
                 IMAGE_HEIGHT,
                 USING_VLC=False,
                 audioPlayerRef=None,
                 pygameRef=None):

        self.USING_VLC = USING_VLC
        self.VIDEO_FILE = VIDEO_NAME
        #get a reference to the audio player
        self.audioPlayerRef = audioPlayerRef

        self.player = None

        if self.USING_VLC:
            if (pygameRef == None):
                print(
                    "VIDEOPLAYER ERROR: don't have a reference to pygame window!"
                )

            self.vlcInstance = vlc.Instance()
            #tmp (remove comment here) self.media = self.vlcInstance.media_new('/home/pi/code/' + self.VIDEO_FILE)
            self.media = self.vlcInstance.media_new(self.VIDEO_FILE)

            # Create new instance of vlc player
            self.player = self.vlcInstance.media_player_new()
            self.player.stop()

            # Pass pygame window id to vlc player, so it can render its contents there.
            win_id = pygameRef.display.get_wm_info()['window']
            self.player.set_xwindow(win_id)
            self.player.set_media(self.media)

            # TODO: correct the line below
            mouse.move(IMAGE_WIDTH, IMAGE_HEIGHT, True, 0)
        else:
            self.omx_stdin = None
            self.omx_process = None
            self.tot_sec = None

        self.STARTED = False
        self.PAUSED = False
        if (self.USING_VLC):
            print("VIDEOPLAYER: using VLC")
        else:
            print("VIDEOPLAYER: using OMX")

        # info about video
        self.info_video = {}
        self.chapters = self.get_chapters()
        self.curr_chapter = 0
        print('VIDEOPLAYER: info video \n\t# chapter:{}\n\t{}'.format(
            len(self.chapters), self.chapters))

    def start(self):
        print("VIDEOPLAYER: Starting video...")
        self.STARTED = True
        self.PAUSED = False

        if self.USING_VLC:
            self.player.play()
        else:
            if self.player:
                self.player.quit()
                self.player = None
            self.player = OMXPlayer(self.VIDEO_FILE, args=['--no-osd'])
        time.sleep(1)

    def stop(self):
        print("VIDEOPLAYER: Stopping video...")
        self.STARTED = False
        #TODO: is it necessary
        #self.PAUSED = True
        if self.USING_VLC:
            self.player.stop()
        else:
            self.player.quit()
            self.player = None

    def pause(self):
        print("VIDEOPLAYER: Pausing video...")
        # TODO: add some code here??
        #self.PAUSED = True #??

    def needUpdate(self):
        return (self.STARTED and self.player)

    def update(self):
        #print("VIDEOPLAYER: update")
        if self.USING_VLC:
            if self.player.get_length() - self.player.get_time(
            ) < 2000 and not self.PAUSED:
                print("VIDEOPLAYER VLC: a due secondi dalla fine")
                self.PAUSED = True
                self.player.set_pause(1)
        else:
            if self.player.duration() - self.player.position(
            ) < 2 and not self.PAUSED:
                print('VIDEOPLAYER OMX: a due secondi dalla fine')
                self.PAUSED = True
                self.player.pause()
        #self.printStatus()

    def printStatus(self):
        print("VIDEOPLAYER: started {}, paused {}".format(
            self.STARTED, self.PAUSED))

    def changeChapter(self, chapter):
        print("VIDEOPLAYER: change chapter")
        if chapter != 0:
            print("VIDEOPLAYER: chapter != 0")
            # in origin era così riga commentata)
            #if self.PAUSED == True:
            #if self.PAUSED == False:
            #print("VIDEOPLAYER: paused is true")
            if self.USING_VLC:
                self.player.set_pause(0)
            else:
                if self.player:
                    self.player.play()
            self.PAUSED = False

            if self.USING_VLC:
                self.handle_chapter_vlc(chapter)
            else:
                self.handle_chapter_omx(chapter)
        """
		if self.USING_VLC:
			if  self.player.get_length() - self.player.get_time() < 2000 and not self.PAUSED:
				self.PAUSED = True
				self.player.set_pause(1)
		else:
			if  self.player.duration() - self.player.position() < 2 and not self.PAUSED:
				print('...pausing video')
				self.PAUSED = True
				self.player.pause()
				
		"""
        """
		#not using language right now
		# return to italian language
		if self.audioPlayerRef:
			self.audioPlayerRef.switchToITA()
		"""

    def isPlaying(self):
        return self.STARTED

    def switch_language(self):
        print("Video: switch language...")
        if self.audioPlayerRef:
            self.audioPlayerRef.switchLanguage()
        if self.player:
            self.player.set_position(0)

    # get all chapters of video file
    def get_chapters(self):
        buff = sp.check_output([
            "ffmpeg", "-i", self.VIDEO_FILE, "-f", 'ffmetadata', "file.txt",
            '-y'
        ],
                               stderr=sp.STDOUT,
                               universal_newlines=True)
        #print(buff)
        self.chapters = []
        self.chapters_info = {}
        names = []
        i = 0
        for line in iter(buff.splitlines()):
            m = re.match(
                r".*Chapter #(\d+:\d+): start (\d+\.\d+), end (\d+\.\d+).*",
                line)
            if m != None and m.group(1) not in names:
                names.append(m.group(1))
                self.chapters.append({
                    "name": i + 1,
                    "start": float(m.group(2)),
                    "end": float(m.group(3))
                })
                i = i + 1
        if len(self.chapters) == 2:
            self.chapters[len(self.chapters) - 1]['name'] = 3
        return self.chapters

    # check where i am:
    # 0: before chapter 1
    # 1: chapter 1
    # 2: chapter 2
    # 3: chapter 3
    # 10 last chapter
    def pos2chapter(self, pos):
        # ~ print('actual position', pos)
        for x in self.chapters:
            if pos >= x['start'] / 1000 and pos <= x['end']:
                return x['name']
        if pos < self.chapters[0]['start']:
            return 0
        if pos > self.chapters[len(self.chapters) - 1]['end']:
            return self.chapters[len(self.chapters) - 1]['name']

    # vlc chapter manager
    def handle_chapter_vlc(self, c):
        print('VIDEOPLAYER VLC: going to', len(self.chapters), c)
        if len(self.chapters) == 2:
            if c == 3:
                print(1)
                self.player.set_chapter(1)
            if c == 1:
                print(2)
                self.player.set_chapter(0)
        else:
            self.player.set_chapter(c - 1)
        self.audioPlayerRef.stop()
        if c == 1:
            self.audioPlayerRef.start()
        self.curr_chapter = c

    # chapter manager
    def handle_chapter_omx(self, c):
        self.curr_chapter = self.pos2chapter(self.player.position())
        print('VIDEOPLAYER OMX: Handle chapter: from', self.curr_chapter, 'to',
              c)
        # ~ if c != curr_chapter and c in [f['name'] for f in chapters]:
        if c in [f['name'] for f in self.chapters]:
            cpt = self.chapters[[
                y for y, x in enumerate(self.chapters) if x['name'] == c
            ][0]]
            time.sleep(1)
            print('going to', cpt['start'])
            self.player.set_position(cpt['start'])
            time.sleep(1)
            self.audioPlayerRef.stop()
            if c == 1:
                self.audioPlayerRef.start()
            self.curr_chapter = c

    def kill(self):
        print("Kill video...")
        if self.USING_VLC:
            self.player.stop()
        else:
            self.player.quit()
            self.player = None
Exemplo n.º 24
0
def main():
    #print( "main" )
    global inputLen, prevInputLen, videoPlayer

    # Open video player
    try:
        print("MAIN: load the video ")
        videoPlayer = OMXPlayer(PATH_TO_VIDEO_FILE,
                                args=['--no-osd', '--adev', 'local'])
        #videoPlayer.set_volume( AUDIO_MIN_VOLUME )

        #2020-13-07 - we are not using VLC anymore :(
        # ~ videoPlayer = vlc.MediaPlayer( PATH_TO_VIDEO_FILE )
        #process = Popen( args, stdin=PIPE, stdout=PIPE )
        #print("This is the omxplayer process id: ",  process.pid )

    except Exception as exc:
        print("MAIN: something went wrong in creating the OMX video player {}".
              format(exc))
        quit()

    #2020-13-07 - we are not a separate thread anymore to check for the actual playhead position
    #checkPositionThread = threading.Thread(target=checkLength)
    #checkPositionThread.start()

    print("MAIN: video length {}".format(videoPlayer.duration()))

    if B_USE_VIDEO:
        videoPlayer.set_volume(AUDIO_MIN_VOLUME)
        # 2020-07-13 - no need to use fullscreen anymore
        # ~ videoPlayer.toggle_fullscreen() # use it to go fullscreen
        videoPlayer.play()

    # initialize Button manager
    buttonManager = ButtonManager(goToStart_CB, muteAudio_CB, polarity=False)

    # get the current number of connected input devices
    inputLen = getInputDevices()
    prevInputLen = inputLen

    # start the shutdown handler function.
    # It will take care of opening and listening on a socket
    # for a "shutdown message" in order to kill the python process
    # and shutdown the RaspberryPi
    shutdownHandlerThread = threading.Thread(target=shutdownHandler)
    shutdownHandlerThread.start()

    # Main loop
    while True:
        # check if someone plugged in a mouse or a keyboard
        if (areThereNewInputsDevices()):
            # if a new input device has been found, tthis very script
            # must be stopped in order to let space for the user to work
            # with the Pi, so...

            # quit video player
            videoPlayer.stop(
            )  # will exit current vlc window (desktop will be visible)

            # TODO: kill all alive thread
            # find a way to do this

            # exit the python script
            quit()
        else:
            buttonManager.update()
            #print("MAIN: position {}".format(position) )
            if B_USE_VIDEO:
                position = videoPlayer.position()
                if videoPlayer.duration() - position <= 1:
                    videoPlayer.set_position(0.0)
            time.sleep(0.1)
Exemplo n.º 25
0
measurements = []
lostDetectionCounterMax = lostInTime * 1000 / delay  #Iteration counts for deactivation
is_playing = False
if __name__ == '__main__':
    try:
        LD_Counter = 0
        while True:
            if (trigger(measurements, GPIO_TRIGGER, GPIO_ECHO)):
                LD_Counter = lostDetectionCounterMax

            if (LD_Counter):
                LD_Counter -= 1
                print("LD_Counter = %d " % LD_Counter) if _debug else True
                if (not is_playing):
                    player.set_alpha(100 if _debug else 255)
                    player.play()
                    print("Video has started")
                    is_playing = True
            else:
                if (is_playing):
                    print("Video has stopped")
                    player.set_position(0)
                    player.set_alpha(0)
                    position = player.position()
                    time.sleep(0.25)
                    print("player.position()", player.position())
                    player.pause()
                    is_playing = False

    # Reset by pressing CTRL + C
    except KeyboardInterrupt:
Exemplo n.º 26
0
player_action.pause()
sleep(2.5)
player_stop.pause()
try:
    while True:
         # Button was pressed
         
        if ( GPIO.input(button) == GPIO.LOW ):
            sleep(1)
            try:
                if (player_action.is_playing() == True):
                    player_action.stop()
                    sleep(1)
                    player_action = OMXPlayer(VIDEO_PATH, dbus_name='org.mpris.MediaPlayer2.omxplayer1')
                else:
                    player_action.play()
                    sleep(1)
            except:
                sleep(1)
                    
                
                
            
except KeyboardInterrupt:
    try:
        player_action.quit()
        player_stop.quit()
    except:
        pass
    pass
Exemplo n.º 27
0
# Create player 1
player1 = OMXPlayer(videos[0].path, dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=['--loop'])

player1.playEvent += lambda _: player_log.info("Play")
player1.pauseEvent += lambda _: player_log.info("Pause")
player1.stopEvent += lambda _: player_log.info("Stop")

player1.pause()
player1.hide_video()
player1.set_position(videos[0].start)
player1.set_volume(videos[0].volume)
player1.set_aspect_mode(videos[0].aspect)

# Show player 1
player1.show_video()
player1.play()

sleep(5)

# Load player 1 with video 2
player1.pause()
player1.hide_video()
player1.load(videos[1].path, pause=True)
player1.set_position(videos[1].start)
player1.set_volume(videos[1].volume)
player1.set_aspect_mode(videos[1].aspect)
player1.show_video()
player1.play()

sleep(5)
Exemplo n.º 28
0
class MusicPlayer():
    def __init__(self, playlist, logger):
        self.playlist = playlist
        self.idx = 0
        self.logger = logger
        self.omxplayer = None

    def get_song_real_url(self, song_url):
        try:
            htmldoc = urlopen(song_url).read().decode('utf8')
        except:
            return (None, None, 0, 0)

        content = json.loads(htmldoc)

        try:
            song_link = content['data']['songList'][0]['songLink']
            song_name = content['data']['songList'][0]['songName']
            song_size = int(content['data']['songList'][0]['size'])
            song_time = int(content['data']['songList'][0]['time'])
        except:
            self.logger.error('get real link failed')
            return (None, None, 0, 0)

        return song_name, song_link, song_size, song_time

    def play(self):
        self.logger.debug('MusicPlayer play')
        song_url = "http://music.baidu.com/data/music/fmlink?" +\
            "type=mp3&rate=320&songIds=%s" % self.playlist[self.idx]['id']
        song_name, song_link, song_size, song_time =\
            self.get_song_real_url(song_url)

        self.play_mp3_by_link(song_link, song_name, song_size, song_time)

    def play_mp3_by_link(self, song_link, song_name, song_size, song_time):
        if song_link:
            self.omxplayer = OMXPlayer(song_link, ['-o', 'both'])
        else:
            self.omxplayer = None

    def pick_next(self):
        self.idx += 1
        if self.idx > len(self.playlist) - 1:
            self.idx = 0

        if self.omxplayer and self.omxplayer.can_play():
            self.omxplayer.quit()

    def pick_previous(self):
        self.idx -= 1
        if self.idx < 0:
            self.idx = 0

        if self.omxplayer and self.omxplayer.can_play():
            self.omxplayer.quit()

    def pause(self):
        if self.omxplayer and self.omxplayer.can_pause():
            self.omxplayer.pause()

    def resume(self):
        if self.omxplayer and self.omxplayer.can_play():
            self.omxplayer.play()

    def is_play_done(self):
        try:
            return self.omxplayer is None or\
                self.omxplayer.can_play() is None
        except Exception as e:
            self.logger.error(e)
            return False

    def stop(self):
        self.playlist = []
        if self.omxplayer:
            self.omxplayer.quit()
Exemplo n.º 29
0
class Player:

    def __init__(self, video_file):
        self.player = None
        self.path = ''
        self.load(video_file)

    def load(self, video_file):
        print('Player loading {0}'.format(video_file))
        #if self.player != None:
        #    self.player.stop()
        #    del self.player
        self.path = os.path.join(media_dir, video_file)
        if self.player is None:
            self.player = OMXPlayer(self.path, args=['--loop', '--blank', '-o', 'both'])
        else:
            self.player.load(self.path)
        self.player.stopEvent += lambda _: self._complete()
        self.player.pauseEvent += lambda _: self._pauseEvent()
        self.player.playEvent += lambda _: self._playEvent()
        self.player.positionEvent += lambda _: self._positionEvent()
        self.player.seekEvent += lambda _: self._seekEvent()

    def _complete(self):
        print('Playback finished.')
   
    def _pauseEvent(self):
        print('Player pause event.')
   
    def _playEvent(self):
        print('Player play event.')

    def _positionEvent(self):
        print('Player position event.')

    def _positionEvent(self):
        print('Player seek event.')

    def set_pause(self, p):
        if p:
            self.player.pause()
        else:
            self.player.play()

    def get_pause(self):
        if self.player.is_playing():
            return False
        else:
            return True

    def toggle_pause(self):
        if self.player.is_playing():
            self.player.pause()
        else:
            self.player.play()

    def stop(self):
        self.player.stop()

    def quit(self):
        self.player.quit()

    def reload(self):
        print('Reloading {0}'.format(self.path))
        self.load(self.path)

    def get_path(self):
        return self.path
Exemplo n.º 30
0
class OmxPlayer(BasePlayer):
    def __init__(self, hplayer, name):
        super().__init__(hplayer, name)

        self._validExt = [
            'mp4', 'm4v', 'mkv', 'avi', 'mov', 'flv', 'mpg', 'wmv', '3gp',
            'mp3', 'aac', 'wma', 'wav', 'flac', 'aif', 'aiff', 'm4a', 'ogg',
            'opus', 'webm', 'jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff'
        ]

        self._thread = None
        self._runflag = threading.Event()
        self.player = None

    ############
    ## private METHODS
    ############

    # MPV THREAD
    def _mpv_thread(self):

        self.emit('player-ready')
        self.emit('status', self.status())

        self.log("player ready")

        while self.isRunning():

            self._runflag.wait(0.37)
            if self._runflag.isSet():
                self.update('time', round(self.player.position(), 2))
                time.sleep(0.05)

        self.isRunning(False)
        return

    def _onPlay(self, p):
        self.update('isPlaying', True)
        self.update('isPaused', False)
        self.emit('playing')
        self._runflag.set()
        self.log('play')

    def _onPause(self, p):
        self.update('isPlaying', False)
        self.update('isPaused', True)
        self.emit('paused')
        self._runflag.clear()
        self.log('pause')

    def _onExit(self, p, c):
        self.player._connection._bus.close()
        self.player._connection = None
        self.player = None
        self._runflag.clear()
        self.update('isPlaying', False)
        self.update('isPaused', False)
        self.emit('end')
        self.emit('stopped')
        self.log('stop')

    ##########
    ## Inherited "abstract" METHODS overloads
    ##########

    #
    # Start the player:
    #   - instantiate mpv subprocess
    #   - connect IPC socket i/o
    #
    def _start(self):

        # Playback thread
        self._thread = threading.Thread(target=self._mpv_thread)
        self._thread.start()

    #
    # Exit the player
    #   - stop subprocess
    #   - close IPC socket
    #
    def _quit(self):
        self.isRunning(False)
        if self._thread:
            # self.log("stopping process thread")
            self._thread.join()
        self.log("stopped")

    def _play(self, path):
        self.log("play", path)

        if self.player:
            self.player.quit()

        self.player = OMXPlayer(path,
                                dbus_name='org.mpris.MediaPlayer2.omxplayer2')
        self.player.playEvent += self._onPlay
        self.player.pauseEvent += self._onPause
        # self.player.stopEvent += self._onStop
        self.player.exitEvent += self._onExit
        self.player.play()
        # self.player.set_video_pos(0,0,100,100)

        # self.update('duration', round(self.player.duration(),2))

    def _stop(self):
        if self.player:
            self.player.stop()

    def _pause(self):
        if self.player:
            self.player.pause()

    def _resume(self):
        if self.player:
            self.player.play()

    def _seekTo(self, milli):
        if self.player:
            self.player.set_position(milli / 1000)
        # self.log("seek to", milli/1000)

    def _skip(self, milli):
        if self._status['time'] + milli / 1000 < self._status['duration']:
            if self.player:
                self.player.seek(milli / 1000)
        # self.log("skip", milli/1000)

    def _applyVolume(self, volume):
        if self.player:
            self.player.set_volume(volume / 10.0)
        self.log("VOLUME to", volume)
Exemplo n.º 31
0
class Video(Player):
    """Video player class."""
    def __init__(self):
        """Init as Player."""
        super(Video, self).__init__()
        self.logger = logging.getLogger("oxo")
        self.close_player = False
        self.stopped = False

    @classmethod
    def filepath(cls, clip):
        """Return disk location of a clip."""
        return os.path.join(DATA_DIR, "clips", clip["filename"])

    def run(self):
        """Thread target."""
        while not self.stopped:
            current_clip = Video.get_next()
            if current_clip is None:
                self.logger.debug("No clips in database. Waiting...")
                sleep(5)
            else:
                self.logger.debug(
                    "Starting video player with clip [{}]".format(
                        current_clip["filename"][:6]))

                full_path = self.filepath(current_clip)

                if machine() == "armv7l":
                    player_args = [
                        '--blank', '-o', 'hdmi', '--loop', '--no-osd',
                        '--aspect-mode', 'fill', '--win', "'0, 0, 810, 540'"
                    ]
                else:
                    player_args = ['-b', '--loop']

                if self.player is None:
                    self.player = OMXPlayer(full_path, player_args)
                else:
                    self.player.load(full_path, player_args)
                    self.player.play()

                sleep(5)
                self.player.pause()
        self.logger.debug("Exit video player")

    @classmethod
    def interact(cls, line, stdin):
        """Enqueue clips continuously through mplayer STDIN."""
        start_playback = "Starting playback..."

        logger = logging.getLogger("oxo")
        if start_playback in line:
            nextclip = cls.get_next()
            path = cls.filepath(nextclip)
            cmd = "loadfile {} 1\n".format(path)
            logger.info("Enqueued clip {}".format(nextclip['filename']))
            stdin.put(cmd)

    @classmethod
    def get_next(cls):
        """Select recently added video or a random one from db."""
        q = Query()
        q_incoming = db.search(q.incoming == True)
        if len(q_incoming) > 0:
            rv = q_incoming[0]
            db.update({"incoming": False}, q.incoming == True)
            logger.info("Enqueuing shortlisted clip {}".format(rv["filename"]))
        else:
            q = Query()
            try:
                q_clips = db.search(q.type == "clip")
            except JSONDecodeError:
                rv = None
            else:
                rv = choice(q_clips) if len(q_clips) > 0 else None
        return rv

    def stop(self):
        """Quit omxplayer instance."""
        self.logger.debug("Stopping {} player...".format(
            self.__class__.__name__))
        self.stopped = True
        if self.running:
            self.player.quit()
            self.logger.info("{} stopped".format(self.__class__.__name__))
        else:
            self.logger.debug("{} did not play".format(
                self.__class__.__name__))
Exemplo n.º 32
0
class VideoPlayer(object):
    def __init__(self):
        self.player = None
        self.logger = LogObject('Video Player')
        self.args = ['-b']

        self.STATUS_MAP = {
            'volume': self._videoVolume,
            'length': self._videoLength,
            'playback': self._playbackStatus,
            'position': self._videoPosition
        }

        self.CONTROL_MAP = {
            'playpause': self._playPause,
            'stop': self._stop,
            'mute': self._mute,
            'unmute': self._unmute,
            'play': self._play,
            'pause': self._pause
        }

        self.SEEK_MAP = {'relative': self._seek, 'absolute': self._setPosition}

    def playUrl(self, url):

        if not self.player:
            self.player = OMXPlayer(url, args=self.args)
        else:
            self.player.load(url)

    def setVolume(self, volume):
        self._checkPlayerExist()
        try:
            self.player.set_volume(volume)
            return self.logger.writeAndReturnLog('VOL0003', {'volume': volume})
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('VOL0004')

    def sendCommand(self, command):
        self._checkPlayerExist()
        try:
            return self.CONTROL_MAP[command]()
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('CTRL0003')

    def _stop(self):
        self.player.quit()
        return self.logger.writeAndReturnLog('CTRL0004')

    def _mute(self):
        self.player.mute()
        return self.logger.writeAndReturnLog('CTRL0006')

    def _unmute(self):
        self.player.unmute()
        return self.logger.writeAndReturnLog('CTRL0007')

    def _playPause(self):
        self.player.play_pause()
        return self.logger.writeAndReturnLog('CTRL0005')

    def _play(self):
        self.player.play()
        return self.logger.writeAndReturnLog('CTRL0008')

    def _pause(self):
        self.player.pause()
        return self.logger.writeAndReturnLog('CTRL0009')

    def seek(self, option, time):
        self._checkPlayerExist()
        try:
            return self.SEEK_MAP[option](time)
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('SEEK0007')

    def _seek(self, seekTime):
        self.player.seek(seekTime)
        return self.logger.writeAndReturnLog('SEEK0005',
                                             {'position': seekTime})

    def _setPosition(self, position):
        if position > self._videoLength() or position < 0:
            self._raisePlayerError('SEEK0004', {'position': position})
        self.player.set_position(position)
        return self.logger.writeAndReturnLog('SEEK0006',
                                             {'position': position})

    def _checkPlayerExist(self):
        if not self.player:
            self._raisePlayerError('CTRL0003')

    def videoStatus(self, status):
        if not self.player:
            self._raisePlayerError('STAT0003')
        try:
            return self.STATUS_MAP[status]()
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('STAT0003')

    def _videoPosition(self):
        return self.player.position()

    def _videoLength(self):
        return self.player.duration()

    def _videoVolume(self):
        return self.player.volume()

    def _playbackStatus(self):
        return self.player.playback_status()

    def _raisePlayerError(self, logReference, variablesDict={}):
        returnMsg = self.logger.writeAndReturnLog(logReference, variablesDict)
        raise PlayerError(returnMsg)
Exemplo n.º 33
0
from pathlib import Path
from time import sleep
import logging
#import RPi.GPIO as GPIO

#GPIO.setmode (GPIO.BOARD)
#GPIO.setwarnings (False)

VIDEO_PATH = "/home/pi/Desktop/elephant.mp4"
player_log = logging.getLogger("Player1")


intro = OMXPlayer(VIDEO_PATH, ['-o', 'local'], dbus_name='org.mpris.MediaPlayer2.omxplayer1')

intro.playEvent += lambda _: player_log.info("Play")
intro.pauseEvent += lambda _: player_log.info("Pause")
intro.stopEvent += lambda _: player_log.info("Stop")

sleep(2.5)

intro.set_position(5)
intro.pause()

sleep(1)
intro.set_aspect_mode("letterbox")
intro.set_video_pos(50,100,1000,1000)

intro.play()

sleep(5)
intro.quit()
Exemplo n.º 34
0
class OmxPlayer():
    def __init__(self):
        self.player = None
        self.paired = False
        self.masterIp = None
        self.audio_volume = 100.0

    # omxplayer callbacks

    def posEvent(self, a, b):
        print('Position event!' + str(a) + " " + str(b))
        # print('Position: ' + str(player.position()) + "s")
        return

    def seekEvent(self, a, b):
        print('seek event! ' + str(b))
        return

    def triggerStart(self, pathToTrack, withPause=False):
        # lrpi_player#105
        # Audio output can be routed through hdmi or the jack,
        # if settings.json is corrupted, default to the hdmi

        settings_json = settings.get_settings()
        output_route = settings_json.get("audio_output")
        normalised_output_route = 'hdmi'
        omxArgs = []

        if output_route == 'hdmi':
            normalised_output_route = 'hdmi'
            omxArgs += ['-w', '--layout', '5.1']
        elif output_route == 'jack':
            normalised_output_route = 'local'

        omxArgs += ['-o', normalised_output_route]

        print('OUTPUT: ' + normalised_output_route)
        print('Full playing args: ' + str(omxArgs))

        if not withPause:
            self.player = OMXPlayer(
                pathToTrack,
                args=omxArgs,
                dbus_name='org.mpris.MediaPlayer2.omxplayer0')
            sleep(0.25)
        elif withPause:
            self.player = OMXPlayer(
                pathToTrack,
                args=omxArgs,
                dbus_name='org.mpris.MediaPlayer2.omxplayer0',
                pause=True)
            # Might need to set the volume to 0 a different way,
            # for some tracks omxplayer plays a short, sharp, shock
            # before setting the volume to 0
            self.player.set_volume(0)
            sleep(0.5)

    def primeForStart(self, pathToTrack):
        self.triggerStart(pathToTrack, withPause=True)

    def start(self, pathToTrack, syncTimestamp=None, master=False):
        print("Playing on omx... :", master)
        print("\n")
        print(pathToTrack)

        settings_json = settings.get_settings()
        volume = settings_json.get("audio_volume")

        try:
            if not master:
                if self.player:
                    self.player.quit()
                self.player = None

            if syncTimestamp:
                pause.until(syncTimestamp)

            if self.player is None or syncTimestamp is None:
                self.triggerStart(pathToTrack)

            self.player.positionEvent += self.posEvent
            self.player.seekEvent += self.seekEvent
            # self.player.set_position(0)

            if volume is not None:
                self.audio_volume = volume
                print("Volume set to %s" % self.audio_volume)

            self.player.set_volume(float(self.audio_volume) / 100.0)

            print('synctime in omxplayer: ', ctime(syncTimestamp))
            if master:
                self.player.play()
            return str(self.player.duration())
        except Exception as e:
            print(
                "ERROR: Could not start player... but audio may still be playing!"
            )
            print("Why: ", e)
            print("returning position 0...")
            return str(0)

    # action 16 is emulated keypress for playPause
    def playPause(self, syncTimestamp=None):
        print("Playpausing with syncTimeStamp: ", syncTimestamp)
        if syncTimestamp:
            pause.until(syncTimestamp)
        self.player.action(16)
        return str(self.player.duration())

    def getPosition(self):
        return self.player.position()

    def getDuration(self):
        return str(self.player.duration())

    def mute(self):
        print(self.player.volume())
        self.player.mute()

    def volumeUp(self):
        print("upper: ", self.player.volume())
        self.player.set_volume(self.player.volume() + 0.1)

    def volumeDown(self, interval):
        # If we're right at the end of the track, don't try to
        # lower the volume or else dbus will disconnect and
        # the server will look at though it's crashed

        if self.player.duration() - self.player.position() > 1:
            print("omx downer: ", self.player.volume())
            if (self.player.volume() <= 0.07 or interval == 0):
                return False
            else:
                self.player.set_volume(self.player.volume() -
                                       ((1.0 / interval) / 4.0))
                return True
        return False

    def seek(self, position, syncTimestamp=None):
        if self.player.can_seek():
            self.player.set_position(self.player.duration() *
                                     (position / 100.0))
        return self.player.duration() * (position / 100.0)

    def status(self, status):
        if self.player != None:
            print('status requested from omxplayer!')
            try:
                status["source"] = self.player.get_source()
                status["playerState"] = self.player.playback_status()
                status["canControl"] = self.player.can_control()
                status["position"] = self.player.position()
                status["trackDuration"] = self.player.duration()
                status["error"] = ""
            except Exception as e:
                status["playerState"] = ""
                status["canControl"] = False
                status[
                    "error"] = "Something went wrong with player status request: " + str(
                        e)

        else:
            status["playerState"] = ""
            status["canControl"] = False
            status["error"] = "Player is not initialized!"

        status["paired"] = self.paired
        status["master_ip"] = self.masterIp

        return status

    def setPaired(self, val, masterIp):
        self.paired = val
        self.masterIp = masterIp
        print('paired set to: ', val)
        print('master_ip set to: ', masterIp)

    def exit(self, syncTimestamp=None):
        if syncTimestamp:
            pause.until(syncTimestamp)

        if self.player:
            self.player.quit()
            self.__del__()
            killOmx()
        else:
            return 1

    def __del__(self):
        if self.player:
            self.player.quit()
        self.player = None
        killOmx()
        print("OMX died")