render.py
← Gallery · core.py · scenes.py · render.py · fidelity.py · export_live.py
"""render.py SCENE AUDIO T0 DUR OUT.mp4 [--w 960 --h 540 --fps 30 --stills t1,t2,...]
The whole pipeline is one function: video(audio, t0, dur, scene) -> mp4."""
import sys, os, argparse, time, numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import core, scenes
from multiprocessing import Pool
_S = None; _LABEL = None
def _frame(t):
f = np.clip(_S.frame(t), 0, 255).astype(np.uint8)
if _LABEL:
from PIL import Image, ImageDraw, ImageFont
im = Image.fromarray(f); d = ImageDraw.Draw(im)
try:
import matplotlib; font = ImageFont.truetype(matplotlib.get_data_path() + "/fonts/ttf/DejaVuSans.ttf", max(12, f.shape[0] // 22))
except Exception: font = ImageFont.load_default()
d.text((14, f.shape[0] - 14), _LABEL, font=font, fill=(235, 225, 205), anchor="ls"); f = np.asarray(im)
return f
def video(audio, t0, dur, scene, out, w=960, h=540, fps=30, stills=None, lead=8.0, procs=1, label=None):
global _S, _LABEL
_LABEL = label
pre = t0 # analyse the whole file: dynamics and whitening are global, pre-roll is free
A = core.Analysis(core.load(audio))
_S = scenes.SCENES[scene](A, w, h)
stateful = scene in ("sand", "locator", "disc")
ts = pre + np.arange(int(dur * fps)) / fps
if stills is not None:
want = [pre + float(v) for v in stills]
if stateful:
k = 0
for t in ts:
f = _S.frame(t)
if k < len(want) and t >= want[k]:
core.save_png(out.replace(".mp4", f"_{want[k]-pre:05.1f}.png"), f); k += 1
if k >= len(want): break
else:
for t in want: core.save_png(out.replace(".mp4", f"_{t-pre:05.1f}.png"), _S.frame(t))
return
V = core.Video(out, w, h, fps, audio, t0, dur); st = time.time()
if stateful or procs == 1:
if stateful and pre > 0:
for t in np.arange(max(pre - 3, 0), pre, 1 / fps): _S.frame(t) # warm up state
for n, t in enumerate(ts):
V.p.stdin.write(_frame(t).tobytes())
if n % 150 == 0: print(scene, n, len(ts), round(time.time() - st), flush=True)
else:
with Pool(procs) as P:
for n, f in enumerate(P.imap(_frame, ts, chunksize=4)):
V.p.stdin.write(f.tobytes())
if n % 150 == 0: print(scene, n, len(ts), round(time.time() - st), flush=True)
V.close()
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("scene"); ap.add_argument("audio"); ap.add_argument("t0", type=float); ap.add_argument("dur", type=float); ap.add_argument("out")
ap.add_argument("--w", type=int, default=960); ap.add_argument("--h", type=int, default=540); ap.add_argument("--fps", type=int, default=30)
ap.add_argument("--stills"); ap.add_argument("--procs", type=int, default=1); ap.add_argument("--label")
a = ap.parse_args()
video(a.audio, a.t0, a.dur, a.scene, a.out, a.w, a.h, a.fps, a.stills.split(",") if a.stills else None, procs=a.procs, label=a.label)