Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

646 строки
17KB

  1. package control
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "mime"
  8. "net/http"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/jan/fm-rds-tx/internal/audio"
  14. "github.com/jan/fm-rds-tx/internal/config"
  15. drypkg "github.com/jan/fm-rds-tx/internal/dryrun"
  16. "github.com/jan/fm-rds-tx/internal/ingest"
  17. "github.com/jan/fm-rds-tx/internal/platform"
  18. )
  19. //go:embed ui.html
  20. var uiHTML []byte
  21. // TXController is an optional interface the Server uses to start/stop TX
  22. // and apply live config changes.
  23. type TXController interface {
  24. StartTX() error
  25. StopTX() error
  26. TXStats() map[string]any
  27. UpdateConfig(patch LivePatch) error
  28. ResetFault() error
  29. }
  30. // LivePatch mirrors the patchable fields from ConfigPatch for the engine.
  31. // nil = no change.
  32. type LivePatch struct {
  33. FrequencyMHz *float64
  34. OutputDrive *float64
  35. StereoEnabled *bool
  36. PilotLevel *float64
  37. RDSInjection *float64
  38. RDSEnabled *bool
  39. LimiterEnabled *bool
  40. LimiterCeiling *float64
  41. PS *string
  42. RadioText *string
  43. }
  44. type Server struct {
  45. mu sync.RWMutex
  46. cfg config.Config
  47. tx TXController
  48. drv platform.SoapyDriver // optional, for runtime stats
  49. streamSrc *audio.StreamSource // optional, for live audio ring stats
  50. audioIngress AudioIngress // optional, for /audio/stream
  51. ingestRt IngestRuntime // optional, for /runtime ingest stats
  52. saveConfig func(config.Config) error
  53. hardReload func()
  54. audit auditCounters
  55. }
  56. type AudioIngress interface {
  57. WritePCM16(data []byte) (int, error)
  58. }
  59. type IngestRuntime interface {
  60. Stats() ingest.Stats
  61. }
  62. type auditEvent string
  63. const (
  64. auditMethodNotAllowed auditEvent = "methodNotAllowed"
  65. auditUnsupportedMediaType auditEvent = "unsupportedMediaType"
  66. auditBodyTooLarge auditEvent = "bodyTooLarge"
  67. auditUnexpectedBody auditEvent = "unexpectedBody"
  68. )
  69. type auditCounters struct {
  70. methodNotAllowed uint64
  71. unsupportedMediaType uint64
  72. bodyTooLarge uint64
  73. unexpectedBody uint64
  74. }
  75. const (
  76. maxConfigBodyBytes = 64 << 10 // 64 KiB
  77. configContentTypeHeader = "application/json"
  78. noBodyErrMsg = "request must not include a body"
  79. audioStreamContentTypeError = "Content-Type must be application/octet-stream or audio/L16"
  80. audioStreamBodyLimitDefault = 512 << 20 // 512 MiB
  81. )
  82. var audioStreamAllowedMediaTypes = []string{
  83. "application/octet-stream",
  84. "audio/l16",
  85. }
  86. var audioStreamBodyLimit = int64(audioStreamBodyLimitDefault) // bytes allowed per /audio/stream request; tests may override.
  87. func isJSONContentType(r *http.Request) bool {
  88. ct := strings.TrimSpace(r.Header.Get("Content-Type"))
  89. if ct == "" {
  90. return false
  91. }
  92. mediaType, _, err := mime.ParseMediaType(ct)
  93. if err != nil {
  94. return false
  95. }
  96. return strings.EqualFold(mediaType, configContentTypeHeader)
  97. }
  98. type ConfigPatch struct {
  99. FrequencyMHz *float64 `json:"frequencyMHz,omitempty"`
  100. OutputDrive *float64 `json:"outputDrive,omitempty"`
  101. StereoEnabled *bool `json:"stereoEnabled,omitempty"`
  102. PilotLevel *float64 `json:"pilotLevel,omitempty"`
  103. RDSInjection *float64 `json:"rdsInjection,omitempty"`
  104. RDSEnabled *bool `json:"rdsEnabled,omitempty"`
  105. ToneLeftHz *float64 `json:"toneLeftHz,omitempty"`
  106. ToneRightHz *float64 `json:"toneRightHz,omitempty"`
  107. ToneAmplitude *float64 `json:"toneAmplitude,omitempty"`
  108. PS *string `json:"ps,omitempty"`
  109. RadioText *string `json:"radioText,omitempty"`
  110. PreEmphasisTauUS *float64 `json:"preEmphasisTauUS,omitempty"`
  111. LimiterEnabled *bool `json:"limiterEnabled,omitempty"`
  112. LimiterCeiling *float64 `json:"limiterCeiling,omitempty"`
  113. }
  114. type IngestSaveRequest struct {
  115. Ingest config.IngestConfig `json:"ingest"`
  116. }
  117. func NewServer(cfg config.Config) *Server {
  118. return &Server{cfg: cfg}
  119. }
  120. func hasRequestBody(r *http.Request) bool {
  121. if r.ContentLength > 0 {
  122. return true
  123. }
  124. for _, te := range r.TransferEncoding {
  125. if strings.EqualFold(te, "chunked") {
  126. return true
  127. }
  128. }
  129. return false
  130. }
  131. func (s *Server) rejectBody(w http.ResponseWriter, r *http.Request) bool {
  132. if !hasRequestBody(r) {
  133. return true
  134. }
  135. s.recordAudit(auditUnexpectedBody)
  136. http.Error(w, noBodyErrMsg, http.StatusBadRequest)
  137. return false
  138. }
  139. func (s *Server) recordAudit(evt auditEvent) {
  140. switch evt {
  141. case auditMethodNotAllowed:
  142. atomic.AddUint64(&s.audit.methodNotAllowed, 1)
  143. case auditUnsupportedMediaType:
  144. atomic.AddUint64(&s.audit.unsupportedMediaType, 1)
  145. case auditBodyTooLarge:
  146. atomic.AddUint64(&s.audit.bodyTooLarge, 1)
  147. case auditUnexpectedBody:
  148. atomic.AddUint64(&s.audit.unexpectedBody, 1)
  149. }
  150. }
  151. func (s *Server) auditSnapshot() map[string]uint64 {
  152. return map[string]uint64{
  153. "methodNotAllowed": atomic.LoadUint64(&s.audit.methodNotAllowed),
  154. "unsupportedMediaType": atomic.LoadUint64(&s.audit.unsupportedMediaType),
  155. "bodyTooLarge": atomic.LoadUint64(&s.audit.bodyTooLarge),
  156. "unexpectedBody": atomic.LoadUint64(&s.audit.unexpectedBody),
  157. }
  158. }
  159. func isAudioStreamContentType(r *http.Request) bool {
  160. ct := strings.TrimSpace(r.Header.Get("Content-Type"))
  161. if ct == "" {
  162. return false
  163. }
  164. mediaType, _, err := mime.ParseMediaType(ct)
  165. if err != nil {
  166. return false
  167. }
  168. for _, allowed := range audioStreamAllowedMediaTypes {
  169. if strings.EqualFold(mediaType, allowed) {
  170. return true
  171. }
  172. }
  173. return false
  174. }
  175. func (s *Server) SetTXController(tx TXController) {
  176. s.mu.Lock()
  177. s.tx = tx
  178. s.mu.Unlock()
  179. }
  180. func (s *Server) SetDriver(drv platform.SoapyDriver) {
  181. s.mu.Lock()
  182. s.drv = drv
  183. s.mu.Unlock()
  184. }
  185. func (s *Server) SetStreamSource(src *audio.StreamSource) {
  186. s.mu.Lock()
  187. s.streamSrc = src
  188. s.mu.Unlock()
  189. }
  190. func (s *Server) SetAudioIngress(ingress AudioIngress) {
  191. s.mu.Lock()
  192. s.audioIngress = ingress
  193. s.mu.Unlock()
  194. }
  195. func (s *Server) SetIngestRuntime(rt IngestRuntime) {
  196. s.mu.Lock()
  197. s.ingestRt = rt
  198. s.mu.Unlock()
  199. }
  200. func (s *Server) SetConfigSaver(save func(config.Config) error) {
  201. s.mu.Lock()
  202. s.saveConfig = save
  203. s.mu.Unlock()
  204. }
  205. func (s *Server) SetHardReload(fn func()) {
  206. s.mu.Lock()
  207. s.hardReload = fn
  208. s.mu.Unlock()
  209. }
  210. func (s *Server) Handler() http.Handler {
  211. mux := http.NewServeMux()
  212. mux.HandleFunc("/", s.handleUI)
  213. mux.HandleFunc("/healthz", s.handleHealth)
  214. mux.HandleFunc("/status", s.handleStatus)
  215. mux.HandleFunc("/dry-run", s.handleDryRun)
  216. mux.HandleFunc("/config", s.handleConfig)
  217. mux.HandleFunc("/config/ingest/save", s.handleIngestSave)
  218. mux.HandleFunc("/runtime", s.handleRuntime)
  219. mux.HandleFunc("/runtime/fault/reset", s.handleRuntimeFaultReset)
  220. mux.HandleFunc("/tx/start", s.handleTXStart)
  221. mux.HandleFunc("/tx/stop", s.handleTXStop)
  222. mux.HandleFunc("/audio/stream", s.handleAudioStream)
  223. return mux
  224. }
  225. func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
  226. w.Header().Set("Content-Type", "application/json")
  227. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
  228. }
  229. func (s *Server) handleUI(w http.ResponseWriter, r *http.Request) {
  230. if r.URL.Path != "/" {
  231. http.NotFound(w, r)
  232. return
  233. }
  234. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  235. w.Header().Set("Cache-Control", "no-cache")
  236. w.Write(uiHTML)
  237. }
  238. func (s *Server) handleStatus(w http.ResponseWriter, _ *http.Request) {
  239. s.mu.RLock()
  240. cfg := s.cfg
  241. tx := s.tx
  242. s.mu.RUnlock()
  243. status := map[string]any{
  244. "service": "fm-rds-tx",
  245. "backend": cfg.Backend.Kind,
  246. "frequencyMHz": cfg.FM.FrequencyMHz,
  247. "stereoEnabled": cfg.FM.StereoEnabled,
  248. "rdsEnabled": cfg.RDS.Enabled,
  249. "preEmphasisTauUS": cfg.FM.PreEmphasisTauUS,
  250. "limiterEnabled": cfg.FM.LimiterEnabled,
  251. "fmModulationEnabled": cfg.FM.FMModulationEnabled,
  252. }
  253. if tx != nil {
  254. if stats := tx.TXStats(); stats != nil {
  255. if ri, ok := stats["runtimeIndicator"]; ok {
  256. status["runtimeIndicator"] = ri
  257. }
  258. if alert, ok := stats["runtimeAlert"]; ok {
  259. status["runtimeAlert"] = alert
  260. }
  261. if queue, ok := stats["queue"]; ok {
  262. status["queue"] = queue
  263. }
  264. if runtimeState, ok := stats["state"]; ok {
  265. status["runtimeState"] = runtimeState
  266. }
  267. }
  268. }
  269. w.Header().Set("Content-Type", "application/json")
  270. _ = json.NewEncoder(w).Encode(status)
  271. }
  272. func (s *Server) handleRuntime(w http.ResponseWriter, _ *http.Request) {
  273. s.mu.RLock()
  274. drv := s.drv
  275. tx := s.tx
  276. stream := s.streamSrc
  277. ingestRt := s.ingestRt
  278. s.mu.RUnlock()
  279. result := map[string]any{}
  280. if drv != nil {
  281. result["driver"] = drv.Stats()
  282. }
  283. if tx != nil {
  284. if stats := tx.TXStats(); stats != nil {
  285. result["engine"] = stats
  286. }
  287. }
  288. if stream != nil {
  289. result["audioStream"] = stream.Stats()
  290. }
  291. if ingestRt != nil {
  292. result["ingest"] = ingestRt.Stats()
  293. }
  294. result["controlAudit"] = s.auditSnapshot()
  295. w.Header().Set("Content-Type", "application/json")
  296. _ = json.NewEncoder(w).Encode(result)
  297. }
  298. func (s *Server) handleRuntimeFaultReset(w http.ResponseWriter, r *http.Request) {
  299. if r.Method != http.MethodPost {
  300. s.recordAudit(auditMethodNotAllowed)
  301. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  302. return
  303. }
  304. if !s.rejectBody(w, r) {
  305. return
  306. }
  307. s.mu.RLock()
  308. tx := s.tx
  309. s.mu.RUnlock()
  310. if tx == nil {
  311. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  312. return
  313. }
  314. if err := tx.ResetFault(); err != nil {
  315. http.Error(w, err.Error(), http.StatusConflict)
  316. return
  317. }
  318. w.Header().Set("Content-Type", "application/json")
  319. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
  320. }
  321. // handleAudioStream accepts raw S16LE PCM via HTTP POST and pushes
  322. // it into the configured ingest http-raw source. Use with:
  323. //
  324. // curl -X POST --data-binary @- http://host:8088/audio/stream < audio.raw
  325. // ffmpeg ... -f s16le -ar 44100 -ac 2 - | curl -X POST --data-binary @- http://host:8088/audio/stream
  326. func (s *Server) handleAudioStream(w http.ResponseWriter, r *http.Request) {
  327. if r.Method != http.MethodPost {
  328. s.recordAudit(auditMethodNotAllowed)
  329. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  330. return
  331. }
  332. if !isAudioStreamContentType(r) {
  333. s.recordAudit(auditUnsupportedMediaType)
  334. http.Error(w, audioStreamContentTypeError, http.StatusUnsupportedMediaType)
  335. return
  336. }
  337. s.mu.RLock()
  338. ingress := s.audioIngress
  339. s.mu.RUnlock()
  340. if ingress == nil {
  341. http.Error(w, "audio ingest not configured (use --audio-http with ingest runtime)", http.StatusServiceUnavailable)
  342. return
  343. }
  344. r.Body = http.MaxBytesReader(w, r.Body, audioStreamBodyLimit)
  345. // Read body in chunks and push to ring buffer
  346. buf := make([]byte, 32768)
  347. totalFrames := 0
  348. for {
  349. n, err := r.Body.Read(buf)
  350. if n > 0 {
  351. written, writeErr := ingress.WritePCM16(buf[:n])
  352. totalFrames += written
  353. if writeErr != nil {
  354. http.Error(w, writeErr.Error(), http.StatusServiceUnavailable)
  355. return
  356. }
  357. }
  358. if err != nil {
  359. if err == io.EOF {
  360. break
  361. }
  362. var maxErr *http.MaxBytesError
  363. if errors.As(err, &maxErr) {
  364. s.recordAudit(auditBodyTooLarge)
  365. http.Error(w, maxErr.Error(), http.StatusRequestEntityTooLarge)
  366. return
  367. }
  368. http.Error(w, err.Error(), http.StatusInternalServerError)
  369. return
  370. }
  371. }
  372. w.Header().Set("Content-Type", "application/json")
  373. _ = json.NewEncoder(w).Encode(map[string]any{
  374. "ok": true,
  375. "frames": totalFrames,
  376. })
  377. }
  378. func (s *Server) handleTXStart(w http.ResponseWriter, r *http.Request) {
  379. if r.Method != http.MethodPost {
  380. s.recordAudit(auditMethodNotAllowed)
  381. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  382. return
  383. }
  384. if !s.rejectBody(w, r) {
  385. return
  386. }
  387. s.mu.RLock()
  388. tx := s.tx
  389. s.mu.RUnlock()
  390. if tx == nil {
  391. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  392. return
  393. }
  394. if err := tx.StartTX(); err != nil {
  395. http.Error(w, err.Error(), http.StatusConflict)
  396. return
  397. }
  398. w.Header().Set("Content-Type", "application/json")
  399. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "started"})
  400. }
  401. func (s *Server) handleTXStop(w http.ResponseWriter, r *http.Request) {
  402. if r.Method != http.MethodPost {
  403. s.recordAudit(auditMethodNotAllowed)
  404. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  405. return
  406. }
  407. if !s.rejectBody(w, r) {
  408. return
  409. }
  410. s.mu.RLock()
  411. tx := s.tx
  412. s.mu.RUnlock()
  413. if tx == nil {
  414. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  415. return
  416. }
  417. if err := tx.StopTX(); err != nil {
  418. http.Error(w, err.Error(), http.StatusInternalServerError)
  419. return
  420. }
  421. w.Header().Set("Content-Type", "application/json")
  422. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "stopped"})
  423. }
  424. func (s *Server) handleDryRun(w http.ResponseWriter, _ *http.Request) {
  425. s.mu.RLock()
  426. cfg := s.cfg
  427. s.mu.RUnlock()
  428. w.Header().Set("Content-Type", "application/json")
  429. _ = json.NewEncoder(w).Encode(drypkg.Generate(cfg))
  430. }
  431. func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
  432. switch r.Method {
  433. case http.MethodGet:
  434. s.mu.RLock()
  435. cfg := s.cfg
  436. s.mu.RUnlock()
  437. w.Header().Set("Content-Type", "application/json")
  438. _ = json.NewEncoder(w).Encode(cfg)
  439. case http.MethodPost:
  440. if !isJSONContentType(r) {
  441. s.recordAudit(auditUnsupportedMediaType)
  442. http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
  443. return
  444. }
  445. r.Body = http.MaxBytesReader(w, r.Body, maxConfigBodyBytes)
  446. var patch ConfigPatch
  447. if err := json.NewDecoder(r.Body).Decode(&patch); err != nil {
  448. statusCode := http.StatusBadRequest
  449. if strings.Contains(err.Error(), "http: request body too large") {
  450. statusCode = http.StatusRequestEntityTooLarge
  451. s.recordAudit(auditBodyTooLarge)
  452. }
  453. http.Error(w, err.Error(), statusCode)
  454. return
  455. }
  456. // Update the server's config snapshot (for GET /config and /status)
  457. s.mu.Lock()
  458. next := s.cfg
  459. if patch.FrequencyMHz != nil {
  460. next.FM.FrequencyMHz = *patch.FrequencyMHz
  461. }
  462. if patch.OutputDrive != nil {
  463. next.FM.OutputDrive = *patch.OutputDrive
  464. }
  465. if patch.ToneLeftHz != nil {
  466. next.Audio.ToneLeftHz = *patch.ToneLeftHz
  467. }
  468. if patch.ToneRightHz != nil {
  469. next.Audio.ToneRightHz = *patch.ToneRightHz
  470. }
  471. if patch.ToneAmplitude != nil {
  472. next.Audio.ToneAmplitude = *patch.ToneAmplitude
  473. }
  474. if patch.PS != nil {
  475. next.RDS.PS = *patch.PS
  476. }
  477. if patch.RadioText != nil {
  478. next.RDS.RadioText = *patch.RadioText
  479. }
  480. if patch.PreEmphasisTauUS != nil {
  481. next.FM.PreEmphasisTauUS = *patch.PreEmphasisTauUS
  482. }
  483. if patch.StereoEnabled != nil {
  484. next.FM.StereoEnabled = *patch.StereoEnabled
  485. }
  486. if patch.LimiterEnabled != nil {
  487. next.FM.LimiterEnabled = *patch.LimiterEnabled
  488. }
  489. if patch.LimiterCeiling != nil {
  490. next.FM.LimiterCeiling = *patch.LimiterCeiling
  491. }
  492. if patch.RDSEnabled != nil {
  493. next.RDS.Enabled = *patch.RDSEnabled
  494. }
  495. if patch.PilotLevel != nil {
  496. next.FM.PilotLevel = *patch.PilotLevel
  497. }
  498. if patch.RDSInjection != nil {
  499. next.FM.RDSInjection = *patch.RDSInjection
  500. }
  501. if err := next.Validate(); err != nil {
  502. s.mu.Unlock()
  503. http.Error(w, err.Error(), http.StatusBadRequest)
  504. return
  505. }
  506. lp := LivePatch{
  507. FrequencyMHz: patch.FrequencyMHz,
  508. OutputDrive: patch.OutputDrive,
  509. StereoEnabled: patch.StereoEnabled,
  510. PilotLevel: patch.PilotLevel,
  511. RDSInjection: patch.RDSInjection,
  512. RDSEnabled: patch.RDSEnabled,
  513. LimiterEnabled: patch.LimiterEnabled,
  514. LimiterCeiling: patch.LimiterCeiling,
  515. PS: patch.PS,
  516. RadioText: patch.RadioText,
  517. }
  518. tx := s.tx
  519. if tx != nil {
  520. if err := tx.UpdateConfig(lp); err != nil {
  521. s.mu.Unlock()
  522. http.Error(w, err.Error(), http.StatusBadRequest)
  523. return
  524. }
  525. }
  526. s.cfg = next
  527. live := tx != nil
  528. s.mu.Unlock()
  529. w.Header().Set("Content-Type", "application/json")
  530. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "live": live})
  531. default:
  532. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  533. }
  534. }
  535. func (s *Server) handleIngestSave(w http.ResponseWriter, r *http.Request) {
  536. if r.Method != http.MethodPost {
  537. s.recordAudit(auditMethodNotAllowed)
  538. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  539. return
  540. }
  541. if !isJSONContentType(r) {
  542. s.recordAudit(auditUnsupportedMediaType)
  543. http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
  544. return
  545. }
  546. r.Body = http.MaxBytesReader(w, r.Body, maxConfigBodyBytes)
  547. var req IngestSaveRequest
  548. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  549. statusCode := http.StatusBadRequest
  550. if strings.Contains(err.Error(), "http: request body too large") {
  551. statusCode = http.StatusRequestEntityTooLarge
  552. s.recordAudit(auditBodyTooLarge)
  553. }
  554. http.Error(w, err.Error(), statusCode)
  555. return
  556. }
  557. s.mu.Lock()
  558. next := s.cfg
  559. next.Ingest = req.Ingest
  560. if err := next.Validate(); err != nil {
  561. s.mu.Unlock()
  562. http.Error(w, err.Error(), http.StatusBadRequest)
  563. return
  564. }
  565. save := s.saveConfig
  566. reload := s.hardReload
  567. if save == nil {
  568. s.mu.Unlock()
  569. http.Error(w, "config save is not configured (start with --config <path>)", http.StatusServiceUnavailable)
  570. return
  571. }
  572. if err := save(next); err != nil {
  573. s.mu.Unlock()
  574. http.Error(w, err.Error(), http.StatusInternalServerError)
  575. return
  576. }
  577. s.cfg = next
  578. s.mu.Unlock()
  579. w.Header().Set("Content-Type", "application/json")
  580. reloadScheduled := reload != nil
  581. _ = json.NewEncoder(w).Encode(map[string]any{
  582. "ok": true,
  583. "saved": true,
  584. "reloadScheduled": reloadScheduled,
  585. })
  586. if reloadScheduled {
  587. go func(fn func()) {
  588. time.Sleep(250 * time.Millisecond)
  589. fn()
  590. }(reload)
  591. }
  592. }