Wideband autonomous SDR analysis engine forked from sdr-visual-suite
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1002 lines
31KB

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "strings"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "sdr-wideband-suite/internal/classifier"
  10. "sdr-wideband-suite/internal/config"
  11. "sdr-wideband-suite/internal/demod"
  12. "sdr-wideband-suite/internal/detector"
  13. "sdr-wideband-suite/internal/dsp"
  14. fftutil "sdr-wideband-suite/internal/fft"
  15. "sdr-wideband-suite/internal/fft/gpufft"
  16. "sdr-wideband-suite/internal/pipeline"
  17. "sdr-wideband-suite/internal/rds"
  18. "sdr-wideband-suite/internal/recorder"
  19. )
  20. type rdsState struct {
  21. dec rds.Decoder
  22. result rds.Result
  23. lastDecode time.Time
  24. busy int32
  25. mu sync.Mutex
  26. }
  27. type dspRuntime struct {
  28. cfg config.Config
  29. det *detector.Detector
  30. derivedDetectors map[string]*derivedDetector
  31. nextDerivedBase int64
  32. window []float64
  33. plan *fftutil.CmplxPlan
  34. detailWindow []float64
  35. detailPlan *fftutil.CmplxPlan
  36. detailFFT int
  37. survWindows map[int][]float64
  38. survPlans map[int]*fftutil.CmplxPlan
  39. survFIR map[int][]float64
  40. dcEnabled bool
  41. iqEnabled bool
  42. useGPU bool
  43. gpuEngine *gpufft.Engine
  44. rdsMap map[int64]*rdsState
  45. streamPhaseState map[int64]*streamExtractState
  46. streamOverlap *streamIQOverlap
  47. arbiter *pipeline.Arbiter
  48. arbitration pipeline.ArbitrationState
  49. gotSamples bool
  50. }
  51. type spectrumArtifacts struct {
  52. allIQ []complex64
  53. surveillanceIQ []complex64
  54. detailIQ []complex64
  55. surveillanceSpectrum []float64
  56. surveillanceSpectra []pipeline.SurveillanceLevelSpectrum
  57. surveillancePlan surveillancePlan
  58. detailSpectrum []float64
  59. finished []detector.Event
  60. detected []detector.Signal
  61. thresholds []float64
  62. noiseFloor float64
  63. now time.Time
  64. }
  65. type derivedDetector struct {
  66. det *detector.Detector
  67. sampleRate int
  68. fftSize int
  69. idBase int64
  70. }
  71. type surveillanceLevelSpec struct {
  72. Level pipeline.AnalysisLevel
  73. Decim int
  74. AllowGPU bool
  75. }
  76. type surveillancePlan struct {
  77. Primary pipeline.AnalysisLevel
  78. Levels []pipeline.AnalysisLevel
  79. LevelSet pipeline.SurveillanceLevelSet
  80. Presentation pipeline.AnalysisLevel
  81. Context pipeline.AnalysisContext
  82. DetectionPolicy pipeline.SurveillanceDetectionPolicy
  83. Specs []surveillanceLevelSpec
  84. }
  85. const derivedIDBlock = int64(1_000_000_000)
  86. func newDSPRuntime(cfg config.Config, det *detector.Detector, window []float64, gpuState *gpuStatus) *dspRuntime {
  87. detailFFT := cfg.Refinement.DetailFFTSize
  88. if detailFFT <= 0 {
  89. detailFFT = cfg.FFTSize
  90. }
  91. rt := &dspRuntime{
  92. cfg: cfg,
  93. det: det,
  94. derivedDetectors: map[string]*derivedDetector{},
  95. nextDerivedBase: -derivedIDBlock,
  96. window: window,
  97. plan: fftutil.NewCmplxPlan(cfg.FFTSize),
  98. detailWindow: fftutil.Hann(detailFFT),
  99. detailPlan: fftutil.NewCmplxPlan(detailFFT),
  100. detailFFT: detailFFT,
  101. survWindows: map[int][]float64{},
  102. survPlans: map[int]*fftutil.CmplxPlan{},
  103. survFIR: map[int][]float64{},
  104. dcEnabled: cfg.DCBlock,
  105. iqEnabled: cfg.IQBalance,
  106. useGPU: cfg.UseGPUFFT,
  107. rdsMap: map[int64]*rdsState{},
  108. streamPhaseState: map[int64]*streamExtractState{},
  109. streamOverlap: &streamIQOverlap{},
  110. arbiter: pipeline.NewArbiter(),
  111. }
  112. if rt.useGPU && gpuState != nil {
  113. snap := gpuState.snapshot()
  114. if snap.Available {
  115. if eng, err := gpufft.New(cfg.FFTSize); err == nil {
  116. rt.gpuEngine = eng
  117. gpuState.set(true, nil)
  118. } else {
  119. gpuState.set(false, err)
  120. rt.useGPU = false
  121. }
  122. }
  123. }
  124. return rt
  125. }
  126. func (rt *dspRuntime) applyUpdate(upd dspUpdate, srcMgr *sourceManager, rec *recorder.Manager, gpuState *gpuStatus) {
  127. prevFFT := rt.cfg.FFTSize
  128. prevSampleRate := rt.cfg.SampleRate
  129. prevUseGPU := rt.useGPU
  130. prevDetailFFT := rt.detailFFT
  131. rt.cfg = upd.cfg
  132. if rec != nil {
  133. rec.Update(rt.cfg.SampleRate, rt.cfg.FFTSize, recorder.Policy{
  134. Enabled: rt.cfg.Recorder.Enabled,
  135. MinSNRDb: rt.cfg.Recorder.MinSNRDb,
  136. MinDuration: mustParseDuration(rt.cfg.Recorder.MinDuration, 1*time.Second),
  137. MaxDuration: mustParseDuration(rt.cfg.Recorder.MaxDuration, 300*time.Second),
  138. PrerollMs: rt.cfg.Recorder.PrerollMs,
  139. RecordIQ: rt.cfg.Recorder.RecordIQ,
  140. RecordAudio: rt.cfg.Recorder.RecordAudio,
  141. AutoDemod: rt.cfg.Recorder.AutoDemod,
  142. AutoDecode: rt.cfg.Recorder.AutoDecode,
  143. MaxDiskMB: rt.cfg.Recorder.MaxDiskMB,
  144. OutputDir: rt.cfg.Recorder.OutputDir,
  145. ClassFilter: rt.cfg.Recorder.ClassFilter,
  146. RingSeconds: rt.cfg.Recorder.RingSeconds,
  147. DeemphasisUs: rt.cfg.Recorder.DeemphasisUs,
  148. ExtractionTaps: rt.cfg.Recorder.ExtractionTaps,
  149. ExtractionBwMult: rt.cfg.Recorder.ExtractionBwMult,
  150. }, rt.cfg.CenterHz, buildDecoderMap(rt.cfg))
  151. }
  152. if upd.det != nil {
  153. rt.det = upd.det
  154. }
  155. if upd.window != nil {
  156. rt.window = upd.window
  157. rt.plan = fftutil.NewCmplxPlan(rt.cfg.FFTSize)
  158. }
  159. detailFFT := rt.cfg.Refinement.DetailFFTSize
  160. if detailFFT <= 0 {
  161. detailFFT = rt.cfg.FFTSize
  162. }
  163. if detailFFT != prevDetailFFT {
  164. rt.detailFFT = detailFFT
  165. rt.detailWindow = fftutil.Hann(detailFFT)
  166. rt.detailPlan = fftutil.NewCmplxPlan(detailFFT)
  167. }
  168. if prevSampleRate != rt.cfg.SampleRate {
  169. rt.survFIR = map[int][]float64{}
  170. }
  171. if prevFFT != rt.cfg.FFTSize {
  172. rt.survWindows = map[int][]float64{}
  173. rt.survPlans = map[int]*fftutil.CmplxPlan{}
  174. }
  175. if upd.det != nil || prevSampleRate != rt.cfg.SampleRate || prevFFT != rt.cfg.FFTSize {
  176. rt.derivedDetectors = map[string]*derivedDetector{}
  177. rt.nextDerivedBase = -derivedIDBlock
  178. }
  179. rt.dcEnabled = upd.dcBlock
  180. rt.iqEnabled = upd.iqBalance
  181. if rt.cfg.FFTSize != prevFFT || rt.cfg.UseGPUFFT != prevUseGPU {
  182. srcMgr.Flush()
  183. rt.gotSamples = false
  184. if rt.gpuEngine != nil {
  185. rt.gpuEngine.Close()
  186. rt.gpuEngine = nil
  187. }
  188. rt.useGPU = rt.cfg.UseGPUFFT
  189. if rt.useGPU && gpuState != nil {
  190. snap := gpuState.snapshot()
  191. if snap.Available {
  192. if eng, err := gpufft.New(rt.cfg.FFTSize); err == nil {
  193. rt.gpuEngine = eng
  194. gpuState.set(true, nil)
  195. } else {
  196. gpuState.set(false, err)
  197. rt.useGPU = false
  198. }
  199. } else {
  200. gpuState.set(false, nil)
  201. rt.useGPU = false
  202. }
  203. } else if gpuState != nil {
  204. gpuState.set(false, nil)
  205. }
  206. }
  207. }
  208. func (rt *dspRuntime) spectrumFromIQ(iq []complex64, gpuState *gpuStatus) []float64 {
  209. return rt.spectrumFromIQWithPlan(iq, rt.window, rt.plan, gpuState, true)
  210. }
  211. func (rt *dspRuntime) spectrumFromIQWithPlan(iq []complex64, window []float64, plan *fftutil.CmplxPlan, gpuState *gpuStatus, allowGPU bool) []float64 {
  212. if len(iq) == 0 {
  213. return nil
  214. }
  215. if allowGPU && rt.useGPU && rt.gpuEngine != nil {
  216. gpuBuf := make([]complex64, len(iq))
  217. if len(window) == len(iq) {
  218. for i := 0; i < len(iq); i++ {
  219. v := iq[i]
  220. w := float32(window[i])
  221. gpuBuf[i] = complex(real(v)*w, imag(v)*w)
  222. }
  223. } else {
  224. copy(gpuBuf, iq)
  225. }
  226. out, err := rt.gpuEngine.Exec(gpuBuf)
  227. if err != nil {
  228. if gpuState != nil {
  229. gpuState.set(false, err)
  230. }
  231. rt.useGPU = false
  232. return fftutil.SpectrumWithPlan(gpuBuf, nil, plan)
  233. }
  234. return fftutil.SpectrumFromFFT(out)
  235. }
  236. return fftutil.SpectrumWithPlan(iq, window, plan)
  237. }
  238. func (rt *dspRuntime) windowForFFT(fftSize int) []float64 {
  239. if fftSize <= 0 {
  240. return nil
  241. }
  242. if fftSize == rt.cfg.FFTSize {
  243. return rt.window
  244. }
  245. if rt.survWindows == nil {
  246. rt.survWindows = map[int][]float64{}
  247. }
  248. if window, ok := rt.survWindows[fftSize]; ok {
  249. return window
  250. }
  251. window := fftutil.Hann(fftSize)
  252. rt.survWindows[fftSize] = window
  253. return window
  254. }
  255. func (rt *dspRuntime) planForFFT(fftSize int) *fftutil.CmplxPlan {
  256. if fftSize <= 0 {
  257. return nil
  258. }
  259. if fftSize == rt.cfg.FFTSize {
  260. return rt.plan
  261. }
  262. if rt.survPlans == nil {
  263. rt.survPlans = map[int]*fftutil.CmplxPlan{}
  264. }
  265. if plan, ok := rt.survPlans[fftSize]; ok {
  266. return plan
  267. }
  268. plan := fftutil.NewCmplxPlan(fftSize)
  269. rt.survPlans[fftSize] = plan
  270. return plan
  271. }
  272. func (rt *dspRuntime) spectrumForLevel(iq []complex64, fftSize int, gpuState *gpuStatus, allowGPU bool) []float64 {
  273. if len(iq) == 0 || fftSize <= 0 {
  274. return nil
  275. }
  276. if len(iq) > fftSize {
  277. iq = iq[len(iq)-fftSize:]
  278. }
  279. window := rt.windowForFFT(fftSize)
  280. plan := rt.planForFFT(fftSize)
  281. return rt.spectrumFromIQWithPlan(iq, window, plan, gpuState, allowGPU)
  282. }
  283. func sanitizeSpectrum(spectrum []float64) {
  284. for i := range spectrum {
  285. if math.IsNaN(spectrum[i]) || math.IsInf(spectrum[i], 0) {
  286. spectrum[i] = -200
  287. }
  288. }
  289. }
  290. func (rt *dspRuntime) decimationTaps(factor int) []float64 {
  291. if factor <= 1 {
  292. return nil
  293. }
  294. if rt.survFIR == nil {
  295. rt.survFIR = map[int][]float64{}
  296. }
  297. if taps, ok := rt.survFIR[factor]; ok {
  298. return taps
  299. }
  300. cutoff := float64(rt.cfg.SampleRate/factor) * 0.5 * 0.8
  301. taps := dsp.LowpassFIR(cutoff, rt.cfg.SampleRate, 101)
  302. rt.survFIR[factor] = taps
  303. return taps
  304. }
  305. func (rt *dspRuntime) decimateSurveillanceIQ(iq []complex64, factor int) []complex64 {
  306. if factor <= 1 {
  307. return iq
  308. }
  309. taps := rt.decimationTaps(factor)
  310. if len(taps) == 0 {
  311. return dsp.Decimate(iq, factor)
  312. }
  313. filtered := dsp.ApplyFIR(iq, taps)
  314. return dsp.Decimate(filtered, factor)
  315. }
  316. func (rt *dspRuntime) captureSpectrum(srcMgr *sourceManager, rec *recorder.Manager, dcBlocker *dsp.DCBlocker, gpuState *gpuStatus) (*spectrumArtifacts, error) {
  317. required := rt.cfg.FFTSize
  318. if rt.detailFFT > required {
  319. required = rt.detailFFT
  320. }
  321. available := required
  322. st := srcMgr.Stats()
  323. if st.BufferSamples > required {
  324. available = (st.BufferSamples / required) * required
  325. if available < required {
  326. available = required
  327. }
  328. }
  329. allIQ, err := srcMgr.ReadIQ(available)
  330. if err != nil {
  331. return nil, err
  332. }
  333. if rec != nil {
  334. rec.Ingest(time.Now(), allIQ)
  335. }
  336. survIQ := allIQ
  337. if len(allIQ) > rt.cfg.FFTSize {
  338. survIQ = allIQ[len(allIQ)-rt.cfg.FFTSize:]
  339. }
  340. detailIQ := survIQ
  341. if rt.detailFFT > 0 && len(allIQ) >= rt.detailFFT {
  342. detailIQ = allIQ[len(allIQ)-rt.detailFFT:]
  343. }
  344. if rt.dcEnabled {
  345. dcBlocker.Apply(allIQ)
  346. }
  347. if rt.iqEnabled {
  348. dsp.IQBalance(survIQ)
  349. if !sameIQBuffer(detailIQ, survIQ) {
  350. detailIQ = append([]complex64(nil), detailIQ...)
  351. dsp.IQBalance(detailIQ)
  352. }
  353. }
  354. survSpectrum := rt.spectrumFromIQ(survIQ, gpuState)
  355. sanitizeSpectrum(survSpectrum)
  356. detailSpectrum := survSpectrum
  357. if !sameIQBuffer(detailIQ, survIQ) {
  358. detailSpectrum = rt.spectrumFromIQWithPlan(detailIQ, rt.detailWindow, rt.detailPlan, gpuState, false)
  359. sanitizeSpectrum(detailSpectrum)
  360. }
  361. policy := pipeline.PolicyFromConfig(rt.cfg)
  362. plan := rt.buildSurveillancePlan(policy)
  363. surveillanceSpectra := make([]pipeline.SurveillanceLevelSpectrum, 0, len(plan.Specs))
  364. for _, spec := range plan.Specs {
  365. if spec.Level.FFTSize <= 0 {
  366. continue
  367. }
  368. var spectrum []float64
  369. if spec.Decim <= 1 {
  370. if spec.Level.FFTSize == len(survSpectrum) {
  371. spectrum = survSpectrum
  372. } else {
  373. spectrum = rt.spectrumForLevel(survIQ, spec.Level.FFTSize, gpuState, spec.AllowGPU)
  374. sanitizeSpectrum(spectrum)
  375. }
  376. } else {
  377. required := spec.Level.FFTSize * spec.Decim
  378. if required > len(survIQ) {
  379. continue
  380. }
  381. src := survIQ
  382. if len(src) > required {
  383. src = src[len(src)-required:]
  384. }
  385. decimated := rt.decimateSurveillanceIQ(src, spec.Decim)
  386. spectrum = rt.spectrumForLevel(decimated, spec.Level.FFTSize, gpuState, false)
  387. sanitizeSpectrum(spectrum)
  388. }
  389. if len(spectrum) == 0 {
  390. continue
  391. }
  392. surveillanceSpectra = append(surveillanceSpectra, pipeline.SurveillanceLevelSpectrum{Level: spec.Level, Spectrum: spectrum})
  393. }
  394. now := time.Now()
  395. finished, detected := rt.det.Process(now, survSpectrum, rt.cfg.CenterHz)
  396. return &spectrumArtifacts{
  397. allIQ: allIQ,
  398. surveillanceIQ: survIQ,
  399. detailIQ: detailIQ,
  400. surveillanceSpectrum: survSpectrum,
  401. surveillanceSpectra: surveillanceSpectra,
  402. surveillancePlan: plan,
  403. detailSpectrum: detailSpectrum,
  404. finished: finished,
  405. detected: detected,
  406. thresholds: rt.det.LastThresholds(),
  407. noiseFloor: rt.det.LastNoiseFloor(),
  408. now: now,
  409. }, nil
  410. }
  411. func (rt *dspRuntime) buildSurveillanceResult(art *spectrumArtifacts) pipeline.SurveillanceResult {
  412. if art == nil {
  413. return pipeline.SurveillanceResult{}
  414. }
  415. policy := pipeline.PolicyFromConfig(rt.cfg)
  416. plan := art.surveillancePlan
  417. if plan.Primary.Name == "" {
  418. plan = rt.buildSurveillancePlan(policy)
  419. }
  420. primaryCandidates := pipeline.CandidatesFromSignalsWithLevel(art.detected, "surveillance-detector", plan.Primary)
  421. derivedCandidates := rt.detectDerivedCandidates(art, plan)
  422. candidates := pipeline.FuseCandidates(primaryCandidates, derivedCandidates)
  423. pipeline.ApplyMonitorWindowMatchesToCandidates(policy, candidates)
  424. scheduled := pipeline.ScheduleCandidates(candidates, policy)
  425. return pipeline.SurveillanceResult{
  426. Level: plan.Primary,
  427. Levels: plan.Levels,
  428. LevelSet: plan.LevelSet,
  429. DetectionPolicy: plan.DetectionPolicy,
  430. DisplayLevel: plan.Presentation,
  431. Context: plan.Context,
  432. Spectra: art.surveillanceSpectra,
  433. Candidates: candidates,
  434. Scheduled: scheduled,
  435. Finished: art.finished,
  436. Signals: art.detected,
  437. NoiseFloor: art.noiseFloor,
  438. Thresholds: art.thresholds,
  439. }
  440. }
  441. func (rt *dspRuntime) detectDerivedCandidates(art *spectrumArtifacts, plan surveillancePlan) []pipeline.Candidate {
  442. if art == nil || len(plan.LevelSet.Derived) == 0 {
  443. return nil
  444. }
  445. spectra := map[string][]float64{}
  446. for _, spec := range art.surveillanceSpectra {
  447. if spec.Level.Name == "" || len(spec.Spectrum) == 0 {
  448. continue
  449. }
  450. spectra[spec.Level.Name] = spec.Spectrum
  451. }
  452. if len(spectra) == 0 {
  453. return nil
  454. }
  455. out := make([]pipeline.Candidate, 0, len(plan.LevelSet.Derived))
  456. for _, level := range plan.LevelSet.Derived {
  457. if level.Name == "" {
  458. continue
  459. }
  460. if !pipeline.IsDetectionLevel(level) {
  461. continue
  462. }
  463. spectrum := spectra[level.Name]
  464. if len(spectrum) == 0 {
  465. continue
  466. }
  467. entry := rt.derivedDetectorForLevel(level)
  468. if entry == nil || entry.det == nil {
  469. continue
  470. }
  471. _, signals := entry.det.Process(art.now, spectrum, level.CenterHz)
  472. if len(signals) == 0 {
  473. continue
  474. }
  475. cands := pipeline.CandidatesFromSignalsWithLevel(signals, "surveillance-derived", level)
  476. for i := range cands {
  477. if cands[i].ID == 0 {
  478. continue
  479. }
  480. cands[i].ID = entry.idBase - cands[i].ID
  481. }
  482. out = append(out, cands...)
  483. }
  484. if len(out) == 0 {
  485. return nil
  486. }
  487. return out
  488. }
  489. func (rt *dspRuntime) derivedDetectorForLevel(level pipeline.AnalysisLevel) *derivedDetector {
  490. if level.SampleRate <= 0 || level.FFTSize <= 0 {
  491. return nil
  492. }
  493. if rt.derivedDetectors == nil {
  494. rt.derivedDetectors = map[string]*derivedDetector{}
  495. }
  496. key := level.Name
  497. if key == "" {
  498. key = fmt.Sprintf("%d:%d", level.SampleRate, level.FFTSize)
  499. }
  500. entry := rt.derivedDetectors[key]
  501. if entry != nil && entry.sampleRate == level.SampleRate && entry.fftSize == level.FFTSize {
  502. return entry
  503. }
  504. if rt.nextDerivedBase == 0 {
  505. rt.nextDerivedBase = -derivedIDBlock
  506. }
  507. entry = &derivedDetector{
  508. det: detector.New(rt.cfg.Detector, level.SampleRate, level.FFTSize),
  509. sampleRate: level.SampleRate,
  510. fftSize: level.FFTSize,
  511. idBase: rt.nextDerivedBase,
  512. }
  513. rt.nextDerivedBase -= derivedIDBlock
  514. rt.derivedDetectors[key] = entry
  515. return entry
  516. }
  517. func (rt *dspRuntime) buildRefinementInput(surv pipeline.SurveillanceResult, now time.Time) pipeline.RefinementInput {
  518. policy := pipeline.PolicyFromConfig(rt.cfg)
  519. baseBudget := pipeline.BudgetModelFromPolicy(policy)
  520. pressure := pipeline.BuildBudgetPressureSummary(baseBudget, rt.arbitration.Refinement, rt.arbitration.Queue)
  521. budget := pipeline.ApplyBudgetRebalance(policy, baseBudget, pressure)
  522. plan := pipeline.BuildRefinementPlanWithBudget(surv.Candidates, policy, budget)
  523. admission := rt.arbiter.AdmitRefinementWithBudget(plan, policy, budget, now)
  524. plan = admission.Plan
  525. workItems := make([]pipeline.RefinementWorkItem, 0, len(admission.WorkItems))
  526. if len(admission.WorkItems) > 0 {
  527. workItems = append(workItems, admission.WorkItems...)
  528. }
  529. scheduled := append([]pipeline.ScheduledCandidate(nil), admission.Admitted...)
  530. workIndex := map[int64]int{}
  531. for i := range workItems {
  532. if workItems[i].Candidate.ID == 0 {
  533. continue
  534. }
  535. workIndex[workItems[i].Candidate.ID] = i
  536. }
  537. windows := make([]pipeline.RefinementWindow, 0, len(scheduled))
  538. for _, sc := range scheduled {
  539. window := pipeline.RefinementWindowForCandidate(policy, sc.Candidate)
  540. windows = append(windows, window)
  541. if idx, ok := workIndex[sc.Candidate.ID]; ok {
  542. workItems[idx].Window = window
  543. }
  544. }
  545. detailFFT := rt.cfg.Refinement.DetailFFTSize
  546. if detailFFT <= 0 {
  547. detailFFT = rt.cfg.FFTSize
  548. }
  549. levelSpan := spanForPolicy(policy, float64(rt.cfg.SampleRate))
  550. if _, maxSpan, ok := windowSpanBounds(windows); ok {
  551. levelSpan = maxSpan
  552. }
  553. level := analysisLevel("refinement", "refinement", "refinement", rt.cfg.SampleRate, detailFFT, rt.cfg.CenterHz, levelSpan, "refinement-window", 1, rt.cfg.SampleRate)
  554. detailLevel := analysisLevel("detail", "detail", "refinement", rt.cfg.SampleRate, detailFFT, rt.cfg.CenterHz, levelSpan, "detail-spectrum", 1, rt.cfg.SampleRate)
  555. if len(workItems) > 0 {
  556. for i := range workItems {
  557. item := &workItems[i]
  558. if item.Window.SpanHz <= 0 {
  559. continue
  560. }
  561. item.Execution = &pipeline.RefinementExecution{
  562. Stage: "refine",
  563. SampleRate: rt.cfg.SampleRate,
  564. FFTSize: detailFFT,
  565. CenterHz: item.Window.CenterHz,
  566. SpanHz: item.Window.SpanHz,
  567. Source: detailLevel.Source,
  568. }
  569. }
  570. }
  571. input := pipeline.RefinementInput{
  572. Level: level,
  573. Detail: detailLevel,
  574. Context: surv.Context,
  575. Request: pipeline.RefinementRequest{Strategy: plan.Strategy, Reason: "surveillance-plan", SpanHintHz: levelSpan},
  576. Budgets: budget,
  577. Admission: admission.Admission,
  578. Candidates: append([]pipeline.Candidate(nil), surv.Candidates...),
  579. Scheduled: scheduled,
  580. WorkItems: workItems,
  581. Plan: plan,
  582. Windows: windows,
  583. SampleRate: rt.cfg.SampleRate,
  584. FFTSize: detailFFT,
  585. CenterHz: rt.cfg.CenterHz,
  586. Source: "surveillance-detector",
  587. }
  588. input.Context.Refinement = level
  589. input.Context.Detail = detailLevel
  590. if !policy.RefinementEnabled {
  591. for i := range input.WorkItems {
  592. item := &input.WorkItems[i]
  593. if item.Status == pipeline.RefinementStatusDropped {
  594. continue
  595. }
  596. item.Status = pipeline.RefinementStatusDropped
  597. item.Reason = pipeline.RefinementReasonDisabled
  598. }
  599. input.Scheduled = nil
  600. input.Request.Reason = pipeline.ReasonAdmissionDisabled
  601. input.Admission.Reason = pipeline.ReasonAdmissionDisabled
  602. input.Admission.Admitted = 0
  603. input.Admission.Skipped = 0
  604. input.Admission.Displaced = 0
  605. input.Plan.Selected = nil
  606. input.Plan.DroppedByBudget = 0
  607. }
  608. rt.setArbitration(policy, input.Budgets, input.Admission, rt.arbitration.Queue)
  609. return input
  610. }
  611. func (rt *dspRuntime) runRefinement(art *spectrumArtifacts, surv pipeline.SurveillanceResult, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementStep {
  612. input := rt.buildRefinementInput(surv, art.now)
  613. markWorkItemsStatus(input.WorkItems, pipeline.RefinementStatusAdmitted, pipeline.RefinementStatusRunning, pipeline.RefinementReasonRunning)
  614. result := rt.refineSignals(art, input, extractMgr, rec)
  615. markWorkItemsCompleted(input.WorkItems, result.Candidates)
  616. return pipeline.RefinementStep{Input: input, Result: result}
  617. }
  618. func (rt *dspRuntime) refineSignals(art *spectrumArtifacts, input pipeline.RefinementInput, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementResult {
  619. if art == nil || len(art.detailIQ) == 0 || len(input.Scheduled) == 0 {
  620. return pipeline.RefinementResult{}
  621. }
  622. policy := pipeline.PolicyFromConfig(rt.cfg)
  623. selectedCandidates := make([]pipeline.Candidate, 0, len(input.Scheduled))
  624. selectedSignals := make([]detector.Signal, 0, len(input.Scheduled))
  625. for _, sc := range input.Scheduled {
  626. selectedCandidates = append(selectedCandidates, sc.Candidate)
  627. selectedSignals = append(selectedSignals, detector.Signal{
  628. ID: sc.Candidate.ID,
  629. FirstBin: sc.Candidate.FirstBin,
  630. LastBin: sc.Candidate.LastBin,
  631. CenterHz: sc.Candidate.CenterHz,
  632. BWHz: sc.Candidate.BandwidthHz,
  633. PeakDb: sc.Candidate.PeakDb,
  634. SNRDb: sc.Candidate.SNRDb,
  635. NoiseDb: sc.Candidate.NoiseDb,
  636. })
  637. }
  638. sampleRate := input.SampleRate
  639. fftSize := input.FFTSize
  640. centerHz := input.CenterHz
  641. if sampleRate <= 0 {
  642. sampleRate = rt.cfg.SampleRate
  643. }
  644. if fftSize <= 0 {
  645. fftSize = rt.cfg.FFTSize
  646. }
  647. if centerHz == 0 {
  648. centerHz = rt.cfg.CenterHz
  649. }
  650. snips, snipRates := extractSignalIQBatch(extractMgr, art.detailIQ, sampleRate, centerHz, selectedSignals)
  651. refined := pipeline.RefineCandidates(selectedCandidates, input.Windows, art.detailSpectrum, sampleRate, fftSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  652. signals := make([]detector.Signal, 0, len(refined))
  653. decisions := make([]pipeline.SignalDecision, 0, len(refined))
  654. for i, ref := range refined {
  655. sig := ref.Signal
  656. signals = append(signals, sig)
  657. cls := sig.Class
  658. snipRate := ref.SnippetRate
  659. decision := pipeline.DecideSignalAction(policy, ref.Candidate, cls)
  660. decisions = append(decisions, decision)
  661. if cls != nil {
  662. pll := classifier.PLLResult{}
  663. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  664. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  665. cls.PLL = &pll
  666. signals[i].PLL = &pll
  667. if cls.ModType == classifier.ClassWFM && pll.Stereo {
  668. cls.ModType = classifier.ClassWFMStereo
  669. }
  670. }
  671. if (cls.ModType == classifier.ClassWFM || cls.ModType == classifier.ClassWFMStereo) && rec != nil {
  672. rt.updateRDS(art.now, rec, &signals[i], cls)
  673. }
  674. }
  675. }
  676. budget := input.Budgets
  677. queueStats := rt.arbiter.ApplyDecisions(decisions, budget, art.now, policy)
  678. rt.setArbitration(policy, budget, input.Admission, queueStats)
  679. summary := summarizeDecisions(decisions)
  680. if rec != nil {
  681. if summary.RecordEnabled > 0 {
  682. rt.cfg.Recorder.Enabled = true
  683. }
  684. if summary.DecodeEnabled > 0 {
  685. rt.cfg.Recorder.AutoDecode = true
  686. }
  687. }
  688. rt.det.UpdateClasses(signals)
  689. return pipeline.RefinementResult{Level: input.Level, Signals: signals, Decisions: decisions, Candidates: selectedCandidates}
  690. }
  691. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  692. if sig == nil || cls == nil {
  693. return
  694. }
  695. keyHz := sig.CenterHz
  696. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  697. keyHz = sig.PLL.ExactHz
  698. }
  699. key := int64(math.Round(keyHz / 25000.0))
  700. st := rt.rdsMap[key]
  701. if st == nil {
  702. st = &rdsState{}
  703. rt.rdsMap[key] = st
  704. }
  705. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  706. st.lastDecode = now
  707. atomic.StoreInt32(&st.busy, 1)
  708. go func(st *rdsState, sigHz float64) {
  709. defer atomic.StoreInt32(&st.busy, 0)
  710. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  711. if len(ringIQ) < ringSR || ringSR <= 0 {
  712. return
  713. }
  714. offset := sigHz - ringCenter
  715. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  716. decim1 := ringSR / 1000000
  717. if decim1 < 1 {
  718. decim1 = 1
  719. }
  720. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  721. f1 := dsp.ApplyFIR(shifted, lp1)
  722. d1 := dsp.Decimate(f1, decim1)
  723. rate1 := ringSR / decim1
  724. decim2 := rate1 / 250000
  725. if decim2 < 1 {
  726. decim2 = 1
  727. }
  728. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  729. f2 := dsp.ApplyFIR(d1, lp2)
  730. decimated := dsp.Decimate(f2, decim2)
  731. actualRate := rate1 / decim2
  732. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  733. if len(rdsBase.Samples) == 0 {
  734. return
  735. }
  736. st.mu.Lock()
  737. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  738. if result.PS != "" {
  739. st.result = result
  740. }
  741. st.mu.Unlock()
  742. }(st, sig.CenterHz)
  743. }
  744. st.mu.Lock()
  745. ps := st.result.PS
  746. st.mu.Unlock()
  747. if ps != "" && sig.PLL != nil {
  748. sig.PLL.RDSStation = strings.TrimSpace(ps)
  749. cls.PLL = sig.PLL
  750. }
  751. }
  752. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  753. if len(rt.rdsMap) > 0 {
  754. activeIDs := make(map[int64]bool, len(displaySignals))
  755. for _, s := range displaySignals {
  756. keyHz := s.CenterHz
  757. if s.PLL != nil && s.PLL.ExactHz != 0 {
  758. keyHz = s.PLL.ExactHz
  759. }
  760. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  761. }
  762. for id := range rt.rdsMap {
  763. if !activeIDs[id] {
  764. delete(rt.rdsMap, id)
  765. }
  766. }
  767. }
  768. if len(rt.streamPhaseState) > 0 {
  769. sigIDs := make(map[int64]bool, len(displaySignals))
  770. for _, s := range displaySignals {
  771. sigIDs[s.ID] = true
  772. }
  773. for id := range rt.streamPhaseState {
  774. if !sigIDs[id] {
  775. delete(rt.streamPhaseState, id)
  776. }
  777. }
  778. }
  779. if rec != nil && len(displaySignals) > 0 {
  780. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  781. _ = aqCfg
  782. }
  783. }
  784. func spanForPolicy(policy pipeline.Policy, fallback float64) float64 {
  785. if policy.MonitorSpanHz > 0 {
  786. return policy.MonitorSpanHz
  787. }
  788. if len(policy.MonitorWindows) > 0 {
  789. maxSpan := 0.0
  790. for _, w := range policy.MonitorWindows {
  791. if w.SpanHz > maxSpan {
  792. maxSpan = w.SpanHz
  793. }
  794. }
  795. if maxSpan > 0 {
  796. return maxSpan
  797. }
  798. }
  799. if policy.MonitorStartHz != 0 && policy.MonitorEndHz != 0 && policy.MonitorEndHz > policy.MonitorStartHz {
  800. return policy.MonitorEndHz - policy.MonitorStartHz
  801. }
  802. return fallback
  803. }
  804. func windowSpanBounds(windows []pipeline.RefinementWindow) (float64, float64, bool) {
  805. minSpan := 0.0
  806. maxSpan := 0.0
  807. ok := false
  808. for _, w := range windows {
  809. if w.SpanHz <= 0 {
  810. continue
  811. }
  812. if !ok || w.SpanHz < minSpan {
  813. minSpan = w.SpanHz
  814. }
  815. if !ok || w.SpanHz > maxSpan {
  816. maxSpan = w.SpanHz
  817. }
  818. ok = true
  819. }
  820. return minSpan, maxSpan, ok
  821. }
  822. func analysisLevel(name, role, truth string, sampleRate int, fftSize int, centerHz float64, spanHz float64, source string, decimation int, baseRate int) pipeline.AnalysisLevel {
  823. level := pipeline.AnalysisLevel{
  824. Name: name,
  825. Role: role,
  826. Truth: truth,
  827. SampleRate: sampleRate,
  828. FFTSize: fftSize,
  829. CenterHz: centerHz,
  830. SpanHz: spanHz,
  831. Source: source,
  832. }
  833. if level.SampleRate > 0 && level.FFTSize > 0 {
  834. level.BinHz = float64(level.SampleRate) / float64(level.FFTSize)
  835. }
  836. if decimation > 0 {
  837. level.Decimation = decimation
  838. } else if baseRate > 0 && level.SampleRate > 0 && baseRate%level.SampleRate == 0 {
  839. level.Decimation = baseRate / level.SampleRate
  840. }
  841. return level
  842. }
  843. func (rt *dspRuntime) buildSurveillancePlan(policy pipeline.Policy) surveillancePlan {
  844. baseRate := rt.cfg.SampleRate
  845. baseFFT := rt.cfg.Surveillance.AnalysisFFTSize
  846. if baseFFT <= 0 {
  847. baseFFT = rt.cfg.FFTSize
  848. }
  849. span := spanForPolicy(policy, float64(baseRate))
  850. detectionPolicy := pipeline.SurveillanceDetectionPolicyFromPolicy(policy)
  851. primary := analysisLevel("surveillance", pipeline.RoleSurveillancePrimary, "surveillance", baseRate, baseFFT, rt.cfg.CenterHz, span, "baseband", 1, baseRate)
  852. levels := []pipeline.AnalysisLevel{primary}
  853. specs := []surveillanceLevelSpec{{Level: primary, Decim: 1, AllowGPU: true}}
  854. context := pipeline.AnalysisContext{Surveillance: primary}
  855. derivedLevels := make([]pipeline.AnalysisLevel, 0, 2)
  856. supportLevels := make([]pipeline.AnalysisLevel, 0, 2)
  857. strategy := strings.ToLower(strings.TrimSpace(policy.SurveillanceStrategy))
  858. switch strategy {
  859. case "multi-res", "multi-resolution", "multi", "multi_res":
  860. decim := 2
  861. derivedRate := baseRate / decim
  862. derivedFFT := baseFFT / decim
  863. if derivedRate >= 200000 && derivedFFT >= 256 {
  864. derivedSpan := spanForPolicy(policy, float64(derivedRate))
  865. role := pipeline.RoleSurveillanceSupport
  866. if detectionPolicy.DerivedDetectionEnabled {
  867. role = pipeline.RoleSurveillanceDerived
  868. }
  869. derived := analysisLevel("surveillance-lowres", role, "surveillance", derivedRate, derivedFFT, rt.cfg.CenterHz, derivedSpan, "decimated", decim, baseRate)
  870. if detectionPolicy.DerivedDetectionEnabled {
  871. levels = append(levels, derived)
  872. derivedLevels = append(derivedLevels, derived)
  873. } else {
  874. supportLevels = append(supportLevels, derived)
  875. }
  876. specs = append(specs, surveillanceLevelSpec{Level: derived, Decim: decim, AllowGPU: false})
  877. context.Derived = append(context.Derived, derived)
  878. }
  879. }
  880. presentation := analysisLevel("presentation", pipeline.RolePresentation, "presentation", baseRate, rt.cfg.Surveillance.DisplayBins, rt.cfg.CenterHz, span, "display", 1, baseRate)
  881. context.Presentation = presentation
  882. if len(derivedLevels) == 0 && detectionPolicy.DerivedDetectionEnabled {
  883. detectionPolicy.DerivedDetectionEnabled = false
  884. detectionPolicy.DerivedDetectionReason = "levels"
  885. }
  886. switch {
  887. case len(derivedLevels) > 0:
  888. detectionPolicy.DerivedDetectionMode = "detection"
  889. case len(supportLevels) > 0:
  890. detectionPolicy.DerivedDetectionMode = "support"
  891. default:
  892. detectionPolicy.DerivedDetectionMode = "disabled"
  893. }
  894. levelSet := pipeline.SurveillanceLevelSet{
  895. Primary: primary,
  896. Derived: append([]pipeline.AnalysisLevel(nil), derivedLevels...),
  897. Support: append([]pipeline.AnalysisLevel(nil), supportLevels...),
  898. Presentation: presentation,
  899. }
  900. detectionLevels := make([]pipeline.AnalysisLevel, 0, 1+len(derivedLevels))
  901. detectionLevels = append(detectionLevels, primary)
  902. detectionLevels = append(detectionLevels, derivedLevels...)
  903. levelSet.Detection = detectionLevels
  904. allLevels := make([]pipeline.AnalysisLevel, 0, 1+len(derivedLevels)+len(supportLevels)+1)
  905. allLevels = append(allLevels, primary)
  906. allLevels = append(allLevels, derivedLevels...)
  907. allLevels = append(allLevels, supportLevels...)
  908. if presentation.Name != "" {
  909. allLevels = append(allLevels, presentation)
  910. }
  911. levelSet.All = allLevels
  912. return surveillancePlan{
  913. Primary: primary,
  914. Levels: levels,
  915. LevelSet: levelSet,
  916. Presentation: presentation,
  917. Context: context,
  918. DetectionPolicy: detectionPolicy,
  919. Specs: specs,
  920. }
  921. }
  922. func sameIQBuffer(a []complex64, b []complex64) bool {
  923. if len(a) != len(b) {
  924. return false
  925. }
  926. if len(a) == 0 {
  927. return true
  928. }
  929. return &a[0] == &b[0]
  930. }
  931. func markWorkItemsStatus(items []pipeline.RefinementWorkItem, from string, to string, reason string) {
  932. for i := range items {
  933. if items[i].Status != from {
  934. continue
  935. }
  936. items[i].Status = to
  937. if reason != "" {
  938. items[i].Reason = reason
  939. }
  940. }
  941. }
  942. func markWorkItemsCompleted(items []pipeline.RefinementWorkItem, candidates []pipeline.Candidate) {
  943. if len(items) == 0 || len(candidates) == 0 {
  944. return
  945. }
  946. done := map[int64]struct{}{}
  947. for _, cand := range candidates {
  948. if cand.ID != 0 {
  949. done[cand.ID] = struct{}{}
  950. }
  951. }
  952. for i := range items {
  953. if _, ok := done[items[i].Candidate.ID]; !ok {
  954. continue
  955. }
  956. items[i].Status = pipeline.RefinementStatusCompleted
  957. items[i].Reason = pipeline.RefinementReasonCompleted
  958. }
  959. }
  960. func (rt *dspRuntime) setArbitration(policy pipeline.Policy, budget pipeline.BudgetModel, admission pipeline.RefinementAdmission, queue pipeline.DecisionQueueStats) {
  961. rt.arbitration = pipeline.BuildArbitrationState(policy, budget, admission, queue)
  962. }