Beispiel #1
0
class Scanner:
    def __init__(self, path, ref_pos, regions, offset = 0):
        self.vp = VideoPlayer(path, False, gBlur = True)
        self.vp.seek(ref_pos)
        self.ref = self.vp.frame
        self.vp.seek(offset)
        self.regions = regions

    def release(self):
        self.vp.release()
        
    def step(self, msec=500):
        ret = self.vp.step(msec)
        if ret:
            self.vp.draw()
        return ret

    def score( self ):
        pixel_sum = 0
        pixel_count = 0
        for r in self.regions:
            ref_crop = self.ref[r[0][1]:r[1][1], r[0][0]:r[1][0]]
            ref_crop = cv.cvtColor(ref_crop, cv.COLOR_BGR2GRAY)
            crop = self.vp.frame[r[0][1]:r[1][1], r[0][0]:r[1][0]]
            crop = cv.cvtColor(crop, cv.COLOR_BGR2GRAY)
            crop = cv.absdiff(ref_crop, crop)
            #a, crop = cv.threshold(crop, 95, 255, cv.THRESH_BINARY)
            a, crop = cv.threshold(crop, 95, 1, cv.THRESH_BINARY)
            pixel_sum += crop.sum()
            pixel_count += crop.shape[0] * crop.shape[1]
            #print( "pixel_data:({0:.2f},{1:.2f}".format(pixel_sum, pixel_count))

        #First tried returning the average. 
        return (pixel_sum/pixel_count) * 100
Beispiel #2
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.timer = QtCore.QTimer()
     self.timer.timeout.connect(self.nextFrame)
     self.image = QImage()
     self.video = VideoPlayer()
     self.frame_counter = 0
     self.parent = parent
     self.status = self.STATUS_NOT_LOADED
     self.play_speed = 1.0
     self.updateRate = 24
Beispiel #3
0
    def loadVideo(self,
                  libraryName,
                  songName,
                  songVideo=None,
                  songVideoStartTime=None,
                  songVideoEndTime=None):
        if not videoAvailable:
            raise NameError('Video (gstreamer) is not available!')
        self.vidSource = None
        if self.songStage == 1:
            songAbsPath = os.path.join(libraryName, songName)
            if songVideo is not None and \
                   os.path.isfile(os.path.join(songAbsPath, songVideo)):
                self.vidSource = os.path.join(songAbsPath, songVideo)
            elif os.path.exists(os.path.join(songAbsPath, "default.avi")):
                Log.warn("Video not found: %s" % \
                         os.path.join(songAbsPath, songVideo))
                self.vidSource = os.path.join(songAbsPath, "default.avi")
        if self.vidSource is None:
            if self.songStage == 1:
                Log.warn("Video not found: %s" % \
                         os.path.join(songAbsPath, "default.avi"))
            songVideoStartTime = None
            songVideoEndTime = None
            self.vidSource = os.path.join(self.pathfull, "default.avi")

        if not os.path.exists(self.vidSource):
            Log.warn("Video not found: %s" % \
                     os.path.join(self.pathfull, "default.avi"))
            Log.warn(
                "No video found, fallbacking to default static image mode for now"
            )
            self.mode = 1  # Fallback
            self.vidSource = None
            return

        winWidth, winHeight = (self.engine.view.geometry[2],
                               self.engine.view.geometry[3])
        Log.debug("Attempting to load video: %s" % self.vidSource)
        try:  # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % self.vidSource)
            self.vidPlayer = VideoPlayer(-1,
                                         self.vidSource, (winWidth, winHeight),
                                         mute=True,
                                         loop=True,
                                         startTime=songVideoStartTime,
                                         endTime=songVideoEndTime)
            self.engine.view.pushLayer(self.vidPlayer)
            self.vidPlayer.paused = True
        except:
            self.mode = 1
            Log.warn("Failed to load video, fallback to default stage mode.")
Beispiel #4
0
class Experiment():
    def __init__(self):
        logging.info('Init Experiment...')
        self.player = VideoPlayer()
        self.tracker = Tracker()
        self.tracker.start()
        pass

    def start_from_i(self, index, name, is_male, age):
        get_gender = lambda b: 'male' if b else 'female'
        userID = str(name) + get_gender(is_male) + str(
            age) + datetime.now().strftime('_%m%d%H%M%S')
        self.player.set_userID(userID)
        self.tracker.set_userID(userID)
        for i in range(index, self.player.video_sum):
            self.tracker.start_track_video_i(i)
            time.sleep(0.5)
            self.player.play_i(i)
            frame_sum, frame_failed = self.tracker.stop_current_track()
            if float(frame_failed) / frame_sum > 0.1:
                self.player.show_attention()
        self.player.stop()

    def start(self, name, is_male=True, age=22):
        self.start_from_i(0, name, is_male, age)
 def init_ui(self):
     self.setWindowTitle(u'Projeto - ' + self.project.name)
     self.setFixedSize(self.size())
     
     player_holder = self.ui.player_widget
     layout = QtGui.QVBoxLayout()
     self.player = VideoPlayer()
     layout.addWidget(self.player)
     player_holder.setLayout(layout)
     
     #self.player.ui.seek_slider.mouse_released.connect(self.update_time_edit)
     
     self.ui.frame_edit.setVisible(False)
     
     self.ui.btn_choose_video.clicked.connect(self.choose_video)
     
     self.ui.btn_add_annotation.clicked.connect(self.add_annotation)
     #self.ui.btn_delete.clicked.connect(self.delete_annotation)
     #self.ui.btn_edit.clicked.connect(self.edit_annotation)
     self.annotation_list_chaged.connect(self.update_annotation_list)
     self.ui.txt_description.textChanged.connect(self.description_changed)
     #self.ui.list_notes.doubleClicked.connect(self.click_over_list)
     
     #self.player.mediaObject().tick.connect(self.update_time_edit)
     self.ui.time_edit.timeChanged.connect(self.editing_time)
     self.ui.time_edit.installEventFilter(self)
     
     self.ui.btn_save_project.clicked.connect(self.save_project)
     self.ui.btn_generate_ncl.clicked.connect(self.generate_ncl)
     self.ui.btn_generate_ncl.setText(u"Gerar e Exibir")
     self.ui.btn_close_project.clicked.connect(self.close_project)
     self.ui.btn_generate_ncl.setEnabled(True)
     
     self.ui.btn_ok.clicked.connect(self.save_edit)
     self.ui.btn_cancel.clicked.connect(self.cancel_edit)
Beispiel #6
0
 def watch(self):
     '''Plays a video after the download'''
     file = QFileDialog.getOpenFileName(self, "Open", self.output,
                                        "mp4 file (*.mp4)")
     file_name = file[0]
     newWidget = VideoPlayer(file_name)
     self.ui.sw_player.addWidget(newWidget)
     self.ui.sw_player.setCurrentWidget(newWidget)
Beispiel #7
0
 def testVideoPlayerLayer(self):
   config = Config.load(Version.appName() + ".ini", setAsDefault = True)
   self.e = GameEngine(config)
   winWidth, winHeight = (self.e.view.geometry[2], self.e.view.geometry[3])
   vidPlayer = VideoPlayer(framerate, self.src, (winWidth, winHeight),
                           loop = False)
   self.e.view.pushLayer(vidPlayer)
   while not vidPlayer.finished:
     self.e.run()
   self.e.view.popLayer(vidPlayer)
   self.e.audio.close()
   self.e.quit()
def main_routine():
    vp = VideoPlayer()
    while True:
        mag_switch = GPIO.input(23)
        if mag_switch:
            if not vp.video_is_playing:
                GPIO.output(24, 0)
                check_for_current()
                global current_video
                vp.set_video(UPLOAD_FOLDER + current_video)
                vp.play_video()
        else:
            GPIO.output(24, 1)
            vp.stop_video()
Beispiel #9
0
 def testVideoPlayerLayer(self):
     config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini",
                          setAsDefault=True)
     self.e = GameEngine(config)
     winWidth, winHeight = (self.e.view.geometry[2],
                            self.e.view.geometry[3])
     vidPlayer = VideoPlayer(framerate,
                             self.src, (winWidth, winHeight),
                             loop=False,
                             startTime=10000,
                             endTime=14000)
     self.e.view.pushLayer(vidPlayer)
     while not vidPlayer.finished:
         self.e.run()
     self.e.view.popLayer(vidPlayer)
     self.e.audio.close()
     self.e.quit()
Beispiel #10
0
  def testVideoPlayerSlaveShowOff(self):
    winWidth, winHeight = 500, 500
    pygame.init()
    flags = DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE
    pygame.display.set_mode((winWidth, winHeight), flags)
    vidPlayer = VideoPlayer(-1, self.src, (winWidth, winHeight))
    glViewport(0, 0, winWidth, winHeight) # Both required as...
    glScissor(0, 0, winWidth, winHeight)  # ...GameEngine changes it
    glClearColor(0, 0, 0, 1.)
    x, y = 0.0, 1.0
    fx, fy, ftheta = 1, 1, 1
    theta = 0.0
    time = 0.0
    clock = pygame.time.Clock()
    while not vidPlayer.finished:
      vidPlayer.run()
      vidPlayer.textureUpdate()
      # Save and clear both transformation matrices
      glMatrixMode(GL_PROJECTION)
      glPushMatrix()
      glLoadIdentity()
      glMatrixMode(GL_MODELVIEW)
      glPushMatrix()
      glLoadIdentity()

      glClear(GL_COLOR_BUFFER_BIT)
      glColor3f(1., 1., 1.)
      glBindTexture(GL_TEXTURE_2D, vidPlayer.videoTex)
      glTranslatef(x, y, 0)
      glRotatef(theta, 0, 0, 1.)
      glScalef(.5, .5, 1.)
      glCallList(vidPlayer.videoList)

      # Restore both transformation matrices
      glPopMatrix()
      glMatrixMode(GL_PROJECTION)
      glPopMatrix()

      pygame.display.flip()

      x = (x + fx*time)
      y = (y + fy*time)
      theta = theta + ftheta
      if x > 1.0 or x < -1.0:
        fx = fx * -1
      if y > 1.0 or y < -1.0:
        fy = fy * -1
      if theta > 90 or theta < -90:
        ftheta = ftheta * -1
      time = time + 0.00001
      clock.tick(60)
    pygame.quit()
Beispiel #11
0
  def loadVideo(self, libraryName, songName, songVideo = None,
                songVideoStartTime = None, songVideoEndTime = None):
    if not videoAvailable:
      raise NameError('Video (gstreamer) is not available!')
    self.vidSource = None
    if self.songStage == 1:
      songAbsPath = os.path.join(libraryName, songName)
      if songVideo is not None and \
             os.path.isfile(os.path.join(songAbsPath, songVideo)):
        self.vidSource = os.path.join(songAbsPath, songVideo)
      elif os.path.exists(os.path.join(songAbsPath, "default.avi")):
        Log.warn("Video not found: %s" % \
                 os.path.join(songAbsPath, songVideo))
        self.vidSource = os.path.join(songAbsPath, "default.avi")
    if self.vidSource is None:
      if self.songStage == 1:
        Log.warn("Video not found: %s" % \
                 os.path.join(songAbsPath, "default.avi"))
      songVideoStartTime = None
      songVideoEndTime = None
      self.vidSource = os.path.join(self.pathfull, "default.avi")

    if not os.path.exists(self.vidSource):
      Log.warn("Video not found: %s" % \
               os.path.join(self.pathfull, "default.avi"))
      Log.warn("No video found, fallbacking to default static image mode for now")
      self.mode = 1 # Fallback
      self.vidSource = None
      return
      
    winWidth, winHeight = (self.engine.view.geometry[2],
                           self.engine.view.geometry[3])
    Log.debug("Attempting to load video: %s" % self.vidSource)
    try: # Catches invalid video files or unsupported formats
      Log.debug("Attempting to load video: %s" % self.vidSource)
      self.vidPlayer = VideoPlayer(-1, self.vidSource, (winWidth, winHeight),
                                   mute = True, loop = True,
                                   startTime = songVideoStartTime,
                                   endTime = songVideoEndTime)
      self.engine.view.pushLayer(self.vidPlayer)
      self.vidPlayer.paused = True
    except:
      self.mode = 1
      Log.warn("Failed to load video, fallback to default stage mode.")
Beispiel #12
0
 def testVideoPlayerSlave(self):
     winWidth, winHeight = 800, 600
     pygame.init()
     flags = DOUBLEBUF | OPENGL | HWPALETTE | HWSURFACE
     pygame.display.set_mode((winWidth, winHeight), flags)
     vidPlayer = VideoPlayer(self.e, framerate, self.src,
                             (winWidth, winHeight))
     glViewport(0, 0, winWidth,
                winHeight)  # Required as GameEngine changes it
     font = self.e.data.font
     while not vidPlayer.finished:
         vidPlayer.run()
         vidPlayer.render()
         pygame.display.flip()
Beispiel #13
0
 def testVideoPlayerSlave(self):
   winWidth, winHeight = 800, 600
   pygame.init()
   flags = DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE
   pygame.display.set_mode((winWidth, winHeight), flags)
   vidPlayer = VideoPlayer(framerate, self.src, (winWidth, winHeight))
   glViewport(0, 0, winWidth, winHeight) # Both required as...
   glScissor(0, 0, winWidth, winHeight)  # ...GameEngine changes it
   glClearColor(0, 0, 0, 1.)
   while not vidPlayer.finished:
     vidPlayer.run()
     vidPlayer.render()
     pygame.display.flip()
   pygame.quit()
