import os, sys, time
os.chdir(os.path.expanduser("~/RVC"))
sys.path.insert(0, os.getcwd())
import numpy as np, soundfile as sf, torch, librosa
import torch.nn.functional as F
import torchaudio.transforms as tat
from configs.config import Config
from infer import rtrvc as rvc_for_realtime

cfg = Config()
print("cfg.device:", cfg.device, "is_half:", cfg.is_half, "cuda_avail:", torch.cuda.is_available())
if torch.cuda.is_available():
    print("gpu:", torch.cuda.get_device_name(0), "cc:", torch.cuda.get_device_capability(0))

pth = os.path.expanduser("~/RVC/assets/weights/Fp231.pth")
index = os.path.expanduser("~/RVC/assets/weights/added_IVF1216_Flat_nprobe_1_Fp231_v2.index")
rvc = rvc_for_realtime.RVC(0, 0.0, pth, index, 0.75, cfg, None)
tgt_sr = rvc.tgt_sr
print("model loaded. tgt_sr =", tgt_sr, "version =", getattr(rvc, "version", "?"))

sr_stream = tgt_sr
zc = sr_stream // 100
block_time, crossfade_time, extra_time = 0.25, 0.05, 2.5
block_frame = int(np.round(block_time * sr_stream / zc)) * zc
block_frame_16k = 160 * block_frame // zc
crossfade_frame = int(np.round(crossfade_time * sr_stream / zc)) * zc
sola_buffer_frame = min(crossfade_frame, 4 * zc)
sola_search_frame = zc
extra_frame = int(np.round(extra_time * sr_stream / zc)) * zc
input_wav = torch.zeros(extra_frame + crossfade_frame + sola_search_frame + block_frame,
                        device=cfg.device, dtype=torch.float32)
input_wav_res = torch.zeros(160 * input_wav.shape[0] // zc, device=cfg.device, dtype=torch.float32)
sola_buffer = torch.zeros(sola_buffer_frame, device=cfg.device, dtype=torch.float32)
sola_den_kernel = torch.ones(1, 1, sola_buffer_frame, device=cfg.device, dtype=torch.float32)
skip_head = extra_frame // zc
return_length = (block_frame + sola_buffer_frame + sola_search_frame) // zc
fade_in = torch.sin(0.5 * np.pi * torch.linspace(0.0, 1.0, steps=sola_buffer_frame,
                                                 device=cfg.device, dtype=torch.float32)) ** 2
fade_out = 1 - fade_in
resampler = tat.Resample(orig_freq=sr_stream, new_freq=16000, dtype=torch.float32).to(cfg.device)

wav, sr = sf.read(os.path.expanduser("~/RVC/assets/weights/p231.flac"), dtype="float32")
if wav.ndim > 1:
    wav = wav.mean(1)
wav = librosa.resample(wav, orig_sr=sr, target_sr=sr_stream)
print("input wav:", wav.shape, sr_stream, "Hz, %.1fs" % (len(wav) / sr_stream))

pad = input_wav.shape[0]
audio = np.concatenate([np.zeros(pad, dtype="float32"), wav])
n_blocks = (len(audio) - pad) // block_frame
outs, times = [], []
for i in range(n_blocks):
    chunk = torch.from_numpy(audio[i * block_frame:(i + 1) * block_frame]).to(cfg.device)
    input_wav[:-block_frame] = input_wav[block_frame:].clone()
    input_wav[-block_frame:] = chunk
    with torch.no_grad():
        resample_input = input_wav[-block_frame - 2 * zc:]
        input_wav_res[-160 * (block_frame // zc + 1):] = resampler(resample_input)[160:]
        t0 = time.perf_counter()
        infer_wav = rvc.infer(input_wav_res, block_frame_16k, skip_head, return_length, "rmvpe")
        conv_input = infer_wav[None, None, : sola_buffer_frame + sola_search_frame]
        cor_nom = F.conv1d(conv_input, sola_buffer[None, None, :])
        cor_den = torch.sqrt(F.conv1d(conv_input ** 2, sola_den_kernel) + 1e-8)
        sola_offset = int(torch.argmax(cor_nom[0, 0] / cor_den[0, 0]))
        infer_wav = infer_wav[sola_offset:]
        infer_wav[:sola_buffer_frame] = infer_wav[:sola_buffer_frame] * fade_in + sola_buffer * fade_out
        sola_buffer[:] = infer_wav[block_frame:block_frame + sola_buffer_frame]
        torch.cuda.synchronize()
        times.append(time.perf_counter() - t0)
        outs.append(infer_wav[:block_frame].cpu().numpy().copy())

out = np.concatenate(outs)
sf.write(os.path.expanduser("~/rvc-rt-out.wav"), out, sr_stream)
print("blocks: %d  avg infer: %.1f ms  RTF: %.3f  (block=%.0f ms)" % (
    n_blocks, 1000 * np.mean(times), np.mean(times) / block_time, block_time * 1000))
print("peak VRAM: %.0f MB" % (torch.cuda.max_memory_allocated() / 1e6))
print("output:", out.shape, "-> ~/rvc-rt-out.wav")
