Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

381 líneas
10KB

  1. package control
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "sync"
  8. "github.com/jan/fm-rds-tx/internal/audio"
  9. "github.com/jan/fm-rds-tx/internal/config"
  10. drypkg "github.com/jan/fm-rds-tx/internal/dryrun"
  11. "github.com/jan/fm-rds-tx/internal/platform"
  12. )
  13. //go:embed ui.html
  14. var uiHTML []byte
  15. // TXController is an optional interface the Server uses to start/stop TX
  16. // and apply live config changes.
  17. type TXController interface {
  18. StartTX() error
  19. StopTX() error
  20. TXStats() map[string]any
  21. UpdateConfig(patch LivePatch) error
  22. ResetFault() error
  23. }
  24. // LivePatch mirrors the patchable fields from ConfigPatch for the engine.
  25. // nil = no change.
  26. type LivePatch struct {
  27. FrequencyMHz *float64
  28. OutputDrive *float64
  29. StereoEnabled *bool
  30. PilotLevel *float64
  31. RDSInjection *float64
  32. RDSEnabled *bool
  33. LimiterEnabled *bool
  34. LimiterCeiling *float64
  35. PS *string
  36. RadioText *string
  37. }
  38. type Server struct {
  39. mu sync.RWMutex
  40. cfg config.Config
  41. tx TXController
  42. drv platform.SoapyDriver // optional, for runtime stats
  43. streamSrc *audio.StreamSource // optional, for live audio ingest
  44. }
  45. type ConfigPatch struct {
  46. FrequencyMHz *float64 `json:"frequencyMHz,omitempty"`
  47. OutputDrive *float64 `json:"outputDrive,omitempty"`
  48. StereoEnabled *bool `json:"stereoEnabled,omitempty"`
  49. PilotLevel *float64 `json:"pilotLevel,omitempty"`
  50. RDSInjection *float64 `json:"rdsInjection,omitempty"`
  51. RDSEnabled *bool `json:"rdsEnabled,omitempty"`
  52. ToneLeftHz *float64 `json:"toneLeftHz,omitempty"`
  53. ToneRightHz *float64 `json:"toneRightHz,omitempty"`
  54. ToneAmplitude *float64 `json:"toneAmplitude,omitempty"`
  55. PS *string `json:"ps,omitempty"`
  56. RadioText *string `json:"radioText,omitempty"`
  57. PreEmphasisTauUS *float64 `json:"preEmphasisTauUS,omitempty"`
  58. LimiterEnabled *bool `json:"limiterEnabled,omitempty"`
  59. LimiterCeiling *float64 `json:"limiterCeiling,omitempty"`
  60. }
  61. func NewServer(cfg config.Config) *Server {
  62. return &Server{cfg: cfg}
  63. }
  64. func (s *Server) SetTXController(tx TXController) {
  65. s.mu.Lock()
  66. s.tx = tx
  67. s.mu.Unlock()
  68. }
  69. func (s *Server) SetDriver(drv platform.SoapyDriver) {
  70. s.mu.Lock()
  71. s.drv = drv
  72. s.mu.Unlock()
  73. }
  74. func (s *Server) SetStreamSource(src *audio.StreamSource) {
  75. s.mu.Lock()
  76. s.streamSrc = src
  77. s.mu.Unlock()
  78. }
  79. func (s *Server) Handler() http.Handler {
  80. mux := http.NewServeMux()
  81. mux.HandleFunc("/", s.handleUI)
  82. mux.HandleFunc("/healthz", s.handleHealth)
  83. mux.HandleFunc("/status", s.handleStatus)
  84. mux.HandleFunc("/dry-run", s.handleDryRun)
  85. mux.HandleFunc("/config", s.handleConfig)
  86. mux.HandleFunc("/runtime", s.handleRuntime)
  87. mux.HandleFunc("/runtime/fault/reset", s.handleRuntimeFaultReset)
  88. mux.HandleFunc("/tx/start", s.handleTXStart)
  89. mux.HandleFunc("/tx/stop", s.handleTXStop)
  90. mux.HandleFunc("/audio/stream", s.handleAudioStream)
  91. return mux
  92. }
  93. func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
  94. w.Header().Set("Content-Type", "application/json")
  95. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
  96. }
  97. func (s *Server) handleUI(w http.ResponseWriter, r *http.Request) {
  98. if r.URL.Path != "/" {
  99. http.NotFound(w, r)
  100. return
  101. }
  102. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  103. w.Header().Set("Cache-Control", "no-cache")
  104. w.Write(uiHTML)
  105. }
  106. func (s *Server) handleStatus(w http.ResponseWriter, _ *http.Request) {
  107. s.mu.RLock()
  108. cfg := s.cfg
  109. tx := s.tx
  110. s.mu.RUnlock()
  111. status := map[string]any{
  112. "service": "fm-rds-tx",
  113. "backend": cfg.Backend.Kind,
  114. "frequencyMHz": cfg.FM.FrequencyMHz,
  115. "stereoEnabled": cfg.FM.StereoEnabled,
  116. "rdsEnabled": cfg.RDS.Enabled,
  117. "preEmphasisTauUS": cfg.FM.PreEmphasisTauUS,
  118. "limiterEnabled": cfg.FM.LimiterEnabled,
  119. "fmModulationEnabled": cfg.FM.FMModulationEnabled,
  120. }
  121. if tx != nil {
  122. if stats := tx.TXStats(); stats != nil {
  123. if ri, ok := stats["runtimeIndicator"]; ok {
  124. status["runtimeIndicator"] = ri
  125. }
  126. if alert, ok := stats["runtimeAlert"]; ok {
  127. status["runtimeAlert"] = alert
  128. }
  129. if queue, ok := stats["queue"]; ok {
  130. status["queue"] = queue
  131. }
  132. }
  133. }
  134. w.Header().Set("Content-Type", "application/json")
  135. _ = json.NewEncoder(w).Encode(status)
  136. }
  137. func (s *Server) handleRuntime(w http.ResponseWriter, _ *http.Request) {
  138. s.mu.RLock()
  139. drv := s.drv
  140. tx := s.tx
  141. stream := s.streamSrc
  142. s.mu.RUnlock()
  143. result := map[string]any{}
  144. if drv != nil {
  145. result["driver"] = drv.Stats()
  146. }
  147. if tx != nil {
  148. result["engine"] = tx.TXStats()
  149. }
  150. if stream != nil {
  151. result["audioStream"] = stream.Stats()
  152. }
  153. w.Header().Set("Content-Type", "application/json")
  154. _ = json.NewEncoder(w).Encode(result)
  155. }
  156. func (s *Server) handleRuntimeFaultReset(w http.ResponseWriter, r *http.Request) {
  157. if r.Method != http.MethodPost {
  158. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  159. return
  160. }
  161. s.mu.RLock()
  162. tx := s.tx
  163. s.mu.RUnlock()
  164. if tx == nil {
  165. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  166. return
  167. }
  168. if err := tx.ResetFault(); err != nil {
  169. http.Error(w, err.Error(), http.StatusConflict)
  170. return
  171. }
  172. w.Header().Set("Content-Type", "application/json")
  173. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
  174. }
  175. // handleAudioStream accepts raw S16LE stereo PCM via HTTP POST and pushes
  176. // it into the live audio ring buffer. Use with:
  177. // curl -X POST --data-binary @- http://host:8088/audio/stream < audio.raw
  178. // ffmpeg ... -f s16le -ar 44100 -ac 2 - | curl -X POST --data-binary @- http://host:8088/audio/stream
  179. func (s *Server) handleAudioStream(w http.ResponseWriter, r *http.Request) {
  180. if r.Method != http.MethodPost {
  181. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  182. return
  183. }
  184. s.mu.RLock()
  185. stream := s.streamSrc
  186. s.mu.RUnlock()
  187. if stream == nil {
  188. http.Error(w, "audio stream not configured (use --audio-stdin or --audio-http)", http.StatusServiceUnavailable)
  189. return
  190. }
  191. // Read body in chunks and push to ring buffer
  192. buf := make([]byte, 32768)
  193. totalFrames := 0
  194. for {
  195. n, err := r.Body.Read(buf)
  196. if n > 0 {
  197. totalFrames += stream.WritePCM(buf[:n])
  198. }
  199. if err != nil {
  200. if err == io.EOF {
  201. break
  202. }
  203. http.Error(w, err.Error(), http.StatusInternalServerError)
  204. return
  205. }
  206. }
  207. w.Header().Set("Content-Type", "application/json")
  208. _ = json.NewEncoder(w).Encode(map[string]any{
  209. "ok": true,
  210. "frames": totalFrames,
  211. "stats": stream.Stats(),
  212. })
  213. }
  214. func (s *Server) handleTXStart(w http.ResponseWriter, r *http.Request) {
  215. if r.Method != http.MethodPost {
  216. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  217. return
  218. }
  219. s.mu.RLock()
  220. tx := s.tx
  221. s.mu.RUnlock()
  222. if tx == nil {
  223. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  224. return
  225. }
  226. if err := tx.StartTX(); err != nil {
  227. http.Error(w, err.Error(), http.StatusConflict)
  228. return
  229. }
  230. w.Header().Set("Content-Type", "application/json")
  231. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "started"})
  232. }
  233. func (s *Server) handleTXStop(w http.ResponseWriter, r *http.Request) {
  234. if r.Method != http.MethodPost {
  235. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  236. return
  237. }
  238. s.mu.RLock()
  239. tx := s.tx
  240. s.mu.RUnlock()
  241. if tx == nil {
  242. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  243. return
  244. }
  245. if err := tx.StopTX(); err != nil {
  246. http.Error(w, err.Error(), http.StatusInternalServerError)
  247. return
  248. }
  249. w.Header().Set("Content-Type", "application/json")
  250. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "stopped"})
  251. }
  252. func (s *Server) handleDryRun(w http.ResponseWriter, _ *http.Request) {
  253. s.mu.RLock()
  254. cfg := s.cfg
  255. s.mu.RUnlock()
  256. w.Header().Set("Content-Type", "application/json")
  257. _ = json.NewEncoder(w).Encode(drypkg.Generate(cfg))
  258. }
  259. func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
  260. switch r.Method {
  261. case http.MethodGet:
  262. s.mu.RLock()
  263. cfg := s.cfg
  264. s.mu.RUnlock()
  265. w.Header().Set("Content-Type", "application/json")
  266. _ = json.NewEncoder(w).Encode(cfg)
  267. case http.MethodPost:
  268. var patch ConfigPatch
  269. if err := json.NewDecoder(r.Body).Decode(&patch); err != nil {
  270. http.Error(w, err.Error(), http.StatusBadRequest)
  271. return
  272. }
  273. // Update the server's config snapshot (for GET /config and /status)
  274. s.mu.Lock()
  275. next := s.cfg
  276. if patch.FrequencyMHz != nil {
  277. next.FM.FrequencyMHz = *patch.FrequencyMHz
  278. }
  279. if patch.OutputDrive != nil {
  280. next.FM.OutputDrive = *patch.OutputDrive
  281. }
  282. if patch.ToneLeftHz != nil {
  283. next.Audio.ToneLeftHz = *patch.ToneLeftHz
  284. }
  285. if patch.ToneRightHz != nil {
  286. next.Audio.ToneRightHz = *patch.ToneRightHz
  287. }
  288. if patch.ToneAmplitude != nil {
  289. next.Audio.ToneAmplitude = *patch.ToneAmplitude
  290. }
  291. if patch.PS != nil {
  292. next.RDS.PS = *patch.PS
  293. }
  294. if patch.RadioText != nil {
  295. next.RDS.RadioText = *patch.RadioText
  296. }
  297. if patch.PreEmphasisTauUS != nil {
  298. next.FM.PreEmphasisTauUS = *patch.PreEmphasisTauUS
  299. }
  300. if patch.StereoEnabled != nil {
  301. next.FM.StereoEnabled = *patch.StereoEnabled
  302. }
  303. if patch.LimiterEnabled != nil {
  304. next.FM.LimiterEnabled = *patch.LimiterEnabled
  305. }
  306. if patch.LimiterCeiling != nil {
  307. next.FM.LimiterCeiling = *patch.LimiterCeiling
  308. }
  309. if patch.RDSEnabled != nil {
  310. next.RDS.Enabled = *patch.RDSEnabled
  311. }
  312. if patch.PilotLevel != nil {
  313. next.FM.PilotLevel = *patch.PilotLevel
  314. }
  315. if patch.RDSInjection != nil {
  316. next.FM.RDSInjection = *patch.RDSInjection
  317. }
  318. if err := next.Validate(); err != nil {
  319. s.mu.Unlock()
  320. http.Error(w, err.Error(), http.StatusBadRequest)
  321. return
  322. }
  323. lp := LivePatch{
  324. FrequencyMHz: patch.FrequencyMHz,
  325. OutputDrive: patch.OutputDrive,
  326. StereoEnabled: patch.StereoEnabled,
  327. PilotLevel: patch.PilotLevel,
  328. RDSInjection: patch.RDSInjection,
  329. RDSEnabled: patch.RDSEnabled,
  330. LimiterEnabled: patch.LimiterEnabled,
  331. LimiterCeiling: patch.LimiterCeiling,
  332. PS: patch.PS,
  333. RadioText: patch.RadioText,
  334. }
  335. tx := s.tx
  336. if tx != nil {
  337. if err := tx.UpdateConfig(lp); err != nil {
  338. s.mu.Unlock()
  339. http.Error(w, err.Error(), http.StatusBadRequest)
  340. return
  341. }
  342. }
  343. s.cfg = next
  344. live := tx != nil
  345. s.mu.Unlock()
  346. w.Header().Set("Content-Type", "application/json")
  347. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "live": live})
  348. default:
  349. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  350. }
  351. }