-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.py
66 lines (57 loc) · 2.01 KB
/
render.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import argparse
import pickle
import time
from sys import stdout
from pyco import cursor, terminal
def render_image(text: str, /):
stdout.write(text)
stdout.flush()
def render_video(frames: list[str], /, fps: int):
cursor.hide()
frame_height = len(frames[0].split("\n"))
actual_frame_height = frame_height
start_y, start_x = cursor.get_position()
start_time = time.perf_counter()
frame_num = 0
frame_total = len(frames)
try:
while frame_num < frame_total:
terminal_size = terminal.get_size()
frame = frames[frame_num]
if terminal_size.lines < frame_height:
actual_frame_height = terminal_size.lines - start_y + 1
frame = "\n".join(frame.split("\n")[:actual_frame_height])
cursor.set_position(start_x, start_y)
render_image(frame)
time_diff = time.perf_counter() - start_time
target_time = frame_num / fps
time_offset = time_diff - target_time
skip_frames = 0
if time_offset > 0:
skip_frames = int(time_offset * fps) + 1
frame_num += skip_frames
elif time_offset < -0.1:
time.sleep(-time_offset - 0.1)
except KeyboardInterrupt as exc:
terminal.reset_all()
cursor.set_position(start_x, start_y + actual_frame_height)
raise SystemExit() from exc
def main():
parser = argparse.ArgumentParser()
parser.add_argument("file")
parser.add_argument("-f", "--fps", type=int, default=30)
parser.add_argument("-l", "--loop", action="store_true")
args = parser.parse_args()
with open(args.file, "rb") as file:
data = pickle.load(file)
media = data["media"]
media_type = data["media_type"]
if media_type == "image":
render_image(media)
elif media_type == "video":
while True:
render_video(media, args.fps)
if not args.loop:
break
if __name__ == "__main__":
main()