Beispiel #14
0
def main():
    playing = None
    configFile = None
    fullscreen = None
    resolution = None
    theme = None
    debug = False
    difficulty = None
    part = None
    mode = 0
    nbrplayers = 1
    for opt, arg in opts:
        if opt in ["--verbose", "-v"]:
            Log.quiet = False
        if opt in ["--config", "-c"]:
            configFile = arg
        if opt in ["--fullscreen", "-f"]:
            fullscreen = arg
        if opt in ["--resolution", "-r"]:
            resolution = arg
        if opt in ["--theme", "-t"]:
            theme = arg
        if opt in ["--song", "-s"]:
            playing = arg
        if opt in ["--part", "-p"]:
            part = arg
        if opt in ["--diff", "-d", "-l"]:
            difficulty = arg
        #evilynux - Multiplayer and mode selection support
        if opt in ["--mode", "-m"]:
            mode = int(arg)
        if opt in ["--nbrplayers", "-n"]:
            nbrplayers = int(arg)

    # Load the configuration file.
    if configFile is not None:
        if configFile.lower() == "reset":
            fileName = os.path.join(Resource.getWritableResourcePath(),
                                    Version.PROGRAM_UNIXSTYLE_NAME + ".ini")
            os.remove(fileName)
            config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini",
                                 setAsDefault=True)
        else:
            config = Config.load(configFile, setAsDefault=True)
    else:
        config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini",
                             setAsDefault=True)

    #Lysdestic - Allow support for manipulating fullscreen via CLI
    if fullscreen is not None:
        Config.set("video", "fullscreen", fullscreen)

    #Lysdestic - Change resolution from CLI
    if resolution is not None:
        Config.set("video", "resolution", resolution)

    #Lysdestic - Alter theme from CLI
    if theme is not None:
        Config.set("coffee", "themename", theme)

    engine = GameEngine(config)
    engine.cmdPlay = 0

    # Check for a valid invocation of one-shot mode.
    if playing is not None:
        Log.debug('Validating song directory for one-shot mode.')
        library = Config.get("game", "base_library")
        basefolder = os.path.join(Version.dataPath(), library, "songs",
                                  playing)
        if not (os.path.exists(os.path.join(basefolder, "song.ini")) and
                (os.path.exists(os.path.join(basefolder, "notes.mid"))
                 or os.path.exists(
                     os.path.join(basefolder, "notes-unedited.mid"))) and
                (os.path.exists(os.path.join(basefolder, "song.ogg"))
                 or os.path.exists(os.path.join(basefolder, "guitar.ogg")))):
            Log.warn(
                "Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                % playing)
            engine.startupMessages.append(
                _("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                  ) % playing)
            playing = None

    # Set up one-shot mode if the invocation is valid for it.
    if playing is not None:
        Log.debug('Entering one-shot mode.')
        Config.set("game", "selected_library", "songs")
        Config.set("game", "selected_song", playing)
        engine.cmdPlay = 1
        if difficulty is not None:
            engine.cmdDiff = int(difficulty)
        if part is not None:
            engine.cmdPart = int(part)
        #evilynux - Multiplayer and mode selection support
        Config.set("game", "players", nbrplayers)
        if nbrplayers == 1:
            Config.set("game", "game_mode", mode)
        else:
            Config.set("game", "game_mode", 0)
            Config.set("game", "multiplayer_mode", mode)

    encoding = Config.get("game", "encoding")
    if encoding is not None:
        #stump: XXX: Everything I have seen indicates that this is a
        # horrible, horrible hack.  Is there another way?  Do we even need this?
        reload(sys)
        sys.setdefaultencoding(encoding)

    # Play the intro video if it is present, we have the capability, and
    # we are not in one-shot mode.
    videoLayer = False
    if videoAvailable and not engine.cmdPlay:
        # TODO: Parameters to add to theme.ini:
        #  - intro_video_file
        #  - intro_video_start_time
        #  - intro_video_end_time
        themename = Config.get("coffee", "themename")
        vidSource = os.path.join(Version.dataPath(), 'themes', themename, \
                                 'menu', 'intro.avi')
        if os.path.isfile(vidSource):
            winWidth, winHeight = engine.view.geometry[2:4]
            songVideoStartTime = 0
            songVideoEndTime = None
            vidPlayer = VideoPlayer(-1,
                                    vidSource, (winWidth, winHeight),
                                    startTime=songVideoStartTime,
                                    endTime=songVideoEndTime)
            if vidPlayer.validFile:
                engine.view.pushLayer(vidPlayer)
                videoLayer = True
                try:
                    engine.ticksAtStart = pygame.time.get_ticks()
                    while not vidPlayer.finished:
                        engine.run()
                    engine.view.popLayer(vidPlayer)
                    engine.view.pushLayer(MainMenu(engine))
                except KeyboardInterrupt:
                    engine.view.popLayer(vidPlayer)
                    engine.view.pushLayer(MainMenu(engine))
    if not videoLayer:
        engine.setStartupLayer(MainMenu(engine))

    #stump: make psyco optional
    if Config.get("performance", "use_psyco"):
        try:
            import psyco
            psyco.profile()
        except:
            Log.error("Unable to enable psyco as requested: ")

    # Run the main game loop.
    try:
        engine.ticksAtStart = pygame.time.get_ticks()
        while engine.run():
            pass
    except KeyboardInterrupt:
        Log.notice("Left mainloop due to KeyboardInterrupt.")
        # don't reraise

    # Restart the program if the engine is asking that we do so.
    if engine.restartRequested:
        Log.notice("Restarting.")
        engine.audio.close()
        try:
            # Extra arguments to insert between the executable we call and our
            # command line arguments.
            args = []
            # Figure out what executable to call.
            if hasattr(sys, "frozen"):
                if os.name == "nt":
                    # When py2exe'd, sys.executable is the name of the EXE.
                    exe = os.path.abspath(
                        unicode(sys.executable, sys.getfilesystemencoding()))
                elif sys.frozen == "macosx_app":
                    # When py2app'd, sys.executable is a Python interpreter copied
                    # into the same dir where we live.
                    exe = os.path.join(
                        os.path.dirname(sys.executable),
                        'FoFiX')  # FIXME: don't hard-code "FoFiX" here
                else:
                    raise RuntimeError, "Don't know how to restart when sys.frozen is %s" % repr(
                        sys.frozen)
            else:
                # When running from source, sys.executable is the Python interpreter
                # being used to run the program.
                exe = sys.executable
                # Pass the optimization level on iif python version >= 2.6.0 as
                # sys.flags has been introduced in 2.6.0.
                if sys.version_info[:3] >= (2, 6,
                                            0) and sys.flags.optimize > 0:
                    args.append('-%s' % ('O' * sys.flags.optimize))
                args.append(__file__)
            os.execv(exe, [sys.executable] + args + sys.argv[1:])
        except:
            Log.error("Restart failed: ")
            raise

    # evilynux - MainMenu class already calls this - useless?
    engine.quit()
Beispiel #15
0
					# ~ videoPlayer.stop()
					videoPlayer.next(videoFiles[nextVideo])
					videoPlayer.player.pause()
					timestamp = time.time()
					connection.run_sender("play " + videoFiles[nextVideo] + " " + str(timestamp) + " \n")
					while time.time() - timestamp < 3:
						c = 10
					videoPlayer.player.play()
			else:
				# stop player at end last video
				videoPlaylist.sort()
				connection.run_sender("stop ")
				videoPlayer.stop()
	
from VideoPlayer import VideoPlayer
videoPlayer = VideoPlayer()
# DICT OF VIDEO FILES. 
# THE KEY IS A CHARACTER OF THE INDEX
videoFiles = get_videos()
# ARRAY OF videoFiles INDEXES. 
# EVERY TIME THE PLAY ORDER CHANGE, 
# IT CHANGES
videoPlaylist = [x for x in videoFiles]
videoPlaylist.sort()
# ABSOLUTE INDEX OF THE videoFiles, 
# USED TO CALCULATE THE NEXT VIDEO AND 
currVideo = 0

#~ currVideoPlaying
videoPlayer.loadVideo(videoFiles[videoPlaylist[currVideo]])
Beispiel #16
0
import cv2
import numpy as np
from VideoPlayer import VideoPlayer
from VideoWriter import VideoWriter
from LineDrawer import LineDrawer
from Model import Model
from LinePicker import LinePicker
from ModelTransformer import ModelTransformer
from HSVTrackbar import HSVPicker

if __name__ == '__main__':

    vp = VideoPlayer(
        'resources/video/field1/cliphd4.mp4')  #inicializa com o caminho
    frames = vp.extract_frames(
    )  # abre o arquivo e retorna um vetor com os frames
    frames_with_line = []  # cria vetor com frames com linha
    field_lines_mask = []  # mascara das linhas do campo

    lp = LinePicker(
        frames[1]
    )  #abre o frame de número 1 para a escolha dos pontos (fp,sc) -apertar enter

    #copia e imprime os pontos
    first_point = lp.first_down_point
    scrimmage = lp.scrimmage_point
    print(first_point, scrimmage)

    HSV_LOW, HSV_HIGH, BLUR = HSVPicker(frames[1]).getHSVMask(
    )  #abre o seletor de filtros pro HSV e retorna os limites da máscara
Beispiel #17
0
class VideoPlayerQWidget(QtWidgets.QWidget):
    STATUS_NOT_LOADED = -1
    STATUS_INIT = 0
    STATUS_PLAYING = 1
    STATUS_PAUSE = 2

    def __init__(self, parent=None):
        super().__init__(parent)
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.nextFrame)
        self.image = QImage()
        self.video = VideoPlayer()
        self.frame_counter = 0
        self.parent = parent
        self.status = self.STATUS_NOT_LOADED
        self.play_speed = 1.0
        self.updateRate = 24

    def get_qimage(self, image: np.ndarray):
        height, width, colors = image.shape
        bytesPerLine = 3 * width

        image = QImage(image.data, width, height, bytesPerLine,
                       QImage.Format_RGB888)

        image = image.rgbSwapped()
        return image

    def getFrameCount(self):
        return self.video.getFrameCount()

    def getCurrentTime(self):
        return self.frame_counter // self.updateRate

    def getCurrentTime_frame(self):
        return self.frame_counter

    def setFrame(self, frame):
        self.timer.stop()
        self.timer.start(1000)
        self.frame_counter = frame
        self.video.setFrame(frame)
        self.parent.updateDurationInfo(frame // 24)
        if self.status == self.STATUS_PLAYING:
            self.timer.start(int((1000 // 24) / self.play_speed))
        elif self.status in (self.STATUS_PAUSE, self.STATUS_INIT):
            self.timer.stop()
        else:
            print("BUG")

    def setVideo(self, path):
        self.frame_counter = 0
        self.video.initialize(path)
        self.status = self.STATUS_INIT

    def play(self):
        if self.status == self.STATUS_INIT:
            self.video.play()
        self.timer.start(int((1000 // 24) / self.play_speed))
        self.status = self.STATUS_PLAYING

    def pause(self):
        self.timer.stop()
        self.status = self.STATUS_PAUSE

    def nextFrame(self):
        ret, frame = self.video.get_next_frame()
        if not ret:
            self.pause()
            self.parent.set_btnPlay()
        self.frame_counter += 1
        try:
            img = self.get_qimage(frame)
            self.image = img.scaled(self.size(), QtCore.Qt.KeepAspectRatio)
            self.update()
            if self.frame_counter % self.updateRate == 0:
                self.parent.set_slider_time(self.frame_counter //
                                            self.updateRate)
        except:
            pass

    def stopPlaying(self):
        if self.status != self.STATUS_NOT_LOADED:
            self.release()

    def paintEvent(self, event):
        painter = QPainter(self)
        x_pos = (self.width() - self.image.width()) // 2
        y_pos = (self.height() - self.image.height()) // 2
        painter.drawImage(x_pos, y_pos, self.image)

    def setPlaySpeed(self, speed):
        if self.play_speed != speed:
            self.play_speed = speed
            if self.status == self.STATUS_PLAYING:
                self.timer.start(int((1000 // 24) / self.play_speed))

    def setUpdateRate(self, rate):
        self.updateRate = rate

    def release(self):
        self.video.release()
Beispiel #18
0
class Stage(object):
    def __init__(self, guitarScene, configFileName):
        self.scene = guitarScene
        self.engine = guitarScene.engine
        self.config = Config.MyConfigParser()
        self.layers = []
        self.reset()

        self.wFull = None  #MFH - needed for new stage background handling
        self.hFull = None

        # evilynux - imported myfingershurt stuff from GuitarScene
        self.mode = self.engine.config.get("game", "stage_mode")
        self.songStage = self.engine.config.get("game", "song_stage")
        self.animatedFolder = self.engine.config.get("game",
                                                     "animated_stage_folder")

        # evilynux - imported myfingershurt stuff from GuitarScene w/ minor modifs
        #MFH TODO - alter logic to accomodate separated animation and slideshow
        #           settings based on seleted animated stage folder
        animationMode = self.engine.config.get("game", "stage_animate")
        slideShowMode = self.engine.config.get("game", "rotate_stages")

        if self.animatedFolder == _("None"):
            self.rotationMode = 0  #MFH: if no animated stage folders are available, disable rotation.
        elif self.animatedFolder == "Normal":
            self.rotationMode = slideShowMode
        else:
            self.rotationMode = animationMode

        self.imgArr = []  #QQstarS:random
        self.imgArrScaleFactors = []  #MFH - for precalculated scale factors
        self.rotateDelay = self.engine.config.get(
            "game", "stage_rotate_delay"
        )  #myfingershurt - user defined stage rotate delay
        self.animateDelay = self.engine.config.get(
            "game", "stage_animate_delay"
        )  #myfingershurt - user defined stage rotate delay
        self.animation = False

        self.indexCount = 0  #QQstarS:random time counter
        self.arrNum = 0  #QQstarS:random the array num
        self.arrDir = 1  #forwards

        self.config.read(configFileName)

        # evilynux - Improved stage error handling
        self.themename = self.engine.data.themeLabel
        self.path = os.path.join("themes", self.themename, "stages")
        self.pathfull = self.engine.getPath(self.path)
        if not os.path.exists(self.pathfull):  # evilynux
            Log.warn("Stage folder does not exist: %s" % self.pathfull)
            self.mode = 1  # Fallback to song-specific stage
        suffix = ".jpg"

    def loadVideo(self,
                  libraryName,
                  songName,
                  songVideo=None,
                  songVideoStartTime=None,
                  songVideoEndTime=None):
        if not videoAvailable:
            raise NameError('Video (gstreamer) is not available!')
        self.vidSource = None
        if self.songStage == 1:
            songAbsPath = os.path.join(libraryName, songName)
            if songVideo is not None and \
                   os.path.isfile(os.path.join(songAbsPath, songVideo)):
                self.vidSource = os.path.join(songAbsPath, songVideo)
            elif os.path.exists(os.path.join(songAbsPath, "default.avi")):
                Log.warn("Video not found: %s" % \
                         os.path.join(songAbsPath, songVideo))
                self.vidSource = os.path.join(songAbsPath, "default.avi")
        if self.vidSource is None:
            if self.songStage == 1:
                Log.warn("Video not found: %s" % \
                         os.path.join(songAbsPath, "default.avi"))
            songVideoStartTime = None
            songVideoEndTime = None
            self.vidSource = os.path.join(self.pathfull, "default.avi")

        if not os.path.exists(self.vidSource):
            Log.warn("Video not found: %s" % \
                     os.path.join(self.pathfull, "default.avi"))
            Log.warn(
                "No video found, fallbacking to default static image mode for now"
            )
            self.mode = 1  # Fallback
            self.vidSource = None
            return

        winWidth, winHeight = (self.engine.view.geometry[2],
                               self.engine.view.geometry[3])
        Log.debug("Attempting to load video: %s" % self.vidSource)
        try:  # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % self.vidSource)
            self.vidPlayer = VideoPlayer(-1,
                                         self.vidSource, (winWidth, winHeight),
                                         mute=True,
                                         loop=True,
                                         startTime=songVideoStartTime,
                                         endTime=songVideoEndTime)
            self.engine.view.pushLayer(self.vidPlayer)
            self.vidPlayer.paused = True
        except:
            self.mode = 1
            Log.warn("Failed to load video, fallback to default stage mode.")

    def restartVideo(self):
        if not videoAvailable or not self.mode == 3:
            return
        self.vidPlayer.loadVideo(self.vidSource)

    def load(self, libraryName, songName, practiceMode=False):
        rm = os.path.join("themes", self.themename, "rockmeter.ini")
        if self.scene.coOpType == True:
            rm = os.path.join("themes", self.themename, "rockmeter_coop.ini")
        elif self.scene.battle == True:
            rm = os.path.join("themes", self.themename,
                              "rockmeter_faceoff.ini")
        elif self.scene.battleGH == True:
            rm = os.path.join("themes", self.themename,
                              "rockmeter_profaceoff.ini")

        rockmeter = self.engine.resource.fileName(rm)
        self.rockmeter = Rockmeter.Rockmeter(self.scene, rockmeter,
                                             self.scene.coOpType)

        # evilynux - Fixes a self.background not defined crash
        self.background = None
        #MFH - new background stage logic:
        if self.mode == 2:  #blank / no stage
            self.songStage = 0
            self.rotationMode = 0
        elif practiceMode:  #check for existing practice stage; always disable stage rotation here
            self.songStage = 0
            self.rotationMode = 0
            self.mode = 1
            #separated practice stages for the instruments by k.i.d
            if self.scene.guitars[0].isDrum:
                background = "practicedrum"
            elif self.scene.guitars[0].isBassGuitar:
                background = "practicebass"
            else:
                background = "practice"
            if not self.engine.loadImgDrawing(
                    self, "background",
                    os.path.join("themes", self.themename, "stages",
                                 background)):
                #MFH - must first fall back on the old practice.png before forcing blank stage mode!
                if not self.engine.loadImgDrawing(
                        self, "background",
                        os.path.join("themes", self.themename, "stages",
                                     "practice")):
                    Log.warn(
                        "No practice stage, fallbacking on a forced Blank stage mode"
                    )  # evilynux
                    self.mode = 2  #if no practice stage, just fall back on a forced Blank stage mode

        elif self.songStage == 1:  #check for song-specific background
            test = True
            if not self.engine.loadImgDrawing(
                    self, "background",
                    os.path.join(libraryName, songName, "background")):
                Log.notice("No song-specific stage found")  # evilynux
                test = False
            if test:  #does a song-specific background exist?
                self.rotationMode = 0
                self.mode = 1
            else:
                self.songStage = 0

        #MFH - now, after the above logic, we can run the normal stage mode logic
        #      only worrying about checking for Blank, song-specific and
        #      practice stage modes
        if self.mode != 2 and self.mode != 3 and self.songStage == 0 and not practiceMode:  #still need to load stage(s)
            #myfingershurt: assign this first
            if self.mode == 1:  #just use Default.png
                if not self.engine.loadImgDrawing(
                        self, "background", os.path.join(self.path,
                                                         "default")):
                    Log.warn(
                        "No default stage; falling back on a forced Blank stage mode"
                    )  # evilynux
                    self.mode = 2  #if no practice stage, just fall back on a forced Blank stage mode

            ##This checks how many Stage-background we have to select from
            if self.mode == 0 and self.rotationMode == 0:  #MFH: just display a random stage
                files = []
                fileIndex = 0
                allfiles = os.listdir(self.pathfull)
                for name in allfiles:
                    if os.path.splitext(name)[0].lower(
                    ) != "practice" and os.path.splitext(name)[0].lower(
                    ) != "practicedrum" and os.path.splitext(name)[0].lower(
                    ) != "practicebass" and name != ".svn":
                        Log.debug("Valid background found, index (" +
                                  str(fileIndex) + "): " + name)
                        files.append(name)
                        fileIndex += 1
                    else:
                        Log.debug("Practice background filtered: " + name)

                # evilynux - improved error handling, fallback to blank background if no background are found
                if fileIndex == 0:
                    Log.warn("No valid stage found!")
                    self.mode = 2
                else:
                    i = random.randint(0, len(files) - 1)
                    filename = files[i]
                    ##End check number of Stage-backgrounds
                    if not self.engine.loadImgDrawing(
                            self, "background",
                            os.path.join(self.path, filename)):
                        self.mode = 2

            elif self.rotationMode > 0 and self.mode != 2:
                files = []
                fileIndex = 0

                if self.animatedFolder == "Random":  #Select one of the subfolders under stages\ to animate randomly
                    numAniStageFolders = len(self.engine.stageFolders)
                    if numAniStageFolders > 0:
                        self.animatedFolder = random.choice(
                            self.engine.stageFolders)
                    else:
                        self.animatedFolder = "Normal"

                elif self.animatedFolder == "None":
                    self.mode = 2

                if self.animatedFolder != "Normal" and self.mode != 2:  #just use the base Stages folder for rotation
                    self.path = os.path.join("themes", self.themename,
                                             "stages", self.animatedFolder)
                    self.pathfull = self.engine.getPath(self.path)
                    self.animation = True

                allfiles = os.listdir(self.pathfull)
                for name in allfiles:

                    if os.path.splitext(
                            name)[1].lower() == ".png" or os.path.splitext(
                                name)[1].lower() == ".jpg" or os.path.splitext(
                                    name)[1].lower() == ".jpeg":
                        if os.path.splitext(name)[0].lower(
                        ) != "practice" and os.path.splitext(name)[0].lower(
                        ) != "practicedrum" and os.path.splitext(
                                name)[0].lower() != "practicebass":
                            Log.debug("Valid background found, index (" +
                                      str(fileIndex) + "): " + name)
                            files.append(name)
                            fileIndex += 1
                        else:
                            Log.debug("Practice background filtered: " + name)
                    files.sort()

            if self.rotationMode > 0 and self.mode != 2:  #alarian: blank stage option is not selected
                #myfingershurt: just populate the image array in order, they are pulled in whatever order requested:
                for j in range(len(files)):
                    self.engine.loadImgDrawing(
                        self, "backgroundA", os.path.join(self.path, files[j]))
                    #MFH: also precalculate each image's scale factor and store in the array
                    imgwidth = self.backgroundA.width1()
                    wfactor = 640.000 / imgwidth
                    self.imgArr.append(
                        getattr(self, "backgroundA",
                                os.path.join(self.path, files[j])))
                    self.imgArrScaleFactors.append(wfactor)

        if self.rotationMode > 0 and len(self.imgArr) == 0:
            self.rotationMode = 0

        if self.mode != 2 and self.background:  #MFH - precalculating scale factor
            imgwidth = self.background.width1()
            self.backgroundScaleFactor = 640.000 / imgwidth

    #stage rotation
    def rotate(self):
        if self.animation:
            whichDelay = self.animateDelay
        else:
            whichDelay = self.rotateDelay
        self.indexCount = self.indexCount + 1
        if self.indexCount > whichDelay:  #myfingershurt - adding user setting for stage rotate delay
            self.indexCount = 0
            if self.rotationMode == 1:  #QQstarS:random
                self.arrNum = random.randint(0, len(self.imgArr) - 1)
            elif self.rotationMode == 2:  #myfingershurt: in order display mode
                self.arrNum += 1
                if self.arrNum > (len(self.imgArr) - 1):
                    self.arrNum = 0
            elif self.rotationMode == 3:  #myfingershurt: in order, back and forth display mode
                if self.arrDir == 1:  #forwards
                    self.arrNum += 1
                    if self.arrNum > (len(self.imgArr) - 1):
                        self.arrNum -= 2
                        self.arrDir = 0
                else:
                    self.arrNum -= 1
                    if self.arrNum < 0:
                        self.arrNum += 2
                        self.arrDir = 1

    def renderBackground(self):
        #myfingershurt: multiple rotation modes
        if self.mode != 2:
            if self.rotationMode == 0:
                self.engine.drawImage(self.background,
                                      scale=(self.backgroundScaleFactor,
                                             -self.backgroundScaleFactor),
                                      coord=(self.wFull / 2, self.hFull / 2))

            #myfingershurt:
            else:
                #MFH - use precalculated scale factors instead
                self.engine.drawImage(
                    self.imgArr[self.arrNum],
                    scale=(self.imgArrScaleFactors[self.arrNum],
                           -self.imgArrScaleFactors[self.arrNum]),
                    coord=(self.wFull / 2, self.hFull / 2))

    def updateDelays(self):
        self.rotateDelay = self.engine.config.get(
            "game", "stage_rotate_delay"
        )  #myfingershurt - user defined stage rotate delay
        self.animateDelay = self.engine.config.get(
            "game", "stage_animate_delay"
        )  #myfingershurt - user defined stage rotate delay

    def reset(self):
        self.lastBeatPos = None
        self.lastQuarterBeatPos = None
        self.lastMissPos = None
        self.lastPickPos = None
        self.beat = 0
        self.quarterBeat = 0
        self.pos = 0.0
        self.playedNotes = []
        self.averageNotes = [0.0]
        self.beatPeriod = 0.0

    def triggerPick(self, pos, notes):
        if notes:
            self.lastPickPos = pos
            self.playedNotes = self.playedNotes[-3:] + [
                sum(notes) / float(len(notes))
            ]
            self.averageNotes[-1] = sum(self.playedNotes) / float(
                len(self.playedNotes))

    def triggerMiss(self, pos):
        self.lastMissPos = pos

    def triggerQuarterBeat(self, pos, quarterBeat):
        self.lastQuarterBeatPos = pos
        self.quarterBeat = quarterBeat

    def triggerBeat(self, pos, beat):
        self.lastBeatPos = pos
        self.beat = beat
        self.averageNotes = self.averageNotes[-4:] + self.averageNotes[-1:]

    def renderLayers(self, layers, visibility):
        self.engine.view.setOrthogonalProjection(normalize=True)
        try:
            for layer in layers:
                layer.render(visibility)
        finally:
            self.engine.view.resetProjection()

    def run(self, pos, period):
        self.pos = pos
        self.beatPeriod = period
        quarterBeat = int(4 * pos / period)

        if quarterBeat > self.quarterBeat:
            self.triggerQuarterBeat(pos, quarterBeat)

        beat = quarterBeat / 4

        if beat > self.beat:
            self.triggerBeat(pos, beat)

    def render(self, visibility):
        if self.mode != 3:
            self.renderBackground()
        self.renderLayers(self.layers, visibility)
        if shaders.enable("stage"):
            height = 0.0
            for i in shaders.var["color"].keys():
                shaders.modVar("color", shaders.var["color"][i], 0.05, 10.0)
                height += shaders.var["color"][i][3] / 3.0
            height = height**2
            shaders.setVar("height", 2 * height)
            shaders.setVar("ambientGlow", height / 1.5)

            shaders.setVar("glowStrength", 60 + height * 80.0)
            glBegin(GL_TRIANGLE_STRIP)
            glVertex3f(-8.0, 1.0, 7.0)
            glVertex3f(8.0, 1.0, 7.0)
            glVertex3f(-8.0, 4.0, 7.0)
            glVertex3f(8.0, 4.0, 7.0)
            glEnd()
            shaders.disable()

        self.scene.renderGuitar()
        self.rockmeter.render(visibility)
Beispiel #19
0
class VideoQueryGUI(tk.Frame):
    FORCE_CREATE = False

    def __init__(self, master):
        super(VideoQueryGUI, self).__init__()
        self.master = master
        master.title("CSCI 576 Project - Video Query System")
        # master.wm_title("Video Player")
        master.wm_protocol("WM_DELETE_WINDOW", self.onClose)

        self.folders = [x[0]
                        for x in os.walk(config.DB_VID_ROOT)][1:]
        self.query_scores = None

        self.corr_plot = np.ones((100, 356, 3), dtype='uint8')*255

        self.create_frames()
        # self.load_database()
        print('%s%s%s' % ('*'*20, 'Loaded GUI', '*'*20))

        self.load_db_thread = threading.Thread(
            target=self.load_database, name='database loader')
        self.load_db_thread.start()

        # self.load_database()
    # def load_database(self):
    #     print('Thread start')
    #     time.sleep(3)
    #     print('Thread end')

    def load_database(self):
        self.update_status('Loading database', clear=True)
        print('Started')
        print('=' * 80)
        print('Database video list')
        print('-' * 80)
        print('\n'.join(['%d. %s' % (i+1, f)
                         for (i, f) in enumerate(self.folders)]))
        print('=' * 80)

        self.db_vids = []
        for selected_folder in self.folders:
            self.update_status(selected_folder)
            pkl_path = glob.glob(os.path.join(selected_folder, '*.pkl'))
            if len(pkl_path) and not self.FORCE_CREATE:
                tic = time.time()
                self.update_status('Loading pre-calculated features')
                with open(pkl_path[0], 'rb') as pkl_fp:
                    v = pickle.load(pkl_fp)
                self.update_status('Loaded in %0.4fs' % (time.time()-tic))
            else:
                tic = time.time()
                self.update_status('Loading video')
                vid_path = selected_folder
                aud_path = glob.glob(os.path.join(selected_folder, '*.wav'))[0]
                v = Video(vid_path, aud_path)
                self.update_status('Loaded in %0.4fs' % (time.time()-tic))

                # Computing features
                tic = time.time()
                self.update_status('Calculating video features')
                extract_features(v)
                self.update_status('Calculated in %0.4fs' % (time.time()-tic))

                self.update_status('Saving results to database')
                with open(os.path.join(selected_folder, '%s.pkl' % v.name), 'wb') as pkl_fp:
                    pickle.dump(v, pkl_fp)
            self.db_vids.append(v)

    def create_frames(self):
        # Top frame - Buttons and list
        self.frame1 = tk.LabelFrame(
            self.master, text='', relief=tk.RAISED
        )

        self.frame1.pack(side='top', expand=True, fill='both')

        self.load_q_button = tk.Button(
            self.frame1, text='Load Query', command=self.load_query_video)
        self.load_q_button.grid(row=0, column=0)

        self.run_button = tk.Button(
            self.frame1, text='Find matches', command=self.run_match)
        self.run_button.grid(row=1, column=0)

        # self.dummy_btn = tk.Button(
        #     self.frame1, text='Debug', command=self.dummy_fn)
        # self.dummy_btn.grid(row=2, column=0)

        self.match_list = tk.Listbox(self.frame1, height=4)
        self.yscroll = tk.Scrollbar(
            self.frame1, orient=tk.VERTICAL, command=self.match_list.yview)
        self.match_list['yscrollcommand'] = self.yscroll.set

        self.match_list.grid(row=0, column=1, rowspan=2, stick='wens')
        self.yscroll.grid(row=0, column=1, rowspan=2, sticky='nse')

        self.match_list.bind('<Double-Button-1>', self.poll_match_list)

        self.curr_selection = -1

        self.frame1.grid_columnconfigure(0, weight=1)
        self.frame1.grid_columnconfigure(1, weight=2)

        # Middle frame - Status box and correlation plots
        self.frame2 = tk.LabelFrame(
            self.master, text='', relief=tk.RAISED,
            height=200
        )
        self.frame2.pack(side='top', expand=True, fill='both')

        self.info_text = tk.StringVar()
        self.info_text.set('STATUS')
        self.info_label = tk.Label(
            self.frame2, textvar=self.info_text, justify=tk.LEFT, anchor='w')
        # self.info_label = tk.Label(self.frame2, text='')
        self.info_label.grid(row=0, column=0, stick='nswe')

        self.corr_curve_label = tk.Label(self.frame2)
        # self.corr_curve_label.config(background='yellow')
        self.corr_curve_label.bind("<Button-1>", self.show_corr_plots)
        self.corr_curve_label.grid(row=0, column=1, stick='nse')

        self.frame2.grid_columnconfigure(0, weight=1)
        self.frame2.grid_columnconfigure(1, weight=1)

        self.query_player = VideoPlayer(self.frame2)
        self.query_player.grid(row=1, column=0, stick='nsw')
        self.db_player = VideoPlayer(self.frame2)
        self.db_player.grid(row=1, column=1, stick='nse')

        self.draw_corr_label()

    def load_query_video(self):
        self.update_status('Select query', clear=True)
        selected_folder = None
        self.master.update()
        selected_folder = askdirectory(
            initialdir=config.QUERY_VID_ROOT, title='Select query folder')
        # selected_folder = askopenfilename(
        #     initialdir=config.QUERY_VID_ROOT, title='Select query folder')
        self.update_status('Selected ' + selected_folder)

        if selected_folder == '':
            return

        self.query_loader = threading.Thread(
            target=self.load_query, args=(selected_folder, ), name='query_loader')
        self.query_loader.start()

        # while self.query_loader.is_alive():
        #     self.update_idletasks()

    def load_query(self, selected_folder=None):
        self.update_status('Loading query video', clear=True)
        if selected_folder == None:
            selected_folder = os.path.join(
                config.QUERY_VID_ROOT, 'subclip_traffic')
            # selected_folder = askdirectory(
            #     initialdir=config.QUERY_VID_ROOT, title='Select query folder')
            # print(selected_folder)
        self.update_status('Selected '+selected_folder)
        # print('Selected '+selected_folder)

        pkl_path = glob.glob(os.path.join(selected_folder, 'query_scores.pkl'))

        # print(pkl_path)

        if len(pkl_path) and not self.FORCE_CREATE:
            vid_pkl_path = [pth for pth in glob.glob(os.path.join(
                selected_folder, '*.pkl')) if not os.path.basename(pth).startswith('query_scores')]
            tic = time.time()
            self.update_status('Loading pre-calculated comparison metrics')
            # print('Loading pre-calculated comparison metrics')
            with open(pkl_path[0], 'rb') as pkl_fp:
                self.query_scores = pickle.load(pkl_fp)
            with open(vid_pkl_path[0], 'rb') as pkl_fp:
                self.query_vid = pickle.load(pkl_fp)
            self.update_status('Loaded in %0.4fs' % (time.time()-tic))
        else:
            pkl_path = [pth for pth in glob.glob(os.path.join(
                selected_folder, '*.pkl')) if not os.path.basename(pth).startswith('query_scores')]

            if len(pkl_path) and not self.FORCE_CREATE:
                tic = time.time()
                self.update_status('Loading pre-calculated features')
                with open(pkl_path[0], 'rb') as pkl_fp:
                    self.query_vid = pickle.load(pkl_fp)
                self.update_status('Loaded in %0.4fs' % (time.time()-tic))
            else:
                # Loading query video
                tic = time.time()
                vid_path = selected_folder
                aud_path = glob.glob(os.path.join(selected_folder, '*.wav'))[0]
                self.update_status('Loading video %s' %
                                   os.path.basename(vid_path))
                self.query_vid = Video(vid_path, aud_path)

                # Computing features
                tic = time.time()
                self.update_status('Calculating video features')
                # print('Calculating video features')
                extract_features(self.query_vid)
                self.update_status('Calculated in %0.4fs' % (time.time()-tic))
                # print('Calculated in %0.4fs' % (time.time()-tic))

                self.update_status('Caching query')
                with open(os.path.join(selected_folder, '%s.pkl' % self.query_vid.name), 'wb') as pkl_fp:
                    pickle.dump(self.query_vid, pkl_fp)

            self.query_scores = {}
            for i, db_vid in enumerate(self.db_vids):
                self.update_status('Comparing features with %s' % db_vid.name)
                tic = time.time()
                self.query_scores[db_vid.name] = compare_features(
                    self.query_vid, db_vid)
                self.update_status('Feature comparison completed in %0.4fs' %
                                   (time.time()-tic))

            self.update_status('Saving results to database')
            with open(os.path.join(selected_folder, 'query_scores.pkl'), 'wb') as pkl_fp:
                pickle.dump(self.query_scores, pkl_fp)
            self.update_status('Saved results to database')

        self.query_player.load_video(self.query_vid)

    def run_match(self):
        if self.query_scores is None:
            self.update_status('No query video selected', clear=True)
            return
        self.update_status('Running query in database', clear=True)
        self.final_ranks = rank_features(self.query_scores)
        self.update_status('Generated ranked list of matches')

        self.match_list.delete(0, tk.END)
        matchlist = [x[0] for x in self.final_ranks]
        for match in matchlist:
            self.match_list.insert(tk.END, match)

        self.poll_match_list()

    def update_status(self, text, clear=False):
        if clear:
            status_text = 'STATUS:\n%s' % text
        else:
            status_text = '%s\n%s' % (self.info_text.get(), text)
        lines = status_text.split('\n')
        if len(lines) < 6:
            status_text = '\n'.join(lines + ['']*(6-len(lines)))
        elif len(lines) > 6:
            status_text = '\n'.join([lines[0]]+lines[-5:])
        self.info_text.set(status_text)

    def poll_match_list(self, event=None):
        current = self.match_list.curselection()[0]
        # print(current)
        if current != self.curr_selection:
            # self.update_status('Selection updated to ' +
            #                    self.final_ranks[current][0])
            curr_video = self.find_matching_db_vid(
                self.final_ranks[current][0])
            self.db_player.load_video(curr_video)
            plot = generate_plot(self.final_ranks[current])
            self.corr_plot = resize(
                plot, (100, 356, 3), preserve_range=True).astype('uint8')
            self.curr_selection = current
        self.master.after(250, self.poll_match_list)

    def show_corr_plots(self, event):
        generate_plots(self.final_ranks, 'Compiled')
        plt.pause(1)

    def draw_corr_label(self):
        im = ImageTk.PhotoImage(
            Image.fromarray(
                self.corr_plot
            )
        )
        self.corr_curve_label.configure(image=im)
        self.corr_curve_label.image = im

        # self.update_status('Drew_plot')
        # self.update_status(repr(self.corr_plot.shape))
        self.master.after(250, self.draw_corr_label)

    def dummy_fn(self):
        self.corr_plot = np.ones(
            (100, 356, 3), dtype='uint8') * np.random.randint(0, 255)
        # self.update_status(str(self.db_player.winfo_width()))

    def find_matching_db_vid(self, vidname):
        for vid in self.db_vids:
            if vid.name == vidname:
                return vid
        else:
            return None

    def onClose(self):
        self.query_player.onClose()
        self.db_player.onClose()
        self.master.quit()
Beispiel #20
0
 def init_ui(self):
     self.setFixedSize(self.size())
     self.ui.radio_info.setChecked(True)
     self.ui.radio_tl.setChecked(True)
     self.ui.btn_choose_icon.setEnabled(False)
     
     self.ui.tabs.setCurrentIndex(0)
     
     layout = QtGui.QHBoxLayout()
     self.ui.tab_content.setLayout(layout)
     self.add_media_widget = AddMediaWidget(self.project, self.annotation)
     layout.addWidget(self.add_media_widget)
     
     self.ui.radio_personalized.toggled.connect(self.personalized_choosed)
     self.ui.btn_choose_icon.clicked.connect(self.choose_icon)
     
     self.lbl_screen = QtGui.QLabel(self.ui.widget_icon)
     self.lbl_screen.resize(self.ui.widget_icon.size())
     self.lbl_screen.setStyleSheet('background-color: rgb(0, 0, 0); \
                                     border-color: rgb(255, 255, 255);\
                                     font: 75 28pt "Ubuntu";\
                                     color: rgb(255, 255, 127);')
     self.lbl_screen.setAlignment(QtCore.Qt.AlignCenter)
     self.lbl_screen.setText("Tela")
     
     self.lbl_icon = MovebleLabel(u"", self.ui.widget_icon)
     self.lbl_icon.resize(30,30)
     self.lbl_icon.move(10,10)
     self.lbl_icon.setStyleSheet('background-color: rgb(255, 255, 0);\
                                         border-color: rgb(255, 255, 255);\
                                         font: 75 8pt "Ubuntu";\
                                         color: rgb(0, 0, 0);')
     self.lbl_icon.setEnabled(False)
     
     self.ui.radio_bl.toggled.connect(self.selected_bl)
     self.ui.radio_br.toggled.connect(self.selected_br)
     self.ui.radio_tr.toggled.connect(self.selected_tr)
     self.ui.radio_tl.toggled.connect(self.selected_tl)
     self.ui.radio_free_position.toggled.connect(self.selected_free_position)
     
     self.ui.btn_ok.clicked.connect(self.ok_pressed)
     self.ui.btn_cancel.clicked.connect(self.cancel_pressed)
     self.ui.btn_preview.clicked.connect(self.preview)
     self.ui.btn_preview.setEnabled(False)
     
     #player_holder = self.ui.player_widget
     #layout = QtGui.QVBoxLayout()
     self.player = VideoPlayer(parent=self.ui.player_widget)
     #layout.addWidget(self.player)
     #self.ui.tab_interaction.setLayout(layout)
     self.player.load_video(self.project.main_media)
     self.player.player.mediaObject().tick.connect(self.update_time_edit)
     #self.player.move(50,0)
     
     
     self.ui.radio_show.toggled.connect(self.selected_show)
     self.ui.radio_back.toggled.connect(self.selected_back)
     self.ui.radio_back_to.toggled.connect(self.selected_back_to)
     self.ui.radio_skip.toggled.connect(self.selected_skip)
     
     self.ui.btn_back_limite.clicked.connect(self.use_time_for_back_limite)
     self.ui.btn_back_point.clicked.connect(self.use_time_for_back_point)
     self.ui.btn_skip.clicked.connect(self.use_time_for_skip)
     
     self.ui.time_media.timeChanged.connect(self.editing_time)
     self.ui.time_media.installEventFilter(self)
     self.ui.time_media.setEnabled(False)
     
     self.ui.radio_show.setChecked(True)
     
     self.ui.ckb_audio.toggled.connect(self.toogled_audio_alert)
     self.ui.btn_choose_audio.clicked.connect(self.choose_audio)
     self.ui.btn_play_audio.clicked.connect(self.play_audio)
Beispiel #21
0
    pygame.init()
    pygame.mouse.set_visible(False)
    # init rendering screen
    displaymode = (IMAGE_WIDTH, IMAGE_HEIGHT)
    screen = pygame.display.set_mode(displaymode)
    pygame.display.toggle_fullscreen()

    # load cover image
    cover = pygame.image.load(IMAGE_NAME).convert()

    # set cover position
    position = pygame.Rect((0, -IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT))
    screen.blit(cover, position)

    audioPlayer = AudioPlayer(AUDIO_NAME)
    videoPlayer = VideoPlayer(VIDEO_NAME, IMAGE_WIDTH, IMAGE_HEIGHT, USE_VLC,
                              audioPlayer, pygame)

    inputLen = getInputDevices()
    prevInputLen = inputLen

    # MAIN LOOP
    while True:
        pygame.mouse.set_cursor((8, 8), (0, 0), (0, 0, 0, 0, 0, 0, 0, 0),
                                (0, 0, 0, 0, 0, 0, 0, 0))
        try:
            if areThereNewInputsDevices():
                hardKill()
                killAll()

            # update digital switches
            if USE_CHAPTERS:
                             bg="black",
                             disabledbackground="black",
                             disabledforeground='snow',
                             justify='center',
                             state='disabled')
txtPlatNumberDisplay.pack(pady=15)

# control panel
control_frame_top = Canvas(MainPanel,
                           width=350,
                           height=5,
                           bg="black",
                           relief=SUNKEN)
control_frame_top.pack(fill=BOTH, expand=False)

board = Label(control_frame_top, width=80, height=-1, bg="black")
board.pack(fill=BOTH, expand=True)

# control panel
control_frame_main = Canvas(MainPanel,
                            width=300,
                            height=700,
                            bg="blue",
                            relief=SUNKEN)
control_frame_main.pack(fill=BOTH, expand=True)

# video player
vid = VideoPlayer(control_frame_main, image=True, algo=True)
vid.command = lambda frame: extract_image(frame)
root.mainloop()
Beispiel #23
0
class Stage(object):
  def __init__(self, guitarScene, configFileName):
    self.scene            = guitarScene
    self.engine           = guitarScene.engine
    self.config           = Config.MyConfigParser()
    self.layers = []
    self.reset()
    

    self.wFull = None   #MFH - needed for new stage background handling
    self.hFull = None
    
    # evilynux - imported myfingershurt stuff from GuitarScene
    self.mode = self.engine.config.get("game", "stage_mode")
    self.songStage = self.engine.config.get("game", "song_stage")
    self.animatedFolder = self.engine.config.get("game", "animated_stage_folder")

    # evilynux - imported myfingershurt stuff from GuitarScene w/ minor modifs
    #MFH TODO - alter logic to accomodate separated animation and slideshow
    #           settings based on seleted animated stage folder
    animationMode = self.engine.config.get("game", "stage_animate")
    slideShowMode = self.engine.config.get("game", "rotate_stages")

    if self.animatedFolder == _("None"):
      self.rotationMode = 0   #MFH: if no animated stage folders are available, disable rotation.
    elif self.animatedFolder == "Normal":
      self.rotationMode = slideShowMode
    else:
      self.rotationMode = animationMode
    
    self.imgArr = [] #QQstarS:random
    self.imgArrScaleFactors = []  #MFH - for precalculated scale factors
    self.rotateDelay = self.engine.config.get("game",  "stage_rotate_delay") #myfingershurt - user defined stage rotate delay
    self.animateDelay = self.engine.config.get("game",  "stage_animate_delay") #myfingershurt - user defined stage rotate delay
    self.animation = False

    self.indexCount = 0 #QQstarS:random time counter
    self.arrNum = 0 #QQstarS:random the array num
    self.arrDir = 1 #forwards

    self.config.read(configFileName)

    # evilynux - Improved stage error handling
    self.themename = self.engine.data.themeLabel
    self.path = os.path.join("themes",self.themename,"stages")
    self.pathfull = self.engine.getPath(self.path)
    if not os.path.exists(self.pathfull): # evilynux
      Log.warn("Stage folder does not exist: %s" % self.pathfull)
      self.mode = 1 # Fallback to song-specific stage
    suffix = ".jpg"

  def loadVideo(self, libraryName, songName, songVideo = None,
                songVideoStartTime = None, songVideoEndTime = None):
    if not videoAvailable:
      raise NameError('Video (gstreamer) is not available!')
    self.vidSource = None
    if self.songStage == 1:
      songAbsPath = os.path.join(libraryName, songName)
      if songVideo is not None and \
             os.path.isfile(os.path.join(songAbsPath, songVideo)):
        self.vidSource = os.path.join(songAbsPath, songVideo)
      elif os.path.exists(os.path.join(songAbsPath, "default.avi")):
        Log.warn("Video not found: %s" % \
                 os.path.join(songAbsPath, songVideo))
        self.vidSource = os.path.join(songAbsPath, "default.avi")
    if self.vidSource is None:
      if self.songStage == 1:
        Log.warn("Video not found: %s" % \
                 os.path.join(songAbsPath, "default.avi"))
      songVideoStartTime = None
      songVideoEndTime = None
      self.vidSource = os.path.join(self.pathfull, "default.avi")

    if not os.path.exists(self.vidSource):
      Log.warn("Video not found: %s" % \
               os.path.join(self.pathfull, "default.avi"))
      Log.warn("No video found, fallbacking to default static image mode for now")
      self.mode = 1 # Fallback
      self.vidSource = None
      return
      
    winWidth, winHeight = (self.engine.view.geometry[2],
                           self.engine.view.geometry[3])
    Log.debug("Attempting to load video: %s" % self.vidSource)
    try: # Catches invalid video files or unsupported formats
      Log.debug("Attempting to load video: %s" % self.vidSource)
      self.vidPlayer = VideoPlayer(-1, self.vidSource, (winWidth, winHeight),
                                   mute = True, loop = True,
                                   startTime = songVideoStartTime,
                                   endTime = songVideoEndTime)
      self.engine.view.pushLayer(self.vidPlayer)
      self.vidPlayer.paused = True
    except:
      self.mode = 1
      Log.warn("Failed to load video, fallback to default stage mode.")

  def restartVideo(self):
    if not videoAvailable or not self.mode == 3:
      return
    self.vidPlayer.loadVideo(self.vidSource)
    
  def load(self, libraryName, songName, practiceMode = False):
    rm = os.path.join("themes", self.themename, "rockmeter.ini")
    if self.scene.coOpType == True:
      rm = os.path.join("themes", self.themename, "rockmeter_coop.ini")
    elif self.scene.battle == True:
      rm = os.path.join("themes", self.themename, "rockmeter_faceoff.ini")
    elif self.scene.battleGH == True:
      rm = os.path.join("themes", self.themename, "rockmeter_profaceoff.ini")
    
    rockmeter = self.engine.resource.fileName(rm)
    self.rockmeter = Rockmeter.Rockmeter(self.scene, rockmeter, self.scene.coOpType)

    # evilynux - Fixes a self.background not defined crash
    self.background = None
    #MFH - new background stage logic:
    if self.mode == 2:   #blank / no stage
      self.songStage = 0
      self.rotationMode = 0
    elif practiceMode:   #check for existing practice stage; always disable stage rotation here
      self.songStage = 0
      self.rotationMode = 0
      self.mode = 1
      #separated practice stages for the instruments by k.i.d
      if self.scene.guitars[0].isDrum:
        background = "practicedrum"
      elif self.scene.guitars[0].isBassGuitar:
        background = "practicebass"
      else:
        background = "practice"
      if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"stages",background)):
        #MFH - must first fall back on the old practice.png before forcing blank stage mode!
        if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"stages","practice")):
          Log.warn("No practice stage, fallbacking on a forced Blank stage mode") # evilynux
          self.mode = 2    #if no practice stage, just fall back on a forced Blank stage mode
            
    elif self.songStage == 1:    #check for song-specific background
      test = True
      if not self.engine.loadImgDrawing(self, "background", os.path.join(libraryName, songName, "background")):
        Log.notice("No song-specific stage found") # evilynux
        test = False
      if test:  #does a song-specific background exist?
        self.rotationMode = 0
        self.mode = 1
      else:
        self.songStage = 0

    #MFH - now, after the above logic, we can run the normal stage mode logic
    #      only worrying about checking for Blank, song-specific and
    #      practice stage modes
    if self.mode != 2 and self.mode != 3 and self.songStage == 0 and not practiceMode: #still need to load stage(s)
      #myfingershurt: assign this first
      if self.mode == 1:   #just use Default.png
        if not self.engine.loadImgDrawing(self, "background", os.path.join(self.path, "default")):
          Log.warn("No default stage; falling back on a forced Blank stage mode") # evilynux
          self.mode = 2    #if no practice stage, just fall back on a forced Blank stage mode

      ##This checks how many Stage-background we have to select from
      if self.mode == 0 and self.rotationMode == 0:  #MFH: just display a random stage
        files = []
        fileIndex = 0
        allfiles = os.listdir(self.pathfull)
        for name in allfiles:
          if os.path.splitext(name)[0].lower() != "practice" and os.path.splitext(name)[0].lower() != "practicedrum" and os.path.splitext(name)[0].lower() != "practicebass" and name != ".svn":
            Log.debug("Valid background found, index (" + str(fileIndex) + "): " + name)
            files.append(name)
            fileIndex += 1
          else:
            Log.debug("Practice background filtered: " + name)
  
        # evilynux - improved error handling, fallback to blank background if no background are found
        if fileIndex == 0:
          Log.warn("No valid stage found!")
          self.mode = 2;
        else:
          i = random.randint(0,len(files)-1)
          filename = files[i]
      ##End check number of Stage-backgrounds
          if not self.engine.loadImgDrawing(self, "background", os.path.join(self.path, filename)):
            self.mode = 2;

      elif self.rotationMode > 0 and self.mode != 2:
        files = []
        fileIndex = 0
        
        if self.animatedFolder == "Random": #Select one of the subfolders under stages\ to animate randomly
          numAniStageFolders = len(self.engine.stageFolders)
          if numAniStageFolders > 0:
            self.animatedFolder = random.choice(self.engine.stageFolders)
          else:
            self.animatedFolder = "Normal"
          
        elif self.animatedFolder == "None":
          self.mode = 2
        
        if self.animatedFolder != "Normal" and self.mode != 2: #just use the base Stages folder for rotation
          self.path = os.path.join("themes",self.themename,"stages",self.animatedFolder)
          self.pathfull = self.engine.getPath(self.path)
          self.animation = True

        allfiles = os.listdir(self.pathfull)
        for name in allfiles:

          if os.path.splitext(name)[1].lower() == ".png" or os.path.splitext(name)[1].lower() == ".jpg" or os.path.splitext(name)[1].lower() == ".jpeg":
            if os.path.splitext(name)[0].lower() != "practice" and os.path.splitext(name)[0].lower() != "practicedrum" and os.path.splitext(name)[0].lower() != "practicebass":
              Log.debug("Valid background found, index (" + str(fileIndex) + "): " + name)
              files.append(name)
              fileIndex += 1
            else:
              Log.debug("Practice background filtered: " + name)
          files.sort()

      if self.rotationMode > 0 and self.mode != 2:   #alarian: blank stage option is not selected
      #myfingershurt: just populate the image array in order, they are pulled in whatever order requested:
        for j in range(len(files)):
          self.engine.loadImgDrawing(self, "backgroundA", os.path.join(self.path, files[j]))
          #MFH: also precalculate each image's scale factor and store in the array
          imgwidth = self.backgroundA.width1()
          wfactor = 640.000/imgwidth
          self.imgArr.append(getattr(self, "backgroundA", os.path.join(self.path, files[j])))
          self.imgArrScaleFactors.append(wfactor)
    
    if self.rotationMode > 0 and len(self.imgArr) == 0:
      self.rotationMode = 0

    if self.mode != 2 and self.background:   #MFH - precalculating scale factor
      imgwidth = self.background.width1()
      self.backgroundScaleFactor = 640.000/imgwidth

  #stage rotation
  def rotate(self):
    if self.animation:
      whichDelay = self.animateDelay
    else:
      whichDelay = self.rotateDelay
    self.indexCount = self.indexCount + 1
    if self.indexCount > whichDelay:   #myfingershurt - adding user setting for stage rotate delay
      self.indexCount = 0
      if self.rotationMode == 1: #QQstarS:random
        self.arrNum = random.randint(0,len(self.imgArr)-1)
      elif self.rotationMode == 2: #myfingershurt: in order display mode
        self.arrNum += 1
        if self.arrNum > (len(self.imgArr)-1):
          self.arrNum = 0
      elif self.rotationMode == 3: #myfingershurt: in order, back and forth display mode
        if self.arrDir == 1:  #forwards
          self.arrNum += 1
          if self.arrNum > (len(self.imgArr)-1):
            self.arrNum -= 2
            self.arrDir = 0
        else:
          self.arrNum -= 1
          if self.arrNum < 0:
            self.arrNum += 2
            self.arrDir = 1

  def renderBackground(self):
    #myfingershurt: multiple rotation modes
    if self.mode != 2:
      if self.rotationMode == 0:
        self.engine.drawImage(self.background, scale = (self.backgroundScaleFactor,-self.backgroundScaleFactor),
                              coord = (self.wFull/2,self.hFull/2))

      #myfingershurt:
      else:
        #MFH - use precalculated scale factors instead
        self.engine.drawImage(self.imgArr[self.arrNum], scale = (self.imgArrScaleFactors[self.arrNum],-self.imgArrScaleFactors[self.arrNum]),
                              coord = (self.wFull/2,self.hFull/2))

  def updateDelays(self):
    self.rotateDelay = self.engine.config.get("game",  "stage_rotate_delay") #myfingershurt - user defined stage rotate delay
    self.animateDelay = self.engine.config.get("game",  "stage_animate_delay") #myfingershurt - user defined stage rotate delay

  def reset(self):
    self.lastBeatPos        = None
    self.lastQuarterBeatPos = None
    self.lastMissPos        = None
    self.lastPickPos        = None
    self.beat               = 0
    self.quarterBeat        = 0
    self.pos                = 0.0
    self.playedNotes        = []
    self.averageNotes       = [0.0]
    self.beatPeriod         = 0.0

  def triggerPick(self, pos, notes):
    if notes:
      self.lastPickPos      = pos
      self.playedNotes      = self.playedNotes[-3:] + [sum(notes) / float(len(notes))]
      self.averageNotes[-1] = sum(self.playedNotes) / float(len(self.playedNotes))

  def triggerMiss(self, pos):
    self.lastMissPos = pos

  def triggerQuarterBeat(self, pos, quarterBeat):
    self.lastQuarterBeatPos = pos
    self.quarterBeat        = quarterBeat

  def triggerBeat(self, pos, beat):
    self.lastBeatPos  = pos
    self.beat         = beat
    self.averageNotes = self.averageNotes[-4:] + self.averageNotes[-1:]

  def renderLayers(self, layers, visibility):
    self.engine.view.setOrthogonalProjection(normalize = True)
    try:
      for layer in layers:
        layer.render(visibility)
    finally:
      self.engine.view.resetProjection()

  def run(self, pos, period):
    self.pos        = pos
    self.beatPeriod = period
    quarterBeat = int(4 * pos / period)

    if quarterBeat > self.quarterBeat:
      self.triggerQuarterBeat(pos, quarterBeat)

    beat = quarterBeat / 4

    if beat > self.beat:
      self.triggerBeat(pos, beat)

  def render(self, visibility):
    if self.mode != 3:
      self.renderBackground()
    self.renderLayers(self.layers, visibility)
    if shaders.enable("stage"):
      height = 0.0
      for i in shaders.var["color"].keys():
        shaders.modVar("color",shaders.var["color"][i],0.05,10.0)
        height += shaders.var["color"][i][3]/3.0
      height=height**2
      shaders.setVar("height",2*height)
      shaders.setVar("ambientGlow",height/1.5)

      shaders.setVar("glowStrength",60+height*80.0)
      glBegin(GL_TRIANGLE_STRIP)
      glVertex3f(-8.0, 1.0,7.0)
      glVertex3f(8.0, 1.0,7.0)
      glVertex3f(-8.0, 4.0,7.0)
      glVertex3f(8.0, 4.0,7.0)
      glEnd()    
      shaders.disable()
      
    self.scene.renderGuitar()
    self.rockmeter.render(visibility)
Beispiel #24
0
 def testVideoPlayerLayer(self):
     vidPlayer = VideoPlayer(self.e, framerate, self.src, loop=False)
     self.e.view.pushLayer(vidPlayer)
     while not vidPlayer.finished:
         self.e.run()
Beispiel #25
0
 def __init__(self, parent, video1FilePath=None, annotation1FilePath=None, video2FilePath=None, annotation2FilePath=None):
     self.root = parent
     # Set status of the player
     self.statusPlayer = StatusPlayer.NOT_STARTED
     self.eventPause = threading.Event()
     # current path
     currentPath = os.path.dirname(os.path.realpath(__file__))
     self.root.title("VDAO - Videos visualization")
     self.pnlMain = tk.PanedWindow(self.root, orient=tk.VERTICAL)
     self.pnlMain.pack(fill=tk.BOTH, expand=True)
     # Define video player 1 
     self.videoPlayer1 = VideoPlayer(parent=self.pnlMain, titleVideo='Video #1', fileName='', videoFilePath='', annotationFilePath='', currentFrameNbr=0, callback_FrameUpdated=self.callback_PlayFrame1, callBack_PlayPauseBtn_Clicked=self.callback_PlayPause, callBack_EquateFrames=self.callBack_EquateFrames)
     # Define video Difference
     self.videoPlayerDifference = VideoPlayer(self.pnlMain, 'Video Difference', "", "", None, 1, None, None, videoIsProcessed=True)
     # Define video player 2        
     self.videoPlayer2 = VideoPlayer(parent=self.pnlMain, titleVideo='Video #2', fileName='', videoFilePath='', annotationFilePath='', currentFrameNbr=0, callback_FrameUpdated=self.callback_PlayFrame2, callBack_PlayPauseBtn_Clicked=self.callback_PlayPause, callBack_EquateFrames=self.callBack_EquateFrames)
    # Buttons
     pnlButtons = tk.PanedWindow(self.root)
     pnlButtons.pack()
     # Load images
     self.imgBackwardsBeg = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_beg.png'))
     self.imgBackwards1 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_1.png'))
     self.imgBackwards5 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_5.png'))
     self.imgBackwards10 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_10.png'))
     self.imgPlay = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','play.png'))
     self.imgPause = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','pause.png'))
     self.imgForwardEnd = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_end.png'))
     self.imgForward1 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_1.png'))
     self.imgForward5 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_5.png'))
     self.imgForward10 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_10.png'))
     self.imgSelectFrame = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','select_frame.png'))
     # Create and add buttons
     self.btnBackwardsBeg = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwardsBeg, state=tk.NORMAL, command=self.btnBackwardsBeg_Clicked)
     self.btnBackwardsBeg.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnBackwards10 = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwards10, state=tk.NORMAL, command=self.btnBackwards10_Clicked)
     self.btnBackwards10.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnBackwards5 = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwards5, state=tk.NORMAL, command=self.btnBackwards5_Clicked)
     self.btnBackwards5.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnBackwards1 = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwards1, state=tk.NORMAL, command=self.btnBackwards1_Clicked)
     self.btnBackwards1.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnPlayPause = tk.Button(pnlButtons, width=24, height=24, image=self.imgPlay, state=tk.NORMAL, command=self.btnPlayPause_Clicked)
     self.btnPlayPause.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnForward1 = tk.Button(pnlButtons, width=24, height=24, image=self.imgForward1, state=tk.NORMAL, command=self.btnForward1_Clicked)
     self.btnForward1.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnForward5 = tk.Button(pnlButtons, width=24, height=24, image=self.imgForward5, state=tk.NORMAL, command=self.btnForward5_Clicked)
     self.btnForward5.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnForward10 = tk.Button(pnlButtons, width=24, height=24, image=self.imgForward10, state=tk.NORMAL, command=self.btnForward10_Clicked)
     self.btnForward10.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnForwardEnd = tk.Button(pnlButtons, width=24, height=24, image=self.imgForwardEnd, state=tk.NORMAL, command=self.btnForwardEnd_Clicked)
     self.btnForwardEnd.pack(side=tk.LEFT, padx=2, pady=2)
     self.btnSelectFrame = tk.Button(pnlButtons, width=24, height=24, image=self.imgSelectFrame, state=tk.NORMAL, command=self.btnSelectFrame_Clicked)
     self.btnSelectFrame.pack(side=tk.LEFT, padx=2, pady=2)
     # Desabilita botoes
     self.ChangeNavButtonsStatus(False)
     # Se tiver não frames para tocar em ambos vídeos
     if self.videoPlayer1.totalFrames == 0 or self.videoPlayer2.totalFrames == 0: # Se vídeo não tem frames para tocar
         self.statusPlayer = StatusPlayer.FAILED
         # self.loadedFrame1 = self.loadedFrame2 = False
         self.videoPlayer1.loadedFrames = self.videoPlayer2.loadedFrames = False
         # Desabilita botão geral para tocar vídeos
         self.btnPlayPause.config(state="disabled")
     else: # Tem frames para tocar em ambos videos
         self.statusPlayer = StatusPlayer.NOT_STARTED 
         # self.loadedFrame1 = self.loadedFrame2 = True
         self.videoPlayer1.loadedFrames = self.videoPlayer2.loadedFrames = True
         # Habilita botão geral para tocar vídeos
         self.btnPlayPause.config(state="normal")
     # Desabilita botões de navegação entre para os 2 vídeos
     self.videoPlayer1.ChangeNavButtonsStatus(False)
     self.videoPlayer2.ChangeNavButtonsStatus(False)
     # Se videoPlayer1 não tiver frames para tocar, desabilita o play
     if self.videoPlayer1.totalFrames == 0:
         self.videoPlayer1.btnPlayPause.config(state="disabled")
     else: # habilita o play
         self.videoPlayer1.btnPlayPause.config(state="normal")
     # Se videoPlayer2 não tiver frames para tocar, desabilita o play
     if self.videoPlayer2.totalFrames == 0:
         self.videoPlayer2.btnPlayPause.config(state="disabled")
     else: # habilita o play
         self.videoPlayer2.btnPlayPause.config(state="normal")
     # identifies last video that was created (0: None, 1: First video, 2: Second video)
     self.lastVideoCreated = 0
     # Creates empty frames
     self.frame1 = self.frame2 = None
Beispiel #26
0
 def __init__(self, path, ref_pos, regions, offset = 0):
     self.vp = VideoPlayer(path, False, gBlur = True)
     self.vp.seek(ref_pos)
     self.ref = self.vp.frame
     self.vp.seek(offset)
     self.regions = regions
Beispiel #27
0
    def create_frames(self):
        # Top frame - Buttons and list
        self.frame1 = tk.LabelFrame(
            self.master, text='', relief=tk.RAISED
        )

        self.frame1.pack(side='top', expand=True, fill='both')

        self.load_q_button = tk.Button(
            self.frame1, text='Load Query', command=self.load_query_video)
        self.load_q_button.grid(row=0, column=0)

        self.run_button = tk.Button(
            self.frame1, text='Find matches', command=self.run_match)
        self.run_button.grid(row=1, column=0)

        # self.dummy_btn = tk.Button(
        #     self.frame1, text='Debug', command=self.dummy_fn)
        # self.dummy_btn.grid(row=2, column=0)

        self.match_list = tk.Listbox(self.frame1, height=4)
        self.yscroll = tk.Scrollbar(
            self.frame1, orient=tk.VERTICAL, command=self.match_list.yview)
        self.match_list['yscrollcommand'] = self.yscroll.set

        self.match_list.grid(row=0, column=1, rowspan=2, stick='wens')
        self.yscroll.grid(row=0, column=1, rowspan=2, sticky='nse')

        self.match_list.bind('<Double-Button-1>', self.poll_match_list)

        self.curr_selection = -1

        self.frame1.grid_columnconfigure(0, weight=1)
        self.frame1.grid_columnconfigure(1, weight=2)

        # Middle frame - Status box and correlation plots
        self.frame2 = tk.LabelFrame(
            self.master, text='', relief=tk.RAISED,
            height=200
        )
        self.frame2.pack(side='top', expand=True, fill='both')

        self.info_text = tk.StringVar()
        self.info_text.set('STATUS')
        self.info_label = tk.Label(
            self.frame2, textvar=self.info_text, justify=tk.LEFT, anchor='w')
        # self.info_label = tk.Label(self.frame2, text='')
        self.info_label.grid(row=0, column=0, stick='nswe')

        self.corr_curve_label = tk.Label(self.frame2)
        # self.corr_curve_label.config(background='yellow')
        self.corr_curve_label.bind("<Button-1>", self.show_corr_plots)
        self.corr_curve_label.grid(row=0, column=1, stick='nse')

        self.frame2.grid_columnconfigure(0, weight=1)
        self.frame2.grid_columnconfigure(1, weight=1)

        self.query_player = VideoPlayer(self.frame2)
        self.query_player.grid(row=1, column=0, stick='nsw')
        self.db_player = VideoPlayer(self.frame2)
        self.db_player.grid(row=1, column=1, stick='nse')

        self.draw_corr_label()
Beispiel #28
0
class ShowContent(QtGui.QDialog):
    def __init__(self, project=None, annotation=None, interaction=None, parent=None):
        super(ShowContent, self).__init__(parent)
        self.is_editing_time = False
        self.project = project
        self.annotation = annotation
        self.interaction = interaction
        
        self.ui = Ui_ShowContent()
        self.ui.setupUi(self)
        self.ui.btn_preview.setVisible(False)
        self.init_ui()
        self.audio_path = None
        
        self.buttons = ["RED", "GREEN", "BLUE", "YELLOW"]
        
        self.load_annotation()
        
        
        self.result = None
        
    def timer_focus_in(self):
        self.player.pause()
        self.is_editing_time = True
        
    def load_annotation(self):
        if self.project is not None and \
                self.annotation is not None:
            
            self.ui.time_begin.setTime(self.annotation.annotation_time)
            self.ui.textEdit.append(self.annotation.description)
            
        if self.annotation.interaction is not None:
            show_content = self.annotation.interaction
            self.ui.ckb_compulsory.setChecked(show_content.compulsory)
            self.ui.ckb_interactive.setChecked(show_content.interactive)
            self.ui.ckb_allows_end_content.setChecked(show_content.allow_end_content)
            self.ui.ckb_show_on_tv.setChecked(show_content.tv)
            self.ui.ckb_show_on_mobile.setChecked(show_content.mobile)
            self.ui.ckb_pause_main_video.setChecked(show_content.pause_main_video)
            self.ui.ckb_viber.setChecked(show_content.viber_alert)
            
            if show_content.sound_alert is not None:
                self.ui.ckb_audio.setChecked(True)
                
                self.audio_path = unicode(show_content.sound_alert)
                self.audio_player = AudioPlayer()
                self.ui.txt_sound.clear()
                self.ui.txt_sound.append(os.path.split(self.audio_path)[1])
                self.audio_player.load_audio(self.audio_path)
                self.audio_player.setVisible(False)
                
            
            if show_content.icon.image == model.Icon.INFO:
                self.ui.radio_info.setChecked(True)
            elif show_content.icon.image == model.Icon.SEXUAL:
                self.ui.radio_sexual.setChecked(True)
            elif show_content.icon.image == model.Icon.VIOLENCE:
                self.ui.radio_violence.setChecked(True)
            elif show_content.icon.image == model.Icon.YES:
                self.ui.radio_yes.setChecked(True)
            elif show_content.icon.image == model.Icon.NO:
                self.ui.radio_no.setChecked(True)
            else:
                self.ui.radio_personalized.setChecked(True)
                self.icon_path = show_content.icon.image
                self.ui.radio_personalized.setIcon(QtGui.QIcon(self.icon_path))
                self.ui.cmb_button.setEnabled(True)
                if show_content.button is not None:
                    self.ui.cmb_button.setCurrentIndex(self.buttons.index(\
                                                        show_content.button))
                
            if show_content.icon.position == model.Icon.BOT_LEFT:
                self.ui.radio_bl.setChecked(True)
            elif show_content.icon.position == model.Icon.BOT_RIGHT:
                self.ui.radio_br.setChecked(True)
            elif show_content.icon.position == model.Icon.TOP_LEFT:
                self.ui.radio_tl.setChecked(True)
            elif show_content.icon.position == model.Icon.TOP_RIGHT:
                self.ui.radio_tr.setChecked(True)
            elif show_content.icon.position == model.Icon.PERSONALIZED:
                self.ui.radio_free_position.setChecked(True)
                
            self.set_icon_boundaries(show_content.icon.bondaries)
            
            before_str = str(show_content.icon.relative_time)
            for index in xrange(self.ui.cmb_icon_before.count()):
                str_index = str(self.ui.cmb_icon_before.itemText(index))
                if before_str == str_index:
                    self.ui.cmb_icon_before.setCurrentIndex(index)
                    break
                
            duration_str = str(show_content.icon.duration_time)
            for index in xrange(self.ui.cmb_icon_duration.count()):
                str_index = str(self.ui.cmb_icon_duration.itemText(index))
                if duration_str == str_index:
                    self.ui.cmb_icon_duration.setCurrentIndex(index)
                    break
                
            for content in show_content.contents:
                self.add_media_widget.add_media_item(content)
                
                
            if show_content.interaction_type == model.ShowContent.SHOW_CONTENT:
                self.ui.radio_show.setChecked(True)
            elif show_content.interaction_type == model.ShowContent.SKIP:
                self.ui.radio_skip.setChecked(True)
                self.ui.time_skip_point.setTime(util.sec_to_qtime(show_content.skip_point))
            elif show_content.interaction_type == model.ShowContent.BACK_5:
                self.ui.radio_back.setChecked(True)
            elif show_content.interaction_type == model.ShowContent.BACK_TO:
                self.ui.radio_back_to.setChecked(True)
                self.ui.time_back_point.setTime(util.sec_to_qtime(show_content.back_point))
                self.ui.time_back_limite.setTime(util.sec_to_qtime(show_content.back_limite))
            
            self.ui.btn_preview.setEnabled(True)
            self.add_media_widget.update_media_list()
            
            
    @QtCore.pyqtSlot(int)
    def update_time_edit(self, time):
        if not self.is_editing_time:
            time_edit = self.ui.time_media
            time_edit.setTime(QtCore.QTime().addMSecs(time))
        
    
    @QtCore.pyqtSlot(QtCore.QTime)
    def editing_time(self, time):
        '''if self.is_editing_time:
            total_time = self.player.player.mediaObject().totalTime()
            max_time = QtCore.QTime(0,0,0).addMSecs(total_time)
            self.ui.time_edit.setTimeRange(QtCore.QTime(0,0,0), max_time)
            
            
            msec = time.hour()
            msec = time.minute() + msec*60
            msec = time.second() + msec*60
            msec = msec*1000 + time.msec()
            self.ui.video_player.seek(msec)'''
        pass
        
    def get_result(self):
        return self.result
    
    def set_icon_boundaries(self, bound):
        self.lbl_icon.move(bound.left, bound.top)
        self.lbl_icon.resize(bound.width, bound.height)
    
    def get_icon_bondaries(self):
        bound = Bondaries()
        qpoint = self.lbl_icon.pos()
        qsize = self.lbl_icon.size()
        bound.width = qsize.width()
        bound.height = qsize.height()
        bound.left = qpoint.x()
        bound.top = qpoint.y()
        qsize = self.lbl_screen.size()
        bound.screen_width, bound.screen_height = qsize.width(), qsize.height()
        print bound
        return bound
        
    def init_ui(self):
        self.setFixedSize(self.size())
        self.ui.radio_info.setChecked(True)
        self.ui.radio_tl.setChecked(True)
        self.ui.btn_choose_icon.setEnabled(False)
        
        self.ui.tabs.setCurrentIndex(0)
        
        layout = QtGui.QHBoxLayout()
        self.ui.tab_content.setLayout(layout)
        self.add_media_widget = AddMediaWidget(self.project, self.annotation)
        layout.addWidget(self.add_media_widget)
        
        self.ui.radio_personalized.toggled.connect(self.personalized_choosed)
        self.ui.btn_choose_icon.clicked.connect(self.choose_icon)
        
        self.lbl_screen = QtGui.QLabel(self.ui.widget_icon)
        self.lbl_screen.resize(self.ui.widget_icon.size())
        self.lbl_screen.setStyleSheet('background-color: rgb(0, 0, 0); \
                                        border-color: rgb(255, 255, 255);\
                                        font: 75 28pt "Ubuntu";\
                                        color: rgb(255, 255, 127);')
        self.lbl_screen.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_screen.setText("Tela")
        
        self.lbl_icon = MovebleLabel(u"", self.ui.widget_icon)
        self.lbl_icon.resize(30,30)
        self.lbl_icon.move(10,10)
        self.lbl_icon.setStyleSheet('background-color: rgb(255, 255, 0);\
                                            border-color: rgb(255, 255, 255);\
                                            font: 75 8pt "Ubuntu";\
                                            color: rgb(0, 0, 0);')
        self.lbl_icon.setEnabled(False)
        
        self.ui.radio_bl.toggled.connect(self.selected_bl)
        self.ui.radio_br.toggled.connect(self.selected_br)
        self.ui.radio_tr.toggled.connect(self.selected_tr)
        self.ui.radio_tl.toggled.connect(self.selected_tl)
        self.ui.radio_free_position.toggled.connect(self.selected_free_position)
        
        self.ui.btn_ok.clicked.connect(self.ok_pressed)
        self.ui.btn_cancel.clicked.connect(self.cancel_pressed)
        self.ui.btn_preview.clicked.connect(self.preview)
        self.ui.btn_preview.setEnabled(False)
        
        #player_holder = self.ui.player_widget
        #layout = QtGui.QVBoxLayout()
        self.player = VideoPlayer(parent=self.ui.player_widget)
        #layout.addWidget(self.player)
        #self.ui.tab_interaction.setLayout(layout)
        self.player.load_video(self.project.main_media)
        self.player.player.mediaObject().tick.connect(self.update_time_edit)
        #self.player.move(50,0)
        
        
        self.ui.radio_show.toggled.connect(self.selected_show)
        self.ui.radio_back.toggled.connect(self.selected_back)
        self.ui.radio_back_to.toggled.connect(self.selected_back_to)
        self.ui.radio_skip.toggled.connect(self.selected_skip)
        
        self.ui.btn_back_limite.clicked.connect(self.use_time_for_back_limite)
        self.ui.btn_back_point.clicked.connect(self.use_time_for_back_point)
        self.ui.btn_skip.clicked.connect(self.use_time_for_skip)
        
        self.ui.time_media.timeChanged.connect(self.editing_time)
        self.ui.time_media.installEventFilter(self)
        self.ui.time_media.setEnabled(False)
        
        self.ui.radio_show.setChecked(True)
        
        self.ui.ckb_audio.toggled.connect(self.toogled_audio_alert)
        self.ui.btn_choose_audio.clicked.connect(self.choose_audio)
        self.ui.btn_play_audio.clicked.connect(self.play_audio)
    
    @QtCore.pyqtSlot(bool)
    def toogled_audio_alert(self, value):
        if value:
            self.ui.btn_choose_audio.setEnabled(True)
            self.ui.btn_play_audio.setEnabled(True)
            self.ui.txt_sound.setEnabled(True)
        else:
            self.ui.btn_choose_audio.setEnabled(False)
            self.ui.btn_play_audio.setEnabled(False)
            self.ui.txt_sound.setEnabled(False)
    
    @QtCore.pyqtSlot()
    def choose_audio(self):
        path = QtGui.QFileDialog.getOpenFileName(self, 
                                                 u'Selecione um áudio',
                                                 HOME_DIRECTORY,
                                                 model.CONTENT_TYPES[model.Media.AUDIO])
        if path == None:
            return
        
        
        
        self.audio_path = unicode(path)
        self.audio_player = AudioPlayer()
        self.ui.txt_sound.clear()
        self.ui.txt_sound.append(os.path.split(self.audio_path)[1])
        self.audio_player.load_audio(self.audio_path)
        self.audio_player.setVisible(False)
    
    @QtCore.pyqtSlot()
    def play_audio(self):
        self.audio_player.play()
        
    def eventFilter(self, myObject, event):
        if myObject == self.ui.time_media:
            if event.type() == QtCore.QEvent.FocusIn:
                self.timer_focus_in()
            elif event.type() == QtCore.QEvent.FocusOut:
                pass
            
        return False
        
    @QtCore.pyqtSlot()
    def use_time_for_back_limite(self):
        self.ui.time_back_limite.setTime(self.ui.time_media.time())
    
    def use_time_for_back_point(self):
        self.ui.time_back_point.setTime(self.ui.time_media.time())
    
    def use_time_for_skip(self):
        self.ui.time_skip_point.setTime(self.ui.time_media.time())
        
    @QtCore.pyqtSlot(bool)
    def selected_show(self, value):
        self.player.stop()
        self.player.setVisible(False)
        self.ui.time_back_limite.setVisible(False)
        self.ui.time_back_point.setVisible(False)
        self.ui.time_skip_point.setVisible(False)
        self.ui.time_media.setVisible(False)
        self.ui.lbl_back_limite.setVisible(False)
        self.ui.lbl_back_point.setVisible(False)
        self.ui.lbl_current_time.setVisible(False)
        self.ui.lbl_skip.setVisible(False)
        self.ui.btn_skip.setVisible(False)
        self.ui.btn_back_limite.setVisible(False)
        self.ui.btn_back_point.setVisible(False)
        
    @QtCore.pyqtSlot(bool)
    def selected_back(self, value):
        self.player.stop()
        self.player.setVisible(False)
        self.ui.time_back_limite.setVisible(False)
        self.ui.time_back_point.setVisible(False)
        self.ui.time_skip_point.setVisible(False)
        self.ui.time_media.setVisible(False)
        self.ui.lbl_back_limite.setVisible(False)
        self.ui.lbl_back_point.setVisible(False)
        self.ui.lbl_current_time.setVisible(False)
        self.ui.lbl_skip.setVisible(False)
        self.ui.btn_skip.setVisible(False)
        self.ui.btn_back_limite.setVisible(False)
        self.ui.btn_back_point.setVisible(False)
    
    @QtCore.pyqtSlot(bool)
    def selected_back_to(self, value):
        self.player.stop()
        self.player.setVisible(True)
        self.ui.time_back_limite.setVisible(True)
        self.ui.time_back_point.setVisible(True)
        self.ui.time_skip_point.setVisible(False)
        self.ui.time_media.setVisible(True)
        self.ui.lbl_back_limite.setVisible(True)
        self.ui.lbl_back_point.setVisible(True)
        self.ui.lbl_current_time.setVisible(True)
        self.ui.lbl_skip.setVisible(False)
        self.ui.btn_skip.setVisible(False)
        self.ui.btn_back_limite.setVisible(True)
        self.ui.btn_back_point.setVisible(True)
        
    @QtCore.pyqtSlot(bool)
    def selected_skip(self, value):
        self.player.stop()
        self.player.setVisible(True)
        self.ui.time_back_limite.setVisible(False)
        self.ui.time_back_point.setVisible(False)
        self.ui.time_skip_point.setVisible(True)
        self.ui.time_media.setVisible(True)
        self.ui.lbl_back_limite.setVisible(False)
        self.ui.lbl_back_point.setVisible(False)
        self.ui.lbl_current_time.setVisible(True)
        self.ui.lbl_skip.setVisible(True)
        self.ui.btn_skip.setVisible(True)
        self.ui.btn_back_limite.setVisible(False)
        self.ui.btn_back_point.setVisible(False)
        
    @QtCore.pyqtSlot()
    def ok_pressed(self):
        show_content = model.ShowContent()
        show_content.compulsory =  self.ui.ckb_compulsory.isChecked()
        show_content.interactive =  self.ui.ckb_interactive.isChecked()
        show_content.allow_end_content = self.ui.ckb_allows_end_content.isChecked()
        show_content.tv = self.ui.ckb_show_on_tv.isChecked()
        show_content.mobile = self.ui.ckb_show_on_mobile.isChecked()
        show_content.pause_main_video = self.ui.ckb_pause_main_video.isChecked()
        show_content.viber_alert = self.ui.ckb_viber.isChecked()
        
        icon = model.Icon()
        if self.ui.radio_personalized.isChecked():
            self.icon_path = util.copy_to_directory(self.project, unicode(self.icon_path))
            icon.image = self.icon_path
            show_content.button = str(self.ui.cmb_button.currentText())
        elif self.ui.radio_info.isChecked():
            icon.image = model.Icon.INFO
            show_content.button = "GREEN"
        elif self.ui.radio_sexual.isChecked():
            icon.image = model.Icon.SEXUAL
            show_content.button = "RED"
        elif self.ui.radio_violence.isChecked():
            icon.image = model.Icon.VIOLENCE
            show_content.button = "RED"
        elif self.ui.radio_yes.isChecked():
            icon.image = model.Icon.YES
            show_content.button = "GREEN"
        elif self.ui.radio_no.isChecked():
            icon.image = model.Icon.NO
            show_content.button = "RED"
            
        icon.relative_time = int(self.ui.cmb_icon_before.itemText(
                                            self.ui.cmb_icon_before.currentIndex()))
        icon.duration_time = int(self.ui.cmb_icon_duration.itemText(
                                            self.ui.cmb_icon_duration.currentIndex()))
        icon.bondaries = self.get_icon_bondaries()
        
        if self.ui.radio_bl.isChecked():
            icon.position = model.Icon.BOT_LEFT
        elif self.ui.radio_br.isChecked():
            icon.position = model.Icon.BOT_RIGHT
        elif self.ui.radio_tl.isChecked():
            icon.position = model.Icon.TOP_LEFT
        elif self.ui.radio_tr.isChecked():
            icon.position = model.Icon.TOP_RIGHT
        elif self.ui.radio_free_position.isChecked():
            icon.position = model.Icon.PERSONALIZED
        
        show_content.icon = icon
        
        if self.ui.ckb_audio.isChecked():
            if self.audio_path is not None:
                realpath = util.copy_to_directory(self.project, 
                                                  self.audio_path)
                
                show_content.sound_alert = realpath
        
        for media in self.add_media_widget.medias:
            show_content.add_content(media)
            
        self.annotation.description = unicode(self.ui.textEdit.toPlainText())
        self.annotation.interaction = show_content
        
        self.annotation.annotation_time = self.ui.time_begin.time()
        self.annotation.description = self.ui.textEdit.toPlainText()
        
        if self.ui.radio_show.isChecked():
            show_content.interaction_type = model.ShowContent.SHOW_CONTENT         
        elif self.ui.radio_skip.isChecked():
            show_content.interaction_type = model.ShowContent.SKIP
            show_content.skip_point = util.qtime_to_sec(self.ui.time_skip_point.time())
        elif self.ui.radio_back.isChecked():
            show_content.interaction_type = model.ShowContent.BACK_5
        elif self.ui.radio_back_to.isChecked():
            print 'back_to'
            show_content.interaction_type = model.ShowContent.BACK_TO
            show_content.back_point = util.qtime_to_sec(self.ui.time_back_point.time())
            show_content.back_limite = util.qtime_to_sec(self.ui.time_back_limite.time())
        
        
        self.result = show_content
        
        self.close()
        
    @QtCore.pyqtSlot()
    def preview(self):
        import generation
        try:
            begintime = util.qtime_to_sec(self.annotation.annotation_time)
            begintime = begintime - int(self.ui.cmb_icon_before.currentText()) - 3
            
            nclgenerator = generation.NclGenerator(self.project, 
                                                   generation.GenerationOptions())
            
            print self.project.directory
            nclgenerator.dump_file(os.path.join(self.project.directory, 
                                                'medias', 'main.ncl'),
                                   begintime)
            
            current_path = os.path.dirname(os.path.realpath(__file__))
            
            src = os.path.join(os.path.split(current_path)[0], 'files', 'medias', "connBase.ncl")
            dst = os.path.join(self.project.directory, "medias", "connBase.ncl")
            import shutil
            
            shutil.copy(src, dst)
        except:
            logging.exception('Error Generating the NCL')
            QtGui.QMessageBox.warning(self, u'Gerando NCL', u"Aconteceu um erro ao gerar o documento multimídia", QtGui.QMessageBox.Ok)
            return
            
        
        import subprocess as sp
        html = os.path.join(self.project.directory, "index.html")
        current_path = os.path.dirname(os.path.realpath(__file__))
        script_path = os.path.join(os.path.split(current_path)[0], 'browser.py')
        sp.Popen(['python', script_path, html])
    
    @QtCore.pyqtSlot()
    def cancel_pressed(self):
        self.close()
        
    @QtCore.pyqtSlot(bool)
    def selected_bl(self, value):
        self.lbl_icon.resize(30,30)
        self.lbl_icon.move(10,150)
        self.lbl_icon.setEnabled(False)
    
    @QtCore.pyqtSlot(bool)
    def selected_br(self, value):
        self.lbl_icon.resize(30,30)
        self.lbl_icon.move(300,150)
        self.lbl_icon.setEnabled(False)
    
    @QtCore.pyqtSlot(bool)
    def selected_tr(self, value):
        self.lbl_icon.resize(30,30)
        self.lbl_icon.move(300,10)
        self.lbl_icon.setEnabled(False)
    
    @QtCore.pyqtSlot(bool)
    def selected_tl(self, value):
        self.lbl_icon.resize(30,30)
        self.lbl_icon.move(10,10)
        self.lbl_icon.setEnabled(False)
    
    @QtCore.pyqtSlot(bool)
    def selected_free_position(self, value):
        self.lbl_icon.setEnabled(True)
        
    @QtCore.pyqtSlot()
    def choose_icon(self):
        path = QtGui.QFileDialog.getOpenFileName(self, 
                                                 u'Selecione uma imagem',
                                                 HOME_DIRECTORY,
                                                 model.CONTENT_TYPES[model.Media.IMAGE])
        if path == None:
            return
        
        self.icon_path = path
        self.ui.radio_personalized.setIcon(QtGui.QIcon(path))
        self.ui.radio_personalized.setText("...")
    
    @QtCore.pyqtSlot(bool)
    def personalized_choosed(self, checked):
        if checked:
            self.ui.btn_choose_icon.setEnabled(True)
        else:
            self.ui.btn_choose_icon.setEnabled(False)
class MainProjectWidget(QtGui.QWidget):
    
    annotation_list_chaged = QtCore.pyqtSignal()
    
    def __init__(self, project, parent=None):
        super(MainProjectWidget, self).__init__(parent)
        self.ui = Ui_MainProjectWidget()
        self.ui.setupUi(self)
        self.project_diretory = project.directory
        self.main_video_path = None
        self.is_editing_time = False
        self.open_widgets = []
        self.project = project

        
        self.init_ui()
        self.load_project()
        
        self.show()
    
    #@QtCore.pyqtSlot(int)
    #def on_video_seek(self, point):
    
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, u"Fechando o projeto...", 
                                           u"Tem certeza que deseja fechar este projeto?",
                                           QtGui.QMessageBox.Yes|QtGui.QMessageBox.No);
                                           
        if reply == QtGui.QMessageBox.No:
            event.ignore()
        else:
            from ProjectChooseWidget import ProjectChooseWidget
            self._choose_widget = ProjectChooseWidget(real_path, home_directory, username)
            event.accept()
        #from ProjectChooseWidget import ProjectChooseWidget
        #self._choose_widget = ProjectChooseWidget(real_path, home_directory, username)
        
        
        
    def init_ui(self):
        self.setWindowTitle(u'Projeto - ' + self.project.name)
        self.setFixedSize(self.size())
        
        player_holder = self.ui.player_widget
        layout = QtGui.QVBoxLayout()
        self.player = VideoPlayer()
        layout.addWidget(self.player)
        player_holder.setLayout(layout)
        
        #self.player.ui.seek_slider.mouse_released.connect(self.update_time_edit)
        
        self.ui.frame_edit.setVisible(False)
        
        self.ui.btn_choose_video.clicked.connect(self.choose_video)
        
        self.ui.btn_add_annotation.clicked.connect(self.add_annotation)
        #self.ui.btn_delete.clicked.connect(self.delete_annotation)
        #self.ui.btn_edit.clicked.connect(self.edit_annotation)
        self.annotation_list_chaged.connect(self.update_annotation_list)
        self.ui.txt_description.textChanged.connect(self.description_changed)
        #self.ui.list_notes.doubleClicked.connect(self.click_over_list)
        
        #self.player.mediaObject().tick.connect(self.update_time_edit)
        self.ui.time_edit.timeChanged.connect(self.editing_time)
        self.ui.time_edit.installEventFilter(self)
        
        self.ui.btn_save_project.clicked.connect(self.save_project)
        self.ui.btn_generate_ncl.clicked.connect(self.generate_ncl)
        self.ui.btn_generate_ncl.setText(u"Gerar e Exibir")
        self.ui.btn_close_project.clicked.connect(self.close_project)
        self.ui.btn_generate_ncl.setEnabled(True)
        
        self.ui.btn_ok.clicked.connect(self.save_edit)
        self.ui.btn_cancel.clicked.connect(self.cancel_edit)
        
        
    def load_project(self):
        project = self.project
        if project.main_media:
            self.main_video_path = project.main_media           
            self.player.load_video(self.main_video_path)
            self.player.player.mediaObject().tick.connect(self.update_time_edit)
            self.ui.txt_main_video.appendPlainText(self.main_video_path)
            self.update_annotation_list()
        
    def eventFilter(self, myObject, event):
        if myObject == self.ui.time_edit:
            if event.type() == QtCore.QEvent.FocusIn:
                self.timer_focus_in()
            elif event.type() == QtCore.QEvent.FocusOut:
                pass
            
        return False
    
    @QtCore.pyqtSlot()
    def close_project(self):
        self.close()
        
        
        
    
    @QtCore.pyqtSlot()
    def save_project(self):
        print self.main_video_path
        self.project.main_media = self.main_video_path
        from datetime import datetime
        self.project.last_modification = datetime.now()
        project_path = os.path.join(unicode(self.project_diretory), 'project.json')
        json_object = self.project.to_json()
        myfile = open(project_path, "w")
        
        import json
        myfile.write(json.dumps(json_object, indent=4, sort_keys=True))
        QtGui.QMessageBox.information(self, u'Salvando projeto...', u'O projeto foi salvo com sucesso.')
        
    
    @QtCore.pyqtSlot()
    def description_changed(self):
        self.player.pause()
    
    @QtCore.pyqtSlot()
    def generate_ncl(self):
        print self.main_video_path
        self.project.main_media = self.main_video_path
        #from datetime import datetime
        self.project.last_modification = datetime.now()
        project_path = os.path.join(unicode(self.project_diretory), 'project.json')
        json_object = self.project.to_json()
        myfile = open(project_path, "w")
        
        import json
        myfile.write(json.dumps(json_object, indent=4, sort_keys=True))
        
        import generation
        try:
            nclgenerator = generation.NclGenerator(self.project, 
                                                   generation.GenerationOptions())
            
            print self.project.directory
            nclgenerator.dump_file(os.path.join(self.project.directory, 
                                                'medias', 'main.ncl'))
            
            current_path = os.path.dirname(os.path.realpath(__file__))
            
            src = os.path.join(os.path.split(current_path)[0], 'files', 'medias', "connBase.ncl")
            dst = os.path.join(self.project_diretory, "medias", "connBase.ncl")
            import shutil
            
            shutil.copy(src, dst)
        except:
            logging.exception('Error Generating the NCL')
            QtGui.QMessageBox.warning(self, u'Gerando NCL', u"Aconteceu um erro ao gerar o documento multimídia", QtGui.QMessageBox.Ok)
            return
            
        QtGui.QMessageBox.information(self, u'Gerando NCL', u"Documento multimídia gerado com sucesso ", QtGui.QMessageBox.Ok)
        
        import subprocess as sp
        html = os.path.join(self.project.directory, "index.html")
        current_path = os.path.dirname(os.path.realpath(__file__))
        script_path = os.path.join(os.path.split(current_path)[0], 'browser.py')
        sp.Popen(['python', script_path, html])
        
    @QtCore.pyqtSlot()
    def update_annotation_list(self):
        self.ui.list_notes.clear()
        sorted_annotations = sorted(self.project.annotations, 
                                    key=lambda ann: ann.annotation_time)
        
        for annotation in sorted_annotations:
            anotationItem = AnnotationListItem(annotation, self)
            item = QtGui.QListWidgetItem()
            item.setSizeHint(QtCore.QSize(40,60))
            self.ui.list_notes.addItem(item)
            self.ui.list_notes.setItemWidget(item, anotationItem)
    
    def save_annotation(self, widget, annotation):
        try:
            self.project.add_annotation(annotation)
        except:
            pass
        try:
            self.annotation_list_chaged.emit()
            self.open_widgets.remove(widget)
        except:
            logger.exception("Error Saving the Annotation.")
    
    def cancel_annotation(self, widget):
        try:
            self.open_widgets.remove(widget)
        except:
            logger.exception("Error Canceling the Annotation.")
            
            
    @QtCore.pyqtSlot()
    def delete_annotation(self):
        item = self.ui.list_notes.currentItem()
        annotation = self.ui.list_notes.itemWidget(item).annotation
        reply = QtGui.QMessageBox.question(self, u"Deletando anotação...", 
                                           u"Tem certeza que excluir esta anotação?",
                                           QtGui.QMessageBox.Yes|QtGui.QMessageBox.No);
                                           
        if reply == QtGui.QMessageBox.No:
            return
        
        if self.project.remove_annotation(annotation):
            self.annotation_list_chaged.emit()
            
            
    @QtCore.pyqtSlot()
    def show_content_widget(self):
        item = self.ui.list_notes.currentItem()
        annotation = self.ui.list_notes.itemWidget(item).annotation
        
        from ShowContent import ShowContent
        widget = ShowContent(self.project, annotation, parent=self)
        widget.exec_()
        self.update_annotation_list()
        
    @QtCore.pyqtSlot()
    def visualize_annotation(self):   
        item = self.ui.list_notes.currentItem()
        annotation = self.ui.list_notes.itemWidget(item).annotation
        import util
        import generation
        try:
            begintime = util.qtime_to_sec(annotation.annotation_time)
            begintime = begintime - annotation.interaction.icon.relative_time - 3
            
            nclgenerator = generation.NclGenerator(self.project, 
                                                   generation.GenerationOptions())
            
            print self.project.directory
            nclgenerator.dump_file(os.path.join(self.project.directory, 
                                                'medias', 'main.ncl'),
                                   begintime)
            
            current_path = os.path.dirname(os.path.realpath(__file__))
            
            src = os.path.join(os.path.split(current_path)[0], 'files', 'medias', "connBase.ncl")
            dst = os.path.join(self.project.directory, "medias", "connBase.ncl")
            import shutil
            
            shutil.copy(src, dst)
        except:
            logging.exception('Error Generating the NCL')
            QtGui.QMessageBox.warning(self, u'Gerando NCL', u"Aconteceu um erro ao gerar o documento multimídia", QtGui.QMessageBox.Ok)
            return
            
        
        import subprocess as sp
        html = os.path.join(self.project.directory, "index.html")
        current_path = os.path.dirname(os.path.realpath(__file__))
        script_path = os.path.join(os.path.split(current_path)[0], 'browser.py')
        sp.Popen(['python', script_path, html])
        
    
    @QtCore.pyqtSlot()
    def edit_annotation(self):
        item = self.ui.list_notes.currentItem()
        self.editing_annotation = self.ui.list_notes.itemWidget(item).annotation
        self.ui.txt_description.setText(self.editing_annotation.description)
        self.ui.time_edit.setTime(self.editing_annotation.annotation_time)
        self.ui.frame_edit.setVisible(True)
        self.ui.txt_description.setFocus()
        
        self.ui.frame_notes.setEnabled(False)
        self.ui.btn_add_annotation.setVisible(False)
        self.ui.btn_save_project.setVisible(False)
        self.ui.btn_generate_ncl.setVisible(False)
        
        
    @QtCore.pyqtSlot()
    def cancel_edit(self):
        self.ui.frame_edit.setVisible(False)
        self.ui.frame_notes.setEnabled(True)
        self.ui.btn_add_annotation.setVisible(True)
        self.ui.btn_save_project.setVisible(True)
        self.ui.btn_generate_ncl.setVisible(True)
        self.ui.txt_description.setText("")
        
        
    @QtCore.pyqtSlot()
    def save_edit(self):
        self.editing_annotation.description = unicode(self.ui.txt_description.toPlainText())
        self.editing_annotation.annotation_time = self.ui.time_edit.time()
        
        self.ui.frame_edit.setVisible(False)
        self.ui.frame_notes.setEnabled(True)
        self.ui.btn_add_annotation.setVisible(True)
        self.ui.btn_save_project.setVisible(True)
        self.ui.btn_generate_ncl.setVisible(True)
        self.ui.txt_description.setText("")
        self.annotation_list_chaged.emit()
        
        QtGui.QMessageBox.information(self, u'Salvando anotação...', u'A anotação foi salva com sucesso.', QtGui.QMessageBox.Ok)
    
        
    @QtCore.pyqtSlot()
    def add_annotation(self):
        if unicode(self.ui.txt_description.toPlainText()) == "":
            QtGui.QMessageBox.warning(self, u"Adicionando Anotação...",
                                      u"Por favor, entre com os detalhes da sua anotação.", 
                                      buttons=QtGui.QMessageBox.Ok)
            return
        
        self.player.pause()
        print self.ui.time_edit.time()
        annotation = model.Annotation(self.project.generate_annotation_id(), 
                                      datetime.now())
        description = self.ui.txt_description.toPlainText()
        
        if description != "":
            annotation.description = description
            
        print self.ui.time_edit.time()
        annotation.annotation_time = self.ui.time_edit.time()
        
        self.project.add_annotation(annotation)
        self.ui.txt_description.setText("")
        self.annotation_list_chaged.emit()
        QtGui.QMessageBox.information(self, u'Adicionando anotação...', u'A anotação foi adicionada com sucesso.', QtGui.QMessageBox.Ok)
        
        
        
        
    @QtCore.pyqtSlot(int)
    def update_time_edit(self, time):
        if not self.is_editing_time:
            time_edit = self.ui.time_edit
            time_edit.setTime(QtCore.QTime().addMSecs(time))
        
        
    @QtCore.pyqtSlot()
    def start_playback(self):
        player = self.ui.video_player
        player.play()
        self.ui.btn_pause.setVisible(True)
        self.ui.btn_play.setVisible(False)
        self.ui.btn_stop.setEnabled(True)
        self.is_editing_time = False
        
    
    @QtCore.pyqtSlot(QtCore.QTime)
    def editing_time(self, time):
        '''if self.is_editing_time:
            total_time = self.player.player.mediaObject().totalTime()
            max_time = QtCore.QTime(0,0,0).addMSecs(total_time)
            self.ui.time_edit.setTimeRange(QtCore.QTime(0,0,0), max_time)
            
            
            msec = time.hour()
            msec = time.minute() + msec*60
            msec = time.second() + msec*60
            msec = msec*1000 + time.msec()
            self.ui.video_player.seek(msec)'''
        pass
            
            
    def timer_focus_in(self):
        self.player.pause()
        self.is_editing_time = True
        
    
    @QtCore.pyqtSlot()
    def choose_video(self):
        path = QtGui.QFileDialog.getOpenFileName(self, 
                                                 u'Selecione o Vídeo Principal',
                                                 unicode(self.project_diretory),
                                                 model.CONTENT_TYPES[model.Media.VIDEO])
        
        print path
        if path is None:
            return
        
        if not os.path.exists(path):
            return
        
        import util
        
        
        self.main_video_path = util.copy_with_dialog(self.project, unicode(path))           
        self.ui.txt_main_video.clear()
        self.ui.txt_main_video.appendPlainText(self.main_video_path)
        
        self.player.stop()
        self.player.load_video( self.main_video_path )
        self.player.player.mediaObject().tick.connect(self.update_time_edit)
        self.player.play()
Beispiel #30
0
class Player:
        
    def btnPlayPause_Clicked(self):
        # Make sure it is showing the correct frame
        self.videoPlayer1.updatedFrames = self.videoPlayer2.updatedFrames

        # Define thread to play
        if not hasattr(self, 'threadPlayOn'):
            self.eventPause = threading.Event()
            self.threadPlayOn = threading.Thread(target=self.PlayOn, args=[]) # Play video from current frame on
            self.eventPause.set()
            # Frames could have changed before first play together
            self.videoPlayer1.cvVideo.set(cv2.CAP_PROP_POS_FRAMES, self.videoPlayer1.currentFrameNbr)
            self.videoPlayer2.cvVideo.set(cv2.CAP_PROP_POS_FRAMES, self.videoPlayer2.currentFrameNbr)
            self.threadPlayOn.start()
        if self.statusPlayer == StatusPlayer.NOT_STARTED: # it hasnt started yet
            self.ChangeNavButtonsStatus(False) # disable navigation buttons
            self.statusPlayer = StatusPlayer.PLAYING # let's play it
            # Update status to each video
            self.videoPlayer1.statusPlayer = StatusPlayer.PLAYING
            self.videoPlayer2.statusPlayer = StatusPlayer.PLAYING
            self.btnPlayPause.config(image=self.imgPause) # image shows it can be paused
            # Enable/Disable buttons
            self.videoPlayer1.ChangeNavButtonsStatus(False) #disable buttons on video1
            self.videoPlayer2.ChangeNavButtonsStatus(False) #disable buttons on video2
            self.videoPlayer1.btnPlayPause.config(state="disabled")
            self.videoPlayer2.btnPlayPause.config(state="disabled")
            self.videoPlayer1.btnPlayPause.config(image=self.imgPause)
            self.videoPlayer2.btnPlayPause.config(image=self.imgPause)
            self.videoPlayer1.lblFrameNumber.configure(text="Frame: %d/%d" % (self.videoPlayer1.currentFrameNbr,self.videoPlayer1.totalFrames))
            self.videoPlayer2.lblFrameNumber.configure(text="Frame: %d/%d" % (self.videoPlayer2.currentFrameNbr,self.videoPlayer2.totalFrames))
            # Define thread to play
            self.eventPause.set() # set event to release it
        elif self.statusPlayer == StatusPlayer.PLAYING: # it is playing
            # Enable/Disable buttons
            self.videoPlayer1.ChangeNavButtonsStatus(True) #enable buttons on video1
            self.videoPlayer2.ChangeNavButtonsStatus(True) #enable buttons on video2
            self.videoPlayer1.btnPlayPause.config(state="normal")
            self.videoPlayer2.btnPlayPause.config(state="normal")
            self.videoPlayer1.btnPlayPause.config(image=self.imgPlay)
            self.videoPlayer2.btnPlayPause.config(image=self.imgPlay)
            self.ChangeNavButtonsStatus(True) # enable navigation buttons
            self.statusPlayer = StatusPlayer.PAUSED # let's pause it
            # Update status to each video
            self.videoPlayer1.statusPlayer = StatusPlayer.PAUSED
            self.videoPlayer2.statusPlayer = StatusPlayer.PAUSED
            self.eventPause.set() # set event to pause it
            self.btnPlayPause.config(image=self.imgPlay) # image shows it can be played
        elif self.statusPlayer == StatusPlayer.PAUSED: # it is paused
             # Enable/Disable buttons
            self.videoPlayer1.ChangeNavButtonsStatus(False) #disable buttons on video1
            self.videoPlayer2.ChangeNavButtonsStatus(False) #disable buttons on video2
            self.videoPlayer1.btnPlayPause.config(state="disabled")
            self.videoPlayer2.btnPlayPause.config(state="disabled")
            self.videoPlayer1.btnPlayPause.config(image=self.imgPause)
            self.videoPlayer2.btnPlayPause.config(image=self.imgPause)
            self.ChangeNavButtonsStatus(False) # disable navigation buttons
            self.statusPlayer = StatusPlayer.PLAYING # let's play it 
            # Update status to each video
            self.videoPlayer1.statusPlayer = StatusPlayer.PLAYING
            self.videoPlayer2.statusPlayer = StatusPlayer.PLAYING
            self.btnPlayPause.config(image=self.imgPause) # image shows it can be paused
            self.eventPause.set() # set event again to release it
    
    def callback_PlayPause(self, enableButtons, newStatus):
        # if (self.loadedFrame1 == True and self.loadedFrame2 == True):
        if self.videoPlayer1.updatedFrames == True and self.videoPlayer2.updatedFrames == True:
            self.statusPlayer = newStatus
            self.ChangeNavButtonsStatus(enableButtons)
            if enableButtons:
                self.btnPlayPause.config(state="normal")
            else:
                self.btnPlayPause.config(state="disabled")

    def ChangeNavButtonsStatus(self, enable):
        if enable:
            self.btnBackwardsBeg.config(state="normal")
            self.btnBackwards1.config(state="normal")
            self.btnBackwards5.config(state="normal")
            self.btnBackwards10.config(state="normal")
            self.btnForwardEnd.config(state="normal")
            self.btnForward1.config(state="normal")
            self.btnForward5.config(state="normal")
            self.btnForward10.config(state="normal")
            self.btnSelectFrame.config(state="normal")
        else:
            self.btnBackwardsBeg.config(state="disabled")
            self.btnBackwards1.config(state="disabled")
            self.btnBackwards5.config(state="disabled")
            self.btnBackwards10.config(state="disabled")
            self.btnForwardEnd.config(state="disabled")
            self.btnForward1.config(state="disabled")
            self.btnForward5.config(state="disabled")
            self.btnForward10.config(state="disabled")
            self.btnSelectFrame.config(state="disabled")

    def PlayOn(self):
        # Plays until both videos have frames to play
        while self.videoPlayer1.cvVideo.isOpened() and self.videoPlayer2.cvVideo.isOpened():
            # If pause event is set to True
            if self.eventPause.isSet():
                self.eventPause.clear() # Set it to False, so we can wait (if it is not cleared, it is True, and it wont be able to wait)
                self.eventPause.wait() # wait unitl it is set again
                self.eventPause.clear()
            ret1,frame1 = self.videoPlayer1.cvVideo.read()
            ret2,frame2 = self.videoPlayer2.cvVideo.read()
            if ret1 and ret2:
                self.videoPlayer1.currentFrameNbr += 1
                self.videoPlayer2.currentFrameNbr += 1
                self.videoPlayer1.ResizeAndRenderFrame(frame1, skippingFrame=False)
                self.videoPlayer2.ResizeAndRenderFrame(frame2, skippingFrame=False)
                self.videoPlayer1.lblFrameNumber.configure(text="Frame: %d/%d" % (self.videoPlayer1.currentFrameNbr,self.videoPlayer1.totalFrames))
                self.videoPlayer2.lblFrameNumber.configure(text="Frame: %d/%d" % (self.videoPlayer2.currentFrameNbr,self.videoPlayer2.totalFrames))
        
    def btnBackwardsBeg_Clicked(self):
        self.videoPlayer1.btnBackwardsBeg_Clicked()
        self.videoPlayer2.btnBackwardsBeg_Clicked()

    def btnBackwards10_Clicked(self):
        self.videoPlayer1.btnBackwards10_Clicked()
        self.videoPlayer2.btnBackwards10_Clicked()

    def btnBackwards5_Clicked(self):
        self.videoPlayer1.btnBackwards5_Clicked()
        self.videoPlayer2.btnBackwards5_Clicked()

    def btnBackwards1_Clicked(self):
        self.videoPlayer1.btnBackwards1_Clicked()
        self.videoPlayer2.btnBackwards1_Clicked()

    def btnForward1_Clicked(self):
        self.videoPlayer1.btnForward1_Clicked()
        self.videoPlayer2.btnForward1_Clicked()

    def btnForward5_Clicked(self):
        self.videoPlayer1.btnForward5_Clicked()
        self.videoPlayer2.btnForward5_Clicked()

    def btnForward10_Clicked(self):
        self.videoPlayer1.btnForward10_Clicked()
        self.videoPlayer2.btnForward10_Clicked()
    
    def btnForwardEnd_Clicked(self):
        self.videoPlayer1.btnForwardEnd_Clicked()
        self.videoPlayer2.btnForwardEnd_Clicked()

    def event_SetFrame(self, frameNumber):
        if frameNumber != None:
            self.videoPlayer1.GoToFrame(frameNumber)
            self.videoPlayer2.GoToFrame(frameNumber)

    def btnSelectFrame_Clicked(self):
        self.inputWindow = tk.Toplevel(self.root)
        inputWindow = InputWindow(parent=self.inputWindow, eventClose=self.event_SetFrame, title="", minValue=1, maxValue=np.min([self.videoPlayer1.totalFrames, self.videoPlayer2.totalFrames]))
        inputWindow.Center(self.inputWindow)

    def PlayDiff(self, skippingFrame):
        if self.videoPlayer1.updatedFrames == self.videoPlayer2.updatedFrames or skippingFrame:
            grayA = cv2.cvtColor(self.frame1, cv2.COLOR_BGR2GRAY)
            grayB = cv2.cvtColor(self.frame2, cv2.COLOR_BGR2GRAY)
            diff = cv2.subtract(grayA, grayB)
            self.videoPlayerDifference.RenderFrame(diff,skippingFrame=False)

    def callBack_EquateFrames(self):
        self.videoPlayer1.updatedFrames = self.videoPlayer2.updatedFrames = True

    def callback_PlayFrame1(self, cvImage, frameNumber, skippingFrame):
        self.frame1 = cvImage
        self.videoPlayer1.updatedFrames = not self.videoPlayer1.updatedFrames
        if self.videoPlayer1.currentFrameNbr != 0 and self.videoPlayer2.currentFrameNbr != 0:
            self.PlayDiff(skippingFrame)

    def callback_PlayFrame2(self, cvImage, frameNumber, skippingFrame):
        self.frame2 = cvImage
        self.videoPlayer2.updatedFrames = not self.videoPlayer2.updatedFrames
        if self.videoPlayer1.currentFrameNbr != 0 and self.videoPlayer2.currentFrameNbr != 0:
            self.PlayDiff(skippingFrame)

    def AddVideo1(self, videoFilePath, annotationFilePath, currentFrameNbr):
        _,fileName = utils.splitPathFile(videoFilePath)
        self.videoPlayer1.UpdateVideoDetails(fileName, videoFilePath, annotationFilePath, currentFrameNbr)

    def AddVideo2(self, videoFilePath, annotationFilePath, currentFrameNbr):
        _,fileName = utils.splitPathFile(videoFilePath)
        self.videoPlayer2.UpdateVideoDetails(fileName, videoFilePath, annotationFilePath, currentFrameNbr)
        # Depois de adicionar o segundo vídeo, habilita botão para tocar os dois vídeos
        self.btnPlayPause.config(state="normal")
        self.ChangeNavButtonsStatus(True)
        # Seta o status como NOT_STARTED para que o vídeo seja tocado
        self.statusPlayer = StatusPlayer.NOT_STARTED
        self.videoPlayer2.loadedFrames = True

    def __init__(self, parent, video1FilePath=None, annotation1FilePath=None, video2FilePath=None, annotation2FilePath=None):
        self.root = parent
        # Set status of the player
        self.statusPlayer = StatusPlayer.NOT_STARTED
        self.eventPause = threading.Event()
        # current path
        currentPath = os.path.dirname(os.path.realpath(__file__))
        self.root.title("VDAO - Videos visualization")
        self.pnlMain = tk.PanedWindow(self.root, orient=tk.VERTICAL)
        self.pnlMain.pack(fill=tk.BOTH, expand=True)
        # Define video player 1 
        self.videoPlayer1 = VideoPlayer(parent=self.pnlMain, titleVideo='Video #1', fileName='', videoFilePath='', annotationFilePath='', currentFrameNbr=0, callback_FrameUpdated=self.callback_PlayFrame1, callBack_PlayPauseBtn_Clicked=self.callback_PlayPause, callBack_EquateFrames=self.callBack_EquateFrames)
        # Define video Difference
        self.videoPlayerDifference = VideoPlayer(self.pnlMain, 'Video Difference', "", "", None, 1, None, None, videoIsProcessed=True)
        # Define video player 2        
        self.videoPlayer2 = VideoPlayer(parent=self.pnlMain, titleVideo='Video #2', fileName='', videoFilePath='', annotationFilePath='', currentFrameNbr=0, callback_FrameUpdated=self.callback_PlayFrame2, callBack_PlayPauseBtn_Clicked=self.callback_PlayPause, callBack_EquateFrames=self.callBack_EquateFrames)
       # Buttons
        pnlButtons = tk.PanedWindow(self.root)
        pnlButtons.pack()
        # Load images
        self.imgBackwardsBeg = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_beg.png'))
        self.imgBackwards1 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_1.png'))
        self.imgBackwards5 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_5.png'))
        self.imgBackwards10 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','rewind_10.png'))
        self.imgPlay = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','play.png'))
        self.imgPause = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','pause.png'))
        self.imgForwardEnd = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_end.png'))
        self.imgForward1 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_1.png'))
        self.imgForward5 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_5.png'))
        self.imgForward10 = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','forward_10.png'))
        self.imgSelectFrame = tk.PhotoImage(file=os.path.join(currentPath,'aux_images','select_frame.png'))
        # Create and add buttons
        self.btnBackwardsBeg = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwardsBeg, state=tk.NORMAL, command=self.btnBackwardsBeg_Clicked)
        self.btnBackwardsBeg.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnBackwards10 = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwards10, state=tk.NORMAL, command=self.btnBackwards10_Clicked)
        self.btnBackwards10.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnBackwards5 = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwards5, state=tk.NORMAL, command=self.btnBackwards5_Clicked)
        self.btnBackwards5.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnBackwards1 = tk.Button(pnlButtons, width=24, height=24, image=self.imgBackwards1, state=tk.NORMAL, command=self.btnBackwards1_Clicked)
        self.btnBackwards1.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnPlayPause = tk.Button(pnlButtons, width=24, height=24, image=self.imgPlay, state=tk.NORMAL, command=self.btnPlayPause_Clicked)
        self.btnPlayPause.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnForward1 = tk.Button(pnlButtons, width=24, height=24, image=self.imgForward1, state=tk.NORMAL, command=self.btnForward1_Clicked)
        self.btnForward1.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnForward5 = tk.Button(pnlButtons, width=24, height=24, image=self.imgForward5, state=tk.NORMAL, command=self.btnForward5_Clicked)
        self.btnForward5.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnForward10 = tk.Button(pnlButtons, width=24, height=24, image=self.imgForward10, state=tk.NORMAL, command=self.btnForward10_Clicked)
        self.btnForward10.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnForwardEnd = tk.Button(pnlButtons, width=24, height=24, image=self.imgForwardEnd, state=tk.NORMAL, command=self.btnForwardEnd_Clicked)
        self.btnForwardEnd.pack(side=tk.LEFT, padx=2, pady=2)
        self.btnSelectFrame = tk.Button(pnlButtons, width=24, height=24, image=self.imgSelectFrame, state=tk.NORMAL, command=self.btnSelectFrame_Clicked)
        self.btnSelectFrame.pack(side=tk.LEFT, padx=2, pady=2)
        # Desabilita botoes
        self.ChangeNavButtonsStatus(False)
        # Se tiver não frames para tocar em ambos vídeos
        if self.videoPlayer1.totalFrames == 0 or self.videoPlayer2.totalFrames == 0: # Se vídeo não tem frames para tocar
            self.statusPlayer = StatusPlayer.FAILED
            # self.loadedFrame1 = self.loadedFrame2 = False
            self.videoPlayer1.loadedFrames = self.videoPlayer2.loadedFrames = False
            # Desabilita botão geral para tocar vídeos
            self.btnPlayPause.config(state="disabled")
        else: # Tem frames para tocar em ambos videos
            self.statusPlayer = StatusPlayer.NOT_STARTED 
            # self.loadedFrame1 = self.loadedFrame2 = True
            self.videoPlayer1.loadedFrames = self.videoPlayer2.loadedFrames = True
            # Habilita botão geral para tocar vídeos
            self.btnPlayPause.config(state="normal")
        # Desabilita botões de navegação entre para os 2 vídeos
        self.videoPlayer1.ChangeNavButtonsStatus(False)
        self.videoPlayer2.ChangeNavButtonsStatus(False)
        # Se videoPlayer1 não tiver frames para tocar, desabilita o play
        if self.videoPlayer1.totalFrames == 0:
            self.videoPlayer1.btnPlayPause.config(state="disabled")
        else: # habilita o play
            self.videoPlayer1.btnPlayPause.config(state="normal")
        # Se videoPlayer2 não tiver frames para tocar, desabilita o play
        if self.videoPlayer2.totalFrames == 0:
            self.videoPlayer2.btnPlayPause.config(state="disabled")
        else: # habilita o play
            self.videoPlayer2.btnPlayPause.config(state="normal")
        # identifies last video that was created (0: None, 1: First video, 2: Second video)
        self.lastVideoCreated = 0
        # Creates empty frames
        self.frame1 = self.frame2 = None
