#!/usr/bin/env python3
"""Check that each server really starts the transcode at timeOffset: compare the first 256 KB of the MP3
stream from the start with the first 256 KB at offset 1500 s (different bytes = the offset was applied),
and decode 2 s of each to compare their loudness envelope with the source FLAC at the same position."""
import hashlib, http.client, json, os, subprocess, sys, tempfile, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bench as b

def grab(port, path, hdrs, n=256 * 1024):
    c = http.client.HTTPConnection("127.0.0.1", port, timeout=120)
    c.request("GET", path, headers=hdrs)
    r = c.getresponse()
    data = r.read(n)
    c.close()
    return data

def rms_db(blob, ss=None, src=None):
    cmd = ["ffmpeg", "-v", "info", "-nostats"] + (["-ss", str(ss)] if ss else []) + ["-t", "2", "-i", src or "-", "-af", "volumedetect", "-f", "null", "-"]
    r = subprocess.run(cmd, input=None if src else blob, capture_output=True)
    for ln in r.stderr.decode().splitlines():
        if "mean_volume" in ln:
            return ln.split("mean_volume:")[1].strip()
    return "?"

name = sys.argv[1]
b.ensure_network()
s = b.SERVERS[name]()
res = {}
try:
    s.destroy(); s.create(); t0 = s.start(); s.wait_ready(t0); s.setup(); s.start_scan(); b.wait_scan(s)
    if name == "jellyfin":
        s.login()
    api = s.api(); hd = api.hdrs()
    lt = api.long_track
    a = grab(s.host_port, api.stream_mp3(lt), hd)
    z = grab(s.host_port, api.stream_mp3(lt, 1500), hd)
    z2 = grab(s.host_port, api.stream_mp3(lt, 1500 + 7), hd)
    src = os.environ["BENCH_LONG_FLAC_FILE"]  # the same long FLAC, as a host path
    res = {"from_start_vs_1500_identical_first_256k": hashlib.md5(a).digest() == hashlib.md5(z).digest(),
           "1500_vs_1507_identical": hashlib.md5(z).digest() == hashlib.md5(z2).digest(),
           "mean_volume_start": rms_db(a), "mean_volume_1500": rms_db(z), "mean_volume_1507": rms_db(z2),
           "source_mean_volume_0s": rms_db(None, 0, src), "source_mean_volume_1500s": rms_db(None, 1500, src),
           "source_mean_volume_1507s": rms_db(None, 1507, src)}
finally:
    s.destroy()
print(json.dumps({name: res}))
