|
0 |
"""\
|
|
1 |
kinoje {options} input-file.yaml output-file.{gif,m4v,mp4}
|
|
2 |
|
|
3 |
Create a movie file from the template and configuration in the given YAML file."""
|
|
4 |
|
|
5 |
# Note: just about everything here is subject to change!
|
|
6 |
|
|
7 |
from datetime import datetime, timedelta
|
|
8 |
from copy import copy
|
|
9 |
import math
|
|
10 |
from optparse import OptionParser
|
|
11 |
import os
|
|
12 |
import re
|
|
13 |
from subprocess import check_call
|
|
14 |
import sys
|
|
15 |
from tempfile import mkdtemp
|
|
16 |
|
|
17 |
from jinja2 import Template
|
|
18 |
import yaml
|
|
19 |
try:
|
|
20 |
from yaml import CLoader as Loader
|
|
21 |
except ImportError:
|
|
22 |
from yaml import Loader
|
|
23 |
|
|
24 |
|
|
25 |
class LoggingExecutor(object):
|
|
26 |
def __init__(self, filename):
|
|
27 |
self.filename = filename
|
|
28 |
self.log = open(filename, 'w')
|
|
29 |
|
|
30 |
def do_it(self, cmd, **kwargs):
|
|
31 |
print cmd
|
|
32 |
try:
|
|
33 |
check_call(cmd, shell=True, stdout=self.log, stderr=self.log, **kwargs)
|
|
34 |
except Exception as e:
|
|
35 |
self.log.close()
|
|
36 |
print str(e)
|
|
37 |
check_call("tail %s" % self.filename, shell=True)
|
|
38 |
sys.exit(1)
|
|
39 |
|
|
40 |
def close(self):
|
|
41 |
self.log.close()
|
|
42 |
|
|
43 |
|
|
44 |
def fmod(n, d):
|
|
45 |
return n - d * int(n / d)
|
|
46 |
|
|
47 |
|
|
48 |
def tween(t, *args):
|
|
49 |
"""Format: after t, each arg should be like
|
|
50 |
((a, b), c)
|
|
51 |
which means: when t >= a and < b, return c,
|
|
52 |
or like
|
|
53 |
((a, b), (c, d))
|
|
54 |
which means:
|
|
55 |
when t >= a and < b, return a value between c and d which is proportional to the
|
|
56 |
position between a and b that t is,
|
|
57 |
or like
|
|
58 |
((a, b), (c, d), f)
|
|
59 |
which means the same as case 2, except the function f is applied to the value between c and d
|
|
60 |
before it is returned.
|
|
61 |
"""
|
|
62 |
nargs = []
|
|
63 |
for x in args:
|
|
64 |
a = x[0]
|
|
65 |
b = x[1]
|
|
66 |
if not isinstance(x[1], tuple):
|
|
67 |
b = (x[1], x[1])
|
|
68 |
if len(x) == 2:
|
|
69 |
f = lambda z: z
|
|
70 |
else:
|
|
71 |
f = x[2]
|
|
72 |
nargs.append((a, b, f))
|
|
73 |
|
|
74 |
for ((low, hi), (sc_low, sc_hi), f) in nargs:
|
|
75 |
if t >= low and t < hi:
|
|
76 |
pos = (t - low) / (hi - low)
|
|
77 |
sc = sc_low + ((sc_hi - sc_low) * pos)
|
|
78 |
return f(sc)
|
|
79 |
raise ValueError(t)
|
|
80 |
|
|
81 |
|
|
82 |
def main():
|
|
83 |
optparser = OptionParser(__doc__)
|
|
84 |
optparser.add_option("--width", default=320, type=int)
|
|
85 |
optparser.add_option("--height", default=200, type=int)
|
|
86 |
|
|
87 |
optparser.add_option("--tiny", default=False, action='store_true')
|
|
88 |
optparser.add_option("--small", default=False, action='store_true')
|
|
89 |
optparser.add_option("--big", default=False, action='store_true')
|
|
90 |
optparser.add_option("--huge", default=False, action='store_true')
|
|
91 |
optparser.add_option("--giant", default=False, action='store_true')
|
|
92 |
optparser.add_option("--square", default=False, action='store_true')
|
|
93 |
|
|
94 |
optparser.add_option("--start", default=0.0, type=float, metavar='INSTANT',
|
|
95 |
help="t-value at which to start rendering the movie. Default=0.0"
|
|
96 |
)
|
|
97 |
optparser.add_option("--stop", default=1.0, type=float, metavar='INSTANT',
|
|
98 |
help="t-value at which to stop rendering the movie. Default=1.0"
|
|
99 |
)
|
|
100 |
optparser.add_option("--duration", default=None, type=float, metavar='SECONDS',
|
|
101 |
help="Override the duration specified in the configuration."
|
|
102 |
)
|
|
103 |
|
|
104 |
optparser.add_option("--fps", default=25.0, type=float, metavar='FPS',
|
|
105 |
help="The number of frames to render for each second. Note that the "
|
|
106 |
"tool that makes a movie file from images might not honour this value exactly."
|
|
107 |
)
|
|
108 |
optparser.add_option("--still", default=None, type=float)
|
|
109 |
optparser.add_option("--view", default=False, action='store_true')
|
|
110 |
optparser.add_option("--twitter", default=False, action='store_true',
|
|
111 |
help="Make the last frame in a GIF animation delay only half as long."
|
|
112 |
)
|
|
113 |
|
|
114 |
optparser.add_option("--config", default=None, type=str)
|
|
115 |
|
|
116 |
(options, args) = optparser.parse_args(sys.argv[1:])
|
|
117 |
|
|
118 |
if options.tiny:
|
|
119 |
options.width = 160
|
|
120 |
options.height = 100
|
|
121 |
if options.small:
|
|
122 |
options.width = 320
|
|
123 |
options.height = 200
|
|
124 |
if options.big:
|
|
125 |
options.width = 640
|
|
126 |
options.height = 400
|
|
127 |
if options.huge:
|
|
128 |
options.width = 800
|
|
129 |
options.height = 600
|
|
130 |
if options.giant:
|
|
131 |
options.width = 1280
|
|
132 |
options.height = 800
|
|
133 |
|
|
134 |
if options.square:
|
|
135 |
options.height = options.width
|
|
136 |
|
|
137 |
if options.still is not None:
|
|
138 |
options.duration = 1.0
|
|
139 |
options.start = options.still
|
|
140 |
|
|
141 |
infilename = args[0]
|
|
142 |
try:
|
|
143 |
outfilename = args[1]
|
|
144 |
except IndexError:
|
|
145 |
(inbase, inext) = os.path.splitext(infilename)
|
|
146 |
outfilename = inbase + '.mp4'
|
|
147 |
(whatever, outext) = os.path.splitext(outfilename)
|
|
148 |
SUPPORTED_OUTPUT_FORMATS = ('.m4v', '.mp4', '.gif')
|
|
149 |
if outext not in SUPPORTED_OUTPUT_FORMATS:
|
|
150 |
raise ValueError("%s not a supported output format (%r)" % (outext, SUPPORTED_OUTPUT_FORMATS))
|
|
151 |
|
|
152 |
with open(infilename, 'r') as file_:
|
|
153 |
config = yaml.load(file_, Loader=Loader)
|
|
154 |
|
|
155 |
if options.config is not None:
|
|
156 |
settings = {}
|
|
157 |
for setting_string in options.config.split(','):
|
|
158 |
key, value = setting_string.split(':')
|
|
159 |
if re.match(r'^\d*\.?\d*$', value):
|
|
160 |
value = float(value)
|
|
161 |
settings[key] = value
|
|
162 |
config.update(settings)
|
|
163 |
|
|
164 |
template = Template(config['template'])
|
|
165 |
|
|
166 |
fun_context = {}
|
|
167 |
for key, value in config.get('functions', {}).iteritems():
|
|
168 |
fun_context[key] = eval("lambda x: " + value)
|
|
169 |
|
|
170 |
tempdir = mkdtemp()
|
|
171 |
|
|
172 |
frame_fmt = "out%05d.png"
|
|
173 |
framerate = options.fps
|
|
174 |
|
|
175 |
duration = options.duration
|
|
176 |
if duration is None:
|
|
177 |
duration = config['duration']
|
|
178 |
|
|
179 |
start_time = options.start * duration
|
|
180 |
stop_time = options.stop * duration
|
|
181 |
requested_duration = stop_time - start_time
|
|
182 |
num_frames = int(requested_duration * framerate)
|
|
183 |
t_step = 1.0 / (duration * framerate)
|
|
184 |
|
|
185 |
print "Start time: t=%s, %s seconds" % (options.start, start_time)
|
|
186 |
print "Stop time: t=%s, %s seconds" % (options.stop, stop_time)
|
|
187 |
print "Requested duration: %s seconds" % requested_duration
|
|
188 |
print "Frame rate: %s fps" % framerate
|
|
189 |
print "Number of frames: %s (rounded to %s)" % (requested_duration * framerate, num_frames)
|
|
190 |
print "t-Step: %s" % t_step
|
|
191 |
|
|
192 |
exe = LoggingExecutor(os.path.join(tempdir, 'movie.log'))
|
|
193 |
t = options.start
|
|
194 |
|
|
195 |
started_at = datetime.now()
|
|
196 |
|
|
197 |
for frame in xrange(num_frames):
|
|
198 |
|
|
199 |
elapsed = (datetime.now() - started_at).total_seconds()
|
|
200 |
eta = '???'
|
|
201 |
if frame > 0:
|
|
202 |
seconds_per_frame = elapsed / float(frame)
|
|
203 |
eta = started_at + timedelta(seconds=num_frames * seconds_per_frame)
|
|
204 |
|
|
205 |
print "t=%s (%s%% done, eta %s)" % (t, int(((t - options.start) / options.stop) * 100), eta)
|
|
206 |
|
|
207 |
out_pov = os.path.join(tempdir, 'out.pov')
|
|
208 |
context = copy(config)
|
|
209 |
context.update(fun_context)
|
|
210 |
context.update({
|
|
211 |
'width': float(options.width),
|
|
212 |
'height': float(options.height),
|
|
213 |
't': t,
|
|
214 |
'math': math,
|
|
215 |
'tween': tween,
|
|
216 |
'fmod': fmod,
|
|
217 |
})
|
|
218 |
with open(out_pov, 'w') as f:
|
|
219 |
f.write(template.render(context))
|
|
220 |
fn = os.path.join(tempdir, frame_fmt % frame)
|
|
221 |
render_type = config.get('type', 'povray')
|
|
222 |
if render_type == 'povray':
|
|
223 |
cmd_template = "povray -D +I{infile} +O{outfile} +W{width} +H{height} +A"
|
|
224 |
elif render_type == 'svg':
|
|
225 |
cmd_template = "inkscape -z -e {outfile} -w {width} -h {height} {infile}"
|
|
226 |
else:
|
|
227 |
raise NotImplementedError
|
|
228 |
cmd = cmd_template.format(
|
|
229 |
infile=out_pov, outfile=fn, width=options.width, height=options.height
|
|
230 |
)
|
|
231 |
exe.do_it(cmd)
|
|
232 |
t += t_step
|
|
233 |
|
|
234 |
if options.still is not None:
|
|
235 |
exe.do_it("eog %s" % fn)
|
|
236 |
sys.exit(0)
|
|
237 |
|
|
238 |
if outext == '.gif':
|
|
239 |
# TODO: show some warning if this is not an integer delay
|
|
240 |
delay = int(100.0 / framerate)
|
|
241 |
|
|
242 |
filenames = [os.path.join(tempdir, frame_fmt % f) for f in xrange(0, num_frames)]
|
|
243 |
if options.twitter:
|
|
244 |
filespec = ' '.join(filenames[:-1] + ['-delay', str(delay / 2), filenames[-1]])
|
|
245 |
else:
|
|
246 |
filespec = ' '.join(filenames)
|
|
247 |
|
|
248 |
# -strip is there to force convert to process all input files. (if no transformation is given,
|
|
249 |
# it can sometimes stop reading input files. leading to skippy animations. who knows why.)
|
|
250 |
exe.do_it("convert -delay %s -loop 0 %s -strip %s" % (
|
|
251 |
delay, filespec, outfilename
|
|
252 |
))
|
|
253 |
finished_at = datetime.now()
|
|
254 |
if options.view:
|
|
255 |
exe.do_it("eog %s" % outfilename)
|
|
256 |
elif outext in ('.mp4', '.m4v'):
|
|
257 |
ifmt = os.path.join(tempdir, frame_fmt)
|
|
258 |
# fun fact: even if you say -r 30, it still picks 25 fps
|
|
259 |
cmd = "ffmpeg -i %s -c:v libx264 -profile:v baseline -pix_fmt yuv420p -r %s -y %s" % (
|
|
260 |
ifmt, int(framerate), outfilename
|
|
261 |
)
|
|
262 |
exe.do_it(cmd)
|
|
263 |
finished_at = datetime.now()
|
|
264 |
if options.view:
|
|
265 |
exe.do_it("vlc %s" % outfilename)
|
|
266 |
else:
|
|
267 |
raise NotImplementedError
|
|
268 |
|
|
269 |
exe.close()
|
|
270 |
|
|
271 |
run_duration = finished_at - started_at
|
|
272 |
print "Finished, took %s seconds" % run_duration.total_seconds()
|