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.

337 line
11KB

  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. type Config struct {
  10. Audio AudioConfig `json:"audio"`
  11. RDS RDSConfig `json:"rds"`
  12. FM FMConfig `json:"fm"`
  13. Backend BackendConfig `json:"backend"`
  14. Control ControlConfig `json:"control"`
  15. Runtime RuntimeConfig `json:"runtime"`
  16. Ingest IngestConfig `json:"ingest"`
  17. }
  18. type AudioConfig struct {
  19. InputPath string `json:"inputPath"`
  20. Gain float64 `json:"gain"`
  21. ToneLeftHz float64 `json:"toneLeftHz"`
  22. ToneRightHz float64 `json:"toneRightHz"`
  23. ToneAmplitude float64 `json:"toneAmplitude"`
  24. }
  25. type RDSConfig struct {
  26. Enabled bool `json:"enabled"`
  27. PI string `json:"pi"`
  28. PS string `json:"ps"`
  29. RadioText string `json:"radioText"`
  30. PTY int `json:"pty"`
  31. }
  32. type FMConfig struct {
  33. FrequencyMHz float64 `json:"frequencyMHz"`
  34. StereoEnabled bool `json:"stereoEnabled"`
  35. PilotLevel float64 `json:"pilotLevel"` // fraction of ±75kHz deviation (0.09 = 9%, ITU standard)
  36. RDSInjection float64 `json:"rdsInjection"` // fraction of ±75kHz deviation (0.04 = 4%, typical)
  37. PreEmphasisTauUS float64 `json:"preEmphasisTauUS"` // time constant in µs: 50 (EU) or 75 (US), 0=off
  38. OutputDrive float64 `json:"outputDrive"`
  39. CompositeRateHz int `json:"compositeRateHz"` // internal DSP/MPX sample rate
  40. MaxDeviationHz float64 `json:"maxDeviationHz"`
  41. LimiterEnabled bool `json:"limiterEnabled"`
  42. LimiterCeiling float64 `json:"limiterCeiling"`
  43. FMModulationEnabled bool `json:"fmModulationEnabled"`
  44. MpxGain float64 `json:"mpxGain"` // hardware calibration: scales entire composite output (default 1.0)
  45. BS412Enabled bool `json:"bs412Enabled"` // ITU-R BS.412 MPX power limiter (EU requirement)
  46. BS412ThresholdDBr float64 `json:"bs412ThresholdDBr"` // power limit in dBr (0 = standard, +3 = relaxed)
  47. }
  48. type BackendConfig struct {
  49. Kind string `json:"kind"`
  50. Driver string `json:"driver,omitempty"`
  51. Device string `json:"device"`
  52. URI string `json:"uri,omitempty"`
  53. DeviceArgs map[string]string `json:"deviceArgs,omitempty"`
  54. OutputPath string `json:"outputPath"`
  55. DeviceSampleRateHz float64 `json:"deviceSampleRateHz"` // actual SDR device rate; 0 = same as compositeRateHz
  56. }
  57. type ControlConfig struct {
  58. ListenAddress string `json:"listenAddress"`
  59. }
  60. type RuntimeConfig struct {
  61. FrameQueueCapacity int `json:"frameQueueCapacity"`
  62. }
  63. type IngestConfig struct {
  64. Kind string `json:"kind"`
  65. PrebufferMs int `json:"prebufferMs"`
  66. StallTimeoutMs int `json:"stallTimeoutMs"`
  67. Reconnect IngestReconnectConfig `json:"reconnect"`
  68. Stdin IngestPCMConfig `json:"stdin"`
  69. HTTPRaw IngestPCMConfig `json:"httpRaw"`
  70. Icecast IngestIcecastConfig `json:"icecast"`
  71. SRT IngestSRTConfig `json:"srt"`
  72. }
  73. type IngestReconnectConfig struct {
  74. Enabled bool `json:"enabled"`
  75. InitialBackoffMs int `json:"initialBackoffMs"`
  76. MaxBackoffMs int `json:"maxBackoffMs"`
  77. }
  78. type IngestPCMConfig struct {
  79. SampleRateHz int `json:"sampleRateHz"`
  80. Channels int `json:"channels"`
  81. Format string `json:"format"`
  82. }
  83. type IngestIcecastConfig struct {
  84. URL string `json:"url"`
  85. Decoder string `json:"decoder"`
  86. RadioText IngestIcecastRadioTextConfig `json:"radioText"`
  87. }
  88. type IngestIcecastRadioTextConfig struct {
  89. Enabled bool `json:"enabled"`
  90. Prefix string `json:"prefix"`
  91. MaxLen int `json:"maxLen"`
  92. OnlyOnChange bool `json:"onlyOnChange"`
  93. }
  94. type IngestSRTConfig struct {
  95. URL string `json:"url"`
  96. Mode string `json:"mode"`
  97. SampleRateHz int `json:"sampleRateHz"`
  98. Channels int `json:"channels"`
  99. }
  100. func Default() Config {
  101. return Config{
  102. Audio: AudioConfig{Gain: 1.0, ToneLeftHz: 1000, ToneRightHz: 1600, ToneAmplitude: 0.4},
  103. RDS: RDSConfig{Enabled: true, PI: "1234", PS: "FMRTX", RadioText: "fm-rds-tx", PTY: 0},
  104. FM: FMConfig{
  105. FrequencyMHz: 100.0,
  106. StereoEnabled: true,
  107. PilotLevel: 0.09,
  108. RDSInjection: 0.04,
  109. PreEmphasisTauUS: 50,
  110. OutputDrive: 0.5,
  111. CompositeRateHz: 228000,
  112. MaxDeviationHz: 75000,
  113. LimiterEnabled: true,
  114. LimiterCeiling: 1.0,
  115. FMModulationEnabled: true,
  116. MpxGain: 1.0,
  117. },
  118. Backend: BackendConfig{Kind: "file", OutputPath: "build/out/composite.f32"},
  119. Control: ControlConfig{ListenAddress: "127.0.0.1:8088"},
  120. Runtime: RuntimeConfig{FrameQueueCapacity: 3},
  121. Ingest: IngestConfig{
  122. Kind: "none",
  123. PrebufferMs: 1500,
  124. StallTimeoutMs: 3000,
  125. Reconnect: IngestReconnectConfig{
  126. Enabled: true,
  127. InitialBackoffMs: 1000,
  128. MaxBackoffMs: 15000,
  129. },
  130. Stdin: IngestPCMConfig{
  131. SampleRateHz: 44100,
  132. Channels: 2,
  133. Format: "s16le",
  134. },
  135. HTTPRaw: IngestPCMConfig{
  136. SampleRateHz: 44100,
  137. Channels: 2,
  138. Format: "s16le",
  139. },
  140. Icecast: IngestIcecastConfig{
  141. Decoder: "auto",
  142. RadioText: IngestIcecastRadioTextConfig{
  143. Enabled: false,
  144. MaxLen: 64,
  145. OnlyOnChange: true,
  146. },
  147. },
  148. SRT: IngestSRTConfig{
  149. Mode: "listener",
  150. SampleRateHz: 48000,
  151. Channels: 2,
  152. },
  153. },
  154. }
  155. }
  156. // ParsePI parses a hex PI code string. Returns an error for invalid input.
  157. func ParsePI(pi string) (uint16, error) {
  158. trimmed := strings.TrimSpace(pi)
  159. if trimmed == "" {
  160. return 0, fmt.Errorf("rds.pi is required")
  161. }
  162. trimmed = strings.TrimPrefix(trimmed, "0x")
  163. trimmed = strings.TrimPrefix(trimmed, "0X")
  164. v, err := strconv.ParseUint(trimmed, 16, 16)
  165. if err != nil {
  166. return 0, fmt.Errorf("invalid rds.pi: %q", pi)
  167. }
  168. return uint16(v), nil
  169. }
  170. func Load(path string) (Config, error) {
  171. cfg := Default()
  172. if path == "" {
  173. return cfg, cfg.Validate()
  174. }
  175. data, err := os.ReadFile(path)
  176. if err != nil {
  177. return Config{}, err
  178. }
  179. if err := json.Unmarshal(data, &cfg); err != nil {
  180. return Config{}, err
  181. }
  182. return cfg, cfg.Validate()
  183. }
  184. func (c Config) Validate() error {
  185. if c.Audio.Gain < 0 || c.Audio.Gain > 4 {
  186. return fmt.Errorf("audio.gain out of range")
  187. }
  188. if c.Audio.ToneLeftHz <= 0 || c.Audio.ToneRightHz <= 0 {
  189. return fmt.Errorf("audio tone frequencies must be positive")
  190. }
  191. if c.Audio.ToneAmplitude < 0 || c.Audio.ToneAmplitude > 1 {
  192. return fmt.Errorf("audio.toneAmplitude out of range")
  193. }
  194. if c.FM.FrequencyMHz < 65 || c.FM.FrequencyMHz > 110 {
  195. return fmt.Errorf("fm.frequencyMHz out of range")
  196. }
  197. if c.FM.PilotLevel < 0 || c.FM.PilotLevel > 0.2 {
  198. return fmt.Errorf("fm.pilotLevel out of range")
  199. }
  200. if c.FM.RDSInjection < 0 || c.FM.RDSInjection > 0.15 {
  201. return fmt.Errorf("fm.rdsInjection out of range")
  202. }
  203. if c.FM.OutputDrive < 0 || c.FM.OutputDrive > 10 {
  204. return fmt.Errorf("fm.outputDrive out of range (0..10)")
  205. }
  206. if c.FM.CompositeRateHz < 96000 || c.FM.CompositeRateHz > 1520000 {
  207. return fmt.Errorf("fm.compositeRateHz out of range")
  208. }
  209. if c.FM.PreEmphasisTauUS < 0 || c.FM.PreEmphasisTauUS > 100 {
  210. return fmt.Errorf("fm.preEmphasisTauUS out of range (0=off, 50=EU, 75=US)")
  211. }
  212. if c.FM.MaxDeviationHz < 0 || c.FM.MaxDeviationHz > 150000 {
  213. return fmt.Errorf("fm.maxDeviationHz out of range")
  214. }
  215. if c.FM.LimiterCeiling < 0 || c.FM.LimiterCeiling > 2 {
  216. return fmt.Errorf("fm.limiterCeiling out of range")
  217. }
  218. if c.FM.MpxGain < 0.1 || c.FM.MpxGain > 5 {
  219. return fmt.Errorf("fm.mpxGain out of range (0.1..5)")
  220. }
  221. if c.Backend.Kind == "" {
  222. return fmt.Errorf("backend.kind is required")
  223. }
  224. if c.Backend.DeviceSampleRateHz < 0 {
  225. return fmt.Errorf("backend.deviceSampleRateHz must be >= 0")
  226. }
  227. if c.Control.ListenAddress == "" {
  228. return fmt.Errorf("control.listenAddress is required")
  229. }
  230. if c.Runtime.FrameQueueCapacity <= 0 {
  231. return fmt.Errorf("runtime.frameQueueCapacity must be > 0")
  232. }
  233. if c.Ingest.Kind == "" {
  234. c.Ingest.Kind = "none"
  235. }
  236. ingestKind := strings.ToLower(strings.TrimSpace(c.Ingest.Kind))
  237. switch ingestKind {
  238. case "none", "stdin", "stdin-pcm", "http-raw", "icecast", "srt":
  239. default:
  240. return fmt.Errorf("ingest.kind unsupported: %s", c.Ingest.Kind)
  241. }
  242. if c.Ingest.PrebufferMs < 0 {
  243. return fmt.Errorf("ingest.prebufferMs must be >= 0")
  244. }
  245. if c.Ingest.StallTimeoutMs < 0 {
  246. return fmt.Errorf("ingest.stallTimeoutMs must be >= 0")
  247. }
  248. if c.Ingest.Reconnect.InitialBackoffMs < 0 || c.Ingest.Reconnect.MaxBackoffMs < 0 {
  249. return fmt.Errorf("ingest.reconnect backoff must be >= 0")
  250. }
  251. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.InitialBackoffMs <= 0 {
  252. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be > 0 when reconnect is enabled")
  253. }
  254. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.MaxBackoffMs <= 0 {
  255. return fmt.Errorf("ingest.reconnect.maxBackoffMs must be > 0 when reconnect is enabled")
  256. }
  257. if c.Ingest.Reconnect.MaxBackoffMs > 0 && c.Ingest.Reconnect.InitialBackoffMs > c.Ingest.Reconnect.MaxBackoffMs {
  258. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be <= maxBackoffMs")
  259. }
  260. if c.Ingest.Stdin.SampleRateHz <= 0 || c.Ingest.HTTPRaw.SampleRateHz <= 0 {
  261. return fmt.Errorf("ingest pcm sampleRateHz must be > 0")
  262. }
  263. if (c.Ingest.Stdin.Channels != 1 && c.Ingest.Stdin.Channels != 2) || (c.Ingest.HTTPRaw.Channels != 1 && c.Ingest.HTTPRaw.Channels != 2) {
  264. return fmt.Errorf("ingest pcm channels must be 1 or 2")
  265. }
  266. if strings.ToLower(strings.TrimSpace(c.Ingest.Stdin.Format)) != "s16le" || strings.ToLower(strings.TrimSpace(c.Ingest.HTTPRaw.Format)) != "s16le" {
  267. return fmt.Errorf("ingest pcm format must be s16le")
  268. }
  269. if ingestKind == "icecast" && strings.TrimSpace(c.Ingest.Icecast.URL) == "" {
  270. return fmt.Errorf("ingest.icecast.url is required when ingest.kind=icecast")
  271. }
  272. if ingestKind == "srt" && strings.TrimSpace(c.Ingest.SRT.URL) == "" {
  273. return fmt.Errorf("ingest.srt.url is required when ingest.kind=srt")
  274. }
  275. switch strings.ToLower(strings.TrimSpace(c.Ingest.SRT.Mode)) {
  276. case "", "listener", "caller", "rendezvous":
  277. default:
  278. return fmt.Errorf("ingest.srt.mode unsupported: %s", c.Ingest.SRT.Mode)
  279. }
  280. if c.Ingest.SRT.SampleRateHz <= 0 {
  281. return fmt.Errorf("ingest.srt.sampleRateHz must be > 0")
  282. }
  283. if c.Ingest.SRT.Channels != 1 && c.Ingest.SRT.Channels != 2 {
  284. return fmt.Errorf("ingest.srt.channels must be 1 or 2")
  285. }
  286. switch strings.ToLower(strings.TrimSpace(c.Ingest.Icecast.Decoder)) {
  287. case "", "auto", "native", "ffmpeg", "fallback":
  288. default:
  289. return fmt.Errorf("ingest.icecast.decoder unsupported: %s", c.Ingest.Icecast.Decoder)
  290. }
  291. if c.Ingest.Icecast.RadioText.MaxLen < 0 || c.Ingest.Icecast.RadioText.MaxLen > 64 {
  292. return fmt.Errorf("ingest.icecast.radioText.maxLen out of range (0-64)")
  293. }
  294. // Fail-loud PI validation
  295. if c.RDS.Enabled {
  296. if _, err := ParsePI(c.RDS.PI); err != nil {
  297. return fmt.Errorf("rds config: %w", err)
  298. }
  299. }
  300. if c.RDS.PTY < 0 || c.RDS.PTY > 31 {
  301. return fmt.Errorf("rds.pty out of range (0-31)")
  302. }
  303. if len(c.RDS.PS) > 8 {
  304. return fmt.Errorf("rds.ps must be <= 8 characters")
  305. }
  306. if len(c.RDS.RadioText) > 64 {
  307. return fmt.Errorf("rds.radioText must be <= 64 characters")
  308. }
  309. return nil
  310. }
  311. // EffectiveDeviceRate returns the device sample rate, falling back to composite rate.
  312. func (c Config) EffectiveDeviceRate() float64 {
  313. if c.Backend.DeviceSampleRateHz > 0 {
  314. return c.Backend.DeviceSampleRateHz
  315. }
  316. return float64(c.FM.CompositeRateHz)
  317. }