import socket
import subprocess
import os
import threading
import time

BIN_PATH = "/opt/md380-emu/md380-emu"
SHM_DIR = "/dev/shm"

def gestisci_emulatore(porta):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1', porta))
    print(f"[*] Vocoder attivo in ascolto sulla porta UDP {porta}")
    
    while True:
        try:
            data, addr = sock.recvfrom(1024)
            if not data: continue
            
            # Percorsi file univoci per ogni porta direttamente nella RAM
            f_in = f"{SHM_DIR}/in_{porta}.bin"
            f_out = f"{SHM_DIR}/out_{porta}.bin"
            
            with open(f_in, "wb") as f:
                f.write(data)
            
            # Se riceviamo 7 byte, è AMBE da decodificare in PCM. Altrimenti è PCM da codificare.
            if len(data) == 7 or len(data) == 9:
                subprocess.run([BIN_PATH, "-d", "-i", f_in, "-o", f_out], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            else:
                subprocess.run([BIN_PATH, "-e", "-i", f_in, "-o", f_out], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                
            if os.path.exists(f_out):
                with open(f_out, "rb") as f:
                    sock.sendto(f.read(), addr)
        except Exception:
            pass

# Avviamo 3 vocoder indipendenti in background
for p in [2470, 2471, 2472]:
    threading.Thread(target=gestisci_emulatore, args=(p,), daemon=True).start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("Chiusura del pool...")
