bridge.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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", "40.0")) # Catch deep sub-bass and 50Hz kicks
  18. FREQ_MAX = float(os.environ.get("FREQ_MAX", "12000.0")) # Capture crisp cymbals and high transients
  19. SILENCE_THRESHOLD = float(os.environ.get("SILENCE_THRESHOLD", "0.5"))
  20. # Dynamic AGC and Frequency Tilt overrides
  21. GAIN_MIN = float(os.environ.get("GAIN_MIN", "800.0")) # Floor: prevents squashing heavily mastered EDM
  22. GAIN_MAX = float(os.environ.get("GAIN_MAX", "8500.0")) # Ceiling: prevents boosting background tape hiss
  23. TILT_EXPONENT = float(os.environ.get("TILT_EXPONENT", "0.42")) # Logarithmic treble compensation curve
  24. DECAY_RATE = float(os.environ.get("DECAY_RATE", "0.998")) # ~10-second slow recovery decay per frame
  25. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
  26. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
  27. # Pre-compute Hanning window to save CPU cycles inside the loop
  28. HANNING_WINDOW = np.hanning(CHUNK_SIZE).astype(np.float32)
  29. # Compute 16 logarithmic frequency bands
  30. FREQ_EDGES = np.logspace(np.log10(FREQ_MIN), np.log10(FREQ_MAX), 17)
  31. fft_freqs = np.fft.rfftfreq(CHUNK_SIZE, 1.0 / SAMPLE_RATE)
  32. bins_idx = []
  33. for i in range(16):
  34. low = FREQ_EDGES[i]
  35. high = FREQ_EDGES[i + 1]
  36. idx = np.where((fft_freqs >= low) & (fft_freqs < high) & (fft_freqs > 0))[0]
  37. if len(idx) == 0:
  38. non_zero_bins = np.where(fft_freqs > 0)[0]
  39. closest = non_zero_bins[np.argmin(np.abs(fft_freqs[non_zero_bins] - low))]
  40. idx = [closest]
  41. bins_idx.append(idx)
  42. # Pre-compute logarithmic treble tilt weights (1/f pink noise balance)
  43. band_centers = np.sqrt(FREQ_EDGES[:-1] * FREQ_EDGES[1:])
  44. TILT_WEIGHTS = ((band_centers / FREQ_MIN) ** TILT_EXPONENT).astype(np.float32)
  45. # State variables
  46. sample_smth = 0.0
  47. silence_frames = 0
  48. running_peak = 0.05 # Initial baseline ceiling
  49. STRUCT_FMT_V2 = "<6s2xffB3x16sd"
  50. start_time = None
  51. frames_processed = 0
  52. while True:
  53. t0 = time.perf_counter()
  54. raw_data = sys.stdin.buffer.read(FRAME_BYTES)
  55. read_duration = time.perf_counter() - t0
  56. if not raw_data or len(raw_data) < FRAME_BYTES:
  57. break
  58. # Gap Detector: If the pipe sat empty for >200ms, reset the clock & AGC baseline
  59. if read_duration > 0.2:
  60. start_time = time.perf_counter()
  61. frames_processed = 0
  62. running_peak = 0.05
  63. if start_time is None:
  64. start_time = time.perf_counter()
  65. # Audio ingestion and magnitude extraction
  66. audio = np.frombuffer(raw_data, dtype=np.int16).astype(np.float32)
  67. left = audio[0::2]
  68. right = audio[1::2]
  69. mono = (left + right) * (1.0 / 65536.0)
  70. raw_mag = float(np.max(np.abs(mono)) * 255.0)
  71. sample_smth = 0.7 * sample_smth + 0.3 * raw_mag
  72. sample_peak = 1 if raw_mag > (sample_smth * 1.5 + 20) else 0
  73. if raw_mag < SILENCE_THRESHOLD:
  74. silence_frames += 1
  75. else:
  76. silence_frames = 0
  77. if silence_frames <= MAX_SILENT_FRAMES:
  78. windowed = mono * HANNING_WINDOW
  79. fft_vals = np.abs(np.fft.rfft(windowed)) * (2.0 / CHUNK_SIZE)
  80. # Vectorized band extraction
  81. raw_energies = np.empty(16, dtype=np.float32)
  82. for i in range(16):
  83. raw_energies[i] = np.mean(fft_vals[bins_idx[i]])
  84. # Apply logarithmic pink noise compensation
  85. tilted_energies = raw_energies * TILT_WEIGHTS
  86. # Asymmetric AGC: Instant attack, slow crawl decay
  87. current_max = float(np.max(tilted_energies))
  88. if current_max > running_peak:
  89. running_peak = current_max
  90. else:
  91. running_peak = max(0.005, running_peak * DECAY_RATE)
  92. # Dynamic gain bounded within strict sanity limits
  93. dynamic_gain = np.clip(255.0 / running_peak, GAIN_MIN, GAIN_MAX)
  94. # Scale into 8-bit unsigned integer array
  95. scaled = np.clip(tilted_energies * dynamic_gain, 0, 255).astype(np.uint8)
  96. fft_result = bytes(scaled)
  97. payload = struct.pack(
  98. STRUCT_FMT_V2,
  99. b"00002\x00",
  100. float(raw_mag),
  101. float(sample_smth),
  102. sample_peak,
  103. fft_result,
  104. float(raw_mag)
  105. )
  106. try:
  107. sock.sendto(payload, (UDP_IP, UDP_PORT))
  108. except Exception:
  109. pass
  110. # Metronome pacing
  111. frames_processed += 1
  112. target_time = start_time + (frames_processed * CHUNK_DURATION)
  113. sleep_time = target_time - time.perf_counter()
  114. if sleep_time > 0:
  115. time.sleep(sleep_time)
  116. elif sleep_time < -1.0:
  117. start_time = time.perf_counter()
  118. frames_processed = 0