Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

568 líneas
21KB

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