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.

566 lines
15KB

  1. package app
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/jan/fm-rds-tx/internal/audio"
  11. cfgpkg "github.com/jan/fm-rds-tx/internal/config"
  12. "github.com/jan/fm-rds-tx/internal/dsp"
  13. offpkg "github.com/jan/fm-rds-tx/internal/offline"
  14. "github.com/jan/fm-rds-tx/internal/output"
  15. "github.com/jan/fm-rds-tx/internal/platform"
  16. )
  17. type EngineState int
  18. const (
  19. EngineIdle EngineState = iota
  20. EngineRunning
  21. EngineStopping
  22. )
  23. func (s EngineState) String() string {
  24. switch s {
  25. case EngineIdle:
  26. return "idle"
  27. case EngineRunning:
  28. return "running"
  29. case EngineStopping:
  30. return "stopping"
  31. default:
  32. return "unknown"
  33. }
  34. }
  35. type RuntimeState string
  36. const (
  37. RuntimeStateIdle RuntimeState = "idle"
  38. RuntimeStateArming RuntimeState = "arming"
  39. RuntimeStatePrebuffering RuntimeState = "prebuffering"
  40. RuntimeStateRunning RuntimeState = "running"
  41. RuntimeStateDegraded RuntimeState = "degraded"
  42. RuntimeStateMuted RuntimeState = "muted"
  43. RuntimeStateFaulted RuntimeState = "faulted"
  44. RuntimeStateStopping RuntimeState = "stopping"
  45. )
  46. func updateMaxDuration(dst *atomic.Uint64, d time.Duration) {
  47. v := uint64(d)
  48. for {
  49. cur := dst.Load()
  50. if v <= cur {
  51. return
  52. }
  53. if dst.CompareAndSwap(cur, v) {
  54. return
  55. }
  56. }
  57. }
  58. func durationMs(ns uint64) float64 {
  59. return float64(ns) / float64(time.Millisecond)
  60. }
  61. type EngineStats struct {
  62. State string `json:"state"`
  63. ChunksProduced uint64 `json:"chunksProduced"`
  64. TotalSamples uint64 `json:"totalSamples"`
  65. Underruns uint64 `json:"underruns"`
  66. LateBuffers uint64 `json:"lateBuffers,omitempty"`
  67. LastError string `json:"lastError,omitempty"`
  68. UptimeSeconds float64 `json:"uptimeSeconds"`
  69. MaxCycleMs float64 `json:"maxCycleMs,omitempty"`
  70. MaxGenerateMs float64 `json:"maxGenerateMs,omitempty"`
  71. MaxUpsampleMs float64 `json:"maxUpsampleMs,omitempty"`
  72. MaxWriteMs float64 `json:"maxWriteMs,omitempty"`
  73. Queue output.QueueStats `json:"queue"`
  74. RuntimeIndicator RuntimeIndicator `json:"runtimeIndicator"`
  75. RuntimeAlert string `json:"runtimeAlert,omitempty"`
  76. }
  77. type RuntimeIndicator string
  78. const (
  79. RuntimeIndicatorNormal RuntimeIndicator = "normal"
  80. RuntimeIndicatorDegraded RuntimeIndicator = "degraded"
  81. RuntimeIndicatorQueueCritical RuntimeIndicator = "queueCritical"
  82. )
  83. const lateBufferIndicatorWindow = 5 * time.Second
  84. // Engine is the continuous TX loop. It generates composite IQ in chunks,
  85. // resamples to device rate, and pushes to hardware in a tight loop.
  86. // The hardware buffer_push call is blocking — it returns when the hardware
  87. // has consumed the previous buffer and is ready for the next one.
  88. // This naturally paces the loop to real-time without a ticker.
  89. type Engine struct {
  90. cfg cfgpkg.Config
  91. driver platform.SoapyDriver
  92. generator *offpkg.Generator
  93. upsampler *dsp.FMUpsampler // nil = same-rate, non-nil = split-rate
  94. chunkDuration time.Duration
  95. deviceRate float64
  96. frameQueue *output.FrameQueue
  97. mu sync.Mutex
  98. state EngineState
  99. cancel context.CancelFunc
  100. startedAt time.Time
  101. wg sync.WaitGroup
  102. runtimeState atomic.Value
  103. chunksProduced atomic.Uint64
  104. totalSamples atomic.Uint64
  105. underruns atomic.Uint64
  106. lateBuffers atomic.Uint64
  107. lateBufferAlertAt atomic.Uint64
  108. maxCycleNs atomic.Uint64
  109. maxGenerateNs atomic.Uint64
  110. maxUpsampleNs atomic.Uint64
  111. maxWriteNs atomic.Uint64
  112. lastError atomic.Value // string
  113. // Live config: pending frequency change, applied between chunks
  114. pendingFreq atomic.Pointer[float64]
  115. // Live audio stream (optional)
  116. streamSrc *audio.StreamSource
  117. }
  118. // SetStreamSource configures a live audio stream as the audio source.
  119. // Must be called before Start(). The StreamResampler is created internally
  120. // to convert from the stream's sample rate to the DSP composite rate.
  121. func (e *Engine) SetStreamSource(src *audio.StreamSource) {
  122. e.streamSrc = src
  123. compositeRate := float64(e.cfg.FM.CompositeRateHz)
  124. if compositeRate <= 0 {
  125. compositeRate = 228000
  126. }
  127. resampler := audio.NewStreamResampler(src, compositeRate)
  128. e.generator.SetExternalSource(resampler)
  129. log.Printf("engine: live audio stream — %d Hz → %.0f Hz (buffer %d frames)",
  130. src.SampleRate, compositeRate, src.Stats().Capacity)
  131. }
  132. // StreamSource returns the live audio stream source, or nil.
  133. // Used by the control server for stats and HTTP audio ingest.
  134. func (e *Engine) StreamSource() *audio.StreamSource {
  135. return e.streamSrc
  136. }
  137. func NewEngine(cfg cfgpkg.Config, driver platform.SoapyDriver) *Engine {
  138. deviceRate := cfg.EffectiveDeviceRate()
  139. compositeRate := float64(cfg.FM.CompositeRateHz)
  140. if compositeRate <= 0 {
  141. compositeRate = 228000
  142. }
  143. var upsampler *dsp.FMUpsampler
  144. if deviceRate > compositeRate*1.001 {
  145. // Split-rate: DSP chain runs at compositeRate (typ. 228 kHz),
  146. // FMUpsampler handles FM modulation + interpolation to deviceRate.
  147. // This halves CPU load compared to running all DSP at deviceRate.
  148. cfg.FM.FMModulationEnabled = false
  149. maxDev := cfg.FM.MaxDeviationHz
  150. if maxDev <= 0 {
  151. maxDev = 75000
  152. }
  153. // mpxGain scales the FM deviation to compensate for hardware
  154. // DAC/SDR scaling factors. DSP chain stays at logical 0-1.0 levels.
  155. if cfg.FM.MpxGain > 0 && cfg.FM.MpxGain != 1.0 {
  156. maxDev *= cfg.FM.MpxGain
  157. }
  158. upsampler = dsp.NewFMUpsampler(compositeRate, deviceRate, maxDev)
  159. log.Printf("engine: split-rate mode — DSP@%.0fHz → upsample@%.0fHz (ratio %.2f)",
  160. compositeRate, deviceRate, deviceRate/compositeRate)
  161. } else {
  162. // Same-rate: entire DSP chain runs at deviceRate.
  163. // Used when deviceRate ≈ compositeRate (e.g. LimeSDR at 228 kHz).
  164. if deviceRate > 0 {
  165. cfg.FM.CompositeRateHz = int(deviceRate)
  166. }
  167. cfg.FM.FMModulationEnabled = true
  168. log.Printf("engine: same-rate mode — DSP@%dHz", cfg.FM.CompositeRateHz)
  169. }
  170. engine := &Engine{
  171. cfg: cfg,
  172. driver: driver,
  173. generator: offpkg.NewGenerator(cfg),
  174. upsampler: upsampler,
  175. chunkDuration: 50 * time.Millisecond,
  176. deviceRate: deviceRate,
  177. state: EngineIdle,
  178. frameQueue: output.NewFrameQueue(cfg.Runtime.FrameQueueCapacity),
  179. }
  180. engine.setRuntimeState(RuntimeStateIdle)
  181. return engine
  182. }
  183. func (e *Engine) SetChunkDuration(d time.Duration) {
  184. e.chunkDuration = d
  185. }
  186. // LiveConfigUpdate carries hot-reloadable parameters from the control API.
  187. // nil pointers mean "no change". Validated before applying.
  188. type LiveConfigUpdate struct {
  189. FrequencyMHz *float64
  190. OutputDrive *float64
  191. StereoEnabled *bool
  192. PilotLevel *float64
  193. RDSInjection *float64
  194. RDSEnabled *bool
  195. LimiterEnabled *bool
  196. LimiterCeiling *float64
  197. PS *string
  198. RadioText *string
  199. }
  200. // UpdateConfig applies live parameter changes without restarting the engine.
  201. // DSP params take effect at the next chunk boundary (~50ms max).
  202. // Frequency changes are applied between chunks via driver.Tune().
  203. // RDS text updates are applied at the next RDS group boundary (~88ms).
  204. func (e *Engine) UpdateConfig(u LiveConfigUpdate) error {
  205. // --- Validate ---
  206. if u.FrequencyMHz != nil {
  207. if *u.FrequencyMHz < 65 || *u.FrequencyMHz > 110 {
  208. return fmt.Errorf("frequencyMHz out of range (65-110)")
  209. }
  210. }
  211. if u.OutputDrive != nil {
  212. if *u.OutputDrive < 0 || *u.OutputDrive > 10 {
  213. return fmt.Errorf("outputDrive out of range (0-10)")
  214. }
  215. }
  216. if u.PilotLevel != nil {
  217. if *u.PilotLevel < 0 || *u.PilotLevel > 0.2 {
  218. return fmt.Errorf("pilotLevel out of range (0-0.2)")
  219. }
  220. }
  221. if u.RDSInjection != nil {
  222. if *u.RDSInjection < 0 || *u.RDSInjection > 0.15 {
  223. return fmt.Errorf("rdsInjection out of range (0-0.15)")
  224. }
  225. }
  226. if u.LimiterCeiling != nil {
  227. if *u.LimiterCeiling < 0 || *u.LimiterCeiling > 2 {
  228. return fmt.Errorf("limiterCeiling out of range (0-2)")
  229. }
  230. }
  231. // --- Frequency: store for run loop to apply via driver.Tune() ---
  232. if u.FrequencyMHz != nil {
  233. freqHz := *u.FrequencyMHz * 1e6
  234. e.pendingFreq.Store(&freqHz)
  235. }
  236. // --- RDS text: forward to encoder atomics ---
  237. if u.PS != nil || u.RadioText != nil {
  238. if enc := e.generator.RDSEncoder(); enc != nil {
  239. ps, rt := "", ""
  240. if u.PS != nil {
  241. ps = *u.PS
  242. }
  243. if u.RadioText != nil {
  244. rt = *u.RadioText
  245. }
  246. enc.UpdateText(ps, rt)
  247. }
  248. }
  249. // --- DSP params: build new LiveParams from current + patch ---
  250. // Read current, apply deltas, store new
  251. current := e.generator.CurrentLiveParams()
  252. next := current // copy
  253. if u.OutputDrive != nil {
  254. next.OutputDrive = *u.OutputDrive
  255. }
  256. if u.StereoEnabled != nil {
  257. next.StereoEnabled = *u.StereoEnabled
  258. }
  259. if u.PilotLevel != nil {
  260. next.PilotLevel = *u.PilotLevel
  261. }
  262. if u.RDSInjection != nil {
  263. next.RDSInjection = *u.RDSInjection
  264. }
  265. if u.RDSEnabled != nil {
  266. next.RDSEnabled = *u.RDSEnabled
  267. }
  268. if u.LimiterEnabled != nil {
  269. next.LimiterEnabled = *u.LimiterEnabled
  270. }
  271. if u.LimiterCeiling != nil {
  272. next.LimiterCeiling = *u.LimiterCeiling
  273. }
  274. e.generator.UpdateLive(next)
  275. return nil
  276. }
  277. func (e *Engine) Start(ctx context.Context) error {
  278. e.mu.Lock()
  279. if e.state != EngineIdle {
  280. e.mu.Unlock()
  281. return fmt.Errorf("engine already in state %s", e.state)
  282. }
  283. if err := e.driver.Start(ctx); err != nil {
  284. e.mu.Unlock()
  285. return fmt.Errorf("driver start: %w", err)
  286. }
  287. runCtx, cancel := context.WithCancel(ctx)
  288. e.cancel = cancel
  289. e.state = EngineRunning
  290. e.setRuntimeState(RuntimeStateArming)
  291. e.startedAt = time.Now()
  292. e.wg.Add(1)
  293. e.mu.Unlock()
  294. go e.run(runCtx)
  295. return nil
  296. }
  297. func (e *Engine) Stop(ctx context.Context) error {
  298. e.mu.Lock()
  299. if e.state != EngineRunning {
  300. e.mu.Unlock()
  301. return nil
  302. }
  303. e.state = EngineStopping
  304. e.setRuntimeState(RuntimeStateStopping)
  305. e.cancel()
  306. e.mu.Unlock()
  307. // Wait for run() goroutine to exit — deterministic, no guessing
  308. e.wg.Wait()
  309. if err := e.driver.Flush(ctx); err != nil {
  310. return err
  311. }
  312. if err := e.driver.Stop(ctx); err != nil {
  313. return err
  314. }
  315. e.mu.Lock()
  316. e.state = EngineIdle
  317. e.setRuntimeState(RuntimeStateIdle)
  318. e.mu.Unlock()
  319. return nil
  320. }
  321. func (e *Engine) Stats() EngineStats {
  322. e.mu.Lock()
  323. state := e.state
  324. startedAt := e.startedAt
  325. e.mu.Unlock()
  326. var uptime float64
  327. if state == EngineRunning {
  328. uptime = time.Since(startedAt).Seconds()
  329. }
  330. errVal, _ := e.lastError.Load().(string)
  331. queue := e.frameQueue.Stats()
  332. lateBuffers := e.lateBuffers.Load()
  333. now := time.Now()
  334. lateAlertAt := e.lateBufferAlertAt.Load()
  335. hasRecentLateBuffers := lateAlertAt > 0 && now.Sub(time.Unix(0, int64(lateAlertAt))) <= lateBufferIndicatorWindow
  336. ri := runtimeIndicator(queue.Health, hasRecentLateBuffers)
  337. return EngineStats{
  338. State: string(e.currentRuntimeState()),
  339. ChunksProduced: e.chunksProduced.Load(),
  340. TotalSamples: e.totalSamples.Load(),
  341. Underruns: e.underruns.Load(),
  342. LateBuffers: lateBuffers,
  343. LastError: errVal,
  344. UptimeSeconds: uptime,
  345. MaxCycleMs: durationMs(e.maxCycleNs.Load()),
  346. MaxGenerateMs: durationMs(e.maxGenerateNs.Load()),
  347. MaxUpsampleMs: durationMs(e.maxUpsampleNs.Load()),
  348. MaxWriteMs: durationMs(e.maxWriteNs.Load()),
  349. Queue: queue,
  350. RuntimeIndicator: ri,
  351. RuntimeAlert: runtimeAlert(queue.Health, hasRecentLateBuffers),
  352. }
  353. }
  354. func runtimeIndicator(queueHealth output.QueueHealth, recentLateBuffers bool) RuntimeIndicator {
  355. switch {
  356. case queueHealth == output.QueueHealthCritical:
  357. return RuntimeIndicatorQueueCritical
  358. case queueHealth == output.QueueHealthLow || recentLateBuffers:
  359. return RuntimeIndicatorDegraded
  360. default:
  361. return RuntimeIndicatorNormal
  362. }
  363. }
  364. func runtimeAlert(queueHealth output.QueueHealth, recentLateBuffers bool) string {
  365. switch {
  366. case queueHealth == output.QueueHealthCritical:
  367. return "queue health critical"
  368. case recentLateBuffers:
  369. return "late buffers"
  370. case queueHealth == output.QueueHealthLow:
  371. return "queue health low"
  372. default:
  373. return ""
  374. }
  375. }
  376. func (e *Engine) run(ctx context.Context) {
  377. e.setRuntimeState(RuntimeStateRunning)
  378. e.wg.Add(1)
  379. go e.writerLoop(ctx)
  380. defer e.wg.Done()
  381. for {
  382. if ctx.Err() != nil {
  383. return
  384. }
  385. // Apply pending frequency change between chunks
  386. if pf := e.pendingFreq.Swap(nil); pf != nil {
  387. if err := e.driver.Tune(ctx, *pf); err != nil {
  388. e.lastError.Store(fmt.Sprintf("tune: %v", err))
  389. } else {
  390. log.Printf("engine: tuned to %.3f MHz", *pf/1e6)
  391. }
  392. }
  393. t0 := time.Now()
  394. frame := e.generator.GenerateFrame(e.chunkDuration)
  395. frame.GeneratedAt = t0
  396. t1 := time.Now()
  397. if e.upsampler != nil {
  398. frame = e.upsampler.Process(frame)
  399. frame.GeneratedAt = t0
  400. }
  401. t2 := time.Now()
  402. genDur := t1.Sub(t0)
  403. upDur := t2.Sub(t1)
  404. updateMaxDuration(&e.maxGenerateNs, genDur)
  405. updateMaxDuration(&e.maxUpsampleNs, upDur)
  406. enqueued := cloneFrame(frame)
  407. if enqueued == nil {
  408. e.lastError.Store("engine: frame clone failed")
  409. e.underruns.Add(1)
  410. continue
  411. }
  412. if err := e.frameQueue.Push(ctx, enqueued); err != nil {
  413. if ctx.Err() != nil {
  414. return
  415. }
  416. if errors.Is(err, output.ErrFrameQueueClosed) {
  417. return
  418. }
  419. e.lastError.Store(err.Error())
  420. e.underruns.Add(1)
  421. select {
  422. case <-time.After(e.chunkDuration):
  423. case <-ctx.Done():
  424. return
  425. }
  426. continue
  427. }
  428. }
  429. }
  430. func (e *Engine) writerLoop(ctx context.Context) {
  431. defer e.wg.Done()
  432. for {
  433. frame, err := e.frameQueue.Pop(ctx)
  434. if err != nil {
  435. if ctx.Err() != nil {
  436. return
  437. }
  438. if errors.Is(err, output.ErrFrameQueueClosed) {
  439. return
  440. }
  441. e.lastError.Store(err.Error())
  442. e.underruns.Add(1)
  443. continue
  444. }
  445. writeStart := time.Now()
  446. n, err := e.driver.Write(ctx, frame)
  447. writeDur := time.Since(writeStart)
  448. cycleDur := writeDur
  449. if !frame.GeneratedAt.IsZero() {
  450. cycleDur = time.Since(frame.GeneratedAt)
  451. }
  452. updateMaxDuration(&e.maxWriteNs, writeDur)
  453. updateMaxDuration(&e.maxCycleNs, cycleDur)
  454. if cycleDur > e.chunkDuration {
  455. late := e.lateBuffers.Add(1)
  456. e.lateBufferAlertAt.Store(uint64(time.Now().UnixNano()))
  457. if late <= 5 || late%20 == 0 {
  458. log.Printf("TX LATE: cycle=%s budget=%s write=%s over=%s",
  459. cycleDur, e.chunkDuration, writeDur, cycleDur-e.chunkDuration)
  460. }
  461. }
  462. if err != nil {
  463. if ctx.Err() != nil {
  464. return
  465. }
  466. e.lastError.Store(err.Error())
  467. e.underruns.Add(1)
  468. select {
  469. case <-time.After(e.chunkDuration):
  470. case <-ctx.Done():
  471. return
  472. }
  473. continue
  474. }
  475. e.chunksProduced.Add(1)
  476. e.totalSamples.Add(uint64(n))
  477. }
  478. }
  479. func cloneFrame(src *output.CompositeFrame) *output.CompositeFrame {
  480. if src == nil {
  481. return nil
  482. }
  483. samples := make([]output.IQSample, len(src.Samples))
  484. copy(samples, src.Samples)
  485. return &output.CompositeFrame{
  486. Samples: samples,
  487. SampleRateHz: src.SampleRateHz,
  488. Timestamp: src.Timestamp,
  489. GeneratedAt: src.GeneratedAt,
  490. Sequence: src.Sequence,
  491. }
  492. }
  493. func (e *Engine) setRuntimeState(state RuntimeState) {
  494. e.runtimeState.Store(state)
  495. }
  496. func (e *Engine) currentRuntimeState() RuntimeState {
  497. if v := e.runtimeState.Load(); v != nil {
  498. if rs, ok := v.(RuntimeState); ok {
  499. return rs
  500. }
  501. }
  502. return RuntimeStateIdle
  503. }