Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

316 行
9.3KB

  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. s.mu.RUnlock()
  108. w.Header().Set("Content-Type", "application/json")
  109. _ = json.NewEncoder(w).Encode(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. }
  120. func (s *Server) handleRuntime(w http.ResponseWriter, _ *http.Request) {
  121. s.mu.RLock()
  122. drv := s.drv
  123. tx := s.tx
  124. stream := s.streamSrc
  125. s.mu.RUnlock()
  126. result := map[string]any{}
  127. if drv != nil {
  128. result["driver"] = drv.Stats()
  129. }
  130. if tx != nil {
  131. result["engine"] = tx.TXStats()
  132. }
  133. if stream != nil {
  134. result["audioStream"] = stream.Stats()
  135. }
  136. w.Header().Set("Content-Type", "application/json")
  137. _ = json.NewEncoder(w).Encode(result)
  138. }
  139. // handleAudioStream accepts raw S16LE stereo PCM via HTTP POST and pushes
  140. // it into the live audio ring buffer. Use with:
  141. // curl -X POST --data-binary @- http://host:8088/audio/stream < audio.raw
  142. // ffmpeg ... -f s16le -ar 44100 -ac 2 - | curl -X POST --data-binary @- http://host:8088/audio/stream
  143. func (s *Server) handleAudioStream(w http.ResponseWriter, r *http.Request) {
  144. if r.Method != http.MethodPost {
  145. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  146. return
  147. }
  148. s.mu.RLock()
  149. stream := s.streamSrc
  150. s.mu.RUnlock()
  151. if stream == nil {
  152. http.Error(w, "audio stream not configured (use --audio-stdin or --audio-http)", http.StatusServiceUnavailable)
  153. return
  154. }
  155. // Read body in chunks and push to ring buffer
  156. buf := make([]byte, 32768)
  157. totalFrames := 0
  158. for {
  159. n, err := r.Body.Read(buf)
  160. if n > 0 {
  161. totalFrames += stream.WritePCM(buf[:n])
  162. }
  163. if err != nil {
  164. if err == io.EOF {
  165. break
  166. }
  167. http.Error(w, err.Error(), http.StatusInternalServerError)
  168. return
  169. }
  170. }
  171. w.Header().Set("Content-Type", "application/json")
  172. _ = json.NewEncoder(w).Encode(map[string]any{
  173. "ok": true,
  174. "frames": totalFrames,
  175. "stats": stream.Stats(),
  176. })
  177. }
  178. func (s *Server) handleTXStart(w http.ResponseWriter, r *http.Request) {
  179. if r.Method != http.MethodPost {
  180. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  181. return
  182. }
  183. s.mu.RLock()
  184. tx := s.tx
  185. s.mu.RUnlock()
  186. if tx == nil {
  187. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  188. return
  189. }
  190. if err := tx.StartTX(); err != nil {
  191. http.Error(w, err.Error(), http.StatusConflict)
  192. return
  193. }
  194. w.Header().Set("Content-Type", "application/json")
  195. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "started"})
  196. }
  197. func (s *Server) handleTXStop(w http.ResponseWriter, r *http.Request) {
  198. if r.Method != http.MethodPost {
  199. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  200. return
  201. }
  202. s.mu.RLock()
  203. tx := s.tx
  204. s.mu.RUnlock()
  205. if tx == nil {
  206. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  207. return
  208. }
  209. if err := tx.StopTX(); err != nil {
  210. http.Error(w, err.Error(), http.StatusInternalServerError)
  211. return
  212. }
  213. w.Header().Set("Content-Type", "application/json")
  214. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "stopped"})
  215. }
  216. func (s *Server) handleDryRun(w http.ResponseWriter, _ *http.Request) {
  217. s.mu.RLock()
  218. cfg := s.cfg
  219. s.mu.RUnlock()
  220. w.Header().Set("Content-Type", "application/json")
  221. _ = json.NewEncoder(w).Encode(drypkg.Generate(cfg))
  222. }
  223. func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
  224. switch r.Method {
  225. case http.MethodGet:
  226. s.mu.RLock()
  227. cfg := s.cfg
  228. s.mu.RUnlock()
  229. w.Header().Set("Content-Type", "application/json")
  230. _ = json.NewEncoder(w).Encode(cfg)
  231. case http.MethodPost:
  232. var patch ConfigPatch
  233. if err := json.NewDecoder(r.Body).Decode(&patch); err != nil {
  234. http.Error(w, err.Error(), http.StatusBadRequest)
  235. return
  236. }
  237. // Update the server's config snapshot (for GET /config and /status)
  238. s.mu.Lock()
  239. next := s.cfg
  240. if patch.FrequencyMHz != nil { next.FM.FrequencyMHz = *patch.FrequencyMHz }
  241. if patch.OutputDrive != nil { next.FM.OutputDrive = *patch.OutputDrive }
  242. if patch.ToneLeftHz != nil { next.Audio.ToneLeftHz = *patch.ToneLeftHz }
  243. if patch.ToneRightHz != nil { next.Audio.ToneRightHz = *patch.ToneRightHz }
  244. if patch.ToneAmplitude != nil { next.Audio.ToneAmplitude = *patch.ToneAmplitude }
  245. if patch.PS != nil { next.RDS.PS = *patch.PS }
  246. if patch.RadioText != nil { next.RDS.RadioText = *patch.RadioText }
  247. if patch.PreEmphasisTauUS != nil { next.FM.PreEmphasisTauUS = *patch.PreEmphasisTauUS }
  248. if patch.StereoEnabled != nil { next.FM.StereoEnabled = *patch.StereoEnabled }
  249. if patch.LimiterEnabled != nil { next.FM.LimiterEnabled = *patch.LimiterEnabled }
  250. if patch.LimiterCeiling != nil { next.FM.LimiterCeiling = *patch.LimiterCeiling }
  251. if patch.RDSEnabled != nil { next.RDS.Enabled = *patch.RDSEnabled }
  252. if patch.PilotLevel != nil { next.FM.PilotLevel = *patch.PilotLevel }
  253. if patch.RDSInjection != nil { next.FM.RDSInjection = *patch.RDSInjection }
  254. if err := next.Validate(); err != nil {
  255. s.mu.Unlock()
  256. http.Error(w, err.Error(), http.StatusBadRequest)
  257. return
  258. }
  259. s.cfg = next
  260. tx := s.tx
  261. s.mu.Unlock()
  262. // Forward live-patchable params to running engine (if active)
  263. if tx != nil {
  264. lp := LivePatch{
  265. FrequencyMHz: patch.FrequencyMHz,
  266. OutputDrive: patch.OutputDrive,
  267. StereoEnabled: patch.StereoEnabled,
  268. PilotLevel: patch.PilotLevel,
  269. RDSInjection: patch.RDSInjection,
  270. RDSEnabled: patch.RDSEnabled,
  271. LimiterEnabled: patch.LimiterEnabled,
  272. LimiterCeiling: patch.LimiterCeiling,
  273. PS: patch.PS,
  274. RadioText: patch.RadioText,
  275. }
  276. if err := tx.UpdateConfig(lp); err != nil {
  277. http.Error(w, err.Error(), http.StatusBadRequest)
  278. return
  279. }
  280. }
  281. w.Header().Set("Content-Type", "application/json")
  282. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "live": tx != nil})
  283. default:
  284. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  285. }
  286. }