Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

550 line
20KB

  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. )
  10. type Config struct {
  11. Audio AudioConfig `json:"audio"`
  12. RDS RDSConfig `json:"rds"`
  13. FM FMConfig `json:"fm"`
  14. Backend BackendConfig `json:"backend"`
  15. Control ControlConfig `json:"control"`
  16. Runtime RuntimeConfig `json:"runtime"`
  17. Ingest IngestConfig `json:"ingest"`
  18. }
  19. type AudioConfig struct {
  20. InputPath string `json:"inputPath"`
  21. Gain float64 `json:"gain"`
  22. ToneLeftHz float64 `json:"toneLeftHz"`
  23. ToneRightHz float64 `json:"toneRightHz"`
  24. ToneAmplitude float64 `json:"toneAmplitude"`
  25. }
  26. type RDSConfig struct {
  27. Enabled bool `json:"enabled"`
  28. PI string `json:"pi"`
  29. PS string `json:"ps"`
  30. RadioText string `json:"radioText"`
  31. PTY int `json:"pty"`
  32. // Traffic
  33. TP bool `json:"tp"` // Traffic Program — station carries traffic info
  34. TA bool `json:"ta"` // Traffic Announcement — currently on air
  35. // Music/Speech & Decoder Info
  36. MS bool `json:"ms"` // true=music, false=speech
  37. DI uint8 `json:"di"` // Decoder Info: bit0=stereo, bit1=artificial head, bit2=compressed, bit3=dynamic PTY
  38. // Alternative Frequencies (MHz, e.g. [93.3, 95.7])
  39. AF []float64 `json:"af,omitempty"`
  40. // Clock-Time (Group 4A)
  41. CTEnabled bool `json:"ctEnabled"`
  42. CTOffsetHalfHours int8 `json:"ctOffsetHalfHours,omitempty"` // 0 = auto from OS
  43. // Program Type Name (Group 10A) — 8-char custom label
  44. PTYN string `json:"ptyn,omitempty"`
  45. // RT+ (Groups 3A + 11A) — auto-parse artist/title from RadioText
  46. RTPlusEnabled bool `json:"rtPlusEnabled"`
  47. RTPlusSeparator string `json:"rtPlusSeparator,omitempty"` // default " - "
  48. // EON — Enhanced Other Networks (Group 14A)
  49. EON []EONEntryConfig `json:"eon,omitempty"`
  50. }
  51. // EONEntryConfig describes another station for EON transmission.
  52. type EONEntryConfig struct {
  53. PI string `json:"pi"` // hex PI code
  54. PS string `json:"ps"` // 8-char station name
  55. PTY int `json:"pty"`
  56. TP bool `json:"tp"`
  57. TA bool `json:"ta"`
  58. AF []float64 `json:"af,omitempty"`
  59. }
  60. type FMConfig struct {
  61. FrequencyMHz float64 `json:"frequencyMHz"`
  62. StereoEnabled bool `json:"stereoEnabled"`
  63. StereoMode string `json:"stereoMode"` // "DSB" (standard), "SSB" (experimental LSB), "VSB" (vestigial)
  64. PilotLevel float64 `json:"pilotLevel"` // fraction of ±75kHz deviation (0.09 = 9%, ITU standard)
  65. RDSInjection float64 `json:"rdsInjection"` // fraction of ±75kHz deviation (0.04 = 4%, typical)
  66. PreEmphasisTauUS float64 `json:"preEmphasisTauUS"` // time constant in µs: 50 (EU) or 75 (US), 0=off
  67. OutputDrive float64 `json:"outputDrive"`
  68. CompositeRateHz int `json:"compositeRateHz"` // internal DSP/MPX sample rate
  69. MaxDeviationHz float64 `json:"maxDeviationHz"`
  70. LimiterEnabled bool `json:"limiterEnabled"`
  71. LimiterCeiling float64 `json:"limiterCeiling"`
  72. FMModulationEnabled bool `json:"fmModulationEnabled"`
  73. MpxGain float64 `json:"mpxGain"` // hardware calibration: scales entire composite output (default 1.0)
  74. BS412Enabled bool `json:"bs412Enabled"` // ITU-R BS.412 MPX power limiter (EU requirement)
  75. BS412ThresholdDBr float64 `json:"bs412ThresholdDBr"` // power limit in dBr (0 = standard, +3 = relaxed)
  76. CompositeClipper CompositeClipperConfig `json:"compositeClipper"` // ITU-R SM.1268 iterative composite clipper
  77. }
  78. // CompositeClipperConfig controls the broadcast-grade composite MPX clipper.
  79. // When enabled, replaces the simple clip→notch chain with an iterative
  80. // clip-filter-clip processor, optionally with soft-knee clipping and
  81. // look-ahead peak limiting.
  82. type CompositeClipperConfig struct {
  83. Enabled bool `json:"enabled"` // false = legacy single-pass clip
  84. Iterations int `json:"iterations"` // clip-filter-clip passes (1-5, default 3)
  85. SoftKnee float64 `json:"softKnee"` // soft-clip transition zone (0=hard, 0.15=moderate, 0.3=gentle)
  86. LookaheadMs float64 `json:"lookaheadMs"` // look-ahead delay (0=off, 1.0=typical)
  87. }
  88. type BackendConfig struct {
  89. Kind string `json:"kind"`
  90. Driver string `json:"driver,omitempty"`
  91. Device string `json:"device"`
  92. URI string `json:"uri,omitempty"`
  93. DeviceArgs map[string]string `json:"deviceArgs,omitempty"`
  94. OutputPath string `json:"outputPath"`
  95. DeviceSampleRateHz float64 `json:"deviceSampleRateHz"` // actual SDR device rate; 0 = same as compositeRateHz
  96. }
  97. type ControlConfig struct {
  98. ListenAddress string `json:"listenAddress"`
  99. }
  100. type RuntimeConfig struct {
  101. FrameQueueCapacity int `json:"frameQueueCapacity"`
  102. }
  103. type IngestConfig struct {
  104. Kind string `json:"kind"`
  105. PrebufferMs int `json:"prebufferMs"`
  106. StallTimeoutMs int `json:"stallTimeoutMs"`
  107. Reconnect IngestReconnectConfig `json:"reconnect"`
  108. Stdin IngestPCMConfig `json:"stdin"`
  109. HTTPRaw IngestPCMConfig `json:"httpRaw"`
  110. Icecast IngestIcecastConfig `json:"icecast"`
  111. SRT IngestSRTConfig `json:"srt"`
  112. AES67 IngestAES67Config `json:"aes67"`
  113. }
  114. type IngestReconnectConfig struct {
  115. Enabled bool `json:"enabled"`
  116. InitialBackoffMs int `json:"initialBackoffMs"`
  117. MaxBackoffMs int `json:"maxBackoffMs"`
  118. }
  119. type IngestPCMConfig struct {
  120. SampleRateHz int `json:"sampleRateHz"`
  121. Channels int `json:"channels"`
  122. Format string `json:"format"`
  123. }
  124. type IngestIcecastConfig struct {
  125. URL string `json:"url"`
  126. Decoder string `json:"decoder"`
  127. RadioText IngestIcecastRadioTextConfig `json:"radioText"`
  128. }
  129. type IngestIcecastRadioTextConfig struct {
  130. Enabled bool `json:"enabled"`
  131. Prefix string `json:"prefix"`
  132. MaxLen int `json:"maxLen"`
  133. OnlyOnChange bool `json:"onlyOnChange"`
  134. }
  135. type IngestSRTConfig struct {
  136. URL string `json:"url"`
  137. Mode string `json:"mode"`
  138. SampleRateHz int `json:"sampleRateHz"`
  139. Channels int `json:"channels"`
  140. }
  141. type IngestAES67Config struct {
  142. SDPPath string `json:"sdpPath"`
  143. SDP string `json:"sdp"`
  144. Discovery IngestAES67DiscoveryConfig `json:"discovery"`
  145. MulticastGroup string `json:"multicastGroup"`
  146. Port int `json:"port"`
  147. InterfaceName string `json:"interfaceName"`
  148. PayloadType int `json:"payloadType"`
  149. SampleRateHz int `json:"sampleRateHz"`
  150. Channels int `json:"channels"`
  151. Encoding string `json:"encoding"`
  152. PacketTimeMs int `json:"packetTimeMs"`
  153. JitterDepthPackets int `json:"jitterDepthPackets"`
  154. ReadBufferBytes int `json:"readBufferBytes"`
  155. }
  156. type IngestAES67DiscoveryConfig struct {
  157. Enabled bool `json:"enabled"`
  158. StreamName string `json:"streamName"`
  159. TimeoutMs int `json:"timeoutMs"`
  160. InterfaceName string `json:"interfaceName"`
  161. SAPGroup string `json:"sapGroup"`
  162. SAPPort int `json:"sapPort"`
  163. }
  164. func Default() Config {
  165. return Config{
  166. // BUG-C fix: tones off by default (was 0.4 — caused unintended audio output).
  167. Audio: AudioConfig{Gain: 1.0, ToneLeftHz: 1000, ToneRightHz: 1600, ToneAmplitude: 0},
  168. RDS: RDSConfig{
  169. Enabled: true,
  170. PI: "1234",
  171. PS: "FMRTX",
  172. RadioText: "fm-rds-tx",
  173. PTY: 0,
  174. MS: true,
  175. DI: 0x01, // stereo
  176. CTEnabled: true,
  177. RTPlusEnabled: true,
  178. RTPlusSeparator: " - ",
  179. },
  180. FM: FMConfig{
  181. FrequencyMHz: 100.0,
  182. StereoEnabled: true,
  183. StereoMode: "DSB",
  184. PilotLevel: 0.09,
  185. RDSInjection: 0.04,
  186. PreEmphasisTauUS: 50,
  187. OutputDrive: 0.5,
  188. CompositeRateHz: 228000,
  189. MaxDeviationHz: 75000,
  190. LimiterEnabled: true,
  191. LimiterCeiling: 1.0,
  192. FMModulationEnabled: true,
  193. MpxGain: 1.0,
  194. CompositeClipper: CompositeClipperConfig{
  195. Enabled: false,
  196. Iterations: 3,
  197. SoftKnee: 0.15,
  198. LookaheadMs: 1.0,
  199. },
  200. },
  201. Backend: BackendConfig{Kind: "file", OutputPath: "build/out/composite.f32"},
  202. Control: ControlConfig{ListenAddress: "127.0.0.1:8088"},
  203. Runtime: RuntimeConfig{FrameQueueCapacity: 3},
  204. Ingest: IngestConfig{
  205. Kind: "none",
  206. PrebufferMs: 1500,
  207. StallTimeoutMs: 3000,
  208. Reconnect: IngestReconnectConfig{
  209. Enabled: true,
  210. InitialBackoffMs: 1000,
  211. MaxBackoffMs: 15000,
  212. },
  213. Stdin: IngestPCMConfig{
  214. SampleRateHz: 44100,
  215. Channels: 2,
  216. Format: "s16le",
  217. },
  218. HTTPRaw: IngestPCMConfig{
  219. SampleRateHz: 44100,
  220. Channels: 2,
  221. Format: "s16le",
  222. },
  223. Icecast: IngestIcecastConfig{
  224. Decoder: "auto",
  225. RadioText: IngestIcecastRadioTextConfig{
  226. Enabled: false,
  227. MaxLen: 64,
  228. OnlyOnChange: true,
  229. },
  230. },
  231. SRT: IngestSRTConfig{
  232. Mode: "listener",
  233. SampleRateHz: 48000,
  234. Channels: 2,
  235. },
  236. AES67: IngestAES67Config{
  237. Discovery: IngestAES67DiscoveryConfig{
  238. TimeoutMs: 3000,
  239. },
  240. PayloadType: 97,
  241. SampleRateHz: 48000,
  242. Channels: 2,
  243. Encoding: "L24",
  244. PacketTimeMs: 1,
  245. JitterDepthPackets: 8,
  246. ReadBufferBytes: 1 << 20,
  247. },
  248. },
  249. }
  250. }
  251. // ParsePI parses a hex PI code string. Returns an error for invalid input.
  252. func ParsePI(pi string) (uint16, error) {
  253. trimmed := strings.TrimSpace(pi)
  254. if trimmed == "" {
  255. return 0, fmt.Errorf("rds.pi is required")
  256. }
  257. trimmed = strings.TrimPrefix(trimmed, "0x")
  258. trimmed = strings.TrimPrefix(trimmed, "0X")
  259. v, err := strconv.ParseUint(trimmed, 16, 16)
  260. if err != nil {
  261. return 0, fmt.Errorf("invalid rds.pi: %q", pi)
  262. }
  263. return uint16(v), nil
  264. }
  265. func Load(path string) (Config, error) {
  266. cfg := Default()
  267. if path == "" {
  268. return cfg, cfg.Validate()
  269. }
  270. data, err := os.ReadFile(path)
  271. if err != nil {
  272. return Config{}, err
  273. }
  274. if err := json.Unmarshal(data, &cfg); err != nil {
  275. return Config{}, err
  276. }
  277. return cfg, cfg.Validate()
  278. }
  279. func Save(path string, cfg Config) error {
  280. if strings.TrimSpace(path) == "" {
  281. return fmt.Errorf("config path is required")
  282. }
  283. if err := cfg.Validate(); err != nil {
  284. return err
  285. }
  286. data, err := json.MarshalIndent(cfg, "", " ")
  287. if err != nil {
  288. return err
  289. }
  290. data = append(data, '\n')
  291. // NEW-1 fix: write to a temp file in the same directory, then rename atomically.
  292. // A direct os.WriteFile on the target leaves a corrupt file if the process
  293. // crashes mid-write. os.Rename is atomic on POSIX filesystems.
  294. dir := filepath.Dir(path)
  295. tmp, err := os.CreateTemp(dir, ".fmrtx-config-*.json.tmp")
  296. if err != nil {
  297. return fmt.Errorf("config save: create temp: %w", err)
  298. }
  299. tmpPath := tmp.Name()
  300. if _, err := tmp.Write(data); err != nil {
  301. _ = tmp.Close()
  302. _ = os.Remove(tmpPath)
  303. return fmt.Errorf("config save: write temp: %w", err)
  304. }
  305. if err := tmp.Sync(); err != nil {
  306. _ = tmp.Close()
  307. _ = os.Remove(tmpPath)
  308. return fmt.Errorf("config save: sync temp: %w", err)
  309. }
  310. if err := tmp.Close(); err != nil {
  311. _ = os.Remove(tmpPath)
  312. return fmt.Errorf("config save: close temp: %w", err)
  313. }
  314. if err := os.Rename(tmpPath, path); err != nil {
  315. _ = os.Remove(tmpPath)
  316. return fmt.Errorf("config save: rename: %w", err)
  317. }
  318. return nil
  319. }
  320. func (c Config) Validate() error {
  321. if c.Audio.Gain < 0 || c.Audio.Gain > 4 {
  322. return fmt.Errorf("audio.gain out of range")
  323. }
  324. // BUG-B fix: only enforce positive freq when amplitude is non-zero.
  325. if c.Audio.ToneAmplitude > 0 && (c.Audio.ToneLeftHz <= 0 || c.Audio.ToneRightHz <= 0) {
  326. return fmt.Errorf("audio tone frequencies must be positive when toneAmplitude > 0")
  327. }
  328. if c.Audio.ToneAmplitude < 0 || c.Audio.ToneAmplitude > 1 {
  329. return fmt.Errorf("audio.toneAmplitude out of range")
  330. }
  331. if c.FM.FrequencyMHz < 65 || c.FM.FrequencyMHz > 110 {
  332. return fmt.Errorf("fm.frequencyMHz out of range")
  333. }
  334. if c.FM.PilotLevel < 0 || c.FM.PilotLevel > 0.2 {
  335. return fmt.Errorf("fm.pilotLevel out of range")
  336. }
  337. if c.FM.RDSInjection < 0 || c.FM.RDSInjection > 0.15 {
  338. return fmt.Errorf("fm.rdsInjection out of range")
  339. }
  340. if c.FM.OutputDrive < 0 || c.FM.OutputDrive > 10 {
  341. return fmt.Errorf("fm.outputDrive out of range (0..10)")
  342. }
  343. if c.FM.CompositeRateHz < 96000 || c.FM.CompositeRateHz > 1520000 {
  344. return fmt.Errorf("fm.compositeRateHz out of range")
  345. }
  346. if c.FM.PreEmphasisTauUS < 0 || c.FM.PreEmphasisTauUS > 100 {
  347. return fmt.Errorf("fm.preEmphasisTauUS out of range (0=off, 50=EU, 75=US)")
  348. }
  349. if c.FM.MaxDeviationHz < 0 || c.FM.MaxDeviationHz > 150000 {
  350. return fmt.Errorf("fm.maxDeviationHz out of range")
  351. }
  352. if c.FM.LimiterCeiling < 0 || c.FM.LimiterCeiling > 2 {
  353. return fmt.Errorf("fm.limiterCeiling out of range")
  354. }
  355. if c.FM.MpxGain < 0.1 || c.FM.MpxGain > 5 {
  356. return fmt.Errorf("fm.mpxGain out of range (0.1..5)")
  357. }
  358. if c.FM.CompositeClipper.Enabled {
  359. if c.FM.CompositeClipper.Iterations < 1 || c.FM.CompositeClipper.Iterations > 5 {
  360. return fmt.Errorf("fm.compositeClipper.iterations out of range (1-5)")
  361. }
  362. if c.FM.CompositeClipper.SoftKnee < 0 || c.FM.CompositeClipper.SoftKnee > 0.5 {
  363. return fmt.Errorf("fm.compositeClipper.softKnee out of range (0-0.5)")
  364. }
  365. if c.FM.CompositeClipper.LookaheadMs < 0 || c.FM.CompositeClipper.LookaheadMs > 5 {
  366. return fmt.Errorf("fm.compositeClipper.lookaheadMs out of range (0-5)")
  367. }
  368. }
  369. if c.Backend.Kind == "" {
  370. return fmt.Errorf("backend.kind is required")
  371. }
  372. if c.Backend.DeviceSampleRateHz < 0 {
  373. return fmt.Errorf("backend.deviceSampleRateHz must be >= 0")
  374. }
  375. if c.Control.ListenAddress == "" {
  376. return fmt.Errorf("control.listenAddress is required")
  377. }
  378. if c.Runtime.FrameQueueCapacity <= 0 {
  379. return fmt.Errorf("runtime.frameQueueCapacity must be > 0")
  380. }
  381. if c.Ingest.Kind == "" {
  382. c.Ingest.Kind = "none"
  383. }
  384. ingestKind := strings.ToLower(strings.TrimSpace(c.Ingest.Kind))
  385. switch ingestKind {
  386. case "none", "stdin", "stdin-pcm", "http-raw", "icecast", "srt", "aes67", "aoip", "aoip-rtp":
  387. default:
  388. return fmt.Errorf("ingest.kind unsupported: %s", c.Ingest.Kind)
  389. }
  390. if c.Ingest.PrebufferMs < 0 {
  391. return fmt.Errorf("ingest.prebufferMs must be >= 0")
  392. }
  393. if c.Ingest.StallTimeoutMs < 0 {
  394. return fmt.Errorf("ingest.stallTimeoutMs must be >= 0")
  395. }
  396. if c.Ingest.Reconnect.InitialBackoffMs < 0 || c.Ingest.Reconnect.MaxBackoffMs < 0 {
  397. return fmt.Errorf("ingest.reconnect backoff must be >= 0")
  398. }
  399. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.InitialBackoffMs <= 0 {
  400. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be > 0 when reconnect is enabled")
  401. }
  402. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.MaxBackoffMs <= 0 {
  403. return fmt.Errorf("ingest.reconnect.maxBackoffMs must be > 0 when reconnect is enabled")
  404. }
  405. if c.Ingest.Reconnect.MaxBackoffMs > 0 && c.Ingest.Reconnect.InitialBackoffMs > c.Ingest.Reconnect.MaxBackoffMs {
  406. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be <= maxBackoffMs")
  407. }
  408. if c.Ingest.Stdin.SampleRateHz <= 0 || c.Ingest.HTTPRaw.SampleRateHz <= 0 {
  409. return fmt.Errorf("ingest pcm sampleRateHz must be > 0")
  410. }
  411. if (c.Ingest.Stdin.Channels != 1 && c.Ingest.Stdin.Channels != 2) || (c.Ingest.HTTPRaw.Channels != 1 && c.Ingest.HTTPRaw.Channels != 2) {
  412. return fmt.Errorf("ingest pcm channels must be 1 or 2")
  413. }
  414. if strings.ToLower(strings.TrimSpace(c.Ingest.Stdin.Format)) != "s16le" || strings.ToLower(strings.TrimSpace(c.Ingest.HTTPRaw.Format)) != "s16le" {
  415. return fmt.Errorf("ingest pcm format must be s16le")
  416. }
  417. if ingestKind == "icecast" && strings.TrimSpace(c.Ingest.Icecast.URL) == "" {
  418. return fmt.Errorf("ingest.icecast.url is required when ingest.kind=icecast")
  419. }
  420. if ingestKind == "srt" && strings.TrimSpace(c.Ingest.SRT.URL) == "" {
  421. return fmt.Errorf("ingest.srt.url is required when ingest.kind=srt")
  422. }
  423. if ingestKind == "aes67" || ingestKind == "aoip" || ingestKind == "aoip-rtp" {
  424. hasSDP := strings.TrimSpace(c.Ingest.AES67.SDP) != ""
  425. hasSDPPath := strings.TrimSpace(c.Ingest.AES67.SDPPath) != ""
  426. discoveryEnabled := c.Ingest.AES67.Discovery.Enabled || strings.TrimSpace(c.Ingest.AES67.Discovery.StreamName) != ""
  427. if hasSDP && hasSDPPath {
  428. return fmt.Errorf("ingest.aes67.sdp and ingest.aes67.sdpPath are mutually exclusive")
  429. }
  430. if !hasSDP && !hasSDPPath {
  431. if strings.TrimSpace(c.Ingest.AES67.MulticastGroup) == "" && !discoveryEnabled {
  432. return fmt.Errorf("ingest.aes67.multicastGroup is required when ingest.kind=%s", ingestKind)
  433. }
  434. if (c.Ingest.AES67.Port <= 0 || c.Ingest.AES67.Port > 65535) && !discoveryEnabled {
  435. return fmt.Errorf("ingest.aes67.port must be 1..65535")
  436. }
  437. }
  438. if c.Ingest.AES67.Discovery.TimeoutMs < 0 {
  439. return fmt.Errorf("ingest.aes67.discovery.timeoutMs must be >= 0")
  440. }
  441. if c.Ingest.AES67.Discovery.SAPPort < 0 || c.Ingest.AES67.Discovery.SAPPort > 65535 {
  442. return fmt.Errorf("ingest.aes67.discovery.sapPort must be 0..65535")
  443. }
  444. if discoveryEnabled && strings.TrimSpace(c.Ingest.AES67.Discovery.StreamName) == "" {
  445. return fmt.Errorf("ingest.aes67.discovery.streamName is required when discovery is enabled")
  446. }
  447. if discoveryEnabled && c.Ingest.AES67.Port > 65535 {
  448. return fmt.Errorf("ingest.aes67.port must be 1..65535")
  449. }
  450. if c.Ingest.AES67.PayloadType < 0 || c.Ingest.AES67.PayloadType > 127 {
  451. return fmt.Errorf("ingest.aes67.payloadType must be 0..127")
  452. }
  453. if c.Ingest.AES67.SampleRateHz <= 0 {
  454. return fmt.Errorf("ingest.aes67.sampleRateHz must be > 0")
  455. }
  456. if c.Ingest.AES67.Channels != 1 && c.Ingest.AES67.Channels != 2 {
  457. return fmt.Errorf("ingest.aes67.channels must be 1 or 2")
  458. }
  459. if strings.ToUpper(strings.TrimSpace(c.Ingest.AES67.Encoding)) != "L24" {
  460. return fmt.Errorf("ingest.aes67.encoding must be L24")
  461. }
  462. if c.Ingest.AES67.PacketTimeMs <= 0 {
  463. return fmt.Errorf("ingest.aes67.packetTimeMs must be > 0")
  464. }
  465. if c.Ingest.AES67.JitterDepthPackets < 1 {
  466. return fmt.Errorf("ingest.aes67.jitterDepthPackets must be >= 1")
  467. }
  468. if c.Ingest.AES67.ReadBufferBytes < 0 {
  469. return fmt.Errorf("ingest.aes67.readBufferBytes must be >= 0")
  470. }
  471. }
  472. switch strings.ToLower(strings.TrimSpace(c.Ingest.SRT.Mode)) {
  473. case "", "listener", "caller", "rendezvous":
  474. default:
  475. return fmt.Errorf("ingest.srt.mode unsupported: %s", c.Ingest.SRT.Mode)
  476. }
  477. if c.Ingest.SRT.SampleRateHz <= 0 {
  478. return fmt.Errorf("ingest.srt.sampleRateHz must be > 0")
  479. }
  480. if c.Ingest.SRT.Channels != 1 && c.Ingest.SRT.Channels != 2 {
  481. return fmt.Errorf("ingest.srt.channels must be 1 or 2")
  482. }
  483. switch strings.ToLower(strings.TrimSpace(c.Ingest.Icecast.Decoder)) {
  484. case "", "auto", "native", "ffmpeg", "fallback":
  485. default:
  486. return fmt.Errorf("ingest.icecast.decoder unsupported: %s", c.Ingest.Icecast.Decoder)
  487. }
  488. if c.Ingest.Icecast.RadioText.MaxLen < 0 || c.Ingest.Icecast.RadioText.MaxLen > 64 {
  489. return fmt.Errorf("ingest.icecast.radioText.maxLen out of range (0-64)")
  490. }
  491. // BUG-D fix: validate PI whenever non-empty, not only when RDS is enabled.
  492. // An invalid PI stored in config causes a silent failure when RDS is later
  493. // enabled via live-patch.
  494. if strings.TrimSpace(c.RDS.PI) != "" {
  495. if _, err := ParsePI(c.RDS.PI); err != nil {
  496. return fmt.Errorf("rds config: %w", err)
  497. }
  498. } else if c.RDS.Enabled {
  499. return fmt.Errorf("rds.pi is required when rds.enabled is true")
  500. }
  501. if c.RDS.PTY < 0 || c.RDS.PTY > 31 {
  502. return fmt.Errorf("rds.pty out of range (0-31)")
  503. }
  504. if len(c.RDS.PS) > 8 {
  505. return fmt.Errorf("rds.ps must be <= 8 characters")
  506. }
  507. if len(c.RDS.RadioText) > 64 {
  508. return fmt.Errorf("rds.radioText must be <= 64 characters")
  509. }
  510. return nil
  511. }
  512. // EffectiveDeviceRate returns the device sample rate, falling back to composite rate.
  513. func (c Config) EffectiveDeviceRate() float64 {
  514. if c.Backend.DeviceSampleRateHz > 0 {
  515. return c.Backend.DeviceSampleRateHz
  516. }
  517. return float64(c.FM.CompositeRateHz)
  518. }