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.

959 line
28KB

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