Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

532 lignes
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) 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. level := pipeline.AnalysisLevel{
  289. Name: "refinement",
  290. SampleRate: rt.cfg.SampleRate,
  291. FFTSize: rt.cfg.FFTSize,
  292. CenterHz: rt.cfg.CenterHz,
  293. SpanHz: spanForPolicy(policy, float64(rt.cfg.SampleRate)),
  294. Source: "refinement-window",
  295. }
  296. input := pipeline.RefinementInput{
  297. Level: level,
  298. Candidates: append([]pipeline.Candidate(nil), surv.Candidates...),
  299. Scheduled: scheduled,
  300. Plan: plan,
  301. Windows: windows,
  302. SampleRate: rt.cfg.SampleRate,
  303. FFTSize: rt.cfg.FFTSize,
  304. CenterHz: rt.cfg.CenterHz,
  305. Source: "surveillance-detector",
  306. }
  307. if !policy.RefinementEnabled {
  308. input.Scheduled = nil
  309. }
  310. return input
  311. }
  312. func (rt *dspRuntime) runRefinement(art *spectrumArtifacts, surv pipeline.SurveillanceResult, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementStep {
  313. input := rt.buildRefinementInput(surv)
  314. result := rt.refineSignals(art, input, extractMgr, rec)
  315. return pipeline.RefinementStep{Input: input, Result: result}
  316. }
  317. func (rt *dspRuntime) refineSignals(art *spectrumArtifacts, input pipeline.RefinementInput, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementResult {
  318. if art == nil || len(art.detailIQ) == 0 || len(input.Scheduled) == 0 {
  319. return pipeline.RefinementResult{}
  320. }
  321. policy := pipeline.PolicyFromConfig(rt.cfg)
  322. selectedCandidates := make([]pipeline.Candidate, 0, len(input.Scheduled))
  323. selectedSignals := make([]detector.Signal, 0, len(input.Scheduled))
  324. for _, sc := range input.Scheduled {
  325. selectedCandidates = append(selectedCandidates, sc.Candidate)
  326. selectedSignals = append(selectedSignals, detector.Signal{
  327. ID: sc.Candidate.ID,
  328. FirstBin: sc.Candidate.FirstBin,
  329. LastBin: sc.Candidate.LastBin,
  330. CenterHz: sc.Candidate.CenterHz,
  331. BWHz: sc.Candidate.BandwidthHz,
  332. PeakDb: sc.Candidate.PeakDb,
  333. SNRDb: sc.Candidate.SNRDb,
  334. NoiseDb: sc.Candidate.NoiseDb,
  335. })
  336. }
  337. sampleRate := input.SampleRate
  338. fftSize := input.FFTSize
  339. centerHz := input.CenterHz
  340. if sampleRate <= 0 {
  341. sampleRate = rt.cfg.SampleRate
  342. }
  343. if fftSize <= 0 {
  344. fftSize = rt.cfg.FFTSize
  345. }
  346. if centerHz == 0 {
  347. centerHz = rt.cfg.CenterHz
  348. }
  349. snips, snipRates := extractSignalIQBatch(extractMgr, art.detailIQ, sampleRate, centerHz, selectedSignals)
  350. refined := pipeline.RefineCandidates(selectedCandidates, input.Windows, art.detailSpectrum, sampleRate, fftSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  351. signals := make([]detector.Signal, 0, len(refined))
  352. decisions := make([]pipeline.SignalDecision, 0, len(refined))
  353. for i, ref := range refined {
  354. sig := ref.Signal
  355. signals = append(signals, sig)
  356. cls := sig.Class
  357. snipRate := ref.SnippetRate
  358. decision := pipeline.DecideSignalAction(policy, ref.Candidate, cls)
  359. decisions = append(decisions, decision)
  360. if cls != nil {
  361. pll := classifier.PLLResult{}
  362. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  363. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  364. cls.PLL = &pll
  365. signals[i].PLL = &pll
  366. if cls.ModType == classifier.ClassWFM && pll.Stereo {
  367. cls.ModType = classifier.ClassWFMStereo
  368. }
  369. }
  370. if (cls.ModType == classifier.ClassWFM || cls.ModType == classifier.ClassWFMStereo) && rec != nil {
  371. rt.updateRDS(art.now, rec, &signals[i], cls)
  372. }
  373. }
  374. }
  375. maxRecord := rt.cfg.Resources.MaxRecordingStreams
  376. maxDecode := rt.cfg.Resources.MaxDecodeJobs
  377. hold := time.Duration(rt.cfg.Resources.DecisionHoldMs) * time.Millisecond
  378. queueStats := rt.decisionQueues.Apply(decisions, maxRecord, maxDecode, hold, art.now, policy)
  379. rt.queueStats = queueStats
  380. summary := summarizeDecisions(decisions)
  381. if rec != nil {
  382. if summary.RecordEnabled > 0 {
  383. rt.cfg.Recorder.Enabled = true
  384. }
  385. if summary.DecodeEnabled > 0 {
  386. rt.cfg.Recorder.AutoDecode = true
  387. }
  388. }
  389. rt.det.UpdateClasses(signals)
  390. return pipeline.RefinementResult{Level: input.Level, Signals: signals, Decisions: decisions, Candidates: selectedCandidates}
  391. }
  392. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  393. if sig == nil || cls == nil {
  394. return
  395. }
  396. keyHz := sig.CenterHz
  397. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  398. keyHz = sig.PLL.ExactHz
  399. }
  400. key := int64(math.Round(keyHz / 25000.0))
  401. st := rt.rdsMap[key]
  402. if st == nil {
  403. st = &rdsState{}
  404. rt.rdsMap[key] = st
  405. }
  406. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  407. st.lastDecode = now
  408. atomic.StoreInt32(&st.busy, 1)
  409. go func(st *rdsState, sigHz float64) {
  410. defer atomic.StoreInt32(&st.busy, 0)
  411. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  412. if len(ringIQ) < ringSR || ringSR <= 0 {
  413. return
  414. }
  415. offset := sigHz - ringCenter
  416. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  417. decim1 := ringSR / 1000000
  418. if decim1 < 1 {
  419. decim1 = 1
  420. }
  421. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  422. f1 := dsp.ApplyFIR(shifted, lp1)
  423. d1 := dsp.Decimate(f1, decim1)
  424. rate1 := ringSR / decim1
  425. decim2 := rate1 / 250000
  426. if decim2 < 1 {
  427. decim2 = 1
  428. }
  429. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  430. f2 := dsp.ApplyFIR(d1, lp2)
  431. decimated := dsp.Decimate(f2, decim2)
  432. actualRate := rate1 / decim2
  433. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  434. if len(rdsBase.Samples) == 0 {
  435. return
  436. }
  437. st.mu.Lock()
  438. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  439. if result.PS != "" {
  440. st.result = result
  441. }
  442. st.mu.Unlock()
  443. }(st, sig.CenterHz)
  444. }
  445. st.mu.Lock()
  446. ps := st.result.PS
  447. st.mu.Unlock()
  448. if ps != "" && sig.PLL != nil {
  449. sig.PLL.RDSStation = strings.TrimSpace(ps)
  450. cls.PLL = sig.PLL
  451. }
  452. }
  453. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  454. if len(rt.rdsMap) > 0 {
  455. activeIDs := make(map[int64]bool, len(displaySignals))
  456. for _, s := range displaySignals {
  457. keyHz := s.CenterHz
  458. if s.PLL != nil && s.PLL.ExactHz != 0 {
  459. keyHz = s.PLL.ExactHz
  460. }
  461. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  462. }
  463. for id := range rt.rdsMap {
  464. if !activeIDs[id] {
  465. delete(rt.rdsMap, id)
  466. }
  467. }
  468. }
  469. if len(rt.streamPhaseState) > 0 {
  470. sigIDs := make(map[int64]bool, len(displaySignals))
  471. for _, s := range displaySignals {
  472. sigIDs[s.ID] = true
  473. }
  474. for id := range rt.streamPhaseState {
  475. if !sigIDs[id] {
  476. delete(rt.streamPhaseState, id)
  477. }
  478. }
  479. }
  480. if rec != nil && len(displaySignals) > 0 {
  481. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  482. _ = aqCfg
  483. }
  484. }
  485. func spanForPolicy(policy pipeline.Policy, fallback float64) float64 {
  486. if policy.MonitorSpanHz > 0 {
  487. return policy.MonitorSpanHz
  488. }
  489. if policy.MonitorStartHz != 0 && policy.MonitorEndHz != 0 && policy.MonitorEndHz > policy.MonitorStartHz {
  490. return policy.MonitorEndHz - policy.MonitorStartHz
  491. }
  492. return fallback
  493. }
  494. func surveillanceLevels(policy pipeline.Policy, primary pipeline.AnalysisLevel, secondary pipeline.AnalysisLevel) []pipeline.AnalysisLevel {
  495. levels := []pipeline.AnalysisLevel{primary}
  496. strategy := strings.ToLower(strings.TrimSpace(policy.SurveillanceStrategy))
  497. switch strategy {
  498. case "multi-res", "multi-resolution", "multi", "multi_res":
  499. if secondary.SampleRate != primary.SampleRate || secondary.FFTSize != primary.FFTSize {
  500. levels = append(levels, secondary)
  501. }
  502. }
  503. return levels
  504. }
  505. func sameIQBuffer(a []complex64, b []complex64) bool {
  506. if len(a) != len(b) {
  507. return false
  508. }
  509. if len(a) == 0 {
  510. return true
  511. }
  512. return &a[0] == &b[0]
  513. }