#!/usr/bin/env python3
"""RVC 局域网服务端
  1) TCP 实时流（默认 8765）：客户端按 block 送 PCM16@48k 单声道，服务端返回 PCM16@48k
  2) HTTP 单次转换（默认 8766）：POST /convert  body=wav，返回 wav
环境变量：RVC_PTH / RVC_INDEX / RVC_PITCH / RVC_BLOCK_MS / RVC_PORT / RVC_HTTP_PORT
"""
import os, sys, io, json, time, socket, struct, threading, traceback, wave
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

HOME = os.path.expanduser("~")
RVC_DIR = os.path.join(HOME, "RVC")
sys.path.insert(0, RVC_DIR)
os.chdir(RVC_DIR)

import numpy as np
import torch
import torch.nn.functional as F
import torchaudio.transforms as tat
from configs.config import Config
from infer import rtrvc

NET_SR = 48000
BLOCK_MS = int(os.environ.get("RVC_BLOCK_MS", "250"))
STREAM_PORT = int(os.environ.get("RVC_PORT", "8765"))
HTTP_PORT = int(os.environ.get("RVC_HTTP_PORT", "8766"))
PTH = os.environ.get("RVC_PTH", os.path.join(RVC_DIR, "assets", "weights", "Fp231.pth"))
INDEX = os.environ.get("RVC_INDEX", os.path.join(RVC_DIR, "assets", "weights",
        "added_IVF1216_Flat_nprobe_1_Fp231_v2.index"))
PITCH = int(os.environ.get("RVC_PITCH", "12"))
INDEX_RATE = float(os.environ.get("RVC_INDEX_RATE", "0.3"))

print("[init] loading RVC model ...", flush=True)
t0 = time.time()
cfg = Config()
rvc = rtrvc.RVC(PITCH, 0.0, PTH, INDEX, INDEX_RATE, cfg, None)
TGT = int(rvc.tgt_sr)
ZC = TGT // 100
MODEL_LOCK = threading.Lock()
print("[init] model ready: tgt_sr=%d, device=%s, %.1fs" % (TGT, cfg.device, time.time() - t0), flush=True)


def block_samples(ms):
    return int(round(TGT * ms / 1000.0 / ZC)) * ZC


