Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

891 linhas
27KB

  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. "golang.org/x/net/websocket"
  14. "github.com/jan/fm-rds-tx/internal/audio"
  15. "github.com/jan/fm-rds-tx/internal/config"
  16. drypkg "github.com/jan/fm-rds-tx/internal/dryrun"
  17. "github.com/jan/fm-rds-tx/internal/ingest"
  18. offpkg "github.com/jan/fm-rds-tx/internal/offline"
  19. "github.com/jan/fm-rds-tx/internal/platform"
  20. )
  21. //go:embed ui.html
  22. var uiHTML []byte
  23. //go:embed logo.png
  24. var logoPNG []byte
  25. // TXController is an optional interface the Server uses to start/stop TX
  26. // and apply live config changes.
  27. type TXController interface {
  28. StartTX() error
  29. StopTX() error
  30. TXStats() map[string]any
  31. UpdateConfig(patch LivePatch) error
  32. ResetFault() error
  33. }
  34. // LivePatch mirrors the patchable fields from ConfigPatch for the engine.
  35. // nil = no change.
  36. type LivePatch struct {
  37. FrequencyMHz *float64
  38. OutputDrive *float64
  39. StereoEnabled *bool
  40. StereoMode *string
  41. PilotLevel *float64
  42. RDSInjection *float64
  43. RDSEnabled *bool
  44. LimiterEnabled *bool
  45. LimiterCeiling *float64
  46. PS *string
  47. RadioText *string
  48. TA *bool
  49. TP *bool
  50. ToneLeftHz *float64
  51. ToneRightHz *float64
  52. ToneAmplitude *float64
  53. AudioGain *float64
  54. CompositeClipperEnabled *bool
  55. }
  56. type Server struct {
  57. mu sync.RWMutex
  58. cfg config.Config
  59. tx TXController
  60. drv platform.SoapyDriver // optional, for runtime stats
  61. streamSrc *audio.StreamSource // optional, for live audio ring stats
  62. audioIngress AudioIngress // optional, for /audio/stream
  63. ingestRt IngestRuntime // optional, for /runtime ingest stats
  64. saveConfig func(config.Config) error
  65. hardReload func()
  66. // BUG-F fix: reloadPending prevents multiple concurrent goroutines from
  67. // calling hardReload when handleIngestSave is hit multiple times quickly.
  68. reloadPending atomic.Bool
  69. audit auditCounters
  70. telemetryHub *TelemetryHub
  71. }
  72. type AudioIngress interface {
  73. WritePCM16(data []byte) (int, error)
  74. }
  75. type IngestRuntime interface {
  76. Stats() ingest.Stats
  77. }
  78. type auditEvent string
  79. const (
  80. auditMethodNotAllowed auditEvent = "methodNotAllowed"
  81. auditUnsupportedMediaType auditEvent = "unsupportedMediaType"
  82. auditBodyTooLarge auditEvent = "bodyTooLarge"
  83. auditUnexpectedBody auditEvent = "unexpectedBody"
  84. )
  85. type auditCounters struct {
  86. methodNotAllowed uint64
  87. unsupportedMediaType uint64
  88. bodyTooLarge uint64
  89. unexpectedBody uint64
  90. }
  91. const (
  92. maxConfigBodyBytes = 64 << 10 // 64 KiB
  93. configContentTypeHeader = "application/json"
  94. noBodyErrMsg = "request must not include a body"
  95. audioStreamContentTypeError = "Content-Type must be application/octet-stream or audio/L16"
  96. audioStreamBodyLimitDefault = 512 << 20 // 512 MiB
  97. )
  98. var audioStreamAllowedMediaTypes = []string{
  99. "application/octet-stream",
  100. "audio/l16",
  101. }
  102. var audioStreamBodyLimit = int64(audioStreamBodyLimitDefault) // bytes allowed per /audio/stream request; tests may override.
  103. func isJSONContentType(r *http.Request) bool {
  104. ct := strings.TrimSpace(r.Header.Get("Content-Type"))
  105. if ct == "" {
  106. return false
  107. }
  108. mediaType, _, err := mime.ParseMediaType(ct)
  109. if err != nil {
  110. return false
  111. }
  112. return strings.EqualFold(mediaType, configContentTypeHeader)
  113. }
  114. type ConfigPatch struct {
  115. FrequencyMHz *float64 `json:"frequencyMHz,omitempty"`
  116. OutputDrive *float64 `json:"outputDrive,omitempty"`
  117. StereoEnabled *bool `json:"stereoEnabled,omitempty"`
  118. StereoMode *string `json:"stereoMode,omitempty"`
  119. PilotLevel *float64 `json:"pilotLevel,omitempty"`
  120. RDSInjection *float64 `json:"rdsInjection,omitempty"`
  121. RDSEnabled *bool `json:"rdsEnabled,omitempty"`
  122. ToneLeftHz *float64 `json:"toneLeftHz,omitempty"`
  123. ToneRightHz *float64 `json:"toneRightHz,omitempty"`
  124. ToneAmplitude *float64 `json:"toneAmplitude,omitempty"`
  125. PS *string `json:"ps,omitempty"`
  126. RadioText *string `json:"radioText,omitempty"`
  127. PreEmphasisTauUS *float64 `json:"preEmphasisTauUS,omitempty"`
  128. LimiterEnabled *bool `json:"limiterEnabled,omitempty"`
  129. LimiterCeiling *float64 `json:"limiterCeiling,omitempty"`
  130. AudioGain *float64 `json:"audioGain,omitempty"`
  131. PI *string `json:"pi,omitempty"`
  132. PTY *int `json:"pty,omitempty"`
  133. TP *bool `json:"tp,omitempty"`
  134. TA *bool `json:"ta,omitempty"`
  135. MS *bool `json:"ms,omitempty"`
  136. CTEnabled *bool `json:"ctEnabled,omitempty"`
  137. RTPlusEnabled *bool `json:"rtPlusEnabled,omitempty"`
  138. RTPlusSeparator *string `json:"rtPlusSeparator,omitempty"`
  139. PTYN *string `json:"ptyn,omitempty"`
  140. LPS *string `json:"lps,omitempty"`
  141. ERTEnabled *bool `json:"ertEnabled,omitempty"`
  142. ERT *string `json:"ert,omitempty"`
  143. RDS2Enabled *bool `json:"rds2Enabled,omitempty"`
  144. StationLogoPath *string `json:"stationLogoPath,omitempty"`
  145. AF *[]float64 `json:"af,omitempty"`
  146. BS412Enabled *bool `json:"bs412Enabled,omitempty"`
  147. BS412ThresholdDBr *float64 `json:"bs412ThresholdDBr,omitempty"`
  148. MpxGain *float64 `json:"mpxGain,omitempty"`
  149. CompositeClipperEnabled *bool `json:"compositeClipperEnabled,omitempty"`
  150. CompositeClipperIterations *int `json:"compositeClipperIterations,omitempty"`
  151. CompositeClipperSoftKnee *float64 `json:"compositeClipperSoftKnee,omitempty"`
  152. CompositeClipperLookaheadMs *float64 `json:"compositeClipperLookaheadMs,omitempty"`
  153. }
  154. type IngestSaveRequest struct {
  155. Ingest config.IngestConfig `json:"ingest"`
  156. }
  157. func NewServer(cfg config.Config) *Server {
  158. return &Server{cfg: cfg, telemetryHub: NewTelemetryHub()}
  159. }
  160. func hasRequestBody(r *http.Request) bool {
  161. if r.ContentLength > 0 {
  162. return true
  163. }
  164. for _, te := range r.TransferEncoding {
  165. if strings.EqualFold(te, "chunked") {
  166. return true
  167. }
  168. }
  169. return false
  170. }
  171. func (s *Server) rejectBody(w http.ResponseWriter, r *http.Request) bool {
  172. // Returns true when the request has an unexpected body and the error response
  173. // has already been written — callers should return immediately in that case.
  174. // Returns false when there is no body (happy path — request should proceed).
  175. if !hasRequestBody(r) {
  176. return false
  177. }
  178. s.recordAudit(auditUnexpectedBody)
  179. http.Error(w, noBodyErrMsg, http.StatusBadRequest)
  180. return true
  181. }
  182. func (s *Server) recordAudit(evt auditEvent) {
  183. switch evt {
  184. case auditMethodNotAllowed:
  185. atomic.AddUint64(&s.audit.methodNotAllowed, 1)
  186. case auditUnsupportedMediaType:
  187. atomic.AddUint64(&s.audit.unsupportedMediaType, 1)
  188. case auditBodyTooLarge:
  189. atomic.AddUint64(&s.audit.bodyTooLarge, 1)
  190. case auditUnexpectedBody:
  191. atomic.AddUint64(&s.audit.unexpectedBody, 1)
  192. }
  193. }
  194. func (s *Server) auditSnapshot() map[string]uint64 {
  195. return map[string]uint64{
  196. "methodNotAllowed": atomic.LoadUint64(&s.audit.methodNotAllowed),
  197. "unsupportedMediaType": atomic.LoadUint64(&s.audit.unsupportedMediaType),
  198. "bodyTooLarge": atomic.LoadUint64(&s.audit.bodyTooLarge),
  199. "unexpectedBody": atomic.LoadUint64(&s.audit.unexpectedBody),
  200. }
  201. }
  202. func isAudioStreamContentType(r *http.Request) bool {
  203. ct := strings.TrimSpace(r.Header.Get("Content-Type"))
  204. if ct == "" {
  205. return false
  206. }
  207. mediaType, _, err := mime.ParseMediaType(ct)
  208. if err != nil {
  209. return false
  210. }
  211. for _, allowed := range audioStreamAllowedMediaTypes {
  212. if strings.EqualFold(mediaType, allowed) {
  213. return true
  214. }
  215. }
  216. return false
  217. }
  218. func (s *Server) TelemetryHub() *TelemetryHub {
  219. return s.telemetryHub
  220. }
  221. func (s *Server) SetTXController(tx TXController) {
  222. s.mu.Lock()
  223. s.tx = tx
  224. s.mu.Unlock()
  225. }
  226. func (s *Server) SetDriver(drv platform.SoapyDriver) {
  227. s.mu.Lock()
  228. s.drv = drv
  229. s.mu.Unlock()
  230. }
  231. func (s *Server) SetStreamSource(src *audio.StreamSource) {
  232. s.mu.Lock()
  233. s.streamSrc = src
  234. s.mu.Unlock()
  235. }
  236. func (s *Server) SetAudioIngress(ingress AudioIngress) {
  237. s.mu.Lock()
  238. s.audioIngress = ingress
  239. s.mu.Unlock()
  240. }
  241. func (s *Server) SetIngestRuntime(rt IngestRuntime) {
  242. s.mu.Lock()
  243. s.ingestRt = rt
  244. s.mu.Unlock()
  245. }
  246. func (s *Server) SetConfigSaver(save func(config.Config) error) {
  247. s.mu.Lock()
  248. s.saveConfig = save
  249. s.mu.Unlock()
  250. }
  251. func (s *Server) SetHardReload(fn func()) {
  252. s.mu.Lock()
  253. s.hardReload = fn
  254. s.mu.Unlock()
  255. }
  256. func (s *Server) Handler() http.Handler {
  257. mux := http.NewServeMux()
  258. mux.HandleFunc("/", s.handleUI)
  259. mux.HandleFunc("/logo", s.handleLogo)
  260. mux.HandleFunc("/healthz", s.handleHealth)
  261. mux.HandleFunc("/status", s.handleStatus)
  262. mux.HandleFunc("/dry-run", s.handleDryRun)
  263. mux.HandleFunc("/config", s.handleConfig)
  264. mux.HandleFunc("/config/ingest/save", s.handleIngestSave)
  265. mux.HandleFunc("/runtime", s.handleRuntime)
  266. mux.HandleFunc("/measurements", s.handleMeasurements)
  267. mux.Handle("/ws/telemetry", websocket.Handler(s.handleTelemetryWS))
  268. mux.HandleFunc("/runtime/fault/reset", s.handleRuntimeFaultReset)
  269. mux.HandleFunc("/tx/start", s.handleTXStart)
  270. mux.HandleFunc("/tx/stop", s.handleTXStop)
  271. mux.HandleFunc("/audio/stream", s.handleAudioStream)
  272. return mux
  273. }
  274. func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
  275. w.Header().Set("Content-Type", "application/json")
  276. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
  277. }
  278. func (s *Server) handleUI(w http.ResponseWriter, r *http.Request) {
  279. if r.URL.Path != "/" {
  280. http.NotFound(w, r)
  281. return
  282. }
  283. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  284. w.Header().Set("Cache-Control", "no-cache")
  285. w.Write(uiHTML)
  286. }
  287. func (s *Server) handleLogo(w http.ResponseWriter, r *http.Request) {
  288. w.Header().Set("Content-Type", "image/png")
  289. w.Header().Set("Cache-Control", "public, max-age=3600")
  290. w.Write(logoPNG)
  291. }
  292. func (s *Server) handleStatus(w http.ResponseWriter, _ *http.Request) {
  293. s.mu.RLock()
  294. cfg := s.cfg
  295. tx := s.tx
  296. s.mu.RUnlock()
  297. status := map[string]any{
  298. "service": "fm-rds-tx",
  299. "backend": cfg.Backend.Kind,
  300. "frequencyMHz": cfg.FM.FrequencyMHz,
  301. "stereoEnabled": cfg.FM.StereoEnabled,
  302. "stereoMode": cfg.FM.StereoMode,
  303. "rdsEnabled": cfg.RDS.Enabled,
  304. "preEmphasisTauUS": cfg.FM.PreEmphasisTauUS,
  305. "limiterEnabled": cfg.FM.LimiterEnabled,
  306. "fmModulationEnabled": cfg.FM.FMModulationEnabled,
  307. }
  308. if tx != nil {
  309. if stats := tx.TXStats(); stats != nil {
  310. if ri, ok := stats["runtimeIndicator"]; ok {
  311. status["runtimeIndicator"] = ri
  312. }
  313. if alert, ok := stats["runtimeAlert"]; ok {
  314. status["runtimeAlert"] = alert
  315. }
  316. if queue, ok := stats["queue"]; ok {
  317. status["queue"] = queue
  318. }
  319. if runtimeState, ok := stats["state"]; ok {
  320. status["runtimeState"] = runtimeState
  321. }
  322. }
  323. }
  324. w.Header().Set("Content-Type", "application/json")
  325. _ = json.NewEncoder(w).Encode(status)
  326. }
  327. func (s *Server) handleMeasurements(w http.ResponseWriter, _ *http.Request) {
  328. s.mu.RLock()
  329. tx := s.tx
  330. s.mu.RUnlock()
  331. result := map[string]any{"noData": true, "stale": true}
  332. if tx != nil {
  333. if stats := tx.TXStats(); stats != nil {
  334. if measurement, ok := stats["measurement"]; ok && measurement != nil {
  335. result = map[string]any{"noData": false, "stale": false, "measurement": measurement}
  336. if state, ok := stats["state"]; ok {
  337. result["state"] = state
  338. }
  339. if applied, ok := stats["appliedFrequencyMHz"]; ok {
  340. result["appliedFrequencyMHz"] = applied
  341. }
  342. if queue, ok := stats["queue"]; ok {
  343. result["queue"] = queue
  344. }
  345. if runtimeIndicator, ok := stats["runtimeIndicator"]; ok {
  346. result["runtimeIndicator"] = runtimeIndicator
  347. }
  348. if runtimeAlert, ok := stats["runtimeAlert"]; ok {
  349. result["runtimeAlert"] = runtimeAlert
  350. }
  351. }
  352. }
  353. }
  354. w.Header().Set("Content-Type", "application/json")
  355. _ = json.NewEncoder(w).Encode(result)
  356. }
  357. func (s *Server) handleTelemetryWS(ws *websocket.Conn) {
  358. if s.telemetryHub == nil {
  359. _ = ws.Close()
  360. return
  361. }
  362. _ = ws.SetDeadline(time.Now().Add(30 * time.Second))
  363. sub, unsubscribe := s.telemetryHub.Subscribe()
  364. defer unsubscribe()
  365. defer ws.Close()
  366. s.mu.RLock()
  367. tx := s.tx
  368. s.mu.RUnlock()
  369. if tx != nil {
  370. if stats := tx.TXStats(); stats != nil {
  371. if measurement, ok := stats["measurement"].(interface{ }); ok {
  372. if m, ok := measurement.(*offpkg.MeasurementSnapshot); ok && m != nil {
  373. _ = ws.SetWriteDeadline(time.Now().Add(2 * time.Second))
  374. if err := websocket.JSON.Send(ws, TelemetryMessage{Type: "measurement", TS: m.Timestamp, Seq: m.Sequence, Data: m}); err != nil {
  375. return
  376. }
  377. }
  378. }
  379. }
  380. }
  381. for msg := range sub.ch {
  382. _ = ws.SetWriteDeadline(time.Now().Add(2 * time.Second))
  383. if err := websocket.JSON.Send(ws, msg); err != nil {
  384. return
  385. }
  386. }
  387. }
  388. func (s *Server) handleRuntime(w http.ResponseWriter, _ *http.Request) {
  389. s.mu.RLock()
  390. drv := s.drv
  391. tx := s.tx
  392. stream := s.streamSrc
  393. ingestRt := s.ingestRt
  394. s.mu.RUnlock()
  395. result := map[string]any{}
  396. if drv != nil {
  397. result["driver"] = drv.Stats()
  398. }
  399. if tx != nil {
  400. if stats := tx.TXStats(); stats != nil {
  401. result["engine"] = stats
  402. }
  403. }
  404. if stream != nil {
  405. result["audioStream"] = stream.Stats()
  406. }
  407. if ingestRt != nil {
  408. result["ingest"] = ingestRt.Stats()
  409. }
  410. result["controlAudit"] = s.auditSnapshot()
  411. w.Header().Set("Content-Type", "application/json")
  412. _ = json.NewEncoder(w).Encode(result)
  413. }
  414. func (s *Server) handleRuntimeFaultReset(w http.ResponseWriter, r *http.Request) {
  415. if r.Method != http.MethodPost {
  416. s.recordAudit(auditMethodNotAllowed)
  417. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  418. return
  419. }
  420. if s.rejectBody(w, r) { // BUG-01 fix: rejectBody returns true when rejected
  421. return
  422. }
  423. s.mu.RLock()
  424. tx := s.tx
  425. s.mu.RUnlock()
  426. if tx == nil {
  427. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  428. return
  429. }
  430. if err := tx.ResetFault(); err != nil {
  431. http.Error(w, err.Error(), http.StatusConflict)
  432. return
  433. }
  434. w.Header().Set("Content-Type", "application/json")
  435. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
  436. }
  437. // handleAudioStream accepts raw S16LE PCM via HTTP POST and pushes
  438. // it into the configured ingest http-raw source. Use with:
  439. //
  440. // curl -X POST --data-binary @- http://host:8088/audio/stream < audio.raw
  441. // ffmpeg ... -f s16le -ar 44100 -ac 2 - | curl -X POST --data-binary @- http://host:8088/audio/stream
  442. func (s *Server) handleAudioStream(w http.ResponseWriter, r *http.Request) {
  443. if r.Method != http.MethodPost {
  444. s.recordAudit(auditMethodNotAllowed)
  445. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  446. return
  447. }
  448. if !isAudioStreamContentType(r) {
  449. s.recordAudit(auditUnsupportedMediaType)
  450. http.Error(w, audioStreamContentTypeError, http.StatusUnsupportedMediaType)
  451. return
  452. }
  453. s.mu.RLock()
  454. ingress := s.audioIngress
  455. s.mu.RUnlock()
  456. if ingress == nil {
  457. http.Error(w, "audio ingest not configured (use --audio-http with ingest runtime)", http.StatusServiceUnavailable)
  458. return
  459. }
  460. // BUG-10 fix: /audio/stream is a long-lived streaming endpoint.
  461. // The global HTTP server ReadTimeout (5s) and WriteTimeout (10s) would
  462. // kill connections mid-stream. Disable them per-request via ResponseController
  463. // (requires Go 1.20+, confirmed Go 1.22).
  464. rc := http.NewResponseController(w)
  465. _ = rc.SetReadDeadline(time.Time{})
  466. _ = rc.SetWriteDeadline(time.Time{})
  467. r.Body = http.MaxBytesReader(w, r.Body, audioStreamBodyLimit)
  468. // Read body in chunks and push to ring buffer
  469. buf := make([]byte, 32768)
  470. totalFrames := 0
  471. for {
  472. n, err := r.Body.Read(buf)
  473. if n > 0 {
  474. written, writeErr := ingress.WritePCM16(buf[:n])
  475. totalFrames += written
  476. if writeErr != nil {
  477. http.Error(w, writeErr.Error(), http.StatusServiceUnavailable)
  478. return
  479. }
  480. }
  481. if err != nil {
  482. if err == io.EOF {
  483. break
  484. }
  485. var maxErr *http.MaxBytesError
  486. if errors.As(err, &maxErr) {
  487. s.recordAudit(auditBodyTooLarge)
  488. http.Error(w, maxErr.Error(), http.StatusRequestEntityTooLarge)
  489. return
  490. }
  491. http.Error(w, err.Error(), http.StatusInternalServerError)
  492. return
  493. }
  494. }
  495. w.Header().Set("Content-Type", "application/json")
  496. _ = json.NewEncoder(w).Encode(map[string]any{
  497. "ok": true,
  498. "frames": totalFrames,
  499. })
  500. }
  501. func (s *Server) handleTXStart(w http.ResponseWriter, r *http.Request) {
  502. if r.Method != http.MethodPost {
  503. s.recordAudit(auditMethodNotAllowed)
  504. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  505. return
  506. }
  507. if s.rejectBody(w, r) { // BUG-01 fix: rejectBody returns true when rejected
  508. return
  509. }
  510. s.mu.RLock()
  511. tx := s.tx
  512. s.mu.RUnlock()
  513. if tx == nil {
  514. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  515. return
  516. }
  517. if err := tx.StartTX(); err != nil {
  518. http.Error(w, err.Error(), http.StatusConflict)
  519. return
  520. }
  521. w.Header().Set("Content-Type", "application/json")
  522. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "started"})
  523. }
  524. func (s *Server) handleTXStop(w http.ResponseWriter, r *http.Request) {
  525. if r.Method != http.MethodPost {
  526. s.recordAudit(auditMethodNotAllowed)
  527. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  528. return
  529. }
  530. if s.rejectBody(w, r) { // BUG-01 fix: rejectBody returns true when rejected
  531. return
  532. }
  533. s.mu.RLock()
  534. tx := s.tx
  535. s.mu.RUnlock()
  536. if tx == nil {
  537. http.Error(w, "tx controller not available", http.StatusServiceUnavailable)
  538. return
  539. }
  540. go func() {
  541. _ = tx.StopTX()
  542. }()
  543. w.Header().Set("Content-Type", "application/json")
  544. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "action": "stop-requested"})
  545. }
  546. func (s *Server) handleDryRun(w http.ResponseWriter, _ *http.Request) {
  547. s.mu.RLock()
  548. cfg := s.cfg
  549. s.mu.RUnlock()
  550. w.Header().Set("Content-Type", "application/json")
  551. _ = json.NewEncoder(w).Encode(drypkg.Generate(cfg))
  552. }
  553. func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
  554. switch r.Method {
  555. case http.MethodGet:
  556. s.mu.RLock()
  557. cfg := s.cfg
  558. s.mu.RUnlock()
  559. w.Header().Set("Content-Type", "application/json")
  560. _ = json.NewEncoder(w).Encode(cfg)
  561. case http.MethodPost:
  562. if !isJSONContentType(r) {
  563. s.recordAudit(auditUnsupportedMediaType)
  564. http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
  565. return
  566. }
  567. r.Body = http.MaxBytesReader(w, r.Body, maxConfigBodyBytes)
  568. var patch ConfigPatch
  569. // BUG-4 fix: reject unknown JSON fields (typos) with 400 rather than
  570. // silently ignoring them (e.g. "outputDrvie" would succeed and do nothing).
  571. dec := json.NewDecoder(r.Body)
  572. dec.DisallowUnknownFields()
  573. if err := dec.Decode(&patch); err != nil {
  574. statusCode := http.StatusBadRequest
  575. if strings.Contains(err.Error(), "http: request body too large") {
  576. statusCode = http.StatusRequestEntityTooLarge
  577. s.recordAudit(auditBodyTooLarge)
  578. }
  579. http.Error(w, err.Error(), statusCode)
  580. return
  581. }
  582. // Update the server's config snapshot (for GET /config and /status)
  583. s.mu.Lock()
  584. next := s.cfg
  585. if patch.FrequencyMHz != nil {
  586. next.FM.FrequencyMHz = *patch.FrequencyMHz
  587. }
  588. if patch.OutputDrive != nil {
  589. next.FM.OutputDrive = *patch.OutputDrive
  590. }
  591. if patch.ToneLeftHz != nil {
  592. next.Audio.ToneLeftHz = *patch.ToneLeftHz
  593. }
  594. if patch.ToneRightHz != nil {
  595. next.Audio.ToneRightHz = *patch.ToneRightHz
  596. }
  597. if patch.ToneAmplitude != nil {
  598. next.Audio.ToneAmplitude = *patch.ToneAmplitude
  599. }
  600. if patch.AudioGain != nil {
  601. next.Audio.Gain = *patch.AudioGain
  602. }
  603. if patch.PS != nil {
  604. next.RDS.PS = *patch.PS
  605. }
  606. if patch.RadioText != nil {
  607. next.RDS.RadioText = *patch.RadioText
  608. }
  609. if patch.PI != nil {
  610. next.RDS.PI = *patch.PI
  611. }
  612. if patch.PTY != nil {
  613. next.RDS.PTY = *patch.PTY
  614. }
  615. if patch.TP != nil {
  616. next.RDS.TP = *patch.TP
  617. }
  618. if patch.TA != nil {
  619. next.RDS.TA = *patch.TA
  620. }
  621. if patch.MS != nil {
  622. next.RDS.MS = *patch.MS
  623. }
  624. if patch.CTEnabled != nil {
  625. next.RDS.CTEnabled = *patch.CTEnabled
  626. }
  627. if patch.RTPlusEnabled != nil {
  628. next.RDS.RTPlusEnabled = *patch.RTPlusEnabled
  629. }
  630. if patch.RTPlusSeparator != nil {
  631. next.RDS.RTPlusSeparator = *patch.RTPlusSeparator
  632. }
  633. if patch.PTYN != nil {
  634. next.RDS.PTYN = *patch.PTYN
  635. }
  636. if patch.LPS != nil {
  637. next.RDS.LPS = *patch.LPS
  638. }
  639. if patch.ERTEnabled != nil {
  640. next.RDS.ERTEnabled = *patch.ERTEnabled
  641. }
  642. if patch.ERT != nil {
  643. next.RDS.ERT = *patch.ERT
  644. }
  645. if patch.RDS2Enabled != nil {
  646. next.RDS.RDS2Enabled = *patch.RDS2Enabled
  647. }
  648. if patch.StationLogoPath != nil {
  649. next.RDS.StationLogoPath = *patch.StationLogoPath
  650. }
  651. if patch.AF != nil {
  652. next.RDS.AF = *patch.AF
  653. }
  654. if patch.PreEmphasisTauUS != nil {
  655. next.FM.PreEmphasisTauUS = *patch.PreEmphasisTauUS
  656. }
  657. if patch.StereoEnabled != nil {
  658. next.FM.StereoEnabled = *patch.StereoEnabled
  659. }
  660. if patch.StereoMode != nil {
  661. next.FM.StereoMode = *patch.StereoMode
  662. }
  663. if patch.LimiterEnabled != nil {
  664. next.FM.LimiterEnabled = *patch.LimiterEnabled
  665. }
  666. if patch.LimiterCeiling != nil {
  667. next.FM.LimiterCeiling = *patch.LimiterCeiling
  668. }
  669. if patch.RDSEnabled != nil {
  670. next.RDS.Enabled = *patch.RDSEnabled
  671. }
  672. if patch.PilotLevel != nil {
  673. next.FM.PilotLevel = *patch.PilotLevel
  674. }
  675. if patch.RDSInjection != nil {
  676. next.FM.RDSInjection = *patch.RDSInjection
  677. }
  678. if patch.BS412Enabled != nil {
  679. next.FM.BS412Enabled = *patch.BS412Enabled
  680. }
  681. if patch.BS412ThresholdDBr != nil {
  682. next.FM.BS412ThresholdDBr = *patch.BS412ThresholdDBr
  683. }
  684. if patch.MpxGain != nil {
  685. next.FM.MpxGain = *patch.MpxGain
  686. }
  687. if patch.CompositeClipperEnabled != nil {
  688. next.FM.CompositeClipper.Enabled = *patch.CompositeClipperEnabled
  689. }
  690. if patch.CompositeClipperIterations != nil {
  691. next.FM.CompositeClipper.Iterations = *patch.CompositeClipperIterations
  692. }
  693. if patch.CompositeClipperSoftKnee != nil {
  694. next.FM.CompositeClipper.SoftKnee = *patch.CompositeClipperSoftKnee
  695. }
  696. if patch.CompositeClipperLookaheadMs != nil {
  697. next.FM.CompositeClipper.LookaheadMs = *patch.CompositeClipperLookaheadMs
  698. }
  699. if err := next.Validate(); err != nil {
  700. s.mu.Unlock()
  701. http.Error(w, err.Error(), http.StatusBadRequest)
  702. return
  703. }
  704. lp := LivePatch{
  705. FrequencyMHz: patch.FrequencyMHz,
  706. OutputDrive: patch.OutputDrive,
  707. StereoEnabled: patch.StereoEnabled,
  708. StereoMode: patch.StereoMode,
  709. PilotLevel: patch.PilotLevel,
  710. RDSInjection: patch.RDSInjection,
  711. RDSEnabled: patch.RDSEnabled,
  712. LimiterEnabled: patch.LimiterEnabled,
  713. LimiterCeiling: patch.LimiterCeiling,
  714. PS: patch.PS,
  715. RadioText: patch.RadioText,
  716. TA: patch.TA,
  717. TP: patch.TP,
  718. ToneLeftHz: patch.ToneLeftHz,
  719. ToneRightHz: patch.ToneRightHz,
  720. ToneAmplitude: patch.ToneAmplitude,
  721. AudioGain: patch.AudioGain,
  722. CompositeClipperEnabled: patch.CompositeClipperEnabled,
  723. }
  724. // NEU-02 fix: determine whether any live-patchable fields are present,
  725. // then release the lock before calling UpdateConfig to avoid holding
  726. // s.mu across a potentially blocking engine call.
  727. tx := s.tx
  728. hasLiveFields := patch.FrequencyMHz != nil || patch.OutputDrive != nil ||
  729. patch.StereoEnabled != nil || patch.StereoMode != nil || patch.PilotLevel != nil ||
  730. patch.RDSInjection != nil || patch.RDSEnabled != nil ||
  731. patch.LimiterEnabled != nil || patch.LimiterCeiling != nil ||
  732. patch.PS != nil || patch.RadioText != nil || patch.TA != nil || patch.TP != nil ||
  733. patch.ToneLeftHz != nil || patch.ToneRightHz != nil ||
  734. patch.ToneAmplitude != nil || patch.AudioGain != nil ||
  735. patch.CompositeClipperEnabled != nil
  736. s.mu.Unlock()
  737. // Apply live fields to running engine outside the lock.
  738. if tx != nil && hasLiveFields {
  739. if err := tx.UpdateConfig(lp); err != nil {
  740. http.Error(w, err.Error(), http.StatusBadRequest)
  741. return
  742. }
  743. }
  744. // Persist the validated config snapshot when a config saver is available.
  745. // This ensures restart-required UI changes survive process restarts instead
  746. // of only updating the in-memory snapshot.
  747. s.mu.RLock()
  748. save := s.saveConfig
  749. s.mu.RUnlock()
  750. if save != nil {
  751. if err := save(next); err != nil {
  752. http.Error(w, err.Error(), http.StatusInternalServerError)
  753. return
  754. }
  755. }
  756. // Commit the server snapshot only after validation, optional persistence,
  757. // and any required live update succeeded.
  758. s.mu.Lock()
  759. s.cfg = next
  760. s.mu.Unlock()
  761. // NEU-03 fix: report live=true only when live-patchable fields were applied.
  762. live := tx != nil && hasLiveFields
  763. w.Header().Set("Content-Type", "application/json")
  764. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "live": live})
  765. default:
  766. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  767. }
  768. }
  769. func (s *Server) handleIngestSave(w http.ResponseWriter, r *http.Request) {
  770. if r.Method != http.MethodPost {
  771. s.recordAudit(auditMethodNotAllowed)
  772. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  773. return
  774. }
  775. if !isJSONContentType(r) {
  776. s.recordAudit(auditUnsupportedMediaType)
  777. http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
  778. return
  779. }
  780. r.Body = http.MaxBytesReader(w, r.Body, maxConfigBodyBytes)
  781. var req IngestSaveRequest
  782. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  783. statusCode := http.StatusBadRequest
  784. if strings.Contains(err.Error(), "http: request body too large") {
  785. statusCode = http.StatusRequestEntityTooLarge
  786. s.recordAudit(auditBodyTooLarge)
  787. }
  788. http.Error(w, err.Error(), statusCode)
  789. return
  790. }
  791. s.mu.Lock()
  792. next := s.cfg
  793. next.Ingest = req.Ingest
  794. if err := next.Validate(); err != nil {
  795. s.mu.Unlock()
  796. http.Error(w, err.Error(), http.StatusBadRequest)
  797. return
  798. }
  799. save := s.saveConfig
  800. reload := s.hardReload
  801. if save == nil {
  802. s.mu.Unlock()
  803. http.Error(w, "config save is not configured (start with --config <path>)", http.StatusServiceUnavailable)
  804. return
  805. }
  806. if err := save(next); err != nil {
  807. s.mu.Unlock()
  808. http.Error(w, err.Error(), http.StatusInternalServerError)
  809. return
  810. }
  811. s.cfg = next
  812. s.mu.Unlock()
  813. w.Header().Set("Content-Type", "application/json")
  814. reloadScheduled := reload != nil
  815. _ = json.NewEncoder(w).Encode(map[string]any{
  816. "ok": true,
  817. "saved": true,
  818. "reloadScheduled": reloadScheduled,
  819. })
  820. if reloadScheduled && s.reloadPending.CompareAndSwap(false, true) {
  821. go func(fn func()) {
  822. time.Sleep(250 * time.Millisecond)
  823. s.reloadPending.Store(false)
  824. fn()
  825. }(reload)
  826. }
  827. }