Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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