#!/usr/bin/env python3
"""DAB+ reaalajas: eeter-rx IQ (1234, 2.4 MSPS int16) -> resample 64/75 -> u8 2.048 MSPS -> mini rtl_tcp server (1236) -> welle-cli.
(FIFO + welle-cli -f ei sobinud: failileja loeb tühja toru EOF-iks ja sünkro kaob.)

  dab_rx.py --channel 7B|10D [--port 7979] [--no-tune]
Heli: http://127.0.0.1:7979/mp3/<SId> (mpv), jaamad + "Hetkel eetris": /mux.json. Kasutajale: käsk `dab` (~/.local/bin/dab).
NB: tuunib eeter-rx DAB-kanalile -> FM (Raadio 2) kuulaja/salvesti jäävad vait, kuni `dab stopp` tuunib tagasi.
"""
import argparse, os, socket, struct, subprocess, sys, time
import numpy as np
from scipy.signal import firwin

CHANNELS = {"5A": 174928000, "7B": 190640000, "10D": 215072000, "12C": 227360000}
UP, DOWN = 64, 75                          # 2.4 MHz * 64/75 = 2.048 MHz
TAPS = 24                                  # tappe faasi kohta


class Resampler:
    """Olekuga polüfaasne ratsionaalne resampler (UP/DOWN), kompleksne sisend."""
    def __init__(self):
        h = firwin(UP * TAPS, 0.9 / DOWN, window=("kaiser", 8.0)) * UP   # lõige ~0,96 MHz (ansambel ±768 kHz)
        self.poly = h.reshape(TAPS, UP).T[:, ::-1].astype(np.float32).copy()   # poly[p] = h[p::UP], ajas tagurpidi
        self.hist = np.zeros(TAPS, np.complex64)
        self.m = 0                             # järgmise väljundsämpli globaalne indeks
        self.n0 = -TAPS                        # buf[0] globaalne sisendindeks

    def __call__(self, x):
        buf = np.concatenate([self.hist, x])
        n_end = self.n0 + len(buf)
        # väljund m kasutab sisendit floor(m*DOWN/UP) ja TAPS-1 eelmist
        m_last = ((n_end - 1) * UP) // DOWN
        ms = np.arange(self.m, m_last + 1)
        t = ms * DOWN
        base, ph = t // UP, t % UP
        idx = (base - self.n0)[:, None] + np.arange(-TAPS + 1, 1)[None, :]
        y = np.einsum("ij,ij->i", buf[idx], self.poly[ph])
        self.m = m_last + 1
        keep = TAPS + 1
        self.hist = buf[-keep:]
        self.n0 = n_end - keep
        return y


def rigctl(cmd):
    with socket.create_connection(("127.0.0.1", 4532), timeout=3) as s:
        s.sendall((cmd + "\nq\n").encode())
        return s.makefile().readline().strip()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--channel", default="10D", choices=CHANNELS)
    ap.add_argument("--port", type=int, default=7979)
    ap.add_argument("--gain", default="40.2")
    ap.add_argument("--no-tune", action="store_true")
    a = ap.parse_args()
    if not a.no_tune:
        rigctl(f"F {CHANNELS[a.channel]}")
        rigctl(f"L RFGAIN {a.gain}")
    srv = socket.socket(); srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind(("127.0.0.1", 1236)); srv.listen(1)
    welle = subprocess.Popen(["welle-cli", "-c", a.channel, "-F", "rtl_tcp,127.0.0.1:1236", "-w", str(a.port), "-T"],
                             stdout=sys.stdout, stderr=sys.stderr)
    print(f"DAB {a.channel} {CHANNELS[a.channel]} Hz -> welle-cli :{a.port}", flush=True)
    srv.settimeout(30)
    try:
        c, _ = srv.accept()
        c.sendall(b"RTL0" + struct.pack(">II", 5, 29))             # tuuner R820T, 29 gain-astet (käske eiratakse)
        c.setblocking(False)
        rs = Resampler()
        s = socket.create_connection(("127.0.0.1", 1234), timeout=10)
        blk = 240000 * 4                                      # 100 ms
        buf = bytearray(blk); view = memoryview(buf)
        while welle.poll() is None:
            got = 0
            while got < blk:
                n = s.recv_into(view[got:], blk - got)
                if not n: raise OSError("eeter-rx ühendus katkes")
                got += n
            try: c.recv(4096)                                 # welle käsud (sagedus/gain) – tuunimine on meie teha
            except BlockingIOError: pass
            d = np.frombuffer(buf, np.int16).astype(np.float32)
            y = rs((d[0::2] + 1j * d[1::2]).astype(np.complex64))
            u = np.empty(2 * len(y), np.uint8)                # int16 = (u8 - 127.4) * 256 -> tagasi
            u[0::2] = np.clip(y.real / 256 + 127.5, 0, 255)
            u[1::2] = np.clip(y.imag / 256 + 127.5, 0, 255)
            c.setblocking(True); c.sendall(u.tobytes()); c.setblocking(False)
    except (OSError, KeyboardInterrupt) as e:
        print(f"lõpp: {e}", flush=True)
    finally:
        welle.terminate()


if __name__ == "__main__":
    main()
