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

512 строки
16KB

  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) captureSpectrum(srcMgr *sourceManager, rec *recorder.Manager, dcBlocker *dsp.DCBlocker, gpuState *gpuStatus) (*spectrumArtifacts, error) {
  142. available := rt.cfg.FFTSize
  143. st := srcMgr.Stats()
  144. if st.BufferSamples > rt.cfg.FFTSize {
  145. available = (st.BufferSamples / rt.cfg.FFTSize) * rt.cfg.FFTSize
  146. if available < rt.cfg.FFTSize {
  147. available = rt.cfg.FFTSize
  148. }
  149. }
  150. allIQ, err := srcMgr.ReadIQ(available)
  151. if err != nil {
  152. return nil, err
  153. }
  154. if rec != nil {
  155. rec.Ingest(time.Now(), allIQ)
  156. }
  157. survIQ := allIQ
  158. if len(allIQ) > rt.cfg.FFTSize {
  159. survIQ = allIQ[len(allIQ)-rt.cfg.FFTSize:]
  160. }
  161. if rt.dcEnabled {
  162. dcBlocker.Apply(survIQ)
  163. }
  164. if rt.iqEnabled {
  165. dsp.IQBalance(survIQ)
  166. }
  167. var spectrum []float64
  168. if rt.useGPU && rt.gpuEngine != nil {
  169. gpuBuf := make([]complex64, len(survIQ))
  170. if len(rt.window) == len(survIQ) {
  171. for i := 0; i < len(survIQ); i++ {
  172. v := survIQ[i]
  173. w := float32(rt.window[i])
  174. gpuBuf[i] = complex(real(v)*w, imag(v)*w)
  175. }
  176. } else {
  177. copy(gpuBuf, survIQ)
  178. }
  179. out, err := rt.gpuEngine.Exec(gpuBuf)
  180. if err != nil {
  181. if gpuState != nil {
  182. gpuState.set(false, err)
  183. }
  184. rt.useGPU = false
  185. spectrum = fftutil.SpectrumWithPlan(gpuBuf, nil, rt.plan)
  186. } else {
  187. spectrum = fftutil.SpectrumFromFFT(out)
  188. }
  189. } else {
  190. spectrum = fftutil.SpectrumWithPlan(survIQ, rt.window, rt.plan)
  191. }
  192. for i := range spectrum {
  193. if math.IsNaN(spectrum[i]) || math.IsInf(spectrum[i], 0) {
  194. spectrum[i] = -200
  195. }
  196. }
  197. now := time.Now()
  198. finished, detected := rt.det.Process(now, spectrum, rt.cfg.CenterHz)
  199. return &spectrumArtifacts{
  200. allIQ: allIQ,
  201. surveillanceIQ: survIQ,
  202. detailIQ: survIQ,
  203. surveillanceSpectrum: spectrum,
  204. detailSpectrum: spectrum,
  205. finished: finished,
  206. detected: detected,
  207. thresholds: rt.det.LastThresholds(),
  208. noiseFloor: rt.det.LastNoiseFloor(),
  209. now: now,
  210. }, nil
  211. }
  212. func (rt *dspRuntime) buildSurveillanceResult(art *spectrumArtifacts) pipeline.SurveillanceResult {
  213. if art == nil {
  214. return pipeline.SurveillanceResult{}
  215. }
  216. policy := pipeline.PolicyFromConfig(rt.cfg)
  217. candidates := pipeline.CandidatesFromSignals(art.detected, "surveillance-detector")
  218. scheduled := pipeline.ScheduleCandidates(candidates, policy)
  219. level := pipeline.AnalysisLevel{
  220. Name: "surveillance",
  221. SampleRate: rt.cfg.SampleRate,
  222. FFTSize: rt.cfg.Surveillance.AnalysisFFTSize,
  223. CenterHz: rt.cfg.CenterHz,
  224. SpanHz: spanForPolicy(policy, float64(rt.cfg.SampleRate)),
  225. Source: "baseband",
  226. }
  227. lowRate := rt.cfg.SampleRate / 2
  228. lowFFT := rt.cfg.Surveillance.AnalysisFFTSize / 2
  229. if lowRate < 200000 {
  230. lowRate = rt.cfg.SampleRate
  231. }
  232. if lowFFT < 256 {
  233. lowFFT = rt.cfg.Surveillance.AnalysisFFTSize
  234. }
  235. lowLevel := pipeline.AnalysisLevel{
  236. Name: "surveillance-lowres",
  237. SampleRate: lowRate,
  238. FFTSize: lowFFT,
  239. CenterHz: rt.cfg.CenterHz,
  240. SpanHz: spanForPolicy(policy, float64(lowRate)),
  241. Source: "downsampled",
  242. }
  243. displayLevel := pipeline.AnalysisLevel{
  244. Name: "presentation",
  245. SampleRate: rt.cfg.SampleRate,
  246. FFTSize: rt.cfg.Surveillance.DisplayBins,
  247. CenterHz: rt.cfg.CenterHz,
  248. SpanHz: spanForPolicy(policy, float64(rt.cfg.SampleRate)),
  249. Source: "display",
  250. }
  251. levels := surveillanceLevels(policy, level, lowLevel)
  252. return pipeline.SurveillanceResult{
  253. Level: level,
  254. Levels: levels,
  255. DisplayLevel: displayLevel,
  256. Candidates: candidates,
  257. Scheduled: scheduled,
  258. Finished: art.finished,
  259. Signals: art.detected,
  260. NoiseFloor: art.noiseFloor,
  261. Thresholds: art.thresholds,
  262. }
  263. }
  264. func (rt *dspRuntime) buildRefinementInput(surv pipeline.SurveillanceResult) pipeline.RefinementInput {
  265. policy := pipeline.PolicyFromConfig(rt.cfg)
  266. plan := pipeline.BuildRefinementPlan(surv.Candidates, policy)
  267. scheduled := append([]pipeline.ScheduledCandidate(nil), surv.Scheduled...)
  268. if len(scheduled) == 0 && len(plan.Selected) > 0 {
  269. scheduled = append([]pipeline.ScheduledCandidate(nil), plan.Selected...)
  270. }
  271. windows := make([]pipeline.RefinementWindow, 0, len(scheduled))
  272. for _, sc := range scheduled {
  273. windows = append(windows, pipeline.RefinementWindowForCandidate(policy, sc.Candidate))
  274. }
  275. level := pipeline.AnalysisLevel{
  276. Name: "refinement",
  277. SampleRate: rt.cfg.SampleRate,
  278. FFTSize: rt.cfg.FFTSize,
  279. CenterHz: rt.cfg.CenterHz,
  280. SpanHz: spanForPolicy(policy, float64(rt.cfg.SampleRate)),
  281. Source: "refinement-window",
  282. }
  283. input := pipeline.RefinementInput{
  284. Level: level,
  285. Candidates: append([]pipeline.Candidate(nil), surv.Candidates...),
  286. Scheduled: scheduled,
  287. Plan: plan,
  288. Windows: windows,
  289. SampleRate: rt.cfg.SampleRate,
  290. FFTSize: rt.cfg.FFTSize,
  291. CenterHz: rt.cfg.CenterHz,
  292. Source: "surveillance-detector",
  293. }
  294. if !policy.RefinementEnabled {
  295. input.Scheduled = nil
  296. }
  297. return input
  298. }
  299. func (rt *dspRuntime) runRefinement(art *spectrumArtifacts, surv pipeline.SurveillanceResult, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementStep {
  300. input := rt.buildRefinementInput(surv)
  301. result := rt.refineSignals(art, input, extractMgr, rec)
  302. return pipeline.RefinementStep{Input: input, Result: result}
  303. }
  304. func (rt *dspRuntime) refineSignals(art *spectrumArtifacts, input pipeline.RefinementInput, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementResult {
  305. if art == nil || len(art.detailIQ) == 0 || len(input.Scheduled) == 0 {
  306. return pipeline.RefinementResult{}
  307. }
  308. policy := pipeline.PolicyFromConfig(rt.cfg)
  309. selectedCandidates := make([]pipeline.Candidate, 0, len(input.Scheduled))
  310. selectedSignals := make([]detector.Signal, 0, len(input.Scheduled))
  311. for _, sc := range input.Scheduled {
  312. selectedCandidates = append(selectedCandidates, sc.Candidate)
  313. selectedSignals = append(selectedSignals, detector.Signal{
  314. ID: sc.Candidate.ID,
  315. FirstBin: sc.Candidate.FirstBin,
  316. LastBin: sc.Candidate.LastBin,
  317. CenterHz: sc.Candidate.CenterHz,
  318. BWHz: sc.Candidate.BandwidthHz,
  319. PeakDb: sc.Candidate.PeakDb,
  320. SNRDb: sc.Candidate.SNRDb,
  321. NoiseDb: sc.Candidate.NoiseDb,
  322. })
  323. }
  324. sampleRate := input.SampleRate
  325. fftSize := input.FFTSize
  326. centerHz := input.CenterHz
  327. if sampleRate <= 0 {
  328. sampleRate = rt.cfg.SampleRate
  329. }
  330. if fftSize <= 0 {
  331. fftSize = rt.cfg.FFTSize
  332. }
  333. if centerHz == 0 {
  334. centerHz = rt.cfg.CenterHz
  335. }
  336. snips, snipRates := extractSignalIQBatch(extractMgr, art.detailIQ, sampleRate, centerHz, selectedSignals)
  337. refined := pipeline.RefineCandidates(selectedCandidates, input.Windows, art.detailSpectrum, sampleRate, fftSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  338. signals := make([]detector.Signal, 0, len(refined))
  339. decisions := make([]pipeline.SignalDecision, 0, len(refined))
  340. for i, ref := range refined {
  341. sig := ref.Signal
  342. signals = append(signals, sig)
  343. cls := sig.Class
  344. snipRate := ref.SnippetRate
  345. decision := pipeline.DecideSignalAction(policy, ref.Candidate, cls)
  346. decisions = append(decisions, decision)
  347. if cls != nil {
  348. pll := classifier.PLLResult{}
  349. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  350. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  351. cls.PLL = &pll
  352. signals[i].PLL = &pll
  353. if cls.ModType == classifier.ClassWFM && pll.Stereo {
  354. cls.ModType = classifier.ClassWFMStereo
  355. }
  356. }
  357. if (cls.ModType == classifier.ClassWFM || cls.ModType == classifier.ClassWFMStereo) && rec != nil {
  358. rt.updateRDS(art.now, rec, &signals[i], cls)
  359. }
  360. }
  361. }
  362. maxRecord := rt.cfg.Resources.MaxRecordingStreams
  363. maxDecode := rt.cfg.Resources.MaxDecodeJobs
  364. hold := time.Duration(rt.cfg.Resources.DecisionHoldMs) * time.Millisecond
  365. queueStats := rt.decisionQueues.Apply(decisions, maxRecord, maxDecode, hold, art.now, policy)
  366. rt.queueStats = queueStats
  367. summary := summarizeDecisions(decisions)
  368. if rec != nil {
  369. if summary.RecordEnabled > 0 {
  370. rt.cfg.Recorder.Enabled = true
  371. }
  372. if summary.DecodeEnabled > 0 {
  373. rt.cfg.Recorder.AutoDecode = true
  374. }
  375. }
  376. rt.det.UpdateClasses(signals)
  377. return pipeline.RefinementResult{Level: input.Level, Signals: signals, Decisions: decisions, Candidates: selectedCandidates}
  378. }
  379. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  380. if sig == nil || cls == nil {
  381. return
  382. }
  383. keyHz := sig.CenterHz
  384. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  385. keyHz = sig.PLL.ExactHz
  386. }
  387. key := int64(math.Round(keyHz / 25000.0))
  388. st := rt.rdsMap[key]
  389. if st == nil {
  390. st = &rdsState{}
  391. rt.rdsMap[key] = st
  392. }
  393. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  394. st.lastDecode = now
  395. atomic.StoreInt32(&st.busy, 1)
  396. go func(st *rdsState, sigHz float64) {
  397. defer atomic.StoreInt32(&st.busy, 0)
  398. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  399. if len(ringIQ) < ringSR || ringSR <= 0 {
  400. return
  401. }
  402. offset := sigHz - ringCenter
  403. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  404. decim1 := ringSR / 1000000
  405. if decim1 < 1 {
  406. decim1 = 1
  407. }
  408. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  409. f1 := dsp.ApplyFIR(shifted, lp1)
  410. d1 := dsp.Decimate(f1, decim1)
  411. rate1 := ringSR / decim1
  412. decim2 := rate1 / 250000
  413. if decim2 < 1 {
  414. decim2 = 1
  415. }
  416. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  417. f2 := dsp.ApplyFIR(d1, lp2)
  418. decimated := dsp.Decimate(f2, decim2)
  419. actualRate := rate1 / decim2
  420. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  421. if len(rdsBase.Samples) == 0 {
  422. return
  423. }
  424. st.mu.Lock()
  425. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  426. if result.PS != "" {
  427. st.result = result
  428. }
  429. st.mu.Unlock()
  430. }(st, sig.CenterHz)
  431. }
  432. st.mu.Lock()
  433. ps := st.result.PS
  434. st.mu.Unlock()
  435. if ps != "" && sig.PLL != nil {
  436. sig.PLL.RDSStation = strings.TrimSpace(ps)
  437. cls.PLL = sig.PLL
  438. }
  439. }
  440. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  441. if len(rt.rdsMap) > 0 {
  442. activeIDs := make(map[int64]bool, len(displaySignals))
  443. for _, s := range displaySignals {
  444. keyHz := s.CenterHz
  445. if s.PLL != nil && s.PLL.ExactHz != 0 {
  446. keyHz = s.PLL.ExactHz
  447. }
  448. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  449. }
  450. for id := range rt.rdsMap {
  451. if !activeIDs[id] {
  452. delete(rt.rdsMap, id)
  453. }
  454. }
  455. }
  456. if len(rt.streamPhaseState) > 0 {
  457. sigIDs := make(map[int64]bool, len(displaySignals))
  458. for _, s := range displaySignals {
  459. sigIDs[s.ID] = true
  460. }
  461. for id := range rt.streamPhaseState {
  462. if !sigIDs[id] {
  463. delete(rt.streamPhaseState, id)
  464. }
  465. }
  466. }
  467. if rec != nil && len(displaySignals) > 0 {
  468. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  469. _ = aqCfg
  470. }
  471. }
  472. func spanForPolicy(policy pipeline.Policy, fallback float64) float64 {
  473. if policy.MonitorSpanHz > 0 {
  474. return policy.MonitorSpanHz
  475. }
  476. if policy.MonitorStartHz != 0 && policy.MonitorEndHz != 0 && policy.MonitorEndHz > policy.MonitorStartHz {
  477. return policy.MonitorEndHz - policy.MonitorStartHz
  478. }
  479. return fallback
  480. }
  481. func surveillanceLevels(policy pipeline.Policy, primary pipeline.AnalysisLevel, secondary pipeline.AnalysisLevel) []pipeline.AnalysisLevel {
  482. levels := []pipeline.AnalysisLevel{primary}
  483. strategy := strings.ToLower(strings.TrimSpace(policy.SurveillanceStrategy))
  484. switch strategy {
  485. case "", "single-resolution":
  486. if secondary.SampleRate != primary.SampleRate || secondary.FFTSize != primary.FFTSize {
  487. levels = append(levels, secondary)
  488. }
  489. default:
  490. if secondary.SampleRate != primary.SampleRate || secondary.FFTSize != primary.FFTSize {
  491. levels = append(levels, secondary)
  492. }
  493. }
  494. return levels
  495. }