# builds the constructed test scene: flite voices (synthetic) + synthetic sound effects, a mandelbrot lavfi video,
# and writes sdh.srt with cue times taken from the measured audio durations.
import subprocess, json, sys, os
def run(*a): subprocess.run(a, check=True, capture_output=True)
def dur(f): return float(subprocess.check_output(["ffprobe","-v","error","-show_entries","format=duration","-of","csv=p=0",f]).decode())
def tts(name, text, voice):
    run("ffmpeg","-y","-v","error","-f","lavfi","-i",f"flite=text='{text}':voice={voice}","-ar","24000","-ac","1",name)
    return dur(name)
def fx(name, expr, d):
    run("ffmpeg","-y","-v","error","-f","lavfi","-i",expr,"-t",str(d),"-ar","24000","-ac","1",name)
lines = {
 "l1": ("Come in, it is open.", "kal"),
 "l2": ("Sorry I am late. The traffic was awful.", "slt"),
 "l3": ("Did you bring the files?", "kal"),
 "l4": ("Right here.", "slt"),
 "l5": ("Let me answer that.", "slt"),
}
D = {k: tts(f"{k}.wav", t, v) for k,(t,v) in lines.items()}
# sound effects: knock = 3 low-passed noise bursts, ring = 2 sine pulses, hum = soft two-note tone
fx("knock.wav","anoisesrc=d=1.0:c=brown:a=0.9,lowpass=f=400,volume='if(lt(mod(t,0.33),0.08),1,0)':eval=frame",1.0)
fx("ring.wav","sine=f=1000:d=1.6,volume='if(lt(mod(t,0.8),0.4),0.6,0)':eval=frame",1.6)
fx("hum.wav","aevalsrc='0.25*sin(2*PI*220*t)+0.2*sin(2*PI*277*t)':d=3.0",3.0)
T = {"knock":0.5, "l1":2.0, "l2":4.2, "l3":8.0, "l4":0, "ring":12.0, "hum":13.6, "l5":0}
T["l4"] = T["l3"] + D["l3"] + 0.35
T["l5"] = 16.8
end = T["l5"] + D["l5"] + 1.2
parts = [("knock.wav",T["knock"]),("l1.wav",T["l1"]),("l2.wav",T["l2"]),("l3.wav",T["l3"]),("l4.wav",T["l4"]),("ring.wav",T["ring"]),("hum.wav",T["hum"]),("l5.wav",T["l5"])]
cmd=["ffmpeg","-y","-v","error"]
for f,_ in parts: cmd += ["-i",f]
flt = ";".join(f"[{i}:a]adelay={int(t*1000)}:all=1[a{i}]" for i,(f,t) in enumerate(parts))
flt += ";" + "".join(f"[a{i}]" for i in range(len(parts))) + f"amix=inputs={len(parts)}:normalize=0,atrim=0:{end:.3f}[out]"
cmd += ["-filter_complex",flt,"-map","[out]","-ar","24000","-ac","1","scene.wav"]
run(*cmd)
run("ffmpeg","-y","-v","error","-f","lavfi","-i",f"mandelbrot=s=640x360:r=25:end_scale=0.05",
    "-i","scene.wav","-vf","tpad=stop_mode=clone:stop_duration=4","-t",f"{end:.3f}","-c:v","libx264","-pix_fmt","yuv420p","-crf","23","-c:a","aac","-b:a","96k","demo.mp4")
def ts(x):
    ms=round(x*1000); h,ms=divmod(ms,3600000); m,ms=divmod(ms,60000); s,ms=divmod(ms,1000); return f"{h:02}:{m:02}:{s:02},{ms:03}"
pad=0.15
cues = [
 (T["knock"], T["knock"]+1.4, "[knocking at the door]"),
 (T["l1"], T["l1"]+D["l1"]+pad, "[Mara] Come in, it is open."),
 (T["l2"], T["l2"]+D["l2"]+pad, "[Joel] Sorry I am late.\nThe traffic was awful."),
 (T["l3"], T["l4"]+D["l4"]+pad, "-[Mara] Did you bring the files?\n-[Joel] Right here."),
 (T["ring"], T["ring"]+1.6, "[phone ringing]"),
 (T["hum"], T["hum"]+3.0, "[soft humming tone plays]"),
 (T["l5"], T["l5"]+D["l5"]+pad, "[Joel] Let me answer that."),
]
open("sdh.srt","w").write("\n".join(f"{i}\n{ts(a)} --> {ts(b)}\n{t}\n" for i,(a,b,t) in enumerate(cues,1)))
json.dump({"dur":D,"T":T,"end":end,"cues":[(a,b,t) for a,b,t in cues]},open("timeline.json","w"),indent=1)
print("end",round(end,3),"durs",{k:round(v,3) for k,v in D.items()})
