import cv2, numpy as np, os, wave, array, math
W,H=544,960
segs=[('pre_v9.mp4',63),('post_A.mp4',90),('post_C.mp4',90),('post_B.mp4',90),('post_D.mp4',90)]

def read(p,n):
    cap=cv2.VideoCapture(p); fs=[]
    while True:
        ok,f=cap.read()
        if not ok: break
        fs.append(f)
    return fs[:n]

def overlay(img, close):
    if close<=0: return img
    out=img.copy(); h=int(round(close*(H/2)))
    if h>0:
        cv2.rectangle(out,(0,0),(W,h),(8,8,10),-1)
        cv2.rectangle(out,(0,H-h),(W,H),(8,8,10),-1)
        cv2.line(out,(0,h),(W,h),(125,125,130),3)
        cv2.line(out,(0,H-h),(W,H-h),(125,125,130),3)
        cv2.line(out,(0,max(0,h-3)),(W,max(0,h-3)),(210,210,215),1)
        cv2.line(out,(0,min(H-1,H-h+3)),(W,min(H-1,H-h+3)),(210,210,215),1)
        for x in range(0,W,90):
            cv2.line(out,(x,0),(x,h),(25,25,28),1)
            cv2.line(out,(x,H-h),(x,H),(25,25,28),1)
    if close>=0.999: out[:]=(5,5,6)
    return out

allf=[]; marks=[]; total=0
for p,n in segs:
    fs=read(p,n); print(p,len(fs),flush=True)
    if len(fs)<n: raise SystemExit('short '+p)
    allf+=fs; total+=n; marks.append(total)
marks=marks[:-1]
print('total',len(allf),'seams',marks,flush=True)

for seam in marks:
    for k in range(-6,7):
        i=seam+k
        if 0<=i<len(allf):
            c=max(0.0,min(1.0,1-abs(k)/6.0))
            allf[i]=overlay(allf[i],c)

os.makedirs('full_frames',exist_ok=True)
for i,f in enumerate(allf): cv2.imwrite(f'full_frames/{i:05d}.png',f)

# audio
SR=44100; dur=len(allf)/24.0; N=int(SR*dur)
def rd(p):
    with wave.open(p,'rb') as w:
        n=w.getnframes(); ch=w.getnchannels(); sw=w.getsampwidth()
        data=w.readframes(n)
    if sw!=2: raise SystemExit('need 16bit')
    a=np.frombuffer(data,dtype=np.int16).astype(np.float32)/32768.0
    if ch>1: a=a.reshape(-1,ch).mean(1)
    return a
music=rd('/home/zyw/Downloads/dl-hub/100-长安Disco-场景图/音频/disco120.wav')
if len(music)<N: music=np.pad(music,(0,N-len(music)))
music=music[:N].copy()
# fades
fi=int(0.15*SR); fo=int(0.7*SR)
music[:fi]*=np.linspace(0,1,fi)
music[-fo:]*=np.linspace(1,0,fo)
click=rd('/home/zyw/Downloads/dl-hub/100-长安Disco-场景图/音频/快门.wav')
times=[m/24.0 for m in marks]+[0.0,dur-0.25]
for t in times:
    i=int(t*SR)
    n=min(len(click),N-i)
    if n>0: music[i:i+n]+=0.9*click[:n]
peak=np.max(np.abs(music)) or 1.0
music=np.clip(music*0.9/peak,-1,1)
with wave.open('full_audio.wav','wb') as w:
    w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
    w.writeframes((music*32767).astype(np.int16).tobytes())
print('audio',dur,N,flush=True)