Beispiel #31
0
    def __init__(self, engine, songName=None):
        self.engine = engine
        self.time = 0.0
        self.offset = 0.5  # akedrou - this seems to fix the delay issue, but I'm not sure why. Return here!
        self.speedDiv = 20000.0
        self.speedDir = 1.0
        self.doneList = []
        self.themename = Config.get("coffee", "themename")

        nf = self.engine.data.font
        bf = self.engine.data.bigFont
        ns = 0.002
        bs = 0.001
        hs = 0.003
        c1 = (1, 1, .5, 1)
        c2 = (1, .75, 0, 1)
        self.text_size = nf.getLineSpacing(scale=hs)

        #akedrou - Translatable Strings:
        self.bank = {}
        self.bank['intro'] = [
            _("This mod was built on Alarian's mod,"),
            _("which was built on UltimateCoffee's Ultimate mod,"),
            _("which was built on RogueF's RF_mod 4.15,"),
            _("which was, of course, built on Frets on Fire 1.2.451,"),
            _("which was created by Unreal Voodoo")
        ]
        self.bank['noOrder'] = [_("No Particular Order")]
        self.bank['coders'] = [_("Active Coders:")]
        self.bank['pastCoders'] = [_("Past Coders:")]
        self.bank['graphics'] = [_("Main Graphic Contributors:")]
        self.bank['translators'] = [_("Translators:")]
        self.bank['Team Hero'] = [_("Team Hero:")]
        self.bank['careerMode'] = [_("Creators of Career Mode")]
        self.bank['honorary'] = [_("Honorary Credits to:")]
        self.bank['donations'] = [_("Donations to MFH")]
        self.bank['adonations'] = [_("Donations to akedrou")]
        self.bank['majorDonor'] = [_("Major Donations:")]
        self.bank['otherDonor'] = [_("Other Donations:")]
        self.bank['other'] = [_("Other Credits:")]
        self.bank['tutorial'] = [
            _("Jurgen FoF tutorial inspired by adam02"),
            _("Drum test song tutorial by Heka"),
            _("Bang Bang Mystery Man song tutorial is from the original FoF"),
            _("Drum Rolls practice tutorial by venom426")
        ]
        self.bank['disclaimer'] = [
            _("If you see your work included in this game and you aren't"),
            _("in the credits, please leave a polite post stating what you"),
            _("did and when, as specific as possible."),
            _("If you can, please provide a link to your original posting"),
            _("of the work in question."),
            _("Then we can properly credit you.")
        ]
        self.bank['thanks'] = [_("Thank you for your contribution.")]
        self.bank['oversight'] = [
            _("Please keep in mind that it is not easy to trace down and"),
            _("credit every single person who contributed; if your name is"),
            _("not included, it was not meant to slight you."),
            _("It was an oversight.")
        ]
        # evilynux - Theme strings
        self.bank['themeCreators'] = [_("%s theme credits:") % self.themename]
        self.bank['themeThanks'] = [
            _("%s theme specific thanks:") % self.themename
        ]
        # Languages
        self.bank['french'] = [_("French")]
        self.bank['french90'] = [_("French (reform 1990)")]
        self.bank['german'] = [_("German")]
        self.bank['italian'] = [_("Italian")]
        self.bank['piglatin'] = [_("Pig Latin")]
        self.bank['portuguese-b'] = [_("Portuguese (Brazilian)")]
        self.bank['russian'] = [_("Russian")]
        self.bank['spanish'] = [_("Spanish")]
        self.bank['swedish'] = [_("Swedish")]

        self.videoLayer = False
        self.background = None

        if videoAvailable:
            # TODO: Parameters to add to theme.ini:
            #  - credits_video_file
            #  - credits_video_start_time
            #  - credits_video_end_time
            vidSource = os.path.join(Version.dataPath(), 'themes', self.themename, \
                                     'menu', 'credits.avi')
            if os.path.exists(vidSource):
                winWidth, winHeight = self.engine.view.geometry[2:4]
                songVideoStartTime = 0
                songVideoEndTime = None
                self.vidPlayer = VideoPlayer(-1,
                                             vidSource, (winWidth, winHeight),
                                             mute=True,
                                             loop=True,
                                             startTime=songVideoStartTime,
                                             endTime=songVideoEndTime)
                if self.vidPlayer.validFile:
                    self.engine.view.pushLayer(self.vidPlayer)
                    self.videoLayer = True

        if not self.videoLayer and \
           not self.engine.loadImgDrawing(self, 'background', os.path.join('themes', self.themename, 'menu', 'credits.png')):
            self.background = None

        if not self.engine.loadImgDrawing(
                self, 'topLayer',
                os.path.join('themes', self.themename, 'menu',
                             'creditstop.png')):
            self.topLayer = None

        space = Text(nf, hs, c1, "center", " ")
        self.credits = [
            Picture(self.engine, "fofix_logo.png", .10),
            Text(nf, ns, c1, "center", "%s" % Version.version())
        ]

        # evilynux: Main FoFiX credits (taken from CREDITS).
        self.parseText("CREDITS")
        # evilynux: Theme credits (taken from data/themes/<theme name>/CREDITS).
        self.parseText(
            os.path.join('data', 'themes', self.themename, 'CREDITS'))

        self.credits.append(space)
        for i in self.bank['disclaimer']:
            self.credits.append(Text(nf, ns, c2, "center", i))
        self.credits.append(space)
        for i in self.bank['thanks']:
            self.credits.append(Text(nf, ns, c2, "center", i))
        self.credits.append(space)
        for i in self.bank['oversight']:
            self.credits.append(Text(nf, ns, c2, "center", i))

        self.credits.extend([
            space,
            Text(nf, ns, c1, "left", _("Made with:")),
            Text(nf, ns, c2, "right", "Python " + sys.version.split(' ')[0]
                 ),  #stump: the version that's actually in use
            Text(nf, bs, c2, "right", "http://www.python.org"),
            space,
            Text(nf, ns, c2, "right", "PyGame " + pygame.version.ver.replace(
                'release', '')),  #stump: the version that's actually in use
            Text(nf, bs, c2, "right", "http://www.pygame.org"),
            space,
            Text(nf, ns, c2, "right", "PyOpenGL " + OpenGL.__version__
                 ),  #evilynux: the version that's actually in use
            Text(nf, bs, c2, "right", "http://pyopengl.sourceforge.net"),
            space,
            #Text(nf, ns, c2, "right",  "Amanith Framework"),
            #Text(nf, bs, c2, "right",  "http://www.amanith.org"),
            #space,
            Text(nf, ns, c2, "right", "Illusoft Collada module 1.4"),
            Text(nf, bs, c2, "right", "http://colladablender.illusoft.com"),
            space,
            Text(nf, ns, c2, "right", "Psyco specializing compiler"),
            Text(nf, bs, c2, "right", "http://psyco.sourceforge.net"),
            space,
            Text(nf, ns, c2, "right", "MXM Python Midi Package 0.1.4"),
            Text(nf, bs, c2, "right",
                 "http://www.mxm.dk/products/public/pythonmidi"),
            space,
            space,
            Text(
                nf, bs, c1, "center",
                _("Source Code available under the GNU General Public License")
            ),
            Text(nf, bs, c2, "center", "http://code.google.com/p/fofix"),
            space,
            space,
            Text(nf, bs, c1, "center",
                 _("Copyright 2006, 2007 by Unreal Voodoo")),
            Text(nf, bs, c1, "center", _("Copyright 2008-2010 by Team FoFiX")),
            space,
            space
        ])
 def __init__(self):
     logging.info('Init Experiment...')
     self.player = VideoPlayer()
     self.tracker = Tracker()
     self.tracker.start()
     pass
        if i == 0: # EOF
            break

        # Comment/Uncomment this line
        if frames == 3:
            break

    bitstream.closeFile()
    print("Video decoded with success!")




    if True:
        info = (height, width, formatC1, fps1)
        videoPlayer01 = VideoPlayer(fromFile=False)
        videoPlayer01.openInfo(info, decoded_matrixes)

        while (videoPlayer01.visualizeFrame()):
            pass
    # Code bellow, altho very hardcoded, shows the up to 3 frame, so we can check whether things went well or not
    if False:
        Y = decoded_matrixes[0]
        U = decoded_matrixes[1]
        V = decoded_matrixes[2]
        YUV = np.dstack((Y, U, V))[:720, :1280, :].astype(np.float)
        YUV[:, :, 0] = YUV[:, :, 0] - 16  # Offset Y by 16
        YUV[:, :, 1:] = YUV[:, :, 1:] - 128  # Offset UV by 128
        # YUV conversion matrix from ITU-R BT.601 version (SDTV)
        # Note the swapped R and B planes!
        #              Y       U       V