Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

356 Zeilen
10KB

  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) refineSignals(art *spectrumArtifacts, extractMgr *extractionManager, rec *recorder.Manager) []detector.Signal {
  207. if art == nil || len(art.iq) == 0 {
  208. return nil
  209. }
  210. policy := pipeline.PolicyFromConfig(rt.cfg)
  211. candidates := pipeline.CandidatesFromSignals(art.detected, "surveillance-detector")
  212. scheduled := pipeline.ScheduleCandidates(candidates, policy)
  213. selected := make([]detector.Signal, 0, len(scheduled))
  214. for _, sc := range scheduled {
  215. selected = append(selected, detector.Signal{
  216. ID: sc.Candidate.ID,
  217. FirstBin: sc.Candidate.FirstBin,
  218. LastBin: sc.Candidate.LastBin,
  219. CenterHz: sc.Candidate.CenterHz,
  220. BWHz: sc.Candidate.BandwidthHz,
  221. PeakDb: sc.Candidate.PeakDb,
  222. SNRDb: sc.Candidate.SNRDb,
  223. NoiseDb: sc.Candidate.NoiseDb,
  224. })
  225. }
  226. snips, snipRates := extractSignalIQBatch(extractMgr, art.iq, rt.cfg.SampleRate, rt.cfg.CenterHz, selected)
  227. refined := pipeline.RefineCandidates(pipeline.CandidatesFromSignals(selected, "scheduled-candidate"), art.spectrum, rt.cfg.SampleRate, rt.cfg.FFTSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  228. signals := make([]detector.Signal, 0, len(refined))
  229. for i, ref := range refined {
  230. sig := ref.Signal
  231. signals = append(signals, sig)
  232. cls := sig.Class
  233. snipRate := ref.SnippetRate
  234. if cls != nil {
  235. pll := classifier.PLLResult{}
  236. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  237. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  238. cls.PLL = &pll
  239. signals[i].PLL = &pll
  240. if cls.ModType == classifier.ClassWFM && pll.Stereo {
  241. cls.ModType = classifier.ClassWFMStereo
  242. }
  243. }
  244. if (cls.ModType == classifier.ClassWFM || cls.ModType == classifier.ClassWFMStereo) && rec != nil {
  245. rt.updateRDS(art.now, rec, &signals[i], cls)
  246. }
  247. }
  248. }
  249. rt.det.UpdateClasses(signals)
  250. return signals
  251. }
  252. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  253. if sig == nil || cls == nil {
  254. return
  255. }
  256. keyHz := sig.CenterHz
  257. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  258. keyHz = sig.PLL.ExactHz
  259. }
  260. key := int64(math.Round(keyHz / 25000.0))
  261. st := rt.rdsMap[key]
  262. if st == nil {
  263. st = &rdsState{}
  264. rt.rdsMap[key] = st
  265. }
  266. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  267. st.lastDecode = now
  268. atomic.StoreInt32(&st.busy, 1)
  269. go func(st *rdsState, sigHz float64) {
  270. defer atomic.StoreInt32(&st.busy, 0)
  271. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  272. if len(ringIQ) < ringSR || ringSR <= 0 {
  273. return
  274. }
  275. offset := sigHz - ringCenter
  276. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  277. decim1 := ringSR / 1000000
  278. if decim1 < 1 {
  279. decim1 = 1
  280. }
  281. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  282. f1 := dsp.ApplyFIR(shifted, lp1)
  283. d1 := dsp.Decimate(f1, decim1)
  284. rate1 := ringSR / decim1
  285. decim2 := rate1 / 250000
  286. if decim2 < 1 {
  287. decim2 = 1
  288. }
  289. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  290. f2 := dsp.ApplyFIR(d1, lp2)
  291. decimated := dsp.Decimate(f2, decim2)
  292. actualRate := rate1 / decim2
  293. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  294. if len(rdsBase.Samples) == 0 {
  295. return
  296. }
  297. st.mu.Lock()
  298. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  299. if result.PS != "" {
  300. st.result = result
  301. }
  302. st.mu.Unlock()
  303. }(st, sig.CenterHz)
  304. }
  305. st.mu.Lock()
  306. ps := st.result.PS
  307. st.mu.Unlock()
  308. if ps != "" && sig.PLL != nil {
  309. sig.PLL.RDSStation = strings.TrimSpace(ps)
  310. cls.PLL = sig.PLL
  311. }
  312. }
  313. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  314. if len(rt.rdsMap) > 0 {
  315. activeIDs := make(map[int64]bool, len(displaySignals))
  316. for _, s := range displaySignals {
  317. keyHz := s.CenterHz
  318. if s.PLL != nil && s.PLL.ExactHz != 0 {
  319. keyHz = s.PLL.ExactHz
  320. }
  321. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  322. }
  323. for id := range rt.rdsMap {
  324. if !activeIDs[id] {
  325. delete(rt.rdsMap, id)
  326. }
  327. }
  328. }
  329. if len(rt.streamPhaseState) > 0 {
  330. sigIDs := make(map[int64]bool, len(displaySignals))
  331. for _, s := range displaySignals {
  332. sigIDs[s.ID] = true
  333. }
  334. for id := range rt.streamPhaseState {
  335. if !sigIDs[id] {
  336. delete(rt.streamPhaseState, id)
  337. }
  338. }
  339. }
  340. if rec != nil && len(displaySignals) > 0 {
  341. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  342. _ = aqCfg
  343. }
  344. }