Browse Source

2to3

master
Fr3deric 8 years ago committed by Frederic
parent
commit
1b7afff887
  1. 306
      miniplayer.py

306
miniplayer.py

@ -1,4 +1,4 @@
#!/usr/bin/python #!/usr/bin/python3
import threading import threading
import os import os
@ -14,170 +14,170 @@ import blup.frame
class AnimationLoaderThread(threading.Thread): class AnimationLoaderThread(threading.Thread):
""" """
This class is used by the player to pre-load an animation while another one This class is used by the player to pre-load an animation while another one
is being played. is being played.
""" """
def __init__(self, filename): def __init__(self, filename):
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.__filename = filename self.__filename = filename
self.__anim = None self.__anim = None
self.__error = False self.__error = False
def run(self): def run(self):
try: try:
self.__anim = blup.animation.load(self.__filename) self.__anim = blup.animation.load(self.__filename)
except Exception as e: except Exception as e:
print '%s: %s while loading %s' % (self.__class__.__name__, print('%s: %s while loading %s' % (self.__class__.__name__,
repr(e), repr(e), self.__filename))
self.__filename) self.__error = True
self.__error = True self.__anim = None
self.__anim = None
def getAnim(self): def getAnim(self):
self.join() self.join()
return self.__anim return self.__anim
class MiniPlayer(object): class MiniPlayer(object):
""" """
Minimal animation player that does nothing but randomly selecting Minimal animation player that does nothing but randomly selecting
animations out of a directory and playing them. animations out of a directory and playing them.
""" """
def __init__(self, animDir, output): def __init__(self, animDir, output):
self.__animDir = animDir self.__animDir = animDir
self.__output = output self.__output = output
self.loopTime = 10000 self.loopTime = 10000
self.gap = 800 self.gap = 800
self.maxPlayNext = 3 self.maxPlayNext = 3
self.__playNext = [] self.__playNext = []
self.__running = False self.__running = False
def terminate(self): def terminate(self):
self.__running = False self.__running = False
def playNext(self, filename): def playNext(self, filename):
""" Add an animation to the queue. """ """ Add an animation to the queue. """
if filename.find('/') >= 0: if filename.find('/') >= 0:
raise ValueError('filename must not contain slashes') raise ValueError('filename must not contain slashes')
if ( os.path.isfile(os.path.join(self.__animDir, filename)) and if ( os.path.isfile(os.path.join(self.__animDir, filename)) and
len(self.__playNext) < self.maxPlayNext ): len(self.__playNext) < self.maxPlayNext ):
self.__playNext.append(filename) self.__playNext.append(filename)
else: else:
return False return False
def getNextFilename(self): def getNextFilename(self):
""" """
Return the next animation filename to be played, either from the queue, Return the next animation filename to be played, either from the queue,
or randomly chosen. or randomly chosen.
""" """
if len(self.__playNext) > 0 and os.path.isfile(self.__playNext[0]): if len(self.__playNext) > 0 and os.path.isfile(self.__playNext[0]):
return self.__playNext.pop(0) return self.__playNext.pop(0)
else: else:
files = os.listdir(self.__animDir) files = os.listdir(self.__animDir)
return random.choice(files) return random.choice(files)
def run(self): def run(self):
""" """
Runs the player until terminate() gets called (e.g. by another thread). Runs the player until terminate() gets called (e.g. by another thread).
""" """
self.__running = True self.__running = True
currentAnim = None currentAnim = None
player = blup.animation.AnimationPlayer() player = blup.animation.AnimationPlayer()
while self.__running: while self.__running:
# begin to load the next animation # begin to load the next animation
filename = os.path.join(self.__animDir, self.getNextFilename()) filename = os.path.join(self.__animDir, self.getNextFilename())
loader = AnimationLoaderThread(filename) loader = AnimationLoaderThread(filename)
loader.start() loader.start()
# play the animation in case it had been successfully loaded before # play the animation in case it had been successfully loaded before
if currentAnim is not None: if currentAnim is not None:
if currentAnim.duration < self.loopTime: if currentAnim.duration < self.loopTime:
count = self.loopTime / currentAnim.duration count = self.loopTime / currentAnim.duration
else: else:
count = 1 count = 1
player.play(currentAnim, self.__output, count=count) player.play(currentAnim, self.__output, count=count)
# show a blank frame for some thime # show a blank frame for some thime
if self.gap > 0 and self.__running: if self.gap > 0 and self.__running:
# TODO: use correct frame size # TODO: use correct frame size
dim = blup.frame.FrameDimension(18,8,8,3) #dim = blup.frame.FrameDimension(18,8,8,3)
self.__output.sendFrame(blup.frame.Frame(dim)) dim = blup.frame.FrameDimension(22, 16, 256, 3)
time.sleep(self.gap / 1000.0) self.__output.sendFrame(blup.frame.Frame(dim))
time.sleep(self.gap / 1000.0)
# get the next animation from the loader
currentAnim = loader.getAnim() # get the next animation from the loader
currentAnim = loader.getAnim()
def printUsage(errMsg=None): def printUsage(errMsg=None):
if errMsg is not None: if errMsg is not None:
print 'error: %s\n' % (errMsg) print('error: %s\n' % (errMsg))
print 'usage: %s [OPTIONS] PATH' % (sys.argv[0]) print('usage: %s [OPTIONS] PATH' % (sys.argv[0]))
print 'where PATH is the directory containing the animations to play' print('where PATH is the directory containing the animations to play')
print 'supported options:' print('supported options:')
print ' -o OUTPUT where to output the frames (default: shell)' print(' -o OUTPUT where to output the frames (default: shell)')
print ' --output OUTPUT\n' print(' --output OUTPUT\n')
print ' -h print this text' print(' -h print(this text')
print ' --help' print(' --help')
def main(): def main():
try: try:
(opts, args) = getopt.gnu_getopt(sys.argv, 'ho:', ['help', 'output=']) (opts, args) = getopt.gnu_getopt(sys.argv, 'ho:', ['help', 'output='])
opts = dict(opts) opts = dict(opts)
except getopt.GetoptError as e: except getopt.GetoptError as e:
printUsage(e.msg) printUsage(e.msg)
sys.exit(1) sys.exit(1)
if opts.has_key('--help'): if '--help' in opts:
printUsage() printUsage()
sys.exit(0) sys.exit(0)
if opts.has_key('-o'): if '-o' in opts:
output = opts['-o'] output = opts['-o']
elif opts.has_key('--output'): elif '--output' in opts:
output = opts['--output'] output = opts['--output']
else: else:
output = 'shell' output = 'shell'
try: try:
out = blup.output.getOutput(output) out = blup.output.getOutput(output)
except blup.output.IllegalOutputSpecificationError: except blup.output.IllegalOutputSpecificationError:
print 'illegal output specification' print('illegal output specification')
print 'available outputs:' print('available outputs:')
print blup.output.getOutputDescriptions() print(blup.output.getOutputDescriptions())
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print 'could not initialize output: %s' % (str(e)) print('could not initialize output: %s' % (str(e)))
sys.exit(1) sys.exit(1)
if len(args) != 2: if len(args) != 2:
printUsage() printUsage()
sys.exit(1) sys.exit(1)
else: else:
animDir = args[1] animDir = args[1]
if not os.path.isdir(animDir): if not os.path.isdir(animDir):
print '%s is not a directory' % (animDir) print('%s is not a directory' % (animDir))
sys.exit(1) sys.exit(1)
p = MiniPlayer(animDir, out) p = MiniPlayer(animDir, out)
try: try:
p.run() p.run()
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit(0) sys.exit(0)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

Loading…
Cancel
Save