Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

356 Zeilen
9.5KB

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