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ů.

915 řádky
27KB

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