Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

334 строки
8.9KB

  1. package app
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/jan/fm-rds-tx/internal/audio"
  10. cfgpkg "github.com/jan/fm-rds-tx/internal/config"
  11. "github.com/jan/fm-rds-tx/internal/dsp"
  12. offpkg "github.com/jan/fm-rds-tx/internal/offline"
  13. "github.com/jan/fm-rds-tx/internal/platform"
  14. )
  15. type EngineState int
  16. const (
  17. EngineIdle EngineState = iota
  18. EngineRunning
  19. EngineStopping
  20. )
  21. func (s EngineState) String() string {
  22. switch s {
  23. case EngineIdle:
  24. return "idle"
  25. case EngineRunning:
  26. return "running"
  27. case EngineStopping:
  28. return "stopping"
  29. default:
  30. return "unknown"
  31. }
  32. }
  33. type EngineStats struct {
  34. State string `json:"state"`
  35. ChunksProduced uint64 `json:"chunksProduced"`
  36. TotalSamples uint64 `json:"totalSamples"`
  37. Underruns uint64 `json:"underruns"`
  38. LastError string `json:"lastError,omitempty"`
  39. UptimeSeconds float64 `json:"uptimeSeconds"`
  40. }
  41. // Engine is the continuous TX loop. It generates composite IQ in chunks,
  42. // resamples to device rate, and pushes to hardware in a tight loop.
  43. // The hardware buffer_push call is blocking — it returns when the hardware
  44. // has consumed the previous buffer and is ready for the next one.
  45. // This naturally paces the loop to real-time without a ticker.
  46. type Engine struct {
  47. cfg cfgpkg.Config
  48. driver platform.SoapyDriver
  49. generator *offpkg.Generator
  50. upsampler *dsp.FMUpsampler // nil = same-rate, non-nil = split-rate
  51. chunkDuration time.Duration
  52. deviceRate float64
  53. mu sync.Mutex
  54. state EngineState
  55. cancel context.CancelFunc
  56. startedAt time.Time
  57. wg sync.WaitGroup
  58. chunksProduced atomic.Uint64
  59. totalSamples atomic.Uint64
  60. underruns atomic.Uint64
  61. lastError atomic.Value // string
  62. // Live config: pending frequency change, applied between chunks
  63. pendingFreq atomic.Pointer[float64]
  64. // Live audio stream (optional)
  65. streamSrc *audio.StreamSource
  66. }
  67. // SetStreamSource configures a live audio stream as the audio source.
  68. // Must be called before Start(). The StreamResampler is created internally
  69. // to convert from the stream's sample rate to the DSP composite rate.
  70. func (e *Engine) SetStreamSource(src *audio.StreamSource) {
  71. e.streamSrc = src
  72. compositeRate := float64(e.cfg.FM.CompositeRateHz)
  73. if compositeRate <= 0 {
  74. compositeRate = 228000
  75. }
  76. resampler := audio.NewStreamResampler(src, compositeRate)
  77. e.generator.SetExternalSource(resampler)
  78. log.Printf("engine: live audio stream — %d Hz → %.0f Hz (buffer %d frames)",
  79. src.SampleRate, compositeRate, src.Stats().Capacity)
  80. }
  81. // StreamSource returns the live audio stream source, or nil.
  82. // Used by the control server for stats and HTTP audio ingest.
  83. func (e *Engine) StreamSource() *audio.StreamSource {
  84. return e.streamSrc
  85. }
  86. func NewEngine(cfg cfgpkg.Config, driver platform.SoapyDriver) *Engine {
  87. deviceRate := cfg.EffectiveDeviceRate()
  88. compositeRate := float64(cfg.FM.CompositeRateHz)
  89. if compositeRate <= 0 {
  90. compositeRate = 228000
  91. }
  92. var upsampler *dsp.FMUpsampler
  93. if deviceRate > compositeRate*1.001 {
  94. // Split-rate: DSP chain runs at compositeRate (typ. 228 kHz),
  95. // FMUpsampler handles FM modulation + interpolation to deviceRate.
  96. // This halves CPU load compared to running all DSP at deviceRate.
  97. cfg.FM.FMModulationEnabled = false
  98. maxDev := cfg.FM.MaxDeviationHz
  99. if maxDev <= 0 {
  100. maxDev = 75000
  101. }
  102. upsampler = dsp.NewFMUpsampler(compositeRate, deviceRate, maxDev)
  103. log.Printf("engine: split-rate mode — DSP@%.0fHz → upsample@%.0fHz (ratio %.2f)",
  104. compositeRate, deviceRate, deviceRate/compositeRate)
  105. } else {
  106. // Same-rate: entire DSP chain runs at deviceRate.
  107. // Used when deviceRate ≈ compositeRate (e.g. LimeSDR at 228 kHz).
  108. if deviceRate > 0 {
  109. cfg.FM.CompositeRateHz = int(deviceRate)
  110. }
  111. cfg.FM.FMModulationEnabled = true
  112. log.Printf("engine: same-rate mode — DSP@%dHz", cfg.FM.CompositeRateHz)
  113. }
  114. return &Engine{
  115. cfg: cfg,
  116. driver: driver,
  117. generator: offpkg.NewGenerator(cfg),
  118. upsampler: upsampler,
  119. chunkDuration: 50 * time.Millisecond,
  120. deviceRate: deviceRate,
  121. state: EngineIdle,
  122. }
  123. }
  124. func (e *Engine) SetChunkDuration(d time.Duration) {
  125. e.chunkDuration = d
  126. }
  127. // LiveConfigUpdate carries hot-reloadable parameters from the control API.
  128. // nil pointers mean "no change". Validated before applying.
  129. type LiveConfigUpdate struct {
  130. FrequencyMHz *float64
  131. OutputDrive *float64
  132. StereoEnabled *bool
  133. PilotLevel *float64
  134. RDSInjection *float64
  135. RDSEnabled *bool
  136. LimiterEnabled *bool
  137. LimiterCeiling *float64
  138. PS *string
  139. RadioText *string
  140. }
  141. // UpdateConfig applies live parameter changes without restarting the engine.
  142. // DSP params take effect at the next chunk boundary (~50ms max).
  143. // Frequency changes are applied between chunks via driver.Tune().
  144. // RDS text updates are applied at the next RDS group boundary (~88ms).
  145. func (e *Engine) UpdateConfig(u LiveConfigUpdate) error {
  146. // --- Validate ---
  147. if u.FrequencyMHz != nil {
  148. if *u.FrequencyMHz < 65 || *u.FrequencyMHz > 110 {
  149. return fmt.Errorf("frequencyMHz out of range (65-110)")
  150. }
  151. }
  152. if u.OutputDrive != nil {
  153. if *u.OutputDrive < 0 || *u.OutputDrive > 3 {
  154. return fmt.Errorf("outputDrive out of range (0-3)")
  155. }
  156. }
  157. if u.PilotLevel != nil {
  158. if *u.PilotLevel < 0 || *u.PilotLevel > 0.2 {
  159. return fmt.Errorf("pilotLevel out of range (0-0.2)")
  160. }
  161. }
  162. if u.RDSInjection != nil {
  163. if *u.RDSInjection < 0 || *u.RDSInjection > 0.15 {
  164. return fmt.Errorf("rdsInjection out of range (0-0.15)")
  165. }
  166. }
  167. if u.LimiterCeiling != nil {
  168. if *u.LimiterCeiling < 0 || *u.LimiterCeiling > 2 {
  169. return fmt.Errorf("limiterCeiling out of range (0-2)")
  170. }
  171. }
  172. // --- Frequency: store for run loop to apply via driver.Tune() ---
  173. if u.FrequencyMHz != nil {
  174. freqHz := *u.FrequencyMHz * 1e6
  175. e.pendingFreq.Store(&freqHz)
  176. }
  177. // --- RDS text: forward to encoder atomics ---
  178. if u.PS != nil || u.RadioText != nil {
  179. if enc := e.generator.RDSEncoder(); enc != nil {
  180. ps, rt := "", ""
  181. if u.PS != nil { ps = *u.PS }
  182. if u.RadioText != nil { rt = *u.RadioText }
  183. enc.UpdateText(ps, rt)
  184. }
  185. }
  186. // --- DSP params: build new LiveParams from current + patch ---
  187. // Read current, apply deltas, store new
  188. current := e.generator.CurrentLiveParams()
  189. next := current // copy
  190. if u.OutputDrive != nil { next.OutputDrive = *u.OutputDrive }
  191. if u.StereoEnabled != nil { next.StereoEnabled = *u.StereoEnabled }
  192. if u.PilotLevel != nil { next.PilotLevel = *u.PilotLevel }
  193. if u.RDSInjection != nil { next.RDSInjection = *u.RDSInjection }
  194. if u.RDSEnabled != nil { next.RDSEnabled = *u.RDSEnabled }
  195. if u.LimiterEnabled != nil { next.LimiterEnabled = *u.LimiterEnabled }
  196. if u.LimiterCeiling != nil { next.LimiterCeiling = *u.LimiterCeiling }
  197. e.generator.UpdateLive(next)
  198. return nil
  199. }
  200. func (e *Engine) Start(ctx context.Context) error {
  201. e.mu.Lock()
  202. if e.state != EngineIdle {
  203. e.mu.Unlock()
  204. return fmt.Errorf("engine already in state %s", e.state)
  205. }
  206. if err := e.driver.Start(ctx); err != nil {
  207. e.mu.Unlock()
  208. return fmt.Errorf("driver start: %w", err)
  209. }
  210. runCtx, cancel := context.WithCancel(ctx)
  211. e.cancel = cancel
  212. e.state = EngineRunning
  213. e.startedAt = time.Now()
  214. e.wg.Add(1)
  215. e.mu.Unlock()
  216. go e.run(runCtx)
  217. return nil
  218. }
  219. func (e *Engine) Stop(ctx context.Context) error {
  220. e.mu.Lock()
  221. if e.state != EngineRunning {
  222. e.mu.Unlock()
  223. return nil
  224. }
  225. e.state = EngineStopping
  226. e.cancel()
  227. e.mu.Unlock()
  228. // Wait for run() goroutine to exit — deterministic, no guessing
  229. e.wg.Wait()
  230. if err := e.driver.Flush(ctx); err != nil {
  231. return err
  232. }
  233. if err := e.driver.Stop(ctx); err != nil {
  234. return err
  235. }
  236. e.mu.Lock()
  237. e.state = EngineIdle
  238. e.mu.Unlock()
  239. return nil
  240. }
  241. func (e *Engine) Stats() EngineStats {
  242. e.mu.Lock()
  243. state := e.state
  244. startedAt := e.startedAt
  245. e.mu.Unlock()
  246. var uptime float64
  247. if state == EngineRunning {
  248. uptime = time.Since(startedAt).Seconds()
  249. }
  250. errVal, _ := e.lastError.Load().(string)
  251. return EngineStats{
  252. State: state.String(),
  253. ChunksProduced: e.chunksProduced.Load(),
  254. TotalSamples: e.totalSamples.Load(),
  255. Underruns: e.underruns.Load(),
  256. LastError: errVal,
  257. UptimeSeconds: uptime,
  258. }
  259. }
  260. func (e *Engine) run(ctx context.Context) {
  261. defer e.wg.Done()
  262. for {
  263. if ctx.Err() != nil {
  264. return
  265. }
  266. // Apply pending frequency change between chunks
  267. if pf := e.pendingFreq.Swap(nil); pf != nil {
  268. if err := e.driver.Tune(ctx, *pf); err != nil {
  269. e.lastError.Store(fmt.Sprintf("tune: %v", err))
  270. } else {
  271. log.Printf("engine: tuned to %.3f MHz", *pf/1e6)
  272. }
  273. }
  274. frame := e.generator.GenerateFrame(e.chunkDuration)
  275. if e.upsampler != nil {
  276. frame = e.upsampler.Process(frame)
  277. }
  278. n, err := e.driver.Write(ctx, frame)
  279. if err != nil {
  280. if ctx.Err() != nil { return }
  281. e.lastError.Store(err.Error())
  282. e.underruns.Add(1)
  283. // Back off to avoid pegging CPU on persistent errors
  284. select {
  285. case <-time.After(e.chunkDuration):
  286. case <-ctx.Done():
  287. return
  288. }
  289. continue
  290. }
  291. e.chunksProduced.Add(1)
  292. e.totalSamples.Add(uint64(n))
  293. }
  294. }