Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

987 рядки
30KB

  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. scheduled := pipeline.ScheduleCandidates(candidates, policy)
  424. return pipeline.SurveillanceResult{
  425. Level: plan.Primary,
  426. Levels: plan.Levels,
  427. LevelSet: plan.LevelSet,
  428. DetectionPolicy: plan.DetectionPolicy,
  429. DisplayLevel: plan.Presentation,
  430. Context: plan.Context,
  431. Spectra: art.surveillanceSpectra,
  432. Candidates: candidates,
  433. Scheduled: scheduled,
  434. Finished: art.finished,
  435. Signals: art.detected,
  436. NoiseFloor: art.noiseFloor,
  437. Thresholds: art.thresholds,
  438. }
  439. }
  440. func (rt *dspRuntime) detectDerivedCandidates(art *spectrumArtifacts, plan surveillancePlan) []pipeline.Candidate {
  441. if art == nil || len(plan.LevelSet.Derived) == 0 {
  442. return nil
  443. }
  444. spectra := map[string][]float64{}
  445. for _, spec := range art.surveillanceSpectra {
  446. if spec.Level.Name == "" || len(spec.Spectrum) == 0 {
  447. continue
  448. }
  449. spectra[spec.Level.Name] = spec.Spectrum
  450. }
  451. if len(spectra) == 0 {
  452. return nil
  453. }
  454. out := make([]pipeline.Candidate, 0, len(plan.LevelSet.Derived))
  455. for _, level := range plan.LevelSet.Derived {
  456. if level.Name == "" {
  457. continue
  458. }
  459. if !pipeline.IsDetectionLevel(level) {
  460. continue
  461. }
  462. spectrum := spectra[level.Name]
  463. if len(spectrum) == 0 {
  464. continue
  465. }
  466. entry := rt.derivedDetectorForLevel(level)
  467. if entry == nil || entry.det == nil {
  468. continue
  469. }
  470. _, signals := entry.det.Process(art.now, spectrum, level.CenterHz)
  471. if len(signals) == 0 {
  472. continue
  473. }
  474. cands := pipeline.CandidatesFromSignalsWithLevel(signals, "surveillance-derived", level)
  475. for i := range cands {
  476. if cands[i].ID == 0 {
  477. continue
  478. }
  479. cands[i].ID = entry.idBase - cands[i].ID
  480. }
  481. out = append(out, cands...)
  482. }
  483. if len(out) == 0 {
  484. return nil
  485. }
  486. return out
  487. }
  488. func (rt *dspRuntime) derivedDetectorForLevel(level pipeline.AnalysisLevel) *derivedDetector {
  489. if level.SampleRate <= 0 || level.FFTSize <= 0 {
  490. return nil
  491. }
  492. if rt.derivedDetectors == nil {
  493. rt.derivedDetectors = map[string]*derivedDetector{}
  494. }
  495. key := level.Name
  496. if key == "" {
  497. key = fmt.Sprintf("%d:%d", level.SampleRate, level.FFTSize)
  498. }
  499. entry := rt.derivedDetectors[key]
  500. if entry != nil && entry.sampleRate == level.SampleRate && entry.fftSize == level.FFTSize {
  501. return entry
  502. }
  503. if rt.nextDerivedBase == 0 {
  504. rt.nextDerivedBase = -derivedIDBlock
  505. }
  506. entry = &derivedDetector{
  507. det: detector.New(rt.cfg.Detector, level.SampleRate, level.FFTSize),
  508. sampleRate: level.SampleRate,
  509. fftSize: level.FFTSize,
  510. idBase: rt.nextDerivedBase,
  511. }
  512. rt.nextDerivedBase -= derivedIDBlock
  513. rt.derivedDetectors[key] = entry
  514. return entry
  515. }
  516. func (rt *dspRuntime) buildRefinementInput(surv pipeline.SurveillanceResult, now time.Time) pipeline.RefinementInput {
  517. policy := pipeline.PolicyFromConfig(rt.cfg)
  518. plan := pipeline.BuildRefinementPlan(surv.Candidates, policy)
  519. admission := rt.arbiter.AdmitRefinement(plan, policy, now)
  520. plan = admission.Plan
  521. workItems := make([]pipeline.RefinementWorkItem, 0, len(admission.WorkItems))
  522. if len(admission.WorkItems) > 0 {
  523. workItems = append(workItems, admission.WorkItems...)
  524. }
  525. scheduled := append([]pipeline.ScheduledCandidate(nil), admission.Admitted...)
  526. workIndex := map[int64]int{}
  527. for i := range workItems {
  528. if workItems[i].Candidate.ID == 0 {
  529. continue
  530. }
  531. workIndex[workItems[i].Candidate.ID] = i
  532. }
  533. windows := make([]pipeline.RefinementWindow, 0, len(scheduled))
  534. for _, sc := range scheduled {
  535. window := pipeline.RefinementWindowForCandidate(policy, sc.Candidate)
  536. windows = append(windows, window)
  537. if idx, ok := workIndex[sc.Candidate.ID]; ok {
  538. workItems[idx].Window = window
  539. }
  540. }
  541. detailFFT := rt.cfg.Refinement.DetailFFTSize
  542. if detailFFT <= 0 {
  543. detailFFT = rt.cfg.FFTSize
  544. }
  545. levelSpan := spanForPolicy(policy, float64(rt.cfg.SampleRate))
  546. if _, maxSpan, ok := windowSpanBounds(windows); ok {
  547. levelSpan = maxSpan
  548. }
  549. level := analysisLevel("refinement", "refinement", "refinement", rt.cfg.SampleRate, detailFFT, rt.cfg.CenterHz, levelSpan, "refinement-window", 1, rt.cfg.SampleRate)
  550. detailLevel := analysisLevel("detail", "detail", "refinement", rt.cfg.SampleRate, detailFFT, rt.cfg.CenterHz, levelSpan, "detail-spectrum", 1, rt.cfg.SampleRate)
  551. if len(workItems) > 0 {
  552. for i := range workItems {
  553. item := &workItems[i]
  554. if item.Window.SpanHz <= 0 {
  555. continue
  556. }
  557. item.Execution = &pipeline.RefinementExecution{
  558. Stage: "refine",
  559. SampleRate: rt.cfg.SampleRate,
  560. FFTSize: detailFFT,
  561. CenterHz: item.Window.CenterHz,
  562. SpanHz: item.Window.SpanHz,
  563. Source: detailLevel.Source,
  564. }
  565. }
  566. }
  567. input := pipeline.RefinementInput{
  568. Level: level,
  569. Detail: detailLevel,
  570. Context: surv.Context,
  571. Request: pipeline.RefinementRequest{Strategy: plan.Strategy, Reason: "surveillance-plan", SpanHintHz: levelSpan},
  572. Budgets: pipeline.BudgetModelFromPolicy(policy),
  573. Admission: admission.Admission,
  574. Candidates: append([]pipeline.Candidate(nil), surv.Candidates...),
  575. Scheduled: scheduled,
  576. WorkItems: workItems,
  577. Plan: plan,
  578. Windows: windows,
  579. SampleRate: rt.cfg.SampleRate,
  580. FFTSize: detailFFT,
  581. CenterHz: rt.cfg.CenterHz,
  582. Source: "surveillance-detector",
  583. }
  584. input.Context.Refinement = level
  585. input.Context.Detail = detailLevel
  586. if !policy.RefinementEnabled {
  587. for i := range input.WorkItems {
  588. item := &input.WorkItems[i]
  589. if item.Status == pipeline.RefinementStatusDropped {
  590. continue
  591. }
  592. item.Status = pipeline.RefinementStatusDropped
  593. item.Reason = pipeline.RefinementReasonDisabled
  594. }
  595. input.Scheduled = nil
  596. input.Request.Reason = pipeline.ReasonAdmissionDisabled
  597. input.Admission.Reason = pipeline.ReasonAdmissionDisabled
  598. input.Admission.Admitted = 0
  599. input.Admission.Skipped = 0
  600. input.Admission.Displaced = 0
  601. input.Plan.Selected = nil
  602. input.Plan.DroppedByBudget = 0
  603. }
  604. rt.setArbitration(policy, input.Budgets, input.Admission, rt.arbitration.Queue)
  605. return input
  606. }
  607. func (rt *dspRuntime) runRefinement(art *spectrumArtifacts, surv pipeline.SurveillanceResult, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementStep {
  608. input := rt.buildRefinementInput(surv, art.now)
  609. markWorkItemsStatus(input.WorkItems, pipeline.RefinementStatusAdmitted, pipeline.RefinementStatusRunning, pipeline.RefinementReasonRunning)
  610. result := rt.refineSignals(art, input, extractMgr, rec)
  611. markWorkItemsCompleted(input.WorkItems, result.Candidates)
  612. return pipeline.RefinementStep{Input: input, Result: result}
  613. }
  614. func (rt *dspRuntime) refineSignals(art *spectrumArtifacts, input pipeline.RefinementInput, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementResult {
  615. if art == nil || len(art.detailIQ) == 0 || len(input.Scheduled) == 0 {
  616. return pipeline.RefinementResult{}
  617. }
  618. policy := pipeline.PolicyFromConfig(rt.cfg)
  619. selectedCandidates := make([]pipeline.Candidate, 0, len(input.Scheduled))
  620. selectedSignals := make([]detector.Signal, 0, len(input.Scheduled))
  621. for _, sc := range input.Scheduled {
  622. selectedCandidates = append(selectedCandidates, sc.Candidate)
  623. selectedSignals = append(selectedSignals, detector.Signal{
  624. ID: sc.Candidate.ID,
  625. FirstBin: sc.Candidate.FirstBin,
  626. LastBin: sc.Candidate.LastBin,
  627. CenterHz: sc.Candidate.CenterHz,
  628. BWHz: sc.Candidate.BandwidthHz,
  629. PeakDb: sc.Candidate.PeakDb,
  630. SNRDb: sc.Candidate.SNRDb,
  631. NoiseDb: sc.Candidate.NoiseDb,
  632. })
  633. }
  634. sampleRate := input.SampleRate
  635. fftSize := input.FFTSize
  636. centerHz := input.CenterHz
  637. if sampleRate <= 0 {
  638. sampleRate = rt.cfg.SampleRate
  639. }
  640. if fftSize <= 0 {
  641. fftSize = rt.cfg.FFTSize
  642. }
  643. if centerHz == 0 {
  644. centerHz = rt.cfg.CenterHz
  645. }
  646. snips, snipRates := extractSignalIQBatch(extractMgr, art.detailIQ, sampleRate, centerHz, selectedSignals)
  647. refined := pipeline.RefineCandidates(selectedCandidates, input.Windows, art.detailSpectrum, sampleRate, fftSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  648. signals := make([]detector.Signal, 0, len(refined))
  649. decisions := make([]pipeline.SignalDecision, 0, len(refined))
  650. for i, ref := range refined {
  651. sig := ref.Signal
  652. signals = append(signals, sig)
  653. cls := sig.Class
  654. snipRate := ref.SnippetRate
  655. decision := pipeline.DecideSignalAction(policy, ref.Candidate, cls)
  656. decisions = append(decisions, decision)
  657. if cls != nil {
  658. pll := classifier.PLLResult{}
  659. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  660. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  661. cls.PLL = &pll
  662. signals[i].PLL = &pll
  663. if cls.ModType == classifier.ClassWFM && pll.Stereo {
  664. cls.ModType = classifier.ClassWFMStereo
  665. }
  666. }
  667. if (cls.ModType == classifier.ClassWFM || cls.ModType == classifier.ClassWFMStereo) && rec != nil {
  668. rt.updateRDS(art.now, rec, &signals[i], cls)
  669. }
  670. }
  671. }
  672. budget := pipeline.BudgetModelFromPolicy(policy)
  673. queueStats := rt.arbiter.ApplyDecisions(decisions, budget, art.now, policy)
  674. rt.setArbitration(policy, budget, input.Admission, queueStats)
  675. summary := summarizeDecisions(decisions)
  676. if rec != nil {
  677. if summary.RecordEnabled > 0 {
  678. rt.cfg.Recorder.Enabled = true
  679. }
  680. if summary.DecodeEnabled > 0 {
  681. rt.cfg.Recorder.AutoDecode = true
  682. }
  683. }
  684. rt.det.UpdateClasses(signals)
  685. return pipeline.RefinementResult{Level: input.Level, Signals: signals, Decisions: decisions, Candidates: selectedCandidates}
  686. }
  687. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  688. if sig == nil || cls == nil {
  689. return
  690. }
  691. keyHz := sig.CenterHz
  692. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  693. keyHz = sig.PLL.ExactHz
  694. }
  695. key := int64(math.Round(keyHz / 25000.0))
  696. st := rt.rdsMap[key]
  697. if st == nil {
  698. st = &rdsState{}
  699. rt.rdsMap[key] = st
  700. }
  701. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  702. st.lastDecode = now
  703. atomic.StoreInt32(&st.busy, 1)
  704. go func(st *rdsState, sigHz float64) {
  705. defer atomic.StoreInt32(&st.busy, 0)
  706. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  707. if len(ringIQ) < ringSR || ringSR <= 0 {
  708. return
  709. }
  710. offset := sigHz - ringCenter
  711. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  712. decim1 := ringSR / 1000000
  713. if decim1 < 1 {
  714. decim1 = 1
  715. }
  716. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  717. f1 := dsp.ApplyFIR(shifted, lp1)
  718. d1 := dsp.Decimate(f1, decim1)
  719. rate1 := ringSR / decim1
  720. decim2 := rate1 / 250000
  721. if decim2 < 1 {
  722. decim2 = 1
  723. }
  724. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  725. f2 := dsp.ApplyFIR(d1, lp2)
  726. decimated := dsp.Decimate(f2, decim2)
  727. actualRate := rate1 / decim2
  728. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  729. if len(rdsBase.Samples) == 0 {
  730. return
  731. }
  732. st.mu.Lock()
  733. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  734. if result.PS != "" {
  735. st.result = result
  736. }
  737. st.mu.Unlock()
  738. }(st, sig.CenterHz)
  739. }
  740. st.mu.Lock()
  741. ps := st.result.PS
  742. st.mu.Unlock()
  743. if ps != "" && sig.PLL != nil {
  744. sig.PLL.RDSStation = strings.TrimSpace(ps)
  745. cls.PLL = sig.PLL
  746. }
  747. }
  748. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  749. if len(rt.rdsMap) > 0 {
  750. activeIDs := make(map[int64]bool, len(displaySignals))
  751. for _, s := range displaySignals {
  752. keyHz := s.CenterHz
  753. if s.PLL != nil && s.PLL.ExactHz != 0 {
  754. keyHz = s.PLL.ExactHz
  755. }
  756. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  757. }
  758. for id := range rt.rdsMap {
  759. if !activeIDs[id] {
  760. delete(rt.rdsMap, id)
  761. }
  762. }
  763. }
  764. if len(rt.streamPhaseState) > 0 {
  765. sigIDs := make(map[int64]bool, len(displaySignals))
  766. for _, s := range displaySignals {
  767. sigIDs[s.ID] = true
  768. }
  769. for id := range rt.streamPhaseState {
  770. if !sigIDs[id] {
  771. delete(rt.streamPhaseState, id)
  772. }
  773. }
  774. }
  775. if rec != nil && len(displaySignals) > 0 {
  776. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  777. _ = aqCfg
  778. }
  779. }
  780. func spanForPolicy(policy pipeline.Policy, fallback float64) float64 {
  781. if policy.MonitorSpanHz > 0 {
  782. return policy.MonitorSpanHz
  783. }
  784. if policy.MonitorStartHz != 0 && policy.MonitorEndHz != 0 && policy.MonitorEndHz > policy.MonitorStartHz {
  785. return policy.MonitorEndHz - policy.MonitorStartHz
  786. }
  787. return fallback
  788. }
  789. func windowSpanBounds(windows []pipeline.RefinementWindow) (float64, float64, bool) {
  790. minSpan := 0.0
  791. maxSpan := 0.0
  792. ok := false
  793. for _, w := range windows {
  794. if w.SpanHz <= 0 {
  795. continue
  796. }
  797. if !ok || w.SpanHz < minSpan {
  798. minSpan = w.SpanHz
  799. }
  800. if !ok || w.SpanHz > maxSpan {
  801. maxSpan = w.SpanHz
  802. }
  803. ok = true
  804. }
  805. return minSpan, maxSpan, ok
  806. }
  807. func analysisLevel(name, role, truth string, sampleRate int, fftSize int, centerHz float64, spanHz float64, source string, decimation int, baseRate int) pipeline.AnalysisLevel {
  808. level := pipeline.AnalysisLevel{
  809. Name: name,
  810. Role: role,
  811. Truth: truth,
  812. SampleRate: sampleRate,
  813. FFTSize: fftSize,
  814. CenterHz: centerHz,
  815. SpanHz: spanHz,
  816. Source: source,
  817. }
  818. if level.SampleRate > 0 && level.FFTSize > 0 {
  819. level.BinHz = float64(level.SampleRate) / float64(level.FFTSize)
  820. }
  821. if decimation > 0 {
  822. level.Decimation = decimation
  823. } else if baseRate > 0 && level.SampleRate > 0 && baseRate%level.SampleRate == 0 {
  824. level.Decimation = baseRate / level.SampleRate
  825. }
  826. return level
  827. }
  828. func (rt *dspRuntime) buildSurveillancePlan(policy pipeline.Policy) surveillancePlan {
  829. baseRate := rt.cfg.SampleRate
  830. baseFFT := rt.cfg.Surveillance.AnalysisFFTSize
  831. if baseFFT <= 0 {
  832. baseFFT = rt.cfg.FFTSize
  833. }
  834. span := spanForPolicy(policy, float64(baseRate))
  835. detectionPolicy := pipeline.SurveillanceDetectionPolicyFromPolicy(policy)
  836. primary := analysisLevel("surveillance", pipeline.RoleSurveillancePrimary, "surveillance", baseRate, baseFFT, rt.cfg.CenterHz, span, "baseband", 1, baseRate)
  837. levels := []pipeline.AnalysisLevel{primary}
  838. specs := []surveillanceLevelSpec{{Level: primary, Decim: 1, AllowGPU: true}}
  839. context := pipeline.AnalysisContext{Surveillance: primary}
  840. derivedLevels := make([]pipeline.AnalysisLevel, 0, 2)
  841. supportLevels := make([]pipeline.AnalysisLevel, 0, 2)
  842. strategy := strings.ToLower(strings.TrimSpace(policy.SurveillanceStrategy))
  843. switch strategy {
  844. case "multi-res", "multi-resolution", "multi", "multi_res":
  845. decim := 2
  846. derivedRate := baseRate / decim
  847. derivedFFT := baseFFT / decim
  848. if derivedRate >= 200000 && derivedFFT >= 256 {
  849. derivedSpan := spanForPolicy(policy, float64(derivedRate))
  850. role := pipeline.RoleSurveillanceSupport
  851. if detectionPolicy.DerivedDetectionEnabled {
  852. role = pipeline.RoleSurveillanceDerived
  853. }
  854. derived := analysisLevel("surveillance-lowres", role, "surveillance", derivedRate, derivedFFT, rt.cfg.CenterHz, derivedSpan, "decimated", decim, baseRate)
  855. if detectionPolicy.DerivedDetectionEnabled {
  856. levels = append(levels, derived)
  857. derivedLevels = append(derivedLevels, derived)
  858. } else {
  859. supportLevels = append(supportLevels, derived)
  860. }
  861. specs = append(specs, surveillanceLevelSpec{Level: derived, Decim: decim, AllowGPU: false})
  862. context.Derived = append(context.Derived, derived)
  863. }
  864. }
  865. presentation := analysisLevel("presentation", pipeline.RolePresentation, "presentation", baseRate, rt.cfg.Surveillance.DisplayBins, rt.cfg.CenterHz, span, "display", 1, baseRate)
  866. context.Presentation = presentation
  867. if len(derivedLevels) == 0 && detectionPolicy.DerivedDetectionEnabled {
  868. detectionPolicy.DerivedDetectionEnabled = false
  869. detectionPolicy.DerivedDetectionReason = "levels"
  870. }
  871. switch {
  872. case len(derivedLevels) > 0:
  873. detectionPolicy.DerivedDetectionMode = "detection"
  874. case len(supportLevels) > 0:
  875. detectionPolicy.DerivedDetectionMode = "support"
  876. default:
  877. detectionPolicy.DerivedDetectionMode = "disabled"
  878. }
  879. levelSet := pipeline.SurveillanceLevelSet{
  880. Primary: primary,
  881. Derived: append([]pipeline.AnalysisLevel(nil), derivedLevels...),
  882. Support: append([]pipeline.AnalysisLevel(nil), supportLevels...),
  883. Presentation: presentation,
  884. }
  885. detectionLevels := make([]pipeline.AnalysisLevel, 0, 1+len(derivedLevels))
  886. detectionLevels = append(detectionLevels, primary)
  887. detectionLevels = append(detectionLevels, derivedLevels...)
  888. levelSet.Detection = detectionLevels
  889. allLevels := make([]pipeline.AnalysisLevel, 0, 1+len(derivedLevels)+len(supportLevels)+1)
  890. allLevels = append(allLevels, primary)
  891. allLevels = append(allLevels, derivedLevels...)
  892. allLevels = append(allLevels, supportLevels...)
  893. if presentation.Name != "" {
  894. allLevels = append(allLevels, presentation)
  895. }
  896. levelSet.All = allLevels
  897. return surveillancePlan{
  898. Primary: primary,
  899. Levels: levels,
  900. LevelSet: levelSet,
  901. Presentation: presentation,
  902. Context: context,
  903. DetectionPolicy: detectionPolicy,
  904. Specs: specs,
  905. }
  906. }
  907. func sameIQBuffer(a []complex64, b []complex64) bool {
  908. if len(a) != len(b) {
  909. return false
  910. }
  911. if len(a) == 0 {
  912. return true
  913. }
  914. return &a[0] == &b[0]
  915. }
  916. func markWorkItemsStatus(items []pipeline.RefinementWorkItem, from string, to string, reason string) {
  917. for i := range items {
  918. if items[i].Status != from {
  919. continue
  920. }
  921. items[i].Status = to
  922. if reason != "" {
  923. items[i].Reason = reason
  924. }
  925. }
  926. }
  927. func markWorkItemsCompleted(items []pipeline.RefinementWorkItem, candidates []pipeline.Candidate) {
  928. if len(items) == 0 || len(candidates) == 0 {
  929. return
  930. }
  931. done := map[int64]struct{}{}
  932. for _, cand := range candidates {
  933. if cand.ID != 0 {
  934. done[cand.ID] = struct{}{}
  935. }
  936. }
  937. for i := range items {
  938. if _, ok := done[items[i].Candidate.ID]; !ok {
  939. continue
  940. }
  941. items[i].Status = pipeline.RefinementStatusCompleted
  942. items[i].Reason = pipeline.RefinementReasonCompleted
  943. }
  944. }
  945. func (rt *dspRuntime) setArbitration(policy pipeline.Policy, budget pipeline.BudgetModel, admission pipeline.RefinementAdmission, queue pipeline.DecisionQueueStats) {
  946. rt.arbitration = pipeline.BuildArbitrationState(policy, budget, admission, queue)
  947. }