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.

439 linhas
15KB

  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. AES67 IngestAES67Config `json:"aes67"`
  73. }
  74. type IngestReconnectConfig struct {
  75. Enabled bool `json:"enabled"`
  76. InitialBackoffMs int `json:"initialBackoffMs"`
  77. MaxBackoffMs int `json:"maxBackoffMs"`
  78. }
  79. type IngestPCMConfig struct {
  80. SampleRateHz int `json:"sampleRateHz"`
  81. Channels int `json:"channels"`
  82. Format string `json:"format"`
  83. }
  84. type IngestIcecastConfig struct {
  85. URL string `json:"url"`
  86. Decoder string `json:"decoder"`
  87. RadioText IngestIcecastRadioTextConfig `json:"radioText"`
  88. }
  89. type IngestIcecastRadioTextConfig struct {
  90. Enabled bool `json:"enabled"`
  91. Prefix string `json:"prefix"`
  92. MaxLen int `json:"maxLen"`
  93. OnlyOnChange bool `json:"onlyOnChange"`
  94. }
  95. type IngestSRTConfig struct {
  96. URL string `json:"url"`
  97. Mode string `json:"mode"`
  98. SampleRateHz int `json:"sampleRateHz"`
  99. Channels int `json:"channels"`
  100. }
  101. type IngestAES67Config struct {
  102. SDPPath string `json:"sdpPath"`
  103. SDP string `json:"sdp"`
  104. Discovery IngestAES67DiscoveryConfig `json:"discovery"`
  105. MulticastGroup string `json:"multicastGroup"`
  106. Port int `json:"port"`
  107. InterfaceName string `json:"interfaceName"`
  108. PayloadType int `json:"payloadType"`
  109. SampleRateHz int `json:"sampleRateHz"`
  110. Channels int `json:"channels"`
  111. Encoding string `json:"encoding"`
  112. PacketTimeMs int `json:"packetTimeMs"`
  113. JitterDepthPackets int `json:"jitterDepthPackets"`
  114. ReadBufferBytes int `json:"readBufferBytes"`
  115. }
  116. type IngestAES67DiscoveryConfig struct {
  117. Enabled bool `json:"enabled"`
  118. StreamName string `json:"streamName"`
  119. TimeoutMs int `json:"timeoutMs"`
  120. InterfaceName string `json:"interfaceName"`
  121. SAPGroup string `json:"sapGroup"`
  122. SAPPort int `json:"sapPort"`
  123. }
  124. func Default() Config {
  125. return Config{
  126. Audio: AudioConfig{Gain: 1.0, ToneLeftHz: 1000, ToneRightHz: 1600, ToneAmplitude: 0.4},
  127. RDS: RDSConfig{Enabled: true, PI: "1234", PS: "FMRTX", RadioText: "fm-rds-tx", PTY: 0},
  128. FM: FMConfig{
  129. FrequencyMHz: 100.0,
  130. StereoEnabled: true,
  131. PilotLevel: 0.09,
  132. RDSInjection: 0.04,
  133. PreEmphasisTauUS: 50,
  134. OutputDrive: 0.5,
  135. CompositeRateHz: 228000,
  136. MaxDeviationHz: 75000,
  137. LimiterEnabled: true,
  138. LimiterCeiling: 1.0,
  139. FMModulationEnabled: true,
  140. MpxGain: 1.0,
  141. },
  142. Backend: BackendConfig{Kind: "file", OutputPath: "build/out/composite.f32"},
  143. Control: ControlConfig{ListenAddress: "127.0.0.1:8088"},
  144. Runtime: RuntimeConfig{FrameQueueCapacity: 3},
  145. Ingest: IngestConfig{
  146. Kind: "none",
  147. PrebufferMs: 1500,
  148. StallTimeoutMs: 3000,
  149. Reconnect: IngestReconnectConfig{
  150. Enabled: true,
  151. InitialBackoffMs: 1000,
  152. MaxBackoffMs: 15000,
  153. },
  154. Stdin: IngestPCMConfig{
  155. SampleRateHz: 44100,
  156. Channels: 2,
  157. Format: "s16le",
  158. },
  159. HTTPRaw: IngestPCMConfig{
  160. SampleRateHz: 44100,
  161. Channels: 2,
  162. Format: "s16le",
  163. },
  164. Icecast: IngestIcecastConfig{
  165. Decoder: "auto",
  166. RadioText: IngestIcecastRadioTextConfig{
  167. Enabled: false,
  168. MaxLen: 64,
  169. OnlyOnChange: true,
  170. },
  171. },
  172. SRT: IngestSRTConfig{
  173. Mode: "listener",
  174. SampleRateHz: 48000,
  175. Channels: 2,
  176. },
  177. AES67: IngestAES67Config{
  178. Discovery: IngestAES67DiscoveryConfig{
  179. TimeoutMs: 3000,
  180. },
  181. PayloadType: 97,
  182. SampleRateHz: 48000,
  183. Channels: 2,
  184. Encoding: "L24",
  185. PacketTimeMs: 1,
  186. JitterDepthPackets: 8,
  187. ReadBufferBytes: 1 << 20,
  188. },
  189. },
  190. }
  191. }
  192. // ParsePI parses a hex PI code string. Returns an error for invalid input.
  193. func ParsePI(pi string) (uint16, error) {
  194. trimmed := strings.TrimSpace(pi)
  195. if trimmed == "" {
  196. return 0, fmt.Errorf("rds.pi is required")
  197. }
  198. trimmed = strings.TrimPrefix(trimmed, "0x")
  199. trimmed = strings.TrimPrefix(trimmed, "0X")
  200. v, err := strconv.ParseUint(trimmed, 16, 16)
  201. if err != nil {
  202. return 0, fmt.Errorf("invalid rds.pi: %q", pi)
  203. }
  204. return uint16(v), nil
  205. }
  206. func Load(path string) (Config, error) {
  207. cfg := Default()
  208. if path == "" {
  209. return cfg, cfg.Validate()
  210. }
  211. data, err := os.ReadFile(path)
  212. if err != nil {
  213. return Config{}, err
  214. }
  215. if err := json.Unmarshal(data, &cfg); err != nil {
  216. return Config{}, err
  217. }
  218. return cfg, cfg.Validate()
  219. }
  220. func Save(path string, cfg Config) error {
  221. if strings.TrimSpace(path) == "" {
  222. return fmt.Errorf("config path is required")
  223. }
  224. if err := cfg.Validate(); err != nil {
  225. return err
  226. }
  227. data, err := json.MarshalIndent(cfg, "", " ")
  228. if err != nil {
  229. return err
  230. }
  231. data = append(data, '\n')
  232. return os.WriteFile(path, data, 0o644)
  233. }
  234. func (c Config) Validate() error {
  235. if c.Audio.Gain < 0 || c.Audio.Gain > 4 {
  236. return fmt.Errorf("audio.gain out of range")
  237. }
  238. if c.Audio.ToneLeftHz <= 0 || c.Audio.ToneRightHz <= 0 {
  239. return fmt.Errorf("audio tone frequencies must be positive")
  240. }
  241. if c.Audio.ToneAmplitude < 0 || c.Audio.ToneAmplitude > 1 {
  242. return fmt.Errorf("audio.toneAmplitude out of range")
  243. }
  244. if c.FM.FrequencyMHz < 65 || c.FM.FrequencyMHz > 110 {
  245. return fmt.Errorf("fm.frequencyMHz out of range")
  246. }
  247. if c.FM.PilotLevel < 0 || c.FM.PilotLevel > 0.2 {
  248. return fmt.Errorf("fm.pilotLevel out of range")
  249. }
  250. if c.FM.RDSInjection < 0 || c.FM.RDSInjection > 0.15 {
  251. return fmt.Errorf("fm.rdsInjection out of range")
  252. }
  253. if c.FM.OutputDrive < 0 || c.FM.OutputDrive > 10 {
  254. return fmt.Errorf("fm.outputDrive out of range (0..10)")
  255. }
  256. if c.FM.CompositeRateHz < 96000 || c.FM.CompositeRateHz > 1520000 {
  257. return fmt.Errorf("fm.compositeRateHz out of range")
  258. }
  259. if c.FM.PreEmphasisTauUS < 0 || c.FM.PreEmphasisTauUS > 100 {
  260. return fmt.Errorf("fm.preEmphasisTauUS out of range (0=off, 50=EU, 75=US)")
  261. }
  262. if c.FM.MaxDeviationHz < 0 || c.FM.MaxDeviationHz > 150000 {
  263. return fmt.Errorf("fm.maxDeviationHz out of range")
  264. }
  265. if c.FM.LimiterCeiling < 0 || c.FM.LimiterCeiling > 2 {
  266. return fmt.Errorf("fm.limiterCeiling out of range")
  267. }
  268. if c.FM.MpxGain < 0.1 || c.FM.MpxGain > 5 {
  269. return fmt.Errorf("fm.mpxGain out of range (0.1..5)")
  270. }
  271. if c.Backend.Kind == "" {
  272. return fmt.Errorf("backend.kind is required")
  273. }
  274. if c.Backend.DeviceSampleRateHz < 0 {
  275. return fmt.Errorf("backend.deviceSampleRateHz must be >= 0")
  276. }
  277. if c.Control.ListenAddress == "" {
  278. return fmt.Errorf("control.listenAddress is required")
  279. }
  280. if c.Runtime.FrameQueueCapacity <= 0 {
  281. return fmt.Errorf("runtime.frameQueueCapacity must be > 0")
  282. }
  283. if c.Ingest.Kind == "" {
  284. c.Ingest.Kind = "none"
  285. }
  286. ingestKind := strings.ToLower(strings.TrimSpace(c.Ingest.Kind))
  287. switch ingestKind {
  288. case "none", "stdin", "stdin-pcm", "http-raw", "icecast", "srt", "aes67", "aoip", "aoip-rtp":
  289. default:
  290. return fmt.Errorf("ingest.kind unsupported: %s", c.Ingest.Kind)
  291. }
  292. if c.Ingest.PrebufferMs < 0 {
  293. return fmt.Errorf("ingest.prebufferMs must be >= 0")
  294. }
  295. if c.Ingest.StallTimeoutMs < 0 {
  296. return fmt.Errorf("ingest.stallTimeoutMs must be >= 0")
  297. }
  298. if c.Ingest.Reconnect.InitialBackoffMs < 0 || c.Ingest.Reconnect.MaxBackoffMs < 0 {
  299. return fmt.Errorf("ingest.reconnect backoff must be >= 0")
  300. }
  301. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.InitialBackoffMs <= 0 {
  302. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be > 0 when reconnect is enabled")
  303. }
  304. if c.Ingest.Reconnect.Enabled && c.Ingest.Reconnect.MaxBackoffMs <= 0 {
  305. return fmt.Errorf("ingest.reconnect.maxBackoffMs must be > 0 when reconnect is enabled")
  306. }
  307. if c.Ingest.Reconnect.MaxBackoffMs > 0 && c.Ingest.Reconnect.InitialBackoffMs > c.Ingest.Reconnect.MaxBackoffMs {
  308. return fmt.Errorf("ingest.reconnect.initialBackoffMs must be <= maxBackoffMs")
  309. }
  310. if c.Ingest.Stdin.SampleRateHz <= 0 || c.Ingest.HTTPRaw.SampleRateHz <= 0 {
  311. return fmt.Errorf("ingest pcm sampleRateHz must be > 0")
  312. }
  313. if (c.Ingest.Stdin.Channels != 1 && c.Ingest.Stdin.Channels != 2) || (c.Ingest.HTTPRaw.Channels != 1 && c.Ingest.HTTPRaw.Channels != 2) {
  314. return fmt.Errorf("ingest pcm channels must be 1 or 2")
  315. }
  316. if strings.ToLower(strings.TrimSpace(c.Ingest.Stdin.Format)) != "s16le" || strings.ToLower(strings.TrimSpace(c.Ingest.HTTPRaw.Format)) != "s16le" {
  317. return fmt.Errorf("ingest pcm format must be s16le")
  318. }
  319. if ingestKind == "icecast" && strings.TrimSpace(c.Ingest.Icecast.URL) == "" {
  320. return fmt.Errorf("ingest.icecast.url is required when ingest.kind=icecast")
  321. }
  322. if ingestKind == "srt" && strings.TrimSpace(c.Ingest.SRT.URL) == "" {
  323. return fmt.Errorf("ingest.srt.url is required when ingest.kind=srt")
  324. }
  325. if ingestKind == "aes67" || ingestKind == "aoip" || ingestKind == "aoip-rtp" {
  326. hasSDP := strings.TrimSpace(c.Ingest.AES67.SDP) != ""
  327. hasSDPPath := strings.TrimSpace(c.Ingest.AES67.SDPPath) != ""
  328. discoveryEnabled := c.Ingest.AES67.Discovery.Enabled || strings.TrimSpace(c.Ingest.AES67.Discovery.StreamName) != ""
  329. if hasSDP && hasSDPPath {
  330. return fmt.Errorf("ingest.aes67.sdp and ingest.aes67.sdpPath are mutually exclusive")
  331. }
  332. if !hasSDP && !hasSDPPath {
  333. if strings.TrimSpace(c.Ingest.AES67.MulticastGroup) == "" && !discoveryEnabled {
  334. return fmt.Errorf("ingest.aes67.multicastGroup is required when ingest.kind=%s", ingestKind)
  335. }
  336. if (c.Ingest.AES67.Port <= 0 || c.Ingest.AES67.Port > 65535) && !discoveryEnabled {
  337. return fmt.Errorf("ingest.aes67.port must be 1..65535")
  338. }
  339. }
  340. if c.Ingest.AES67.Discovery.TimeoutMs < 0 {
  341. return fmt.Errorf("ingest.aes67.discovery.timeoutMs must be >= 0")
  342. }
  343. if c.Ingest.AES67.Discovery.SAPPort < 0 || c.Ingest.AES67.Discovery.SAPPort > 65535 {
  344. return fmt.Errorf("ingest.aes67.discovery.sapPort must be 0..65535")
  345. }
  346. if discoveryEnabled && strings.TrimSpace(c.Ingest.AES67.Discovery.StreamName) == "" {
  347. return fmt.Errorf("ingest.aes67.discovery.streamName is required when discovery is enabled")
  348. }
  349. if discoveryEnabled && c.Ingest.AES67.Port > 65535 {
  350. return fmt.Errorf("ingest.aes67.port must be 1..65535")
  351. }
  352. if c.Ingest.AES67.PayloadType < 0 || c.Ingest.AES67.PayloadType > 127 {
  353. return fmt.Errorf("ingest.aes67.payloadType must be 0..127")
  354. }
  355. if c.Ingest.AES67.SampleRateHz <= 0 {
  356. return fmt.Errorf("ingest.aes67.sampleRateHz must be > 0")
  357. }
  358. if c.Ingest.AES67.Channels != 1 && c.Ingest.AES67.Channels != 2 {
  359. return fmt.Errorf("ingest.aes67.channels must be 1 or 2")
  360. }
  361. if strings.ToUpper(strings.TrimSpace(c.Ingest.AES67.Encoding)) != "L24" {
  362. return fmt.Errorf("ingest.aes67.encoding must be L24")
  363. }
  364. if c.Ingest.AES67.PacketTimeMs <= 0 {
  365. return fmt.Errorf("ingest.aes67.packetTimeMs must be > 0")
  366. }
  367. if c.Ingest.AES67.JitterDepthPackets < 1 {
  368. return fmt.Errorf("ingest.aes67.jitterDepthPackets must be >= 1")
  369. }
  370. if c.Ingest.AES67.ReadBufferBytes < 0 {
  371. return fmt.Errorf("ingest.aes67.readBufferBytes must be >= 0")
  372. }
  373. }
  374. switch strings.ToLower(strings.TrimSpace(c.Ingest.SRT.Mode)) {
  375. case "", "listener", "caller", "rendezvous":
  376. default:
  377. return fmt.Errorf("ingest.srt.mode unsupported: %s", c.Ingest.SRT.Mode)
  378. }
  379. if c.Ingest.SRT.SampleRateHz <= 0 {
  380. return fmt.Errorf("ingest.srt.sampleRateHz must be > 0")
  381. }
  382. if c.Ingest.SRT.Channels != 1 && c.Ingest.SRT.Channels != 2 {
  383. return fmt.Errorf("ingest.srt.channels must be 1 or 2")
  384. }
  385. switch strings.ToLower(strings.TrimSpace(c.Ingest.Icecast.Decoder)) {
  386. case "", "auto", "native", "ffmpeg", "fallback":
  387. default:
  388. return fmt.Errorf("ingest.icecast.decoder unsupported: %s", c.Ingest.Icecast.Decoder)
  389. }
  390. if c.Ingest.Icecast.RadioText.MaxLen < 0 || c.Ingest.Icecast.RadioText.MaxLen > 64 {
  391. return fmt.Errorf("ingest.icecast.radioText.maxLen out of range (0-64)")
  392. }
  393. // Fail-loud PI validation
  394. if c.RDS.Enabled {
  395. if _, err := ParsePI(c.RDS.PI); err != nil {
  396. return fmt.Errorf("rds config: %w", err)
  397. }
  398. }
  399. if c.RDS.PTY < 0 || c.RDS.PTY > 31 {
  400. return fmt.Errorf("rds.pty out of range (0-31)")
  401. }
  402. if len(c.RDS.PS) > 8 {
  403. return fmt.Errorf("rds.ps must be <= 8 characters")
  404. }
  405. if len(c.RDS.RadioText) > 64 {
  406. return fmt.Errorf("rds.radioText must be <= 64 characters")
  407. }
  408. return nil
  409. }
  410. // EffectiveDeviceRate returns the device sample rate, falling back to composite rate.
  411. func (c Config) EffectiveDeviceRate() float64 {
  412. if c.Backend.DeviceSampleRateHz > 0 {
  413. return c.Backend.DeviceSampleRateHz
  414. }
  415. return float64(c.FM.CompositeRateHz)
  416. }