Wideband autonomous SDR analysis engine forked from sdr-visual-suite
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

555 行
17KB

  1. package main
  2. import (
  3. "math"
  4. "strings"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "sdr-wideband-suite/internal/classifier"
  9. "sdr-wideband-suite/internal/config"
  10. "sdr-wideband-suite/internal/demod"
  11. "sdr-wideband-suite/internal/detector"
  12. "sdr-wideband-suite/internal/dsp"
  13. fftutil "sdr-wideband-suite/internal/fft"
  14. "sdr-wideband-suite/internal/fft/gpufft"
  15. "sdr-wideband-suite/internal/pipeline"
  16. "sdr-wideband-suite/internal/rds"
  17. "sdr-wideband-suite/internal/recorder"
  18. )
  19. type rdsState struct {
  20. dec rds.Decoder
  21. result rds.Result
  22. lastDecode time.Time
  23. busy int32
  24. mu sync.Mutex
  25. }
  26. type dspRuntime struct {
  27. cfg config.Config
  28. det *detector.Detector
  29. window []float64
  30. plan *fftutil.CmplxPlan
  31. dcEnabled bool
  32. iqEnabled bool
  33. useGPU bool
  34. gpuEngine *gpufft.Engine
  35. rdsMap map[int64]*rdsState
  36. streamPhaseState map[int64]*streamExtractState
  37. streamOverlap *streamIQOverlap
  38. decisionQueues *decisionQueues
  39. queueStats decisionQueueStats
  40. gotSamples bool
  41. }
  42. type spectrumArtifacts struct {
  43. allIQ []complex64
  44. surveillanceIQ []complex64
  45. detailIQ []complex64
  46. surveillanceSpectrum []float64
  47. detailSpectrum []float64
  48. finished []detector.Event
  49. detected []detector.Signal
  50. thresholds []float64
  51. noiseFloor float64
  52. now time.Time
  53. }
  54. func newDSPRuntime(cfg config.Config, det *detector.Detector, window []float64, gpuState *gpuStatus) *dspRuntime {
  55. rt := &dspRuntime{
  56. cfg: cfg,
  57. det: det,
  58. window: window,
  59. plan: fftutil.NewCmplxPlan(cfg.FFTSize),
  60. dcEnabled: cfg.DCBlock,
  61. iqEnabled: cfg.IQBalance,
  62. useGPU: cfg.UseGPUFFT,
  63. rdsMap: map[int64]*rdsState{},
  64. streamPhaseState: map[int64]*streamExtractState{},
  65. streamOverlap: &streamIQOverlap{},
  66. }
  67. if rt.useGPU && gpuState != nil {
  68. snap := gpuState.snapshot()
  69. if snap.Available {
  70. if eng, err := gpufft.New(cfg.FFTSize); err == nil {
  71. rt.gpuEngine = eng
  72. gpuState.set(true, nil)
  73. } else {
  74. gpuState.set(false, err)
  75. rt.useGPU = false
  76. }
  77. }
  78. }
  79. return rt
  80. }
  81. func (rt *dspRuntime) applyUpdate(upd dspUpdate, srcMgr *sourceManager, rec *recorder.Manager, gpuState *gpuStatus) {
  82. prevFFT := rt.cfg.FFTSize
  83. prevUseGPU := rt.useGPU
  84. rt.cfg = upd.cfg
  85. if rec != nil {
  86. rec.Update(rt.cfg.SampleRate, rt.cfg.FFTSize, recorder.Policy{
  87. Enabled: rt.cfg.Recorder.Enabled,
  88. MinSNRDb: rt.cfg.Recorder.MinSNRDb,
  89. MinDuration: mustParseDuration(rt.cfg.Recorder.MinDuration, 1*time.Second),
  90. MaxDuration: mustParseDuration(rt.cfg.Recorder.MaxDuration, 300*time.Second),
  91. PrerollMs: rt.cfg.Recorder.PrerollMs,
  92. RecordIQ: rt.cfg.Recorder.RecordIQ,
  93. RecordAudio: rt.cfg.Recorder.RecordAudio,
  94. AutoDemod: rt.cfg.Recorder.AutoDemod,
  95. AutoDecode: rt.cfg.Recorder.AutoDecode,
  96. MaxDiskMB: rt.cfg.Recorder.MaxDiskMB,
  97. OutputDir: rt.cfg.Recorder.OutputDir,
  98. ClassFilter: rt.cfg.Recorder.ClassFilter,
  99. RingSeconds: rt.cfg.Recorder.RingSeconds,
  100. DeemphasisUs: rt.cfg.Recorder.DeemphasisUs,
  101. ExtractionTaps: rt.cfg.Recorder.ExtractionTaps,
  102. ExtractionBwMult: rt.cfg.Recorder.ExtractionBwMult,
  103. }, rt.cfg.CenterHz, buildDecoderMap(rt.cfg))
  104. }
  105. if upd.det != nil {
  106. rt.det = upd.det
  107. }
  108. if upd.window != nil {
  109. rt.window = upd.window
  110. rt.plan = fftutil.NewCmplxPlan(rt.cfg.FFTSize)
  111. }
  112. rt.dcEnabled = upd.dcBlock
  113. rt.iqEnabled = upd.iqBalance
  114. if rt.cfg.FFTSize != prevFFT || rt.cfg.UseGPUFFT != prevUseGPU {
  115. srcMgr.Flush()
  116. rt.gotSamples = false
  117. if rt.gpuEngine != nil {
  118. rt.gpuEngine.Close()
  119. rt.gpuEngine = nil
  120. }
  121. rt.useGPU = rt.cfg.UseGPUFFT
  122. if rt.useGPU && gpuState != nil {
  123. snap := gpuState.snapshot()
  124. if snap.Available {
  125. if eng, err := gpufft.New(rt.cfg.FFTSize); err == nil {
  126. rt.gpuEngine = eng
  127. gpuState.set(true, nil)
  128. } else {
  129. gpuState.set(false, err)
  130. rt.useGPU = false
  131. }
  132. } else {
  133. gpuState.set(false, nil)
  134. rt.useGPU = false
  135. }
  136. } else if gpuState != nil {
  137. gpuState.set(false, nil)
  138. }
  139. }
  140. }
  141. func (rt *dspRuntime) spectrumFromIQ(iq []complex64, gpuState *gpuStatus) []float64 {
  142. if len(iq) == 0 {
  143. return nil
  144. }
  145. if rt.useGPU && rt.gpuEngine != nil {
  146. gpuBuf := make([]complex64, len(iq))
  147. if len(rt.window) == len(iq) {
  148. for i := 0; i < len(iq); i++ {
  149. v := iq[i]
  150. w := float32(rt.window[i])
  151. gpuBuf[i] = complex(real(v)*w, imag(v)*w)
  152. }
  153. } else {
  154. copy(gpuBuf, iq)
  155. }
  156. out, err := rt.gpuEngine.Exec(gpuBuf)
  157. if err != nil {
  158. if gpuState != nil {
  159. gpuState.set(false, err)
  160. }
  161. rt.useGPU = false
  162. return fftutil.SpectrumWithPlan(gpuBuf, nil, rt.plan)
  163. }
  164. return fftutil.SpectrumFromFFT(out)
  165. }
  166. return fftutil.SpectrumWithPlan(iq, rt.window, rt.plan)
  167. }
  168. func (rt *dspRuntime) captureSpectrum(srcMgr *sourceManager, rec *recorder.Manager, dcBlocker *dsp.DCBlocker, gpuState *gpuStatus) (*spectrumArtifacts, error) {
  169. available := rt.cfg.FFTSize
  170. st := srcMgr.Stats()
  171. if st.BufferSamples > rt.cfg.FFTSize {
  172. available = (st.BufferSamples / rt.cfg.FFTSize) * rt.cfg.FFTSize
  173. if available < rt.cfg.FFTSize {
  174. available = rt.cfg.FFTSize
  175. }
  176. }
  177. allIQ, err := srcMgr.ReadIQ(available)
  178. if err != nil {
  179. return nil, err
  180. }
  181. if rec != nil {
  182. rec.Ingest(time.Now(), allIQ)
  183. }
  184. survIQ := allIQ
  185. if len(allIQ) > rt.cfg.FFTSize {
  186. survIQ = allIQ[len(allIQ)-rt.cfg.FFTSize:]
  187. }
  188. if rt.dcEnabled {
  189. dcBlocker.Apply(survIQ)
  190. }
  191. if rt.iqEnabled {
  192. dsp.IQBalance(survIQ)
  193. }
  194. survSpectrum := rt.spectrumFromIQ(survIQ, gpuState)
  195. for i := range survSpectrum {
  196. if math.IsNaN(survSpectrum[i]) || math.IsInf(survSpectrum[i], 0) {
  197. survSpectrum[i] = -200
  198. }
  199. }
  200. detailIQ := survIQ
  201. detailSpectrum := survSpectrum
  202. if !sameIQBuffer(detailIQ, survIQ) {
  203. detailSpectrum = rt.spectrumFromIQ(detailIQ, gpuState)
  204. for i := range detailSpectrum {
  205. if math.IsNaN(detailSpectrum[i]) || math.IsInf(detailSpectrum[i], 0) {
  206. detailSpectrum[i] = -200
  207. }
  208. }
  209. }
  210. now := time.Now()
  211. finished, detected := rt.det.Process(now, survSpectrum, rt.cfg.CenterHz)
  212. return &spectrumArtifacts{
  213. allIQ: allIQ,
  214. surveillanceIQ: survIQ,
  215. detailIQ: detailIQ,
  216. surveillanceSpectrum: survSpectrum,
  217. detailSpectrum: detailSpectrum,
  218. finished: finished,
  219. detected: detected,
  220. thresholds: rt.det.LastThresholds(),
  221. noiseFloor: rt.det.LastNoiseFloor(),
  222. now: now,
  223. }, nil
  224. }
  225. func (rt *dspRuntime) buildSurveillanceResult(art *spectrumArtifacts) pipeline.SurveillanceResult {
  226. if art == nil {
  227. return pipeline.SurveillanceResult{}
  228. }
  229. policy := pipeline.PolicyFromConfig(rt.cfg)
  230. candidates := pipeline.CandidatesFromSignals(art.detected, "surveillance-detector")
  231. scheduled := pipeline.ScheduleCandidates(candidates, policy)
  232. level := pipeline.AnalysisLevel{
  233. Name: "surveillance",
  234. SampleRate: rt.cfg.SampleRate,
  235. FFTSize: rt.cfg.Surveillance.AnalysisFFTSize,
  236. CenterHz: rt.cfg.CenterHz,
  237. SpanHz: spanForPolicy(policy, float64(rt.cfg.SampleRate)),
  238. Source: "baseband",
  239. }
  240. lowRate := rt.cfg.SampleRate / 2
  241. lowFFT := rt.cfg.Surveillance.AnalysisFFTSize / 2
  242. if lowRate < 200000 {
  243. lowRate = rt.cfg.SampleRate
  244. }
  245. if lowFFT < 256 {
  246. lowFFT = rt.cfg.Surveillance.AnalysisFFTSize
  247. }
  248. lowLevel := pipeline.AnalysisLevel{
  249. Name: "surveillance-lowres",
  250. SampleRate: lowRate,
  251. FFTSize: lowFFT,
  252. CenterHz: rt.cfg.CenterHz,
  253. SpanHz: spanForPolicy(policy, float64(lowRate)),
  254. Source: "downsampled",
  255. }
  256. displayLevel := pipeline.AnalysisLevel{
  257. Name: "presentation",
  258. SampleRate: rt.cfg.SampleRate,
  259. FFTSize: rt.cfg.Surveillance.DisplayBins,
  260. CenterHz: rt.cfg.CenterHz,
  261. SpanHz: spanForPolicy(policy, float64(rt.cfg.SampleRate)),
  262. Source: "display",
  263. }
  264. levels := surveillanceLevels(policy, level, lowLevel)
  265. return pipeline.SurveillanceResult{
  266. Level: level,
  267. Levels: levels,
  268. DisplayLevel: displayLevel,
  269. Candidates: candidates,
  270. Scheduled: scheduled,
  271. Finished: art.finished,
  272. Signals: art.detected,
  273. NoiseFloor: art.noiseFloor,
  274. Thresholds: art.thresholds,
  275. }
  276. }
  277. func (rt *dspRuntime) buildRefinementInput(surv pipeline.SurveillanceResult) pipeline.RefinementInput {
  278. policy := pipeline.PolicyFromConfig(rt.cfg)
  279. plan := pipeline.BuildRefinementPlan(surv.Candidates, policy)
  280. scheduled := append([]pipeline.ScheduledCandidate(nil), surv.Scheduled...)
  281. if len(scheduled) == 0 && len(plan.Selected) > 0 {
  282. scheduled = append([]pipeline.ScheduledCandidate(nil), plan.Selected...)
  283. }
  284. windows := make([]pipeline.RefinementWindow, 0, len(scheduled))
  285. for _, sc := range scheduled {
  286. windows = append(windows, pipeline.RefinementWindowForCandidate(policy, sc.Candidate))
  287. }
  288. levelSpan := spanForPolicy(policy, float64(rt.cfg.SampleRate))
  289. if _, maxSpan, ok := windowSpanBounds(windows); ok {
  290. levelSpan = maxSpan
  291. }
  292. level := pipeline.AnalysisLevel{
  293. Name: "refinement",
  294. SampleRate: rt.cfg.SampleRate,
  295. FFTSize: rt.cfg.FFTSize,
  296. CenterHz: rt.cfg.CenterHz,
  297. SpanHz: levelSpan,
  298. Source: "refinement-window",
  299. }
  300. input := pipeline.RefinementInput{
  301. Level: level,
  302. Candidates: append([]pipeline.Candidate(nil), surv.Candidates...),
  303. Scheduled: scheduled,
  304. Plan: plan,
  305. Windows: windows,
  306. SampleRate: rt.cfg.SampleRate,
  307. FFTSize: rt.cfg.FFTSize,
  308. CenterHz: rt.cfg.CenterHz,
  309. Source: "surveillance-detector",
  310. }
  311. if !policy.RefinementEnabled {
  312. input.Scheduled = nil
  313. }
  314. return input
  315. }
  316. func (rt *dspRuntime) runRefinement(art *spectrumArtifacts, surv pipeline.SurveillanceResult, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementStep {
  317. input := rt.buildRefinementInput(surv)
  318. result := rt.refineSignals(art, input, extractMgr, rec)
  319. return pipeline.RefinementStep{Input: input, Result: result}
  320. }
  321. func (rt *dspRuntime) refineSignals(art *spectrumArtifacts, input pipeline.RefinementInput, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementResult {
  322. if art == nil || len(art.detailIQ) == 0 || len(input.Scheduled) == 0 {
  323. return pipeline.RefinementResult{}
  324. }
  325. policy := pipeline.PolicyFromConfig(rt.cfg)
  326. selectedCandidates := make([]pipeline.Candidate, 0, len(input.Scheduled))
  327. selectedSignals := make([]detector.Signal, 0, len(input.Scheduled))
  328. for _, sc := range input.Scheduled {
  329. selectedCandidates = append(selectedCandidates, sc.Candidate)
  330. selectedSignals = append(selectedSignals, detector.Signal{
  331. ID: sc.Candidate.ID,
  332. FirstBin: sc.Candidate.FirstBin,
  333. LastBin: sc.Candidate.LastBin,
  334. CenterHz: sc.Candidate.CenterHz,
  335. BWHz: sc.Candidate.BandwidthHz,
  336. PeakDb: sc.Candidate.PeakDb,
  337. SNRDb: sc.Candidate.SNRDb,
  338. NoiseDb: sc.Candidate.NoiseDb,
  339. })
  340. }
  341. sampleRate := input.SampleRate
  342. fftSize := input.FFTSize
  343. centerHz := input.CenterHz
  344. if sampleRate <= 0 {
  345. sampleRate = rt.cfg.SampleRate
  346. }
  347. if fftSize <= 0 {
  348. fftSize = rt.cfg.FFTSize
  349. }
  350. if centerHz == 0 {
  351. centerHz = rt.cfg.CenterHz
  352. }
  353. snips, snipRates := extractSignalIQBatch(extractMgr, art.detailIQ, sampleRate, centerHz, selectedSignals)
  354. refined := pipeline.RefineCandidates(selectedCandidates, input.Windows, art.detailSpectrum, sampleRate, fftSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  355. signals := make([]detector.Signal, 0, len(refined))
  356. decisions := make([]pipeline.SignalDecision, 0, len(refined))
  357. for i, ref := range refined {
  358. sig := ref.Signal
  359. signals = append(signals, sig)
  360. cls := sig.Class
  361. snipRate := ref.SnippetRate
  362. decision := pipeline.DecideSignalAction(policy, ref.Candidate, cls)
  363. decisions = append(decisions, decision)
  364. if cls != nil {
  365. pll := classifier.PLLResult{}
  366. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  367. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  368. cls.PLL = &pll
  369. signals[i].PLL = &pll
  370. if cls.ModType == classifier.ClassWFM && pll.Stereo {
  371. cls.ModType = classifier.ClassWFMStereo
  372. }
  373. }
  374. if (cls.ModType == classifier.ClassWFM || cls.ModType == classifier.ClassWFMStereo) && rec != nil {
  375. rt.updateRDS(art.now, rec, &signals[i], cls)
  376. }
  377. }
  378. }
  379. maxRecord := rt.cfg.Resources.MaxRecordingStreams
  380. maxDecode := rt.cfg.Resources.MaxDecodeJobs
  381. hold := time.Duration(rt.cfg.Resources.DecisionHoldMs) * time.Millisecond
  382. queueStats := rt.decisionQueues.Apply(decisions, maxRecord, maxDecode, hold, art.now, policy)
  383. rt.queueStats = queueStats
  384. summary := summarizeDecisions(decisions)
  385. if rec != nil {
  386. if summary.RecordEnabled > 0 {
  387. rt.cfg.Recorder.Enabled = true
  388. }
  389. if summary.DecodeEnabled > 0 {
  390. rt.cfg.Recorder.AutoDecode = true
  391. }
  392. }
  393. rt.det.UpdateClasses(signals)
  394. return pipeline.RefinementResult{Level: input.Level, Signals: signals, Decisions: decisions, Candidates: selectedCandidates}
  395. }
  396. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  397. if sig == nil || cls == nil {
  398. return
  399. }
  400. keyHz := sig.CenterHz
  401. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  402. keyHz = sig.PLL.ExactHz
  403. }
  404. key := int64(math.Round(keyHz / 25000.0))
  405. st := rt.rdsMap[key]
  406. if st == nil {
  407. st = &rdsState{}
  408. rt.rdsMap[key] = st
  409. }
  410. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  411. st.lastDecode = now
  412. atomic.StoreInt32(&st.busy, 1)
  413. go func(st *rdsState, sigHz float64) {
  414. defer atomic.StoreInt32(&st.busy, 0)
  415. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  416. if len(ringIQ) < ringSR || ringSR <= 0 {
  417. return
  418. }
  419. offset := sigHz - ringCenter
  420. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  421. decim1 := ringSR / 1000000
  422. if decim1 < 1 {
  423. decim1 = 1
  424. }
  425. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  426. f1 := dsp.ApplyFIR(shifted, lp1)
  427. d1 := dsp.Decimate(f1, decim1)
  428. rate1 := ringSR / decim1
  429. decim2 := rate1 / 250000
  430. if decim2 < 1 {
  431. decim2 = 1
  432. }
  433. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  434. f2 := dsp.ApplyFIR(d1, lp2)
  435. decimated := dsp.Decimate(f2, decim2)
  436. actualRate := rate1 / decim2
  437. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  438. if len(rdsBase.Samples) == 0 {
  439. return
  440. }
  441. st.mu.Lock()
  442. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  443. if result.PS != "" {
  444. st.result = result
  445. }
  446. st.mu.Unlock()
  447. }(st, sig.CenterHz)
  448. }
  449. st.mu.Lock()
  450. ps := st.result.PS
  451. st.mu.Unlock()
  452. if ps != "" && sig.PLL != nil {
  453. sig.PLL.RDSStation = strings.TrimSpace(ps)
  454. cls.PLL = sig.PLL
  455. }
  456. }
  457. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  458. if len(rt.rdsMap) > 0 {
  459. activeIDs := make(map[int64]bool, len(displaySignals))
  460. for _, s := range displaySignals {
  461. keyHz := s.CenterHz
  462. if s.PLL != nil && s.PLL.ExactHz != 0 {
  463. keyHz = s.PLL.ExactHz
  464. }
  465. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  466. }
  467. for id := range rt.rdsMap {
  468. if !activeIDs[id] {
  469. delete(rt.rdsMap, id)
  470. }
  471. }
  472. }
  473. if len(rt.streamPhaseState) > 0 {
  474. sigIDs := make(map[int64]bool, len(displaySignals))
  475. for _, s := range displaySignals {
  476. sigIDs[s.ID] = true
  477. }
  478. for id := range rt.streamPhaseState {
  479. if !sigIDs[id] {
  480. delete(rt.streamPhaseState, id)
  481. }
  482. }
  483. }
  484. if rec != nil && len(displaySignals) > 0 {
  485. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  486. _ = aqCfg
  487. }
  488. }
  489. func spanForPolicy(policy pipeline.Policy, fallback float64) float64 {
  490. if policy.MonitorSpanHz > 0 {
  491. return policy.MonitorSpanHz
  492. }
  493. if policy.MonitorStartHz != 0 && policy.MonitorEndHz != 0 && policy.MonitorEndHz > policy.MonitorStartHz {
  494. return policy.MonitorEndHz - policy.MonitorStartHz
  495. }
  496. return fallback
  497. }
  498. func windowSpanBounds(windows []pipeline.RefinementWindow) (float64, float64, bool) {
  499. minSpan := 0.0
  500. maxSpan := 0.0
  501. ok := false
  502. for _, w := range windows {
  503. if w.SpanHz <= 0 {
  504. continue
  505. }
  506. if !ok || w.SpanHz < minSpan {
  507. minSpan = w.SpanHz
  508. }
  509. if !ok || w.SpanHz > maxSpan {
  510. maxSpan = w.SpanHz
  511. }
  512. ok = true
  513. }
  514. return minSpan, maxSpan, ok
  515. }
  516. func surveillanceLevels(policy pipeline.Policy, primary pipeline.AnalysisLevel, secondary pipeline.AnalysisLevel) []pipeline.AnalysisLevel {
  517. levels := []pipeline.AnalysisLevel{primary}
  518. strategy := strings.ToLower(strings.TrimSpace(policy.SurveillanceStrategy))
  519. switch strategy {
  520. case "multi-res", "multi-resolution", "multi", "multi_res":
  521. if secondary.SampleRate != primary.SampleRate || secondary.FFTSize != primary.FFTSize {
  522. levels = append(levels, secondary)
  523. }
  524. }
  525. return levels
  526. }
  527. func sameIQBuffer(a []complex64, b []complex64) bool {
  528. if len(a) != len(b) {
  529. return false
  530. }
  531. if len(a) == 0 {
  532. return true
  533. }
  534. return &a[0] == &b[0]
  535. }