class Engine:
    """与 realtime_gui 相同的分块 + SOLA 逻辑，输入输出都是 40k(float32)。"""

    def __init__(self, ms=BLOCK_MS):
        self.block = block_samples(ms)
        self.bf16 = 160 * self.block // ZC
        self.cross = int(round(0.05 * TGT / ZC)) * ZC
        self.sola_buf = min(self.cross, 4 * ZC)
        self.sola_search = ZC
        self.extra = int(round(2.5 * TGT / ZC)) * ZC
        n = self.extra + self.cross + self.sola_search + self.block
        self.in_wav = torch.zeros(n, device=cfg.device, dtype=torch.float32)
        self.in_res = torch.zeros(160 * n // ZC, device=cfg.device, dtype=torch.float32)
        self.sola = torch.zeros(self.sola_buf, device=cfg.device, dtype=torch.float32)
        self.kernel = torch.ones(1, 1, self.sola_buf, device=cfg.device, dtype=torch.float32)
        self.skip = self.extra // ZC
        self.ret = (self.block + self.sola_buf + self.sola_search) // ZC
        self.fade_in = torch.sin(0.5 * np.pi * torch.linspace(
            0.0, 1.0, steps=self.sola_buf, device=cfg.device, dtype=torch.float32)) ** 2
        self.fade_out = 1 - self.fade_in
        self.rs_in = tat.Resample(orig_freq=TGT, new_freq=16000, dtype=torch.float32).to(cfg.device)

    def process(self, chunk):
        if len(chunk) < self.block:
            chunk = np.pad(chunk, (0, self.block - len(chunk)))
        elif len(chunk) > self.block:
            chunk = chunk[: self.block]
        ch = torch.from_numpy(np.ascontiguousarray(chunk, dtype=np.float32)).to(cfg.device)
        self.in_wav[:-self.block] = self.in_wav[self.block:].clone()
        self.in_wav[-self.block:] = ch
        with torch.no_grad(), MODEL_LOCK:
            res = self.in_wav[-self.block - 2 * ZC:]
            self.in_res[-160 * (self.block // ZC + 1):] = self.rs_in(res)[160:]
            wav = rvc.infer(self.in_res, self.bf16, self.skip, self.ret, "rmvpe")
            conv = wav[None, None, : self.sola_buf + self.sola_search]
            nom = F.conv1d(conv, self.sola[None, None, :])
            den = torch.sqrt(F.conv1d(conv ** 2, self.kernel) + 1e-8)
            off = int(torch.argmax(nom[0, 0] / den[0, 0]))
            wav = wav[off:]
            wav[: self.sola_buf] = wav[: self.sola_buf] * self.fade_in + self.sola * self.fade_out
            self.sola[:] = wav[self.block: self.block + self.sola_buf]
            out = wav[: self.block].detach().cpu().numpy().copy()
        return out


rs_down = tat.Resample(orig_freq=NET_SR, new_freq=TGT, dtype=torch.float32)
rs_up = tat.Resample(orig_freq=TGT, new_freq=NET_SR, dtype=torch.float32)


def recv_exact(conn, n):
    buf = b""
    while len(buf) < n:
        part = conn.recv(n - len(buf))
        if not part:
            return None
        buf += part
    return buf


def recv_frame(conn):
    hdr = recv_exact(conn, 4)
    if hdr is None:
        return None
    (n,) = struct.unpack(">I", hdr)
    if n == 0 or n > 50 * 1024 * 1024:
        return None
    return recv_exact(conn, n)


def send_frame(conn, payload):
    conn.sendall(struct.pack(">I", len(payload)) + payload)


def handle_client(conn, addr):
    print("[stream] client %s:%d connected" % addr, flush=True)
    conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    conn.settimeout(60)
    try:
        hello = recv_frame(conn)
        conf = json.loads(hello.decode("utf-8")) if hello else {}
        ms = int(conf.get("block_ms", BLOCK_MS))
        net_block = int(NET_SR * ms / 1000)
        eng = Engine(ms)
        n_in = 0
        while True:
            payload = recv_frame(conn)
            if payload is None:
                break
            x = np.frombuffer(payload, dtype="<i2").astype(np.float32) / 32768.0
            if len(x) < net_block:
                x = np.pad(x, (0, net_block - len(x)))
            x40 = rs_down(torch.from_numpy(x[:net_block])).numpy()
            y40 = eng.process(x40)
            y48 = rs_up(torch.from_numpy(y40)).numpy()
            send_frame(conn, (np.clip(y48, -1.0, 1.0) * 32767.0).astype("<i2").tobytes())
            n_in += 1
            if n_in % 40 == 0:
                print("[stream] %s: %d blocks" % (addr[0], n_in), flush=True)
    except Exception:
        traceback.print_exc()
    finally:
        try:
            conn.close()
        except Exception:
            pass
        print("[stream] client %s:%d closed" % addr, flush=True)


def serve_stream():
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind(("0.0.0.0", STREAM_PORT))
    srv.listen(4)
    print("[stream] listening on 0.0.0.0:%d (block %d ms @ %d Hz)" % (STREAM_PORT, BLOCK_MS, NET_SR), flush=True)
    while True:
        conn, addr = srv.accept()
        threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()


def convert_wav(data):
    with wave.open(io.BytesIO(data), "rb") as w:
        sr, ch, nframes = w.getframerate(), w.getnchannels(), w.getnframes()
        raw = w.readframes(nframes)
    x = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
    if ch > 1:
        x = x.reshape(-1, ch).mean(1)
    if sr != NET_SR:
        import librosa
        x = librosa.resample(x, orig_sr=sr, target_sr=NET_SR)
    net_block = int(NET_SR * BLOCK_MS / 1000)
    eng = Engine(BLOCK_MS)
    out = []
    for i in range(0, len(x) - net_block + 1, net_block):
        x40 = rs_down(torch.from_numpy(x[i:i + net_block])).numpy()
        y40 = eng.process(x40)
        out.append(rs_up(torch.from_numpy(y40)).numpy())
    y = np.concatenate(out) if out else np.zeros(1, dtype=np.float32)
    buf = io.BytesIO()
    with wave.open(buf, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(NET_SR)
        w.writeframes((np.clip(y, -1, 1) * 32767).astype("<i2").tobytes())
    return buf.getvalue()


class HTTPHandler(BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        print("[http] " + fmt % args, flush=True)

    def do_GET(self):
        if self.path.startswith("/health"):
            body = json.dumps({"ok": True, "tgt_sr": TGT, "block_ms": BLOCK_MS,
                               "pitch": PITCH, "model": os.path.basename(PTH)}).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_error(404)

    def do_POST(self):
        if not self.path.startswith("/convert"):
            self.send_error(404)
            return
        n = int(self.headers.get("Content-Length", "0"))
        data = self.rfile.read(n)
        try:
            t0 = time.time()
            out = convert_wav(data)
            print("[http] converted %d bytes in %.1fs" % (len(data), time.time() - t0), flush=True)
            self.send_response(200)
            self.send_header("Content-Type", "audio/wav")
            self.send_header("Content-Length", str(len(out)))
            self.end_headers()
            self.wfile.write(out)
        except Exception:
            traceback.print_exc()
            self.send_error(500)


if __name__ == "__main__":
    threading.Thread(target=serve_stream, daemon=True).start()
    httpd = ThreadingHTTPServer(("0.0.0.0", HTTP_PORT), HTTPHandler)
    print("[http] listening on 0.0.0.0:%d (POST /convert, GET /health)" % HTTP_PORT, flush=True)
    httpd.serve_forever()
