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

888 строки
26KB

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