import os, json, subprocess
import numpy as np
from scipy.io import wavfile
from scipy.signal import butter, sosfilt
A="/var/aiadultvideo/output/aiadult/"; OUT=A+"pitchtest2/"
os.makedirs(OUT,exist_ok=True)
SR=16000
def wav_of(mp4,dst):
    subprocess.run(["ffmpeg","-y","-v","error","-i",mp4,"-vn","-ac","1","-ar",str(SR),"-c:a","pcm_s16le",dst],check=True)
    sr,x=wavfile.read(dst); return x.astype(np.float64)
sos_hp=butter(4,120,btype="highpass",fs=SR,output="sos")
sos_bp=butter(4,[300,3400],btype="bandpass",fs=SR,output="sos")
def frames(x,fl=640,hop=160):
    n=1+(len(x)-fl)//hop
    return np.stack([x[i*hop:i*hop+fl] for i in range(n)])
def yin(fr):
    out=np.full(len(fr),np.nan); tmin,tmax=40,267
    for i,f in enumerate(fr):
        f=f-f.mean()
        if np.sum(f**2)<1e-6: continue
        d=np.full(tmax+1,np.nan)
        for tau in range(tmin,tmax+1): d[tau]=np.sum((f[:len(f)-tau]-f[tau:])**2)
        cm=np.ones(tmax+1); run=0.0
        for tau in range(1,tmax+1):
            run+=d[tau] if not np.isnan(d[tau]) else 0.0
            if run>0: cm[tau]=d[tau]*tau/run
        best=None
        for tau in range(tmin,tmax+1):
            if cm[tau]<0.18 and tau+1<=tmax and cm[tau]<=cm[tau+1]: best=tau; break
        if best is None:
            seg=cm[tmin:tmax+1]; j=int(np.nanargmin(seg))
            if seg[j]<0.35: best=tmin+j
        if best: out[i]=SR/best
    return out
def speech_f0(x):
    y=sosfilt(sos_hp,x)
    fr=frames(y)
    band=sosfilt(sos_bp,x)
    frb=frames(band)
    e=20*np.log10(np.sqrt((frb**2).mean(1)+1e-12)/32768.0)
    noise=float(np.percentile(e,10)); peak=float(np.percentile(e,99))
    thr=max(noise+10.0,peak-25.0)
    v=e>thr
    f0=yin(fr)
    ok=v&~np.isnan(f0)&(f0>80)&(f0<500)
    vv=f0[ok]
    if len(vv)<5: return {"n":int(len(vv)),"median":None}
    segs=[];i=0;n=len(v)
    while i<n:
        if not v[i]: i+=1; continue
        j=i
        while j+1<n and v[j+1]: j+=1
        segs.append((round(i*0.01,2),round(j*0.01,2))); i=j+1
    return {"n":int(len(vv)),"median":round(float(np.median(vv)),1),
            "p10":round(float(np.percentile(vv,10)),1),"p90":round(float(np.percentile(vv,90)),1),
            "voiced_sec":round(float(v.sum())*0.01,2),"segments":segs}
# --- sanity: synthetic tone test ---
t=np.arange(int(2.0*SR))/SR
tone=(0.3*np.sin(2*np.pi*200*t)*32768).astype(np.int16)
wavfile.write(OUT+"tone200.wav",SR,tone)
subprocess.run(["ffmpeg","-y","-v","error","-i",OUT+"tone200.wav","-af","rubberband=pitch=1.2223","-ar",str(SR),OUT+"tone200_shift.wav"],check=True)
sr,ts=wavfile.read(OUT+"tone200_shift.wav")
tf=frames(ts.astype(np.float64)); f0t=yin(tf); v=~np.isnan(f0t)
synth={"in_hz":200,"factor":1.2223,"expected_hz":round(200*1.2223,1),
       "measured_hz":round(float(np.median(f0t[v])),1) if v.any() else None}
print("SYNTH",json.dumps(synth),flush=True)
JOBS=[("S04_v9","ep01_delivery/S04_v9.mp4",254.0),
      ("S06_v24","ep01_delivery/S06_v24.mp4",254.0),
      ("S07_v15_old","ep01_delivery/S07_v15.mp4",254.0),
      ("S08_v27_old","ep01_delivery/S08_v27.mp4",254.0)]
res={"synthetic":synth,"jobs":{}}
for tag,rel,target in JOBS:
    src=A+rel
    xs=wav_of(src,OUT+tag+"_src.wav")
    before=speech_f0(xs)
    base=before.get("median")
    if not base: print(tag,"NO SPEECH",flush=True); continue
    factor=target/base
    dst=OUT+tag+"_pitch254_v2.mp4"
    subprocess.run(["ffmpeg","-y","-v","error","-i",src,"-c:v","copy","-af","rubberband=pitch=%.6f"%factor,"-c:a","aac","-b:a","192k",dst],check=True)
    xo=wav_of(dst,OUT+tag+"_out.wav")
    after=speech_f0(xo)
    ent={"src":src,"dst":dst,"target":target,"factor":round(factor,6),
         "semitones":round(12*np.log2(factor),2),"before":before,"after":after,
         "expected_after":round(base*factor,1)}
    res["jobs"][tag]=ent
    print(tag,json.dumps(ent,ensure_ascii=False),flush=True)
json.dump(res,open(OUT+"pitchfix.json","w"),ensure_ascii=False,indent=1)
print("PITCHFIX_DONE",flush=True)
