Wideband autonomous SDR analysis engine forked from sdr-visual-suite
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

410 line
12KB

  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. gotSamples bool
  39. }
  40. type spectrumArtifacts struct {
  41. allIQ []complex64
  42. iq []complex64
  43. spectrum []float64
  44. finished []detector.Event
  45. detected []detector.Signal
  46. thresholds []float64
  47. noiseFloor float64
  48. now time.Time
  49. }
  50. func newDSPRuntime(cfg config.Config, det *detector.Detector, window []float64, gpuState *gpuStatus) *dspRuntime {
  51. rt := &dspRuntime{
  52. cfg: cfg,
  53. det: det,
  54. window: window,
  55. plan: fftutil.NewCmplxPlan(cfg.FFTSize),
  56. dcEnabled: cfg.DCBlock,
  57. iqEnabled: cfg.IQBalance,
  58. useGPU: cfg.UseGPUFFT,
  59. rdsMap: map[int64]*rdsState{},
  60. streamPhaseState: map[int64]*streamExtractState{},
  61. streamOverlap: &streamIQOverlap{},
  62. }
  63. if rt.useGPU && gpuState != nil {
  64. snap := gpuState.snapshot()
  65. if snap.Available {
  66. if eng, err := gpufft.New(cfg.FFTSize); err == nil {
  67. rt.gpuEngine = eng
  68. gpuState.set(true, nil)
  69. } else {
  70. gpuState.set(false, err)
  71. rt.useGPU = false
  72. }
  73. }
  74. }
  75. return rt
  76. }
  77. func (rt *dspRuntime) applyUpdate(upd dspUpdate, srcMgr *sourceManager, rec *recorder.Manager, gpuState *gpuStatus) {
  78. prevFFT := rt.cfg.FFTSize
  79. prevUseGPU := rt.useGPU
  80. rt.cfg = upd.cfg
  81. if rec != nil {
  82. rec.Update(rt.cfg.SampleRate, rt.cfg.FFTSize, recorder.Policy{
  83. Enabled: rt.cfg.Recorder.Enabled,
  84. MinSNRDb: rt.cfg.Recorder.MinSNRDb,
  85. MinDuration: mustParseDuration(rt.cfg.Recorder.MinDuration, 1*time.Second),
  86. MaxDuration: mustParseDuration(rt.cfg.Recorder.MaxDuration, 300*time.Second),
  87. PrerollMs: rt.cfg.Recorder.PrerollMs,
  88. RecordIQ: rt.cfg.Recorder.RecordIQ,
  89. RecordAudio: rt.cfg.Recorder.RecordAudio,
  90. AutoDemod: rt.cfg.Recorder.AutoDemod,
  91. AutoDecode: rt.cfg.Recorder.AutoDecode,
  92. MaxDiskMB: rt.cfg.Recorder.MaxDiskMB,
  93. OutputDir: rt.cfg.Recorder.OutputDir,
  94. ClassFilter: rt.cfg.Recorder.ClassFilter,
  95. RingSeconds: rt.cfg.Recorder.RingSeconds,
  96. DeemphasisUs: rt.cfg.Recorder.DeemphasisUs,
  97. ExtractionTaps: rt.cfg.Recorder.ExtractionTaps,
  98. ExtractionBwMult: rt.cfg.Recorder.ExtractionBwMult,
  99. }, rt.cfg.CenterHz, buildDecoderMap(rt.cfg))
  100. }
  101. if upd.det != nil {
  102. rt.det = upd.det
  103. }
  104. if upd.window != nil {
  105. rt.window = upd.window
  106. rt.plan = fftutil.NewCmplxPlan(rt.cfg.FFTSize)
  107. }
  108. rt.dcEnabled = upd.dcBlock
  109. rt.iqEnabled = upd.iqBalance
  110. if rt.cfg.FFTSize != prevFFT || rt.cfg.UseGPUFFT != prevUseGPU {
  111. srcMgr.Flush()
  112. rt.gotSamples = false
  113. if rt.gpuEngine != nil {
  114. rt.gpuEngine.Close()
  115. rt.gpuEngine = nil
  116. }
  117. rt.useGPU = rt.cfg.UseGPUFFT
  118. if rt.useGPU && gpuState != nil {
  119. snap := gpuState.snapshot()
  120. if snap.Available {
  121. if eng, err := gpufft.New(rt.cfg.FFTSize); err == nil {
  122. rt.gpuEngine = eng
  123. gpuState.set(true, nil)
  124. } else {
  125. gpuState.set(false, err)
  126. rt.useGPU = false
  127. }
  128. } else {
  129. gpuState.set(false, nil)
  130. rt.useGPU = false
  131. }
  132. } else if gpuState != nil {
  133. gpuState.set(false, nil)
  134. }
  135. }
  136. }
  137. func (rt *dspRuntime) captureSpectrum(srcMgr *sourceManager, rec *recorder.Manager, dcBlocker *dsp.DCBlocker, gpuState *gpuStatus) (*spectrumArtifacts, error) {
  138. available := rt.cfg.FFTSize
  139. st := srcMgr.Stats()
  140. if st.BufferSamples > rt.cfg.FFTSize {
  141. available = (st.BufferSamples / rt.cfg.FFTSize) * rt.cfg.FFTSize
  142. if available < rt.cfg.FFTSize {
  143. available = rt.cfg.FFTSize
  144. }
  145. }
  146. allIQ, err := srcMgr.ReadIQ(available)
  147. if err != nil {
  148. return nil, err
  149. }
  150. if rec != nil {
  151. rec.Ingest(time.Now(), allIQ)
  152. }
  153. iq := allIQ
  154. if len(allIQ) > rt.cfg.FFTSize {
  155. iq = allIQ[len(allIQ)-rt.cfg.FFTSize:]
  156. }
  157. if rt.dcEnabled {
  158. dcBlocker.Apply(iq)
  159. }
  160. if rt.iqEnabled {
  161. dsp.IQBalance(iq)
  162. }
  163. var spectrum []float64
  164. if rt.useGPU && rt.gpuEngine != nil {
  165. gpuBuf := make([]complex64, len(iq))
  166. if len(rt.window) == len(iq) {
  167. for i := 0; i < len(iq); i++ {
  168. v := iq[i]
  169. w := float32(rt.window[i])
  170. gpuBuf[i] = complex(real(v)*w, imag(v)*w)
  171. }
  172. } else {
  173. copy(gpuBuf, iq)
  174. }
  175. out, err := rt.gpuEngine.Exec(gpuBuf)
  176. if err != nil {
  177. if gpuState != nil {
  178. gpuState.set(false, err)
  179. }
  180. rt.useGPU = false
  181. spectrum = fftutil.SpectrumWithPlan(gpuBuf, nil, rt.plan)
  182. } else {
  183. spectrum = fftutil.SpectrumFromFFT(out)
  184. }
  185. } else {
  186. spectrum = fftutil.SpectrumWithPlan(iq, rt.window, rt.plan)
  187. }
  188. for i := range spectrum {
  189. if math.IsNaN(spectrum[i]) || math.IsInf(spectrum[i], 0) {
  190. spectrum[i] = -200
  191. }
  192. }
  193. now := time.Now()
  194. finished, detected := rt.det.Process(now, spectrum, rt.cfg.CenterHz)
  195. return &spectrumArtifacts{
  196. allIQ: allIQ,
  197. iq: iq,
  198. spectrum: spectrum,
  199. finished: finished,
  200. detected: detected,
  201. thresholds: rt.det.LastThresholds(),
  202. noiseFloor: rt.det.LastNoiseFloor(),
  203. now: now,
  204. }, nil
  205. }
  206. func (rt *dspRuntime) buildSurveillanceResult(art *spectrumArtifacts) pipeline.SurveillanceResult {
  207. if art == nil {
  208. return pipeline.SurveillanceResult{}
  209. }
  210. policy := pipeline.PolicyFromConfig(rt.cfg)
  211. candidates := pipeline.CandidatesFromSignals(art.detected, "surveillance-detector")
  212. scheduled := pipeline.ScheduleCandidates(candidates, policy)
  213. return pipeline.SurveillanceResult{
  214. Candidates: candidates,
  215. Scheduled: scheduled,
  216. Finished: art.finished,
  217. Signals: art.detected,
  218. NoiseFloor: art.noiseFloor,
  219. Thresholds: art.thresholds,
  220. }
  221. }
  222. func (rt *dspRuntime) buildRefinementInput(surv pipeline.SurveillanceResult) pipeline.RefinementInput {
  223. policy := pipeline.PolicyFromConfig(rt.cfg)
  224. input := pipeline.RefinementInput{
  225. Candidates: append([]pipeline.Candidate(nil), surv.Candidates...),
  226. Scheduled: append([]pipeline.ScheduledCandidate(nil), surv.Scheduled...),
  227. SampleRate: rt.cfg.SampleRate,
  228. FFTSize: rt.cfg.FFTSize,
  229. CenterHz: rt.cfg.CenterHz,
  230. Source: "surveillance-detector",
  231. }
  232. if !policy.RefinementEnabled {
  233. input.Scheduled = nil
  234. }
  235. return input
  236. }
  237. func (rt *dspRuntime) refineSignals(art *spectrumArtifacts, input pipeline.RefinementInput, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementResult {
  238. if art == nil || len(art.iq) == 0 || len(input.Scheduled) == 0 {
  239. return pipeline.RefinementResult{}
  240. }
  241. policy := pipeline.PolicyFromConfig(rt.cfg)
  242. selectedCandidates := make([]pipeline.Candidate, 0, len(input.Scheduled))
  243. selectedSignals := make([]detector.Signal, 0, len(input.Scheduled))
  244. for _, sc := range input.Scheduled {
  245. selectedCandidates = append(selectedCandidates, sc.Candidate)
  246. selectedSignals = append(selectedSignals, detector.Signal{
  247. ID: sc.Candidate.ID,
  248. FirstBin: sc.Candidate.FirstBin,
  249. LastBin: sc.Candidate.LastBin,
  250. CenterHz: sc.Candidate.CenterHz,
  251. BWHz: sc.Candidate.BandwidthHz,
  252. PeakDb: sc.Candidate.PeakDb,
  253. SNRDb: sc.Candidate.SNRDb,
  254. NoiseDb: sc.Candidate.NoiseDb,
  255. })
  256. }
  257. sampleRate := input.SampleRate
  258. fftSize := input.FFTSize
  259. centerHz := input.CenterHz
  260. if sampleRate <= 0 {
  261. sampleRate = rt.cfg.SampleRate
  262. }
  263. if fftSize <= 0 {
  264. fftSize = rt.cfg.FFTSize
  265. }
  266. if centerHz == 0 {
  267. centerHz = rt.cfg.CenterHz
  268. }
  269. snips, snipRates := extractSignalIQBatch(extractMgr, art.iq, sampleRate, centerHz, selectedSignals)
  270. refined := pipeline.RefineCandidates(selectedCandidates, art.spectrum, sampleRate, fftSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  271. signals := make([]detector.Signal, 0, len(refined))
  272. decisions := make([]pipeline.SignalDecision, 0, len(refined))
  273. for i, ref := range refined {
  274. sig := ref.Signal
  275. signals = append(signals, sig)
  276. cls := sig.Class
  277. snipRate := ref.SnippetRate
  278. decision := pipeline.DecideSignalAction(policy, ref.Candidate, cls)
  279. decisions = append(decisions, decision)
  280. if decision.ShouldAutoDecode && rec != nil {
  281. rt.cfg.Recorder.AutoDecode = true
  282. }
  283. if decision.ShouldRecord && rec != nil {
  284. rt.cfg.Recorder.Enabled = true
  285. }
  286. if cls != nil {
  287. pll := classifier.PLLResult{}
  288. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  289. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  290. cls.PLL = &pll
  291. signals[i].PLL = &pll
  292. if cls.ModType == classifier.ClassWFM && pll.Stereo {
  293. cls.ModType = classifier.ClassWFMStereo
  294. }
  295. }
  296. if (cls.ModType == classifier.ClassWFM || cls.ModType == classifier.ClassWFMStereo) && rec != nil {
  297. rt.updateRDS(art.now, rec, &signals[i], cls)
  298. }
  299. }
  300. }
  301. rt.det.UpdateClasses(signals)
  302. return pipeline.RefinementResult{Signals: signals, Decisions: decisions, Candidates: selectedCandidates}
  303. }
  304. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  305. if sig == nil || cls == nil {
  306. return
  307. }
  308. keyHz := sig.CenterHz
  309. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  310. keyHz = sig.PLL.ExactHz
  311. }
  312. key := int64(math.Round(keyHz / 25000.0))
  313. st := rt.rdsMap[key]
  314. if st == nil {
  315. st = &rdsState{}
  316. rt.rdsMap[key] = st
  317. }
  318. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  319. st.lastDecode = now
  320. atomic.StoreInt32(&st.busy, 1)
  321. go func(st *rdsState, sigHz float64) {
  322. defer atomic.StoreInt32(&st.busy, 0)
  323. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  324. if len(ringIQ) < ringSR || ringSR <= 0 {
  325. return
  326. }
  327. offset := sigHz - ringCenter
  328. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  329. decim1 := ringSR / 1000000
  330. if decim1 < 1 {
  331. decim1 = 1
  332. }
  333. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  334. f1 := dsp.ApplyFIR(shifted, lp1)
  335. d1 := dsp.Decimate(f1, decim1)
  336. rate1 := ringSR / decim1
  337. decim2 := rate1 / 250000
  338. if decim2 < 1 {
  339. decim2 = 1
  340. }
  341. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  342. f2 := dsp.ApplyFIR(d1, lp2)
  343. decimated := dsp.Decimate(f2, decim2)
  344. actualRate := rate1 / decim2
  345. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  346. if len(rdsBase.Samples) == 0 {
  347. return
  348. }
  349. st.mu.Lock()
  350. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  351. if result.PS != "" {
  352. st.result = result
  353. }
  354. st.mu.Unlock()
  355. }(st, sig.CenterHz)
  356. }
  357. st.mu.Lock()
  358. ps := st.result.PS
  359. st.mu.Unlock()
  360. if ps != "" && sig.PLL != nil {
  361. sig.PLL.RDSStation = strings.TrimSpace(ps)
  362. cls.PLL = sig.PLL
  363. }
  364. }
  365. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  366. if len(rt.rdsMap) > 0 {
  367. activeIDs := make(map[int64]bool, len(displaySignals))
  368. for _, s := range displaySignals {
  369. keyHz := s.CenterHz
  370. if s.PLL != nil && s.PLL.ExactHz != 0 {
  371. keyHz = s.PLL.ExactHz
  372. }
  373. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  374. }
  375. for id := range rt.rdsMap {
  376. if !activeIDs[id] {
  377. delete(rt.rdsMap, id)
  378. }
  379. }
  380. }
  381. if len(rt.streamPhaseState) > 0 {
  382. sigIDs := make(map[int64]bool, len(displaySignals))
  383. for _, s := range displaySignals {
  384. sigIDs[s.ID] = true
  385. }
  386. for id := range rt.streamPhaseState {
  387. if !sigIDs[id] {
  388. delete(rt.streamPhaseState, id)
  389. }
  390. }
  391. }
  392. if rec != nil && len(displaySignals) > 0 {
  393. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  394. _ = aqCfg
  395. }
  396. }