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

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