bridge.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import os
  2. import sys
  3. import time
  4. import socket
  5. import struct
  6. import numpy as np
  7. # Network settings
  8. UDP_IP = os.environ.get("UDP_IP", "239.0.0.1")
  9. UDP_PORT = int(os.environ.get("UDP_PORT", "11988"))
  10. # Audio stream constants
  11. SAMPLE_RATE = 44100
  12. CHUNK_SIZE = 1024
  13. CHUNK_DURATION = CHUNK_SIZE / SAMPLE_RATE
  14. FRAME_BYTES = CHUNK_SIZE * 4
  15. MAX_SILENT_FRAMES = 43 # ~1 second of silence at 43.06 FPS
  16. # DSP tuning environment overrides
  17. FREQ_MIN = float(os.environ.get("FREQ_MIN", "100.0"))
  18. FREQ_MAX = float(os.environ.get("FREQ_MAX", "8000.0"))
  19. GAIN_MULT = float(os.environ.get("GAIN_MULT", "3500.0"))
  20. SILENCE_THRESHOLD = float(os.environ.get("SILENCE_THRESHOLD", "0.5"))
  21. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  22. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  23. # Compute 16 logarithmic frequency bands
  24. FREQ_EDGES = np.logspace(np.log10(FREQ_MIN), np.log10(FREQ_MAX), 17)
  25. fft_freqs = np.fft.rfftfreq(CHUNK_SIZE, 1.0 / SAMPLE_RATE)
  26. bins_idx = []
  27. for i in range(16):
  28. low = FREQ_EDGES[i]
  29. high = FREQ_EDGES[i + 1]
  30. idx = np.where((fft_freqs >= low) & (fft_freqs < high) & (fft_freqs > 0))[0]
  31. if len(idx) == 0:
  32. non_zero_bins = np.where(fft_freqs > 0)[0]
  33. closest = non_zero_bins[np.argmin(np.abs(fft_freqs[non_zero_bins] - low))]
  34. idx = [closest]
  35. bins_idx.append(idx)
  36. sample_smth = 0.0
  37. clock_target = time.perf_counter()
  38. silence_frames = 0
  39. # Canonical 44-byte WLED AudioReactive V2 struct layout
  40. STRUCT_FMT_V2 = "<6s2xffB3x16sd"
  41. while True:
  42. raw_data = sys.stdin.buffer.read(FRAME_BYTES)
  43. if not raw_data or len(raw_data) < FRAME_BYTES:
  44. break
  45. # Pacing at real-time audio speed to avoid CPU runaway
  46. clock_target += CHUNK_DURATION
  47. delay = clock_target - time.perf_counter()
  48. if delay > 0:
  49. time.sleep(delay)
  50. elif delay < -0.2:
  51. clock_target = time.perf_counter()
  52. audio = np.frombuffer(raw_data, dtype=np.int16).astype(np.float32)
  53. left = audio[0::2]
  54. right = audio[1::2]
  55. mono = (left + right) / (2.0 * 32768.0)
  56. raw_mag = float(np.max(np.abs(mono)) * 255.0)
  57. sample_smth = 0.7 * sample_smth + 0.3 * raw_mag
  58. sample_peak = 1 if raw_mag > (sample_smth * 1.5 + 20) else 0
  59. if raw_mag < SILENCE_THRESHOLD:
  60. silence_frames += 1
  61. else:
  62. silence_frames = 0
  63. if silence_frames > MAX_SILENT_FRAMES:
  64. continue
  65. windowed = mono * np.hanning(CHUNK_SIZE)
  66. fft_vals = np.abs(np.fft.rfft(windowed)) / (CHUNK_SIZE / 2)
  67. fft_result = bytearray(16)
  68. for i in range(16):
  69. energy = float(np.mean(fft_vals[bins_idx[i]])) * GAIN_MULT
  70. fft_result[i] = min(255, int(np.clip(energy, 0, 255)))
  71. payload = struct.pack(
  72. STRUCT_FMT_V2,
  73. b"00002\x00",
  74. float(raw_mag),
  75. float(sample_smth),
  76. sample_peak,
  77. bytes(fft_result),
  78. float(raw_mag)
  79. )
  80. try:
  81. sock.sendto(payload, (UDP_IP, UDP_PORT))
  82. except Exception:
  83. pass