Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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