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.

309 linhas
10KB

  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. }
  72. type IngestReconnectConfig struct {
  73. Enabled bool `json:"enabled"`
  74. InitialBackoffMs int `json:"initialBackoffMs"`
  75. MaxBackoffMs int `json:"maxBackoffMs"`
  76. }
  77. type IngestPCMConfig struct {
  78. SampleRateHz int `json:"sampleRateHz"`
  79. Channels int `json:"channels"`
  80. Format string `json:"format"`
  81. }
  82. type IngestIcecastConfig struct {
  83. URL string `json:"url"`
  84. Decoder string `json:"decoder"`
  85. RadioText IngestIcecastRadioTextConfig `json:"radioText"`
  86. }
  87. type IngestIcecastRadioTextConfig struct {
  88. Enabled bool `json:"enabled"`
  89. Prefix string `json:"prefix"`
  90. MaxLen int `json:"maxLen"`
  91. OnlyOnChange bool `json:"onlyOnChange"`
  92. }
  93. func Default() Config {
  94. return Config{
  95. Audio: AudioConfig{Gain: 1.0, ToneLeftHz: 1000, ToneRightHz: 1600, ToneAmplitude: 0.4},
  96. RDS: RDSConfig{Enabled: true, PI: "1234", PS: "FMRTX", RadioText: "fm-rds-tx", PTY: 0},
  97. FM: FMConfig{
  98. FrequencyMHz: 100.0,
  99. StereoEnabled: true,
  100. PilotLevel: 0.09,
  101. RDSInjection: 0.04,
  102. PreEmphasisTauUS: 50,
  103. OutputDrive: 0.5,
  104. CompositeRateHz: 228000,
  105. MaxDeviationHz: 75000,
  106. LimiterEnabled: true,
  107. LimiterCeiling: 1.0,
  108. FMModulationEnabled: true,
  109. MpxGain: 1.0,
  110. },
  111. Backend: BackendConfig{Kind: "file", OutputPath: "build/out/composite.f32"},
  112. Control: ControlConfig{ListenAddress: "127.0.0.1:8088"},
  113. Runtime: RuntimeConfig{FrameQueueCapacity: 3},
  114. Ingest: IngestConfig{
  115. Kind: "none",
  116. PrebufferMs: 1500,
  117. StallTimeoutMs: 3000,
  118. Reconnect: IngestReconnectConfig{
  119. Enabled: true,
  120. InitialBackoffMs: 1000,
  121. MaxBackoffMs: 15000,
  122. },
  123. Stdin: IngestPCMConfig{
  124. SampleRateHz: 44100,
  125. Channels: 2,
  126. Format: "s16le",
  127. },
  128. HTTPRaw: IngestPCMConfig{
  129. SampleRateHz: 44100,
  130. Channels: 2,
  131. Format: "s16le",
  132. },
  133. Icecast: IngestIcecastConfig{
  134. Decoder: "auto",
  135. RadioText: IngestIcecastRadioTextConfig{
  136. Enabled: false,
  137. MaxLen: 64,
  138. OnlyOnChange: true,
  139. },
  140. },
  141. },
  142. }
  143. }
  144. // ParsePI parses a hex PI code string. Returns an error for invalid input.
  145. func ParsePI(pi string) (uint16, error) {
  146. trimmed := strings.TrimSpace(pi)
  147. if trimmed == "" {
  148. return 0, fmt.Errorf("rds.pi is required")
  149. }
  150. trimmed = strings.TrimPrefix(trimmed, "0x")
  151. trimmed = strings.TrimPrefix(trimmed, "0X")
  152. v, err := strconv.ParseUint(trimmed, 16, 16)
  153. if err != nil {
  154. return 0, fmt.Errorf("invalid rds.pi: %q", pi)
  155. }
  156. return uint16(v), nil
  157. }
  158. func Load(path string) (Config, error) {
  159. cfg := Default()
  160. if path == "" {
  161. return cfg, cfg.Validate()
  162. }
  163. data, err := os.ReadFile(path)
  164. if err != nil {
  165. return Config{}, err
  166. }
  167. if err := json.Unmarshal(data, &cfg); err != nil {
  168. return Config{}, err
  169. }
  170. return cfg, cfg.Validate()
  171. }
  172. func (c Config) Validate() error {
  173. if c.Audio.Gain < 0 || c.Audio.Gain > 4 {
  174. return fmt.Errorf("audio.gain out of range")
  175. }
  176. if c.Audio.ToneLeftHz <= 0 || c.Audio.ToneRightHz <= 0 {
  177. return fmt.Errorf("audio tone frequencies must be positive")
  178. }
  179. if c.Audio.ToneAmplitude < 0 || c.Audio.ToneAmplitude > 1 {
  180. return fmt.Errorf("audio.toneAmplitude out of range")
  181. }
  182. if c.FM.FrequencyMHz < 65 || c.FM.FrequencyMHz > 110 {
  183. return fmt.Errorf("fm.frequencyMHz out of range")
  184. }
  185. if c.FM.PilotLevel < 0 || c.FM.PilotLevel > 0.2 {
  186. return fmt.Errorf("fm.pilotLevel out of range")
  187. }
  188. if c.FM.RDSInjection < 0 || c.FM.RDSInjection > 0.15 {
  189. return fmt.Errorf("fm.rdsInjection out of range")
  190. }
  191. if c.FM.OutputDrive < 0 || c.FM.OutputDrive > 10 {
  192. return fmt.Errorf("fm.outputDrive out of range (0..10)")
  193. }
  194. if c.FM.CompositeRateHz < 96000 || c.FM.CompositeRateHz > 1520000 {
  195. return fmt.Errorf("fm.compositeRateHz out of range")
  196. }
  197. if c.FM.PreEmphasisTauUS < 0 || c.FM.PreEmphasisTauUS > 100 {
  198. return fmt.Errorf("fm.preEmphasisTauUS out of range (0=off, 50=EU, 75=US)")
  199. }
  200. if c.FM.MaxDeviationHz < 0 || c.FM.MaxDeviationHz > 150000 {
  201. return fmt.Errorf("fm.maxDeviationHz out of range")
  202. }
  203. if c.FM.LimiterCeiling < 0 || c.FM.LimiterCeiling > 2 {
  204. return fmt.Errorf("fm.limiterCeiling out of range")
  205. }
  206. if c.FM.MpxGain < 0.1 || c.FM.MpxGain > 5 {
  207. return fmt.Errorf("fm.mpxGain out of range (0.1..5)")
  208. }
  209. if c.Backend.Kind == "" {
  210. return fmt.Errorf("backend.kind is required")
  211. }
  212. if c.Backend.DeviceSampleRateHz < 0 {
  213. return fmt.Errorf("backend.deviceSampleRateHz must be >= 0")
  214. }
  215. if c.Control.ListenAddress == "" {
  216. return fmt.Errorf("control.listenAddress is required")
  217. }
  218. if c.Runtime.FrameQueueCapacity <= 0 {
  219. return fmt.Errorf("runtime.frameQueueCapacity must be > 0")
  220. }
  221. if c.Ingest.Kind == "" {
  222. c.Ingest.Kind = "none"
  223. }
  224. switch strings.ToLower(strings.TrimSpace(c.Ingest.Kind)) {
  225. case "none", "stdin", "stdin-pcm", "http-raw", "icecast":
  226. default:
  227. return fmt.Errorf("ingest.kind unsupported: %s", c.Ingest.Kind)
  228. }
  229. if c.Ingest.PrebufferMs < 0 {
  230. return fmt.Errorf("ingest.prebufferMs must be >= 0")
  231. }
  232. if c.Ingest.StallTimeoutMs < 0 {
  233. return fmt.Errorf("ingest.stallTimeoutMs must be >= 0")
  234. }
  235. if c.Ingest.Reconnect.InitialBackoffMs < 0 || c.Ingest.Reconnect.MaxBackoffMs < 0 {
  236. return fmt.Errorf("ingest.reconnect backoff must be >= 0")
  237. }
  238. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.InitialBackoffMs <= 0 {
  239. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be > 0 when reconnect is enabled")
  240. }
  241. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.MaxBackoffMs <= 0 {
  242. return fmt.Errorf("ingest.reconnect.maxBackoffMs must be > 0 when reconnect is enabled")
  243. }
  244. if c.Ingest.Reconnect.MaxBackoffMs > 0 && c.Ingest.Reconnect.InitialBackoffMs > c.Ingest.Reconnect.MaxBackoffMs {
  245. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be <= maxBackoffMs")
  246. }
  247. if c.Ingest.Stdin.SampleRateHz <= 0 || c.Ingest.HTTPRaw.SampleRateHz <= 0 {
  248. return fmt.Errorf("ingest pcm sampleRateHz must be > 0")
  249. }
  250. if (c.Ingest.Stdin.Channels != 1 && c.Ingest.Stdin.Channels != 2) || (c.Ingest.HTTPRaw.Channels != 1 && c.Ingest.HTTPRaw.Channels != 2) {
  251. return fmt.Errorf("ingest pcm channels must be 1 or 2")
  252. }
  253. if strings.ToLower(strings.TrimSpace(c.Ingest.Stdin.Format)) != "s16le" || strings.ToLower(strings.TrimSpace(c.Ingest.HTTPRaw.Format)) != "s16le" {
  254. return fmt.Errorf("ingest pcm format must be s16le")
  255. }
  256. if c.Ingest.Kind == "icecast" && strings.TrimSpace(c.Ingest.Icecast.URL) == "" {
  257. return fmt.Errorf("ingest.icecast.url is required when ingest.kind=icecast")
  258. }
  259. switch strings.ToLower(strings.TrimSpace(c.Ingest.Icecast.Decoder)) {
  260. case "", "auto", "native", "ffmpeg", "fallback":
  261. default:
  262. return fmt.Errorf("ingest.icecast.decoder unsupported: %s", c.Ingest.Icecast.Decoder)
  263. }
  264. if c.Ingest.Icecast.RadioText.MaxLen < 0 || c.Ingest.Icecast.RadioText.MaxLen > 64 {
  265. return fmt.Errorf("ingest.icecast.radioText.maxLen out of range (0-64)")
  266. }
  267. // Fail-loud PI validation
  268. if c.RDS.Enabled {
  269. if _, err := ParsePI(c.RDS.PI); err != nil {
  270. return fmt.Errorf("rds config: %w", err)
  271. }
  272. }
  273. if c.RDS.PTY < 0 || c.RDS.PTY > 31 {
  274. return fmt.Errorf("rds.pty out of range (0-31)")
  275. }
  276. if len(c.RDS.PS) > 8 {
  277. return fmt.Errorf("rds.ps must be <= 8 characters")
  278. }
  279. if len(c.RDS.RadioText) > 64 {
  280. return fmt.Errorf("rds.radioText must be <= 64 characters")
  281. }
  282. return nil
  283. }
  284. // EffectiveDeviceRate returns the device sample rate, falling back to composite rate.
  285. func (c Config) EffectiveDeviceRate() float64 {
  286. if c.Backend.DeviceSampleRateHz > 0 {
  287. return c.Backend.DeviceSampleRateHz
  288. }
  289. return float64(c.FM.CompositeRateHz)
  290. }