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

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