Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

965 rindas
29KB

  1. package app
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "math"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/jan/fm-rds-tx/internal/audio"
  12. cfgpkg "github.com/jan/fm-rds-tx/internal/config"
  13. "github.com/jan/fm-rds-tx/internal/dsp"
  14. "github.com/jan/fm-rds-tx/internal/license"
  15. offpkg "github.com/jan/fm-rds-tx/internal/offline"
  16. "github.com/jan/fm-rds-tx/internal/output"
  17. "github.com/jan/fm-rds-tx/internal/platform"
  18. )
  19. type EngineState int
  20. const (
  21. EngineIdle EngineState = iota
  22. EngineRunning
  23. EngineStopping
  24. )
  25. func (s EngineState) String() string {
  26. switch s {
  27. case EngineIdle:
  28. return "idle"
  29. case EngineRunning:
  30. return "running"
  31. case EngineStopping:
  32. return "stopping"
  33. default:
  34. return "unknown"
  35. }
  36. }
  37. type RuntimeState string
  38. const (
  39. RuntimeStateIdle RuntimeState = "idle"
  40. RuntimeStateArming RuntimeState = "arming"
  41. RuntimeStatePrebuffering RuntimeState = "prebuffering"
  42. RuntimeStateRunning RuntimeState = "running"
  43. RuntimeStateDegraded RuntimeState = "degraded"
  44. RuntimeStateMuted RuntimeState = "muted"
  45. RuntimeStateFaulted RuntimeState = "faulted"
  46. RuntimeStateStopping RuntimeState = "stopping"
  47. )
  48. func updateMaxDuration(dst *atomic.Uint64, d time.Duration) {
  49. v := uint64(d)
  50. for {
  51. cur := dst.Load()
  52. if v <= cur {
  53. return
  54. }
  55. if dst.CompareAndSwap(cur, v) {
  56. return
  57. }
  58. }
  59. }
  60. func durationMs(ns uint64) float64 {
  61. return float64(ns) / float64(time.Millisecond)
  62. }
  63. type EngineStats struct {
  64. State string `json:"state"`
  65. RuntimeStateDurationSeconds float64 `json:"runtimeStateDurationSeconds"`
  66. ChunksProduced uint64 `json:"chunksProduced"`
  67. TotalSamples uint64 `json:"totalSamples"`
  68. Underruns uint64 `json:"underruns"`
  69. LateBuffers uint64 `json:"lateBuffers,omitempty"`
  70. LastError string `json:"lastError,omitempty"`
  71. UptimeSeconds float64 `json:"uptimeSeconds"`
  72. MaxCycleMs float64 `json:"maxCycleMs,omitempty"`
  73. MaxGenerateMs float64 `json:"maxGenerateMs,omitempty"`
  74. MaxUpsampleMs float64 `json:"maxUpsampleMs,omitempty"`
  75. MaxWriteMs float64 `json:"maxWriteMs,omitempty"`
  76. MaxQueueResidenceMs float64 `json:"maxQueueResidenceMs,omitempty"`
  77. MaxPipelineLatencyMs float64 `json:"maxPipelineLatencyMs,omitempty"`
  78. Queue output.QueueStats `json:"queue"`
  79. RuntimeIndicator RuntimeIndicator `json:"runtimeIndicator"`
  80. RuntimeAlert string `json:"runtimeAlert,omitempty"`
  81. AppliedFrequencyMHz float64 `json:"appliedFrequencyMHz"`
  82. ActivePS string `json:"activePS,omitempty"`
  83. ActiveRadioText string `json:"activeRadioText,omitempty"`
  84. Measurement *offpkg.MeasurementSnapshot `json:"measurement,omitempty"`
  85. LastFault *FaultEvent `json:"lastFault,omitempty"`
  86. DegradedTransitions uint64 `json:"degradedTransitions"`
  87. MutedTransitions uint64 `json:"mutedTransitions"`
  88. FaultedTransitions uint64 `json:"faultedTransitions"`
  89. FaultCount uint64 `json:"faultCount"`
  90. FaultHistory []FaultEvent `json:"faultHistory,omitempty"`
  91. TransitionHistory []RuntimeTransition `json:"transitionHistory,omitempty"`
  92. }
  93. type RuntimeIndicator string
  94. const (
  95. RuntimeIndicatorNormal RuntimeIndicator = "normal"
  96. RuntimeIndicatorDegraded RuntimeIndicator = "degraded"
  97. RuntimeIndicatorQueueCritical RuntimeIndicator = "queueCritical"
  98. )
  99. type RuntimeTransition struct {
  100. Time time.Time `json:"time"`
  101. From RuntimeState `json:"from"`
  102. To RuntimeState `json:"to"`
  103. Severity string `json:"severity"`
  104. }
  105. const (
  106. lateBufferIndicatorWindow = 2 * time.Second
  107. writeLateTolerance = 10 * time.Millisecond
  108. queueCriticalStreakThreshold = 3
  109. queueMutedStreakThreshold = queueCriticalStreakThreshold * 2
  110. queueMutedRecoveryThreshold = queueCriticalStreakThreshold
  111. queueFaultedStreakThreshold = queueCriticalStreakThreshold
  112. faultRepeatWindow = 1 * time.Second
  113. lateBufferStreakThreshold = 3 // consecutive late writes required before alerting
  114. faultHistoryCapacity = 8
  115. runtimeTransitionHistoryCapacity = 8
  116. )
  117. // Engine is the continuous TX loop. It generates composite IQ in chunks,
  118. // resamples to device rate, and pushes to hardware in a tight loop.
  119. // The hardware buffer_push call is blocking — it returns when the hardware
  120. // has consumed the previous buffer and is ready for the next one.
  121. // This naturally paces the loop to real-time without a ticker.
  122. type Engine struct {
  123. cfg cfgpkg.Config
  124. driver platform.SoapyDriver
  125. generator *offpkg.Generator
  126. upsampler *dsp.FMUpsampler // nil = same-rate, non-nil = split-rate
  127. chunkDuration time.Duration
  128. deviceRate float64
  129. frameQueue *output.FrameQueue
  130. mu sync.Mutex
  131. state EngineState
  132. cancel context.CancelFunc
  133. startedAt time.Time
  134. wg sync.WaitGroup
  135. runtimeState atomic.Value
  136. stateMu sync.Mutex // guards setRuntimeState check-then-store (NEW-2 fix)
  137. chunksProduced atomic.Uint64
  138. totalSamples atomic.Uint64
  139. underruns atomic.Uint64
  140. lateBuffers atomic.Uint64
  141. lateBufferAlertAt atomic.Uint64
  142. lateBufferStreak atomic.Uint64 // consecutive late writes; reset on clean write
  143. criticalStreak atomic.Uint64
  144. mutedRecoveryStreak atomic.Uint64
  145. mutedFaultStreak atomic.Uint64
  146. maxCycleNs atomic.Uint64
  147. maxGenerateNs atomic.Uint64
  148. maxUpsampleNs atomic.Uint64
  149. maxWriteNs atomic.Uint64
  150. maxQueueResidenceNs atomic.Uint64
  151. maxPipelineNs atomic.Uint64
  152. lastError atomic.Value // string
  153. lastFault atomic.Value // *FaultEvent
  154. faultHistoryMu sync.Mutex
  155. faultHistory []FaultEvent
  156. transitionHistoryMu sync.Mutex
  157. transitionHistory []RuntimeTransition
  158. degradedTransitions atomic.Uint64
  159. mutedTransitions atomic.Uint64
  160. faultedTransitions atomic.Uint64
  161. faultEvents atomic.Uint64
  162. runtimeStateEnteredAt atomic.Uint64
  163. // Live config: pending frequency change, applied between chunks
  164. pendingFreq atomic.Pointer[float64]
  165. // Most recently tuned frequency (Hz)
  166. appliedFreqHz atomic.Uint64
  167. // Live audio stream (optional)
  168. streamSrc *audio.StreamSource
  169. }
  170. // SetStreamSource configures a live audio stream as the audio source.
  171. // Must be called before Start(). The StreamResampler is created internally
  172. // to convert from the stream's sample rate to the DSP composite rate.
  173. func (e *Engine) SetStreamSource(src *audio.StreamSource) {
  174. e.streamSrc = src
  175. compositeRate := float64(e.cfg.FM.CompositeRateHz)
  176. if compositeRate <= 0 {
  177. compositeRate = 228000
  178. }
  179. resampler := audio.NewStreamResampler(src, compositeRate)
  180. if err := e.generator.SetExternalSource(resampler); err != nil {
  181. // Should never happen: SetStreamSource must be called before Start().
  182. log.Printf("engine: SetExternalSource failed (called too late): %v", err)
  183. return
  184. }
  185. log.Printf("engine: live audio stream wired — initial %d Hz → %.0f Hz composite (buffer %d frames); actual decoded rate auto-corrects on first chunk",
  186. src.SampleRate, compositeRate, src.Stats().Capacity)
  187. }
  188. // SetLicenseState passes license/jingle state to the generator.
  189. // Must be called before Start(). It does not implicitly enable watermarking.
  190. func (e *Engine) SetLicenseState(s *license.State, _ string) {
  191. e.generator.SetLicense(s)
  192. }
  193. // ConfigureWatermark explicitly enables or disables the optional program-audio watermark.
  194. // Must be called before Start().
  195. func (e *Engine) ConfigureWatermark(enabled bool, key string) {
  196. e.generator.ConfigureWatermark(enabled, key)
  197. }
  198. // StreamSource returns the live audio stream source, or nil.
  199. // Used by the control server for stats and HTTP audio ingest.
  200. func (e *Engine) StreamSource() *audio.StreamSource {
  201. return e.streamSrc
  202. }
  203. func NewEngine(cfg cfgpkg.Config, driver platform.SoapyDriver) *Engine {
  204. deviceRate := cfg.EffectiveDeviceRate()
  205. compositeRate := float64(cfg.FM.CompositeRateHz)
  206. if compositeRate <= 0 {
  207. compositeRate = 228000
  208. }
  209. var upsampler *dsp.FMUpsampler
  210. if deviceRate > compositeRate*1.001 {
  211. // Split-rate: DSP chain runs at compositeRate (typ. 228 kHz),
  212. // FMUpsampler handles FM modulation + interpolation to deviceRate.
  213. // This halves CPU load compared to running all DSP at deviceRate.
  214. cfg.FM.FMModulationEnabled = false
  215. maxDev := cfg.FM.MaxDeviationHz
  216. if maxDev <= 0 {
  217. maxDev = 75000
  218. }
  219. // mpxGain scales the FM deviation to compensate for hardware
  220. // DAC/SDR scaling factors. DSP chain stays at logical 0-1.0 levels.
  221. if cfg.FM.MpxGain > 0 && cfg.FM.MpxGain != 1.0 {
  222. maxDev *= cfg.FM.MpxGain
  223. }
  224. upsampler = dsp.NewFMUpsampler(compositeRate, deviceRate, maxDev)
  225. log.Printf("engine: split-rate mode — DSP@%.0fHz → upsample@%.0fHz (ratio %.2f)",
  226. compositeRate, deviceRate, deviceRate/compositeRate)
  227. } else {
  228. // Same-rate: entire DSP chain runs at deviceRate.
  229. // Used when deviceRate ≈ compositeRate (e.g. LimeSDR at 228 kHz).
  230. if deviceRate > 0 {
  231. cfg.FM.CompositeRateHz = int(deviceRate)
  232. }
  233. cfg.FM.FMModulationEnabled = true
  234. log.Printf("engine: same-rate mode — DSP@%dHz", cfg.FM.CompositeRateHz)
  235. }
  236. engine := &Engine{
  237. cfg: cfg,
  238. driver: driver,
  239. generator: offpkg.NewGenerator(cfg),
  240. upsampler: upsampler,
  241. chunkDuration: 50 * time.Millisecond,
  242. deviceRate: deviceRate,
  243. state: EngineIdle,
  244. frameQueue: output.NewFrameQueue(cfg.Runtime.FrameQueueCapacity),
  245. faultHistory: make([]FaultEvent, 0, faultHistoryCapacity),
  246. transitionHistory: make([]RuntimeTransition, 0, runtimeTransitionHistoryCapacity),
  247. }
  248. initFreqHz := cfg.FM.FrequencyMHz * 1e6
  249. engine.appliedFreqHz.Store(math.Float64bits(initFreqHz))
  250. engine.setRuntimeState(RuntimeStateIdle)
  251. return engine
  252. }
  253. func (e *Engine) SetChunkDuration(d time.Duration) {
  254. e.chunkDuration = d
  255. }
  256. // LiveConfigUpdate carries hot-reloadable parameters from the control API.
  257. // nil pointers mean "no change". Validated before applying.
  258. type LiveConfigUpdate struct {
  259. FrequencyMHz *float64
  260. OutputDrive *float64
  261. StereoEnabled *bool
  262. StereoMode *string
  263. PilotLevel *float64
  264. RDSInjection *float64
  265. RDSEnabled *bool
  266. LimiterEnabled *bool
  267. LimiterCeiling *float64
  268. PS *string
  269. RadioText *string
  270. TA *bool
  271. TP *bool
  272. // Tone and gain: live-patchable without engine restart.
  273. ToneLeftHz *float64
  274. ToneRightHz *float64
  275. ToneAmplitude *float64
  276. AudioGain *float64
  277. CompositeClipperEnabled *bool
  278. }
  279. // UpdateConfig applies live parameter changes without restarting the engine.
  280. // DSP params take effect at the next chunk boundary (~50ms max).
  281. // Frequency changes are applied between chunks via driver.Tune().
  282. // RDS text updates are applied at the next RDS group boundary (~88ms).
  283. func (e *Engine) UpdateConfig(u LiveConfigUpdate) error {
  284. // --- Validate ---
  285. if u.FrequencyMHz != nil {
  286. if *u.FrequencyMHz < 65 || *u.FrequencyMHz > 110 {
  287. return fmt.Errorf("frequencyMHz out of range (65-110)")
  288. }
  289. }
  290. if u.OutputDrive != nil {
  291. if *u.OutputDrive < 0 || *u.OutputDrive > 10 {
  292. return fmt.Errorf("outputDrive out of range (0-10)")
  293. }
  294. }
  295. if u.PilotLevel != nil {
  296. if *u.PilotLevel < 0 || *u.PilotLevel > 0.2 {
  297. return fmt.Errorf("pilotLevel out of range (0-0.2)")
  298. }
  299. }
  300. if u.RDSInjection != nil {
  301. if *u.RDSInjection < 0 || *u.RDSInjection > 0.15 {
  302. return fmt.Errorf("rdsInjection out of range (0-0.15)")
  303. }
  304. }
  305. if u.LimiterCeiling != nil {
  306. if *u.LimiterCeiling < 0 || *u.LimiterCeiling > 2 {
  307. return fmt.Errorf("limiterCeiling out of range (0-2)")
  308. }
  309. }
  310. if u.ToneAmplitude != nil {
  311. if *u.ToneAmplitude < 0 || *u.ToneAmplitude > 1 {
  312. return fmt.Errorf("toneAmplitude out of range (0-1)")
  313. }
  314. }
  315. if u.AudioGain != nil {
  316. if *u.AudioGain < 0 || *u.AudioGain > 4 {
  317. return fmt.Errorf("audioGain out of range (0-4)")
  318. }
  319. }
  320. // --- Frequency: store for run loop to apply via driver.Tune() ---
  321. if u.FrequencyMHz != nil {
  322. freqHz := *u.FrequencyMHz * 1e6
  323. e.pendingFreq.Store(&freqHz)
  324. }
  325. // --- RDS text: forward to encoder atomics ---
  326. if u.PS != nil || u.RadioText != nil {
  327. if enc := e.generator.RDSEncoder(); enc != nil {
  328. ps, rt := "", ""
  329. if u.PS != nil {
  330. ps = *u.PS
  331. }
  332. if u.RadioText != nil {
  333. rt = *u.RadioText
  334. }
  335. enc.UpdateText(ps, rt)
  336. }
  337. }
  338. // --- RDS traffic flags: live-update ---
  339. if u.TA != nil || u.TP != nil {
  340. if enc := e.generator.RDSEncoder(); enc != nil {
  341. if u.TA != nil {
  342. enc.UpdateTA(*u.TA)
  343. }
  344. if u.TP != nil {
  345. enc.UpdateTP(*u.TP)
  346. }
  347. }
  348. }
  349. // --- DSP params: build new LiveParams from current + patch ---
  350. // Read current, apply deltas, store new
  351. current := e.generator.CurrentLiveParams()
  352. next := current // copy
  353. if u.OutputDrive != nil {
  354. next.OutputDrive = *u.OutputDrive
  355. }
  356. if u.StereoEnabled != nil {
  357. next.StereoEnabled = *u.StereoEnabled
  358. }
  359. if u.StereoMode != nil {
  360. next.StereoMode = *u.StereoMode
  361. }
  362. if u.PilotLevel != nil {
  363. next.PilotLevel = *u.PilotLevel
  364. }
  365. if u.RDSInjection != nil {
  366. next.RDSInjection = *u.RDSInjection
  367. }
  368. if u.RDSEnabled != nil {
  369. next.RDSEnabled = *u.RDSEnabled
  370. }
  371. if u.LimiterEnabled != nil {
  372. next.LimiterEnabled = *u.LimiterEnabled
  373. }
  374. if u.LimiterCeiling != nil {
  375. next.LimiterCeiling = *u.LimiterCeiling
  376. }
  377. if u.ToneLeftHz != nil {
  378. next.ToneLeftHz = *u.ToneLeftHz
  379. }
  380. if u.ToneRightHz != nil {
  381. next.ToneRightHz = *u.ToneRightHz
  382. }
  383. if u.ToneAmplitude != nil {
  384. next.ToneAmplitude = *u.ToneAmplitude
  385. }
  386. if u.AudioGain != nil {
  387. next.AudioGain = *u.AudioGain
  388. }
  389. if u.CompositeClipperEnabled != nil {
  390. next.CompositeClipperEnabled = *u.CompositeClipperEnabled
  391. }
  392. e.generator.UpdateLive(next)
  393. return nil
  394. }
  395. func (e *Engine) Start(ctx context.Context) error {
  396. e.mu.Lock()
  397. if e.state != EngineIdle {
  398. e.mu.Unlock()
  399. return fmt.Errorf("engine already in state %s", e.state)
  400. }
  401. if err := e.driver.Start(ctx); err != nil {
  402. e.mu.Unlock()
  403. return fmt.Errorf("driver start: %w", err)
  404. }
  405. e.generator.Reset()
  406. if e.upsampler != nil {
  407. e.upsampler.Reset()
  408. }
  409. runCtx, cancel := context.WithCancel(ctx)
  410. e.cancel = cancel
  411. e.state = EngineRunning
  412. e.setRuntimeState(RuntimeStateArming)
  413. e.startedAt = time.Now()
  414. // BUG-A fix: discard any frames left from a previous run so writerLoop
  415. // does not send stale data with expired timestamps on restart.
  416. e.frameQueue.Drain()
  417. e.wg.Add(1)
  418. e.mu.Unlock()
  419. go e.run(runCtx)
  420. return nil
  421. }
  422. func (e *Engine) Stop(ctx context.Context) error {
  423. e.mu.Lock()
  424. if e.state != EngineRunning {
  425. e.mu.Unlock()
  426. return nil
  427. }
  428. e.state = EngineStopping
  429. e.setRuntimeState(RuntimeStateStopping)
  430. e.cancel()
  431. e.mu.Unlock()
  432. // Wait for run() goroutine to exit — deterministic, no guessing
  433. e.wg.Wait()
  434. if err := e.driver.Flush(ctx); err != nil {
  435. return err
  436. }
  437. if err := e.driver.Stop(ctx); err != nil {
  438. return err
  439. }
  440. e.mu.Lock()
  441. e.state = EngineIdle
  442. e.setRuntimeState(RuntimeStateIdle)
  443. e.mu.Unlock()
  444. return nil
  445. }
  446. func (e *Engine) Stats() EngineStats {
  447. e.mu.Lock()
  448. state := e.state
  449. startedAt := e.startedAt
  450. e.mu.Unlock()
  451. var uptime float64
  452. if state == EngineRunning {
  453. uptime = time.Since(startedAt).Seconds()
  454. }
  455. errVal, _ := e.lastError.Load().(string)
  456. queue := e.frameQueue.Stats()
  457. lateBuffers := e.lateBuffers.Load()
  458. hasRecentLateBuffers := e.hasRecentLateBuffers()
  459. ri := runtimeIndicator(queue.Health, hasRecentLateBuffers)
  460. lastFault := e.lastFaultEvent()
  461. activePS, activeRT := "", ""
  462. if enc := e.generator.RDSEncoder(); enc != nil {
  463. activePS, activeRT = enc.CurrentText()
  464. }
  465. return EngineStats{
  466. State: string(e.currentRuntimeState()),
  467. RuntimeStateDurationSeconds: e.runtimeStateDurationSeconds(),
  468. ChunksProduced: e.chunksProduced.Load(),
  469. TotalSamples: e.totalSamples.Load(),
  470. Underruns: e.underruns.Load(),
  471. LateBuffers: lateBuffers,
  472. LastError: errVal,
  473. UptimeSeconds: uptime,
  474. MaxCycleMs: durationMs(e.maxCycleNs.Load()),
  475. MaxGenerateMs: durationMs(e.maxGenerateNs.Load()),
  476. MaxUpsampleMs: durationMs(e.maxUpsampleNs.Load()),
  477. MaxWriteMs: durationMs(e.maxWriteNs.Load()),
  478. MaxQueueResidenceMs: durationMs(e.maxQueueResidenceNs.Load()),
  479. MaxPipelineLatencyMs: durationMs(e.maxPipelineNs.Load()),
  480. Queue: queue,
  481. RuntimeIndicator: ri,
  482. RuntimeAlert: runtimeAlert(queue.Health, hasRecentLateBuffers),
  483. AppliedFrequencyMHz: e.appliedFrequencyMHz(),
  484. ActivePS: activePS,
  485. ActiveRadioText: activeRT,
  486. Measurement: e.generator.LatestMeasurement(),
  487. LastFault: lastFault,
  488. DegradedTransitions: e.degradedTransitions.Load(),
  489. MutedTransitions: e.mutedTransitions.Load(),
  490. FaultedTransitions: e.faultedTransitions.Load(),
  491. FaultCount: e.faultEvents.Load(),
  492. FaultHistory: e.FaultHistory(),
  493. TransitionHistory: e.TransitionHistory(),
  494. }
  495. }
  496. func (e *Engine) appliedFrequencyMHz() float64 {
  497. bits := e.appliedFreqHz.Load()
  498. return math.Float64frombits(bits) / 1e6
  499. }
  500. func runtimeIndicator(queueHealth output.QueueHealth, recentLateBuffers bool) RuntimeIndicator {
  501. switch {
  502. case queueHealth == output.QueueHealthCritical:
  503. return RuntimeIndicatorQueueCritical
  504. case queueHealth == output.QueueHealthLow || recentLateBuffers:
  505. return RuntimeIndicatorDegraded
  506. default:
  507. return RuntimeIndicatorNormal
  508. }
  509. }
  510. func runtimeAlert(queueHealth output.QueueHealth, recentLateBuffers bool) string {
  511. switch {
  512. case queueHealth == output.QueueHealthCritical:
  513. return "queue health critical"
  514. case recentLateBuffers:
  515. return "late buffers"
  516. case queueHealth == output.QueueHealthLow:
  517. return "queue health low"
  518. default:
  519. return ""
  520. }
  521. }
  522. func runtimeStateSeverity(state RuntimeState) string {
  523. switch state {
  524. case RuntimeStateRunning:
  525. return "ok"
  526. case RuntimeStateDegraded, RuntimeStateMuted:
  527. return "warn"
  528. case RuntimeStateFaulted:
  529. return "err"
  530. default:
  531. return "info"
  532. }
  533. }
  534. func (e *Engine) run(ctx context.Context) {
  535. e.setRuntimeState(RuntimeStatePrebuffering)
  536. e.wg.Add(1)
  537. go e.writerLoop(ctx)
  538. defer e.wg.Done()
  539. for {
  540. if ctx.Err() != nil {
  541. return
  542. }
  543. // Apply pending frequency change between chunks
  544. if pf := e.pendingFreq.Swap(nil); pf != nil {
  545. if err := e.driver.Tune(ctx, *pf); err != nil {
  546. e.lastError.Store(fmt.Sprintf("tune: %v", err))
  547. } else {
  548. e.appliedFreqHz.Store(math.Float64bits(*pf))
  549. log.Printf("engine: tuned to %.3f MHz", *pf/1e6)
  550. }
  551. }
  552. t0 := time.Now()
  553. frame := e.generator.GenerateFrame(e.chunkDuration)
  554. frame.GeneratedAt = t0
  555. t1 := time.Now()
  556. if e.upsampler != nil {
  557. frame = e.upsampler.Process(frame)
  558. frame.GeneratedAt = t0
  559. }
  560. t2 := time.Now()
  561. genDur := t1.Sub(t0)
  562. upDur := t2.Sub(t1)
  563. updateMaxDuration(&e.maxGenerateNs, genDur)
  564. updateMaxDuration(&e.maxUpsampleNs, upDur)
  565. // cloneFrame never returns nil when src is non-nil (NEW-3: dead nil check removed)
  566. enqueued := cloneFrame(frame)
  567. enqueued.EnqueuedAt = time.Now()
  568. if err := e.frameQueue.Push(ctx, enqueued); err != nil {
  569. if ctx.Err() != nil {
  570. return
  571. }
  572. if errors.Is(err, output.ErrFrameQueueClosed) {
  573. return
  574. }
  575. e.lastError.Store(err.Error())
  576. e.underruns.Add(1)
  577. select {
  578. case <-time.After(e.chunkDuration):
  579. case <-ctx.Done():
  580. return
  581. }
  582. continue
  583. }
  584. queueStats := e.frameQueue.Stats()
  585. e.evaluateRuntimeState(queueStats, e.hasRecentLateBuffers())
  586. }
  587. }
  588. func (e *Engine) writerLoop(ctx context.Context) {
  589. defer e.wg.Done()
  590. for {
  591. frame, err := e.frameQueue.Pop(ctx)
  592. if err != nil {
  593. if ctx.Err() != nil {
  594. return
  595. }
  596. if errors.Is(err, output.ErrFrameQueueClosed) {
  597. return
  598. }
  599. e.lastError.Store(err.Error())
  600. e.underruns.Add(1)
  601. continue
  602. }
  603. frame.DequeuedAt = time.Now()
  604. queueResidence := time.Duration(0)
  605. if !frame.EnqueuedAt.IsZero() {
  606. queueResidence = frame.DequeuedAt.Sub(frame.EnqueuedAt)
  607. }
  608. writeStart := time.Now()
  609. frame.WriteStartedAt = writeStart
  610. n, err := e.driver.Write(ctx, frame)
  611. writeDur := time.Since(writeStart)
  612. pipelineLatency := writeDur
  613. if !frame.GeneratedAt.IsZero() {
  614. pipelineLatency = time.Since(frame.GeneratedAt)
  615. }
  616. updateMaxDuration(&e.maxWriteNs, writeDur)
  617. updateMaxDuration(&e.maxQueueResidenceNs, queueResidence)
  618. updateMaxDuration(&e.maxPipelineNs, pipelineLatency)
  619. updateMaxDuration(&e.maxCycleNs, writeDur)
  620. queueStats := e.frameQueue.Stats()
  621. e.evaluateRuntimeState(queueStats, e.hasRecentLateBuffers())
  622. lateOver := writeDur - e.chunkDuration
  623. if lateOver > writeLateTolerance {
  624. streak := e.lateBufferStreak.Add(1)
  625. late := e.lateBuffers.Add(1)
  626. // Only arm the alert window once the streak threshold is reached.
  627. // Isolated OS-scheduling or USB jitter spikes (single late writes)
  628. // are normal on a loaded system and must not trigger degraded state.
  629. // This mirrors the queue-health streak logic.
  630. if streak >= lateBufferStreakThreshold {
  631. e.lateBufferAlertAt.Store(uint64(time.Now().UnixNano()))
  632. }
  633. if late <= 5 || late%20 == 0 {
  634. log.Printf("TX LATE [streak=%d]: write=%s budget=%s over=%s tolerance=%s queueResidence=%s pipeline=%s",
  635. streak, writeDur, e.chunkDuration, lateOver, writeLateTolerance, queueResidence, pipelineLatency)
  636. }
  637. } else {
  638. // Clean write — reset the consecutive streak so isolated spikes
  639. // never accumulate toward the threshold.
  640. e.lateBufferStreak.Store(0)
  641. }
  642. if err != nil {
  643. if ctx.Err() != nil {
  644. return
  645. }
  646. e.recordFault(FaultReasonWriteTimeout, FaultSeverityWarn, fmt.Sprintf("driver write error: %v", err))
  647. e.lastError.Store(err.Error())
  648. e.underruns.Add(1)
  649. select {
  650. case <-time.After(e.chunkDuration):
  651. case <-ctx.Done():
  652. return
  653. }
  654. continue
  655. }
  656. e.chunksProduced.Add(1)
  657. e.totalSamples.Add(uint64(n))
  658. }
  659. }
  660. func cloneFrame(src *output.CompositeFrame) *output.CompositeFrame {
  661. if src == nil {
  662. return nil
  663. }
  664. samples := make([]output.IQSample, len(src.Samples))
  665. copy(samples, src.Samples)
  666. return &output.CompositeFrame{
  667. Samples: samples,
  668. SampleRateHz: src.SampleRateHz,
  669. Timestamp: src.Timestamp,
  670. GeneratedAt: src.GeneratedAt,
  671. EnqueuedAt: src.EnqueuedAt,
  672. DequeuedAt: src.DequeuedAt,
  673. WriteStartedAt: src.WriteStartedAt,
  674. Sequence: src.Sequence,
  675. }
  676. }
  677. func (e *Engine) setRuntimeState(state RuntimeState) {
  678. // NEW-2 fix: hold stateMu so that concurrent calls from run() and
  679. // writerLoop() cannot both see prev != state and both record a
  680. // spurious duplicate transition.
  681. e.stateMu.Lock()
  682. defer e.stateMu.Unlock()
  683. now := time.Now()
  684. prev := e.currentRuntimeState()
  685. if prev != state {
  686. e.recordRuntimeTransition(prev, state, now)
  687. switch state {
  688. case RuntimeStateDegraded:
  689. e.degradedTransitions.Add(1)
  690. case RuntimeStateMuted:
  691. e.mutedTransitions.Add(1)
  692. case RuntimeStateFaulted:
  693. e.faultedTransitions.Add(1)
  694. }
  695. e.runtimeStateEnteredAt.Store(uint64(now.UnixNano()))
  696. } else if e.runtimeStateEnteredAt.Load() == 0 {
  697. e.runtimeStateEnteredAt.Store(uint64(now.UnixNano()))
  698. }
  699. e.runtimeState.Store(state)
  700. }
  701. func (e *Engine) currentRuntimeState() RuntimeState {
  702. if v := e.runtimeState.Load(); v != nil {
  703. if rs, ok := v.(RuntimeState); ok {
  704. return rs
  705. }
  706. }
  707. return RuntimeStateIdle
  708. }
  709. func (e *Engine) runtimeStateDurationSeconds() float64 {
  710. if ts := e.runtimeStateEnteredAt.Load(); ts != 0 {
  711. return time.Since(time.Unix(0, int64(ts))).Seconds()
  712. }
  713. return 0
  714. }
  715. func (e *Engine) hasRecentLateBuffers() bool {
  716. lateAlertAt := e.lateBufferAlertAt.Load()
  717. if lateAlertAt == 0 {
  718. return false
  719. }
  720. return time.Since(time.Unix(0, int64(lateAlertAt))) <= lateBufferIndicatorWindow
  721. }
  722. func (e *Engine) lastFaultEvent() *FaultEvent {
  723. return copyFaultEvent(e.loadLastFault())
  724. }
  725. // LastFault exposes the most recent captured fault, if any.
  726. func (e *Engine) LastFault() *FaultEvent {
  727. return e.lastFaultEvent()
  728. }
  729. func (e *Engine) FaultHistory() []FaultEvent {
  730. e.faultHistoryMu.Lock()
  731. defer e.faultHistoryMu.Unlock()
  732. history := make([]FaultEvent, len(e.faultHistory))
  733. copy(history, e.faultHistory)
  734. return history
  735. }
  736. func (e *Engine) TransitionHistory() []RuntimeTransition {
  737. e.transitionHistoryMu.Lock()
  738. defer e.transitionHistoryMu.Unlock()
  739. history := make([]RuntimeTransition, len(e.transitionHistory))
  740. copy(history, e.transitionHistory)
  741. return history
  742. }
  743. func (e *Engine) recordRuntimeTransition(from, to RuntimeState, when time.Time) {
  744. if when.IsZero() {
  745. when = time.Now()
  746. }
  747. ev := RuntimeTransition{
  748. Time: when,
  749. From: from,
  750. To: to,
  751. Severity: runtimeStateSeverity(to),
  752. }
  753. e.transitionHistoryMu.Lock()
  754. defer e.transitionHistoryMu.Unlock()
  755. if len(e.transitionHistory) >= runtimeTransitionHistoryCapacity {
  756. copy(e.transitionHistory, e.transitionHistory[1:])
  757. e.transitionHistory[len(e.transitionHistory)-1] = ev
  758. return
  759. }
  760. e.transitionHistory = append(e.transitionHistory, ev)
  761. }
  762. func (e *Engine) recordFault(reason FaultReason, severity FaultSeverity, message string) {
  763. if reason == "" {
  764. reason = FaultReasonUnknown
  765. }
  766. now := time.Now()
  767. if last := e.loadLastFault(); last != nil {
  768. if last.Reason == reason && last.Severity == severity && now.Sub(last.Time) < faultRepeatWindow {
  769. return
  770. }
  771. }
  772. ev := &FaultEvent{
  773. Time: now,
  774. Reason: reason,
  775. Severity: severity,
  776. Message: message,
  777. }
  778. e.lastFault.Store(ev)
  779. e.appendFaultHistory(ev)
  780. e.faultEvents.Add(1)
  781. }
  782. func (e *Engine) loadLastFault() *FaultEvent {
  783. if v := e.lastFault.Load(); v != nil {
  784. if ev, ok := v.(*FaultEvent); ok {
  785. return ev
  786. }
  787. }
  788. return nil
  789. }
  790. func copyFaultEvent(source *FaultEvent) *FaultEvent {
  791. if source == nil {
  792. return nil
  793. }
  794. copy := *source
  795. return &copy
  796. }
  797. func (e *Engine) appendFaultHistory(ev *FaultEvent) {
  798. e.faultHistoryMu.Lock()
  799. defer e.faultHistoryMu.Unlock()
  800. if len(e.faultHistory) >= faultHistoryCapacity {
  801. copy(e.faultHistory, e.faultHistory[1:])
  802. e.faultHistory[len(e.faultHistory)-1] = *ev
  803. return
  804. }
  805. e.faultHistory = append(e.faultHistory, *ev)
  806. }
  807. func (e *Engine) evaluateRuntimeState(queue output.QueueStats, hasLateBuffers bool) {
  808. state := e.currentRuntimeState()
  809. switch state {
  810. case RuntimeStateStopping, RuntimeStateFaulted:
  811. return
  812. case RuntimeStateMuted:
  813. if queue.Health == output.QueueHealthCritical {
  814. if count := e.mutedFaultStreak.Add(1); count >= queueFaultedStreakThreshold {
  815. e.mutedFaultStreak.Store(0)
  816. e.recordFault(FaultReasonQueueCritical, FaultSeverityFaulted,
  817. fmt.Sprintf("queue health critical for %d checks while muted (depth=%d)", count, queue.Depth))
  818. e.setRuntimeState(RuntimeStateFaulted)
  819. return
  820. }
  821. } else {
  822. e.mutedFaultStreak.Store(0)
  823. }
  824. if queue.Health == output.QueueHealthNormal && !hasLateBuffers {
  825. if count := e.mutedRecoveryStreak.Add(1); count >= queueMutedRecoveryThreshold {
  826. e.mutedRecoveryStreak.Store(0)
  827. e.mutedFaultStreak.Store(0)
  828. e.recordFault(FaultReasonQueueCritical, FaultSeverityDegraded,
  829. fmt.Sprintf("queue healthy for %d checks after mute", count))
  830. e.setRuntimeState(RuntimeStateDegraded)
  831. }
  832. } else {
  833. e.mutedRecoveryStreak.Store(0)
  834. }
  835. return
  836. }
  837. if state == RuntimeStatePrebuffering {
  838. if queue.Depth >= 1 {
  839. e.setRuntimeState(RuntimeStateRunning)
  840. }
  841. return
  842. }
  843. critical := queue.Health == output.QueueHealthCritical
  844. if critical {
  845. count := e.criticalStreak.Add(1)
  846. if count >= queueMutedStreakThreshold {
  847. e.recordFault(FaultReasonQueueCritical, FaultSeverityMuted,
  848. fmt.Sprintf("queue health critical for %d consecutive checks (depth=%d)", count, queue.Depth))
  849. e.setRuntimeState(RuntimeStateMuted)
  850. return
  851. }
  852. if count >= queueCriticalStreakThreshold {
  853. e.recordFault(FaultReasonQueueCritical, FaultSeverityDegraded,
  854. fmt.Sprintf("queue health critical (depth=%d)", queue.Depth))
  855. e.setRuntimeState(RuntimeStateDegraded)
  856. return
  857. }
  858. } else {
  859. e.criticalStreak.Store(0)
  860. }
  861. if hasLateBuffers {
  862. e.recordFault(FaultReasonLateBuffers, FaultSeverityWarn,
  863. fmt.Sprintf("late buffers detected (health=%s)", queue.Health))
  864. e.setRuntimeState(RuntimeStateDegraded)
  865. return
  866. }
  867. e.setRuntimeState(RuntimeStateRunning)
  868. }
  869. // ResetFault attempts to move the engine out of the faulted state.
  870. func (e *Engine) ResetFault() error {
  871. state := e.currentRuntimeState()
  872. if state != RuntimeStateFaulted {
  873. return fmt.Errorf("engine not in faulted state (current=%s)", state)
  874. }
  875. e.criticalStreak.Store(0)
  876. e.mutedRecoveryStreak.Store(0)
  877. e.mutedFaultStreak.Store(0)
  878. e.setRuntimeState(RuntimeStateDegraded)
  879. return nil
  880. }