bg
[sso] / shaken_and_spit_out / pgfw / VideoRecorder.py
1 from os import makedirs
2 from os.path import exists, join
3 from tempfile import TemporaryFile
4 from time import strftime
5
6 from pygame.image import tostring, frombuffer, save
7 from pygame.time import get_ticks
8
9 from GameChild import GameChild
10
11 class VideoRecorder(GameChild):
12
13 def __init__(self, parent):
14 GameChild.__init__(self, parent)
15 self.display_surface = self.get_display_surface()
16 self.delegate = self.get_delegate()
17 self.load_configuration()
18 self.reset()
19 self.subscribe(self.respond)
20
21 def load_configuration(self):
22 config = self.get_configuration("video-recordings")
23 self.root = config["path"]
24 self.directory_name_format = config["directory-name-format"]
25 self.file_extension = config["file-extension"]
26 self.frame_format = config["frame-format"]
27 self.framerate = config["framerate"]
28
29 def reset(self):
30 self.recording = False
31 self.frame_length = None
32 self.frames = None
33 self.last_frame = 0
34
35 def respond(self, event):
36 compare = self.delegate.compare
37 if compare(event, "record-video"):
38 self.toggle_record()
39 elif compare(event, "reset-game"):
40 self.reset()
41
42 def toggle_record(self):
43 recording = not self.recording
44 if recording:
45 self.frame_length = len(self.get_string())
46 self.frames = TemporaryFile()
47 else:
48 self.write_frames()
49 self.recording = recording
50
51 def get_string(self):
52 return tostring(self.display_surface, self.frame_format)
53
54 def write_frames(self):
55 root = join(self.root, strftime(self.directory_name_format))
56 if not exists(root):
57 makedirs(root)
58 size = self.display_surface.get_size()
59 frames = self.frames
60 frames.seek(0)
61 for ii, frame in enumerate(iter(lambda: frames.read(self.frame_length),
62 "")):
63 path = join(root, "%04i.png" % ii)
64 save(frombuffer(frame, size, self.frame_format), path)
65 print "wrote video frames to " + root
66
67 def update(self):
68 ticks = get_ticks()
69 if self.recording and ticks - self.last_frame >= self.framerate:
70 self.frames.write(self.get_string())
71 self.last_frame = ticks