Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

656 wiersze
20KB

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