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

1200 строки
38KB

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "sdr-wideband-suite/internal/classifier"
  12. "sdr-wideband-suite/internal/config"
  13. "sdr-wideband-suite/internal/demod"
  14. "sdr-wideband-suite/internal/detector"
  15. "sdr-wideband-suite/internal/dsp"
  16. "sdr-wideband-suite/internal/logging"
  17. fftutil "sdr-wideband-suite/internal/fft"
  18. "sdr-wideband-suite/internal/fft/gpufft"
  19. "sdr-wideband-suite/internal/pipeline"
  20. "sdr-wideband-suite/internal/rds"
  21. "sdr-wideband-suite/internal/recorder"
  22. "sdr-wideband-suite/internal/telemetry"
  23. )
  24. type rdsState struct {
  25. dec rds.Decoder
  26. result rds.Result
  27. lastDecode time.Time
  28. busy int32
  29. mu sync.Mutex
  30. }
  31. var forceFixedStreamReadSamples = func() int {
  32. raw := strings.TrimSpace(os.Getenv("SDR_FORCE_FIXED_STREAM_READ_SAMPLES"))
  33. if raw == "" {
  34. return 0
  35. }
  36. v, err := strconv.Atoi(raw)
  37. if err != nil || v <= 0 {
  38. return 0
  39. }
  40. return v
  41. }()
  42. type dspRuntime struct {
  43. cfg config.Config
  44. det *detector.Detector
  45. derivedDetectors map[string]*derivedDetector
  46. nextDerivedBase int64
  47. window []float64
  48. plan *fftutil.CmplxPlan
  49. detailWindow []float64
  50. detailPlan *fftutil.CmplxPlan
  51. detailFFT int
  52. survWindows map[int][]float64
  53. survPlans map[int]*fftutil.CmplxPlan
  54. survFIR map[int][]float64
  55. dcEnabled bool
  56. iqEnabled bool
  57. useGPU bool
  58. gpuEngine *gpufft.Engine
  59. rdsMap map[int64]*rdsState
  60. streamPhaseState map[int64]*streamExtractState
  61. streamOverlap *streamIQOverlap
  62. arbiter *pipeline.Arbiter
  63. arbitration pipeline.ArbitrationState
  64. gotSamples bool
  65. telemetry *telemetry.Collector
  66. lastAllIQTail []complex64
  67. }
  68. type spectrumArtifacts struct {
  69. allIQ []complex64
  70. streamDropped bool
  71. surveillanceIQ []complex64
  72. detailIQ []complex64
  73. surveillanceSpectrum []float64
  74. surveillanceSpectra []pipeline.SurveillanceLevelSpectrum
  75. surveillancePlan surveillancePlan
  76. detailSpectrum []float64
  77. finished []detector.Event
  78. detected []detector.Signal
  79. thresholds []float64
  80. noiseFloor float64
  81. now time.Time
  82. }
  83. type derivedDetector struct {
  84. det *detector.Detector
  85. sampleRate int
  86. fftSize int
  87. idBase int64
  88. }
  89. type surveillanceLevelSpec struct {
  90. Level pipeline.AnalysisLevel
  91. Decim int
  92. AllowGPU bool
  93. }
  94. type surveillancePlan struct {
  95. Primary pipeline.AnalysisLevel
  96. Levels []pipeline.AnalysisLevel
  97. LevelSet pipeline.SurveillanceLevelSet
  98. Presentation pipeline.AnalysisLevel
  99. Context pipeline.AnalysisContext
  100. DetectionPolicy pipeline.SurveillanceDetectionPolicy
  101. Specs []surveillanceLevelSpec
  102. }
  103. const derivedIDBlock = int64(1_000_000_000)
  104. func newDSPRuntime(cfg config.Config, det *detector.Detector, window []float64, gpuState *gpuStatus, coll *telemetry.Collector) *dspRuntime {
  105. detailFFT := cfg.Refinement.DetailFFTSize
  106. if detailFFT <= 0 {
  107. detailFFT = cfg.FFTSize
  108. }
  109. rt := &dspRuntime{
  110. cfg: cfg,
  111. det: det,
  112. derivedDetectors: map[string]*derivedDetector{},
  113. nextDerivedBase: -derivedIDBlock,
  114. window: window,
  115. plan: fftutil.NewCmplxPlan(cfg.FFTSize),
  116. detailWindow: fftutil.Hann(detailFFT),
  117. detailPlan: fftutil.NewCmplxPlan(detailFFT),
  118. detailFFT: detailFFT,
  119. survWindows: map[int][]float64{},
  120. survPlans: map[int]*fftutil.CmplxPlan{},
  121. survFIR: map[int][]float64{},
  122. dcEnabled: cfg.DCBlock,
  123. iqEnabled: cfg.IQBalance,
  124. useGPU: cfg.UseGPUFFT,
  125. rdsMap: map[int64]*rdsState{},
  126. streamPhaseState: map[int64]*streamExtractState{},
  127. streamOverlap: &streamIQOverlap{},
  128. arbiter: pipeline.NewArbiter(),
  129. telemetry: coll,
  130. }
  131. if rt.useGPU && gpuState != nil {
  132. snap := gpuState.snapshot()
  133. if snap.Available {
  134. if eng, err := gpufft.New(cfg.FFTSize); err == nil {
  135. rt.gpuEngine = eng
  136. gpuState.set(true, nil)
  137. } else {
  138. gpuState.set(false, err)
  139. rt.useGPU = false
  140. }
  141. }
  142. }
  143. return rt
  144. }
  145. func (rt *dspRuntime) applyUpdate(upd dspUpdate, srcMgr *sourceManager, rec *recorder.Manager, gpuState *gpuStatus) {
  146. prevFFT := rt.cfg.FFTSize
  147. prevSampleRate := rt.cfg.SampleRate
  148. prevUseGPU := rt.useGPU
  149. prevDetailFFT := rt.detailFFT
  150. rt.cfg = upd.cfg
  151. if rec != nil {
  152. rec.Update(rt.cfg.SampleRate, rt.cfg.FFTSize, recorder.Policy{
  153. Enabled: rt.cfg.Recorder.Enabled,
  154. MinSNRDb: rt.cfg.Recorder.MinSNRDb,
  155. MinDuration: mustParseDuration(rt.cfg.Recorder.MinDuration, 1*time.Second),
  156. MaxDuration: mustParseDuration(rt.cfg.Recorder.MaxDuration, 300*time.Second),
  157. PrerollMs: rt.cfg.Recorder.PrerollMs,
  158. RecordIQ: rt.cfg.Recorder.RecordIQ,
  159. RecordAudio: rt.cfg.Recorder.RecordAudio,
  160. AutoDemod: rt.cfg.Recorder.AutoDemod,
  161. AutoDecode: rt.cfg.Recorder.AutoDecode,
  162. MaxDiskMB: rt.cfg.Recorder.MaxDiskMB,
  163. OutputDir: rt.cfg.Recorder.OutputDir,
  164. ClassFilter: rt.cfg.Recorder.ClassFilter,
  165. RingSeconds: rt.cfg.Recorder.RingSeconds,
  166. DeemphasisUs: rt.cfg.Recorder.DeemphasisUs,
  167. ExtractionTaps: rt.cfg.Recorder.ExtractionTaps,
  168. ExtractionBwMult: rt.cfg.Recorder.ExtractionBwMult,
  169. }, rt.cfg.CenterHz, buildDecoderMap(rt.cfg))
  170. }
  171. if upd.det != nil {
  172. rt.det = upd.det
  173. }
  174. if upd.window != nil {
  175. rt.window = upd.window
  176. rt.plan = fftutil.NewCmplxPlan(rt.cfg.FFTSize)
  177. }
  178. detailFFT := rt.cfg.Refinement.DetailFFTSize
  179. if detailFFT <= 0 {
  180. detailFFT = rt.cfg.FFTSize
  181. }
  182. if detailFFT != prevDetailFFT {
  183. rt.detailFFT = detailFFT
  184. rt.detailWindow = fftutil.Hann(detailFFT)
  185. rt.detailPlan = fftutil.NewCmplxPlan(detailFFT)
  186. }
  187. if prevSampleRate != rt.cfg.SampleRate {
  188. rt.survFIR = map[int][]float64{}
  189. }
  190. if prevFFT != rt.cfg.FFTSize {
  191. rt.survWindows = map[int][]float64{}
  192. rt.survPlans = map[int]*fftutil.CmplxPlan{}
  193. }
  194. if upd.det != nil || prevSampleRate != rt.cfg.SampleRate || prevFFT != rt.cfg.FFTSize {
  195. rt.derivedDetectors = map[string]*derivedDetector{}
  196. rt.nextDerivedBase = -derivedIDBlock
  197. }
  198. rt.dcEnabled = upd.dcBlock
  199. rt.iqEnabled = upd.iqBalance
  200. if rt.cfg.FFTSize != prevFFT || rt.cfg.UseGPUFFT != prevUseGPU {
  201. srcMgr.Flush()
  202. rt.gotSamples = false
  203. if rt.gpuEngine != nil {
  204. rt.gpuEngine.Close()
  205. rt.gpuEngine = nil
  206. }
  207. rt.useGPU = rt.cfg.UseGPUFFT
  208. if rt.useGPU && gpuState != nil {
  209. snap := gpuState.snapshot()
  210. if snap.Available {
  211. if eng, err := gpufft.New(rt.cfg.FFTSize); err == nil {
  212. rt.gpuEngine = eng
  213. gpuState.set(true, nil)
  214. } else {
  215. gpuState.set(false, err)
  216. rt.useGPU = false
  217. }
  218. } else {
  219. gpuState.set(false, nil)
  220. rt.useGPU = false
  221. }
  222. } else if gpuState != nil {
  223. gpuState.set(false, nil)
  224. }
  225. }
  226. if rt.telemetry != nil {
  227. rt.telemetry.Event("dsp_config_update", "info", "dsp runtime configuration updated", nil, map[string]any{
  228. "fft_size": rt.cfg.FFTSize,
  229. "sample_rate": rt.cfg.SampleRate,
  230. "use_gpu_fft": rt.cfg.UseGPUFFT,
  231. "detail_fft": rt.detailFFT,
  232. "surv_strategy": rt.cfg.Surveillance.Strategy,
  233. })
  234. }
  235. }
  236. func (rt *dspRuntime) spectrumFromIQ(iq []complex64, gpuState *gpuStatus) []float64 {
  237. return rt.spectrumFromIQWithPlan(iq, rt.window, rt.plan, gpuState, true)
  238. }
  239. func (rt *dspRuntime) spectrumFromIQWithPlan(iq []complex64, window []float64, plan *fftutil.CmplxPlan, gpuState *gpuStatus, allowGPU bool) []float64 {
  240. if len(iq) == 0 {
  241. return nil
  242. }
  243. if allowGPU && rt.useGPU && rt.gpuEngine != nil {
  244. gpuBuf := make([]complex64, len(iq))
  245. if len(window) == len(iq) {
  246. for i := 0; i < len(iq); i++ {
  247. v := iq[i]
  248. w := float32(window[i])
  249. gpuBuf[i] = complex(real(v)*w, imag(v)*w)
  250. }
  251. } else {
  252. copy(gpuBuf, iq)
  253. }
  254. out, err := rt.gpuEngine.Exec(gpuBuf)
  255. if err != nil {
  256. if gpuState != nil {
  257. gpuState.set(false, err)
  258. }
  259. rt.useGPU = false
  260. return fftutil.SpectrumWithPlan(gpuBuf, nil, plan)
  261. }
  262. return fftutil.SpectrumFromFFT(out)
  263. }
  264. return fftutil.SpectrumWithPlan(iq, window, plan)
  265. }
  266. func (rt *dspRuntime) windowForFFT(fftSize int) []float64 {
  267. if fftSize <= 0 {
  268. return nil
  269. }
  270. if fftSize == rt.cfg.FFTSize {
  271. return rt.window
  272. }
  273. if rt.survWindows == nil {
  274. rt.survWindows = map[int][]float64{}
  275. }
  276. if window, ok := rt.survWindows[fftSize]; ok {
  277. return window
  278. }
  279. window := fftutil.Hann(fftSize)
  280. rt.survWindows[fftSize] = window
  281. return window
  282. }
  283. func (rt *dspRuntime) planForFFT(fftSize int) *fftutil.CmplxPlan {
  284. if fftSize <= 0 {
  285. return nil
  286. }
  287. if fftSize == rt.cfg.FFTSize {
  288. return rt.plan
  289. }
  290. if rt.survPlans == nil {
  291. rt.survPlans = map[int]*fftutil.CmplxPlan{}
  292. }
  293. if plan, ok := rt.survPlans[fftSize]; ok {
  294. return plan
  295. }
  296. plan := fftutil.NewCmplxPlan(fftSize)
  297. rt.survPlans[fftSize] = plan
  298. return plan
  299. }
  300. func (rt *dspRuntime) spectrumForLevel(iq []complex64, fftSize int, gpuState *gpuStatus, allowGPU bool) []float64 {
  301. if len(iq) == 0 || fftSize <= 0 {
  302. return nil
  303. }
  304. if len(iq) > fftSize {
  305. iq = iq[len(iq)-fftSize:]
  306. }
  307. window := rt.windowForFFT(fftSize)
  308. plan := rt.planForFFT(fftSize)
  309. return rt.spectrumFromIQWithPlan(iq, window, plan, gpuState, allowGPU)
  310. }
  311. func sanitizeSpectrum(spectrum []float64) {
  312. for i := range spectrum {
  313. if math.IsNaN(spectrum[i]) || math.IsInf(spectrum[i], 0) {
  314. spectrum[i] = -200
  315. }
  316. }
  317. }
  318. func (rt *dspRuntime) decimationTaps(factor int) []float64 {
  319. if factor <= 1 {
  320. return nil
  321. }
  322. if rt.survFIR == nil {
  323. rt.survFIR = map[int][]float64{}
  324. }
  325. if taps, ok := rt.survFIR[factor]; ok {
  326. return taps
  327. }
  328. cutoff := float64(rt.cfg.SampleRate/factor) * 0.5 * 0.8
  329. taps := dsp.LowpassFIR(cutoff, rt.cfg.SampleRate, 101)
  330. rt.survFIR[factor] = taps
  331. return taps
  332. }
  333. func (rt *dspRuntime) decimateSurveillanceIQ(iq []complex64, factor int) []complex64 {
  334. if factor <= 1 {
  335. return iq
  336. }
  337. taps := rt.decimationTaps(factor)
  338. if len(taps) == 0 {
  339. return dsp.Decimate(iq, factor)
  340. }
  341. filtered := dsp.ApplyFIR(iq, taps)
  342. return dsp.Decimate(filtered, factor)
  343. }
  344. func meanMagComplex(samples []complex64) float64 {
  345. if len(samples) == 0 {
  346. return 0
  347. }
  348. var sum float64
  349. for _, v := range samples {
  350. sum += math.Hypot(float64(real(v)), float64(imag(v)))
  351. }
  352. return sum / float64(len(samples))
  353. }
  354. func phaseStepAbs(a, b complex64) float64 {
  355. num := float64(real(a))*float64(imag(b)) - float64(imag(a))*float64(real(b))
  356. den := float64(real(a))*float64(real(b)) + float64(imag(a))*float64(imag(b))
  357. return math.Abs(math.Atan2(num, den))
  358. }
  359. func boundaryMetrics(prevTail []complex64, curr []complex64, window int) (float64, float64, float64, int) {
  360. if len(curr) == 0 {
  361. return 0, 0, 0, 0
  362. }
  363. if window <= 0 {
  364. window = 16
  365. }
  366. headN := window
  367. if len(curr) < headN {
  368. headN = len(curr)
  369. }
  370. headMean := meanMagComplex(curr[:headN])
  371. if len(prevTail) == 0 {
  372. return headMean, 0, 0, headN
  373. }
  374. tailN := window
  375. if len(prevTail) < tailN {
  376. tailN = len(prevTail)
  377. }
  378. tailMean := meanMagComplex(prevTail[len(prevTail)-tailN:])
  379. deltaMag := math.Abs(headMean - tailMean)
  380. phaseJump := phaseStepAbs(prevTail[len(prevTail)-1], curr[0])
  381. score := deltaMag + phaseJump
  382. return headMean, tailMean, score, headN
  383. }
  384. func tailWindowComplex(src []complex64, n int) []complex64 {
  385. if n <= 0 || len(src) == 0 {
  386. return nil
  387. }
  388. if len(src) <= n {
  389. out := make([]complex64, len(src))
  390. copy(out, src)
  391. return out
  392. }
  393. out := make([]complex64, n)
  394. copy(out, src[len(src)-n:])
  395. return out
  396. }
  397. func (rt *dspRuntime) captureSpectrum(srcMgr *sourceManager, rec *recorder.Manager, dcBlocker *dsp.DCBlocker, gpuState *gpuStatus) (*spectrumArtifacts, error) {
  398. start := time.Now()
  399. required := rt.cfg.FFTSize
  400. if rt.detailFFT > required {
  401. required = rt.detailFFT
  402. }
  403. available := required
  404. st := srcMgr.Stats()
  405. if rt.telemetry != nil {
  406. rt.telemetry.SetGauge("source.buffer_samples", float64(st.BufferSamples), nil)
  407. rt.telemetry.SetGauge("source.last_sample_ago_ms", float64(st.LastSampleAgoMs), nil)
  408. rt.telemetry.SetGauge("source.dropped", float64(st.Dropped), nil)
  409. rt.telemetry.SetGauge("source.resets", float64(st.Resets), nil)
  410. }
  411. if forceFixedStreamReadSamples > 0 {
  412. available = forceFixedStreamReadSamples
  413. if available < required {
  414. available = required
  415. }
  416. available = (available / required) * required
  417. if available < required {
  418. available = required
  419. }
  420. logging.Warn("boundary", "fixed_stream_read_samples", "configured", forceFixedStreamReadSamples, "effective", available, "required", required)
  421. } else if st.BufferSamples > required {
  422. available = (st.BufferSamples / required) * required
  423. if available < required {
  424. available = required
  425. }
  426. }
  427. logging.Debug("capture", "read_iq", "required", required, "available", available, "buf", st.BufferSamples, "reset", st.Resets, "drop", st.Dropped)
  428. readStart := time.Now()
  429. allIQ, err := srcMgr.ReadIQ(available)
  430. if err != nil {
  431. if rt.telemetry != nil {
  432. rt.telemetry.IncCounter("capture.read.error", 1, nil)
  433. }
  434. return nil, err
  435. }
  436. if rt.telemetry != nil {
  437. rt.telemetry.Observe("capture.read.duration_ms", float64(time.Since(readStart).Microseconds())/1000.0, nil)
  438. rt.telemetry.Observe("capture.read.samples", float64(len(allIQ)), nil)
  439. }
  440. if rec != nil {
  441. ingestStart := time.Now()
  442. rec.Ingest(time.Now(), allIQ)
  443. if rt.telemetry != nil {
  444. rt.telemetry.Observe("capture.ingest.duration_ms", float64(time.Since(ingestStart).Microseconds())/1000.0, nil)
  445. }
  446. }
  447. // Cap allIQ for downstream extraction to prevent buffer bloat.
  448. // Without this cap, buffer accumulation during processing stalls causes
  449. // increasingly large reads → longer extraction → more accumulation
  450. // (positive feedback loop). For audio streaming this creates >150ms
  451. // feed gaps that produce audible clicks.
  452. // The ring buffer (Ingest above) gets the full data; only extraction is capped.
  453. maxStreamSamples := rt.cfg.SampleRate / rt.cfg.FrameRate * 2
  454. if maxStreamSamples < required {
  455. maxStreamSamples = required
  456. }
  457. maxStreamSamples = (maxStreamSamples / required) * required
  458. streamDropped := false
  459. if len(allIQ) > maxStreamSamples {
  460. allIQ = allIQ[len(allIQ)-maxStreamSamples:]
  461. streamDropped = true
  462. if rt.telemetry != nil {
  463. rt.telemetry.IncCounter("capture.stream_drop.count", 1, nil)
  464. rt.telemetry.Event("iq_dropped", "warn", "capture IQ dropped before extraction", nil, map[string]any{
  465. "max_stream_samples": maxStreamSamples,
  466. "required": required,
  467. })
  468. }
  469. }
  470. logging.Debug("capture", "iq_len", "len", len(allIQ), "surv_fft", rt.cfg.FFTSize, "detail_fft", rt.detailFFT)
  471. survIQ := allIQ
  472. if len(allIQ) > rt.cfg.FFTSize {
  473. survIQ = allIQ[len(allIQ)-rt.cfg.FFTSize:]
  474. }
  475. detailIQ := survIQ
  476. if rt.detailFFT > 0 && len(allIQ) >= rt.detailFFT {
  477. detailIQ = allIQ[len(allIQ)-rt.detailFFT:]
  478. }
  479. if rt.dcEnabled {
  480. dcBlocker.Apply(allIQ)
  481. if rt.telemetry != nil {
  482. rt.telemetry.IncCounter("dsp.dc_block.apply", 1, nil)
  483. }
  484. }
  485. if rt.iqEnabled {
  486. dsp.IQBalance(survIQ)
  487. if !sameIQBuffer(detailIQ, survIQ) {
  488. detailIQ = append([]complex64(nil), detailIQ...)
  489. dsp.IQBalance(detailIQ)
  490. }
  491. }
  492. if rt.telemetry != nil {
  493. rt.telemetry.SetGauge("iq.stage.all.length", float64(len(allIQ)), nil)
  494. rt.telemetry.SetGauge("iq.stage.surveillance.length", float64(len(survIQ)), nil)
  495. rt.telemetry.SetGauge("iq.stage.detail.length", float64(len(detailIQ)), nil)
  496. rt.telemetry.Observe("capture.total.duration_ms", float64(time.Since(start).Microseconds())/1000.0, nil)
  497. headMean, tailMean, boundaryScore, boundaryWindow := boundaryMetrics(rt.lastAllIQTail, allIQ, 32)
  498. rt.telemetry.SetGauge("iq.boundary.all.head_mean_mag", headMean, nil)
  499. rt.telemetry.SetGauge("iq.boundary.all.prev_tail_mean_mag", tailMean, nil)
  500. rt.telemetry.Observe("iq.boundary.all.discontinuity_score", boundaryScore, nil)
  501. if len(rt.lastAllIQTail) > 0 && len(allIQ) > 0 {
  502. deltaMag := math.Abs(math.Hypot(float64(real(allIQ[0])), float64(imag(allIQ[0]))) - math.Hypot(float64(real(rt.lastAllIQTail[len(rt.lastAllIQTail)-1])), float64(imag(rt.lastAllIQTail[len(rt.lastAllIQTail)-1]))))
  503. phaseJump := phaseStepAbs(rt.lastAllIQTail[len(rt.lastAllIQTail)-1], allIQ[0])
  504. rt.telemetry.Observe("iq.boundary.all.delta_mag", deltaMag, nil)
  505. rt.telemetry.Observe("iq.boundary.all.delta_phase", phaseJump, nil)
  506. if rt.telemetry.ShouldSampleHeavy() {
  507. rt.telemetry.Event("alliq_boundary", "info", "allIQ boundary snapshot", nil, map[string]any{
  508. "window": boundaryWindow,
  509. "head_mean_mag": headMean,
  510. "prev_tail_mean_mag": tailMean,
  511. "delta_mag": deltaMag,
  512. "delta_phase": phaseJump,
  513. "discontinuity_score": boundaryScore,
  514. "alliq_len": len(allIQ),
  515. "stream_dropped": streamDropped,
  516. })
  517. }
  518. }
  519. if rt.telemetry.ShouldSampleHeavy() {
  520. observeIQStats(rt.telemetry, "capture_all", allIQ, nil)
  521. observeIQStats(rt.telemetry, "capture_surveillance", survIQ, nil)
  522. observeIQStats(rt.telemetry, "capture_detail", detailIQ, nil)
  523. }
  524. }
  525. rt.lastAllIQTail = tailWindowComplex(allIQ, 32)
  526. survSpectrum := rt.spectrumFromIQ(survIQ, gpuState)
  527. sanitizeSpectrum(survSpectrum)
  528. detailSpectrum := survSpectrum
  529. if !sameIQBuffer(detailIQ, survIQ) {
  530. detailSpectrum = rt.spectrumFromIQWithPlan(detailIQ, rt.detailWindow, rt.detailPlan, gpuState, false)
  531. sanitizeSpectrum(detailSpectrum)
  532. }
  533. policy := pipeline.PolicyFromConfig(rt.cfg)
  534. plan := rt.buildSurveillancePlan(policy)
  535. surveillanceSpectra := make([]pipeline.SurveillanceLevelSpectrum, 0, len(plan.Specs))
  536. for _, spec := range plan.Specs {
  537. if spec.Level.FFTSize <= 0 {
  538. continue
  539. }
  540. var spectrum []float64
  541. if spec.Decim <= 1 {
  542. if spec.Level.FFTSize == len(survSpectrum) {
  543. spectrum = survSpectrum
  544. } else {
  545. spectrum = rt.spectrumForLevel(survIQ, spec.Level.FFTSize, gpuState, spec.AllowGPU)
  546. sanitizeSpectrum(spectrum)
  547. }
  548. } else {
  549. required := spec.Level.FFTSize * spec.Decim
  550. if required > len(survIQ) {
  551. continue
  552. }
  553. src := survIQ
  554. if len(src) > required {
  555. src = src[len(src)-required:]
  556. }
  557. decimated := rt.decimateSurveillanceIQ(src, spec.Decim)
  558. spectrum = rt.spectrumForLevel(decimated, spec.Level.FFTSize, gpuState, false)
  559. sanitizeSpectrum(spectrum)
  560. }
  561. if len(spectrum) == 0 {
  562. continue
  563. }
  564. surveillanceSpectra = append(surveillanceSpectra, pipeline.SurveillanceLevelSpectrum{Level: spec.Level, Spectrum: spectrum})
  565. }
  566. now := time.Now()
  567. finished, detected := rt.det.Process(now, survSpectrum, rt.cfg.CenterHz)
  568. if rt.telemetry != nil {
  569. rt.telemetry.SetGauge("signals.detected.count", float64(len(detected)), nil)
  570. rt.telemetry.SetGauge("signals.finished.count", float64(len(finished)), nil)
  571. }
  572. return &spectrumArtifacts{
  573. allIQ: allIQ,
  574. streamDropped: streamDropped,
  575. surveillanceIQ: survIQ,
  576. detailIQ: detailIQ,
  577. surveillanceSpectrum: survSpectrum,
  578. surveillanceSpectra: surveillanceSpectra,
  579. surveillancePlan: plan,
  580. detailSpectrum: detailSpectrum,
  581. finished: finished,
  582. detected: detected,
  583. thresholds: rt.det.LastThresholds(),
  584. noiseFloor: rt.det.LastNoiseFloor(),
  585. now: now,
  586. }, nil
  587. }
  588. func (rt *dspRuntime) buildSurveillanceResult(art *spectrumArtifacts) pipeline.SurveillanceResult {
  589. if art == nil {
  590. return pipeline.SurveillanceResult{}
  591. }
  592. policy := pipeline.PolicyFromConfig(rt.cfg)
  593. plan := art.surveillancePlan
  594. if plan.Primary.Name == "" {
  595. plan = rt.buildSurveillancePlan(policy)
  596. }
  597. primaryCandidates := pipeline.CandidatesFromSignalsWithLevel(art.detected, "surveillance-detector", plan.Primary)
  598. derivedCandidates := rt.detectDerivedCandidates(art, plan)
  599. candidates := pipeline.FuseCandidates(primaryCandidates, derivedCandidates)
  600. pipeline.ApplyMonitorWindowMatchesToCandidates(policy, candidates)
  601. scheduled := pipeline.ScheduleCandidates(candidates, policy)
  602. return pipeline.SurveillanceResult{
  603. Level: plan.Primary,
  604. Levels: plan.Levels,
  605. LevelSet: plan.LevelSet,
  606. DetectionPolicy: plan.DetectionPolicy,
  607. DisplayLevel: plan.Presentation,
  608. Context: plan.Context,
  609. Spectra: art.surveillanceSpectra,
  610. Candidates: candidates,
  611. Scheduled: scheduled,
  612. Finished: art.finished,
  613. Signals: art.detected,
  614. NoiseFloor: art.noiseFloor,
  615. Thresholds: art.thresholds,
  616. }
  617. }
  618. func (rt *dspRuntime) detectDerivedCandidates(art *spectrumArtifacts, plan surveillancePlan) []pipeline.Candidate {
  619. if art == nil || len(plan.LevelSet.Derived) == 0 {
  620. return nil
  621. }
  622. spectra := map[string][]float64{}
  623. for _, spec := range art.surveillanceSpectra {
  624. if spec.Level.Name == "" || len(spec.Spectrum) == 0 {
  625. continue
  626. }
  627. spectra[spec.Level.Name] = spec.Spectrum
  628. }
  629. if len(spectra) == 0 {
  630. return nil
  631. }
  632. out := make([]pipeline.Candidate, 0, len(plan.LevelSet.Derived))
  633. for _, level := range plan.LevelSet.Derived {
  634. if level.Name == "" {
  635. continue
  636. }
  637. if !pipeline.IsDetectionLevel(level) {
  638. continue
  639. }
  640. spectrum := spectra[level.Name]
  641. if len(spectrum) == 0 {
  642. continue
  643. }
  644. entry := rt.derivedDetectorForLevel(level)
  645. if entry == nil || entry.det == nil {
  646. continue
  647. }
  648. _, signals := entry.det.Process(art.now, spectrum, level.CenterHz)
  649. if len(signals) == 0 {
  650. continue
  651. }
  652. cands := pipeline.CandidatesFromSignalsWithLevel(signals, "surveillance-derived", level)
  653. for i := range cands {
  654. if cands[i].ID == 0 {
  655. continue
  656. }
  657. cands[i].ID = entry.idBase - cands[i].ID
  658. }
  659. out = append(out, cands...)
  660. }
  661. if len(out) == 0 {
  662. return nil
  663. }
  664. return out
  665. }
  666. func (rt *dspRuntime) derivedDetectorForLevel(level pipeline.AnalysisLevel) *derivedDetector {
  667. if level.SampleRate <= 0 || level.FFTSize <= 0 {
  668. return nil
  669. }
  670. if rt.derivedDetectors == nil {
  671. rt.derivedDetectors = map[string]*derivedDetector{}
  672. }
  673. key := level.Name
  674. if key == "" {
  675. key = fmt.Sprintf("%d:%d", level.SampleRate, level.FFTSize)
  676. }
  677. entry := rt.derivedDetectors[key]
  678. if entry != nil && entry.sampleRate == level.SampleRate && entry.fftSize == level.FFTSize {
  679. return entry
  680. }
  681. if rt.nextDerivedBase == 0 {
  682. rt.nextDerivedBase = -derivedIDBlock
  683. }
  684. entry = &derivedDetector{
  685. det: detector.New(rt.cfg.Detector, level.SampleRate, level.FFTSize),
  686. sampleRate: level.SampleRate,
  687. fftSize: level.FFTSize,
  688. idBase: rt.nextDerivedBase,
  689. }
  690. rt.nextDerivedBase -= derivedIDBlock
  691. rt.derivedDetectors[key] = entry
  692. return entry
  693. }
  694. func (rt *dspRuntime) buildRefinementInput(surv pipeline.SurveillanceResult, now time.Time) pipeline.RefinementInput {
  695. policy := pipeline.PolicyFromConfig(rt.cfg)
  696. baseBudget := pipeline.BudgetModelFromPolicy(policy)
  697. pressure := pipeline.BuildBudgetPressureSummary(baseBudget, rt.arbitration.Refinement, rt.arbitration.Queue)
  698. budget := pipeline.ApplyBudgetRebalance(policy, baseBudget, pressure)
  699. plan := pipeline.BuildRefinementPlanWithBudget(surv.Candidates, policy, budget)
  700. admission := rt.arbiter.AdmitRefinementWithBudget(plan, policy, budget, now)
  701. plan = admission.Plan
  702. workItems := make([]pipeline.RefinementWorkItem, 0, len(admission.WorkItems))
  703. if len(admission.WorkItems) > 0 {
  704. workItems = append(workItems, admission.WorkItems...)
  705. }
  706. scheduled := append([]pipeline.ScheduledCandidate(nil), admission.Admitted...)
  707. workIndex := map[int64]int{}
  708. for i := range workItems {
  709. if workItems[i].Candidate.ID == 0 {
  710. continue
  711. }
  712. workIndex[workItems[i].Candidate.ID] = i
  713. }
  714. windows := make([]pipeline.RefinementWindow, 0, len(scheduled))
  715. for _, sc := range scheduled {
  716. window := pipeline.RefinementWindowForCandidate(policy, sc.Candidate)
  717. windows = append(windows, window)
  718. if idx, ok := workIndex[sc.Candidate.ID]; ok {
  719. workItems[idx].Window = window
  720. }
  721. }
  722. detailFFT := rt.cfg.Refinement.DetailFFTSize
  723. if detailFFT <= 0 {
  724. detailFFT = rt.cfg.FFTSize
  725. }
  726. levelSpan := spanForPolicy(policy, float64(rt.cfg.SampleRate))
  727. if _, maxSpan, ok := windowSpanBounds(windows); ok {
  728. levelSpan = maxSpan
  729. }
  730. level := analysisLevel("refinement", "refinement", "refinement", rt.cfg.SampleRate, detailFFT, rt.cfg.CenterHz, levelSpan, "refinement-window", 1, rt.cfg.SampleRate)
  731. detailLevel := analysisLevel("detail", "detail", "refinement", rt.cfg.SampleRate, detailFFT, rt.cfg.CenterHz, levelSpan, "detail-spectrum", 1, rt.cfg.SampleRate)
  732. if len(workItems) > 0 {
  733. for i := range workItems {
  734. item := &workItems[i]
  735. if item.Window.SpanHz <= 0 {
  736. continue
  737. }
  738. item.Execution = &pipeline.RefinementExecution{
  739. Stage: "refine",
  740. SampleRate: rt.cfg.SampleRate,
  741. FFTSize: detailFFT,
  742. CenterHz: item.Window.CenterHz,
  743. SpanHz: item.Window.SpanHz,
  744. Source: detailLevel.Source,
  745. }
  746. }
  747. }
  748. input := pipeline.RefinementInput{
  749. Level: level,
  750. Detail: detailLevel,
  751. Context: surv.Context,
  752. Request: pipeline.RefinementRequest{Strategy: plan.Strategy, Reason: "surveillance-plan", SpanHintHz: levelSpan},
  753. Budgets: budget,
  754. Admission: admission.Admission,
  755. Candidates: append([]pipeline.Candidate(nil), surv.Candidates...),
  756. Scheduled: scheduled,
  757. WorkItems: workItems,
  758. Plan: plan,
  759. Windows: windows,
  760. SampleRate: rt.cfg.SampleRate,
  761. FFTSize: detailFFT,
  762. CenterHz: rt.cfg.CenterHz,
  763. Source: "surveillance-detector",
  764. }
  765. input.Context.Refinement = level
  766. input.Context.Detail = detailLevel
  767. if !policy.RefinementEnabled {
  768. for i := range input.WorkItems {
  769. item := &input.WorkItems[i]
  770. if item.Status == pipeline.RefinementStatusDropped {
  771. continue
  772. }
  773. item.Status = pipeline.RefinementStatusDropped
  774. item.Reason = pipeline.RefinementReasonDisabled
  775. }
  776. input.Scheduled = nil
  777. input.Request.Reason = pipeline.ReasonAdmissionDisabled
  778. input.Admission.Reason = pipeline.ReasonAdmissionDisabled
  779. input.Admission.Admitted = 0
  780. input.Admission.Skipped = 0
  781. input.Admission.Displaced = 0
  782. input.Plan.Selected = nil
  783. input.Plan.DroppedByBudget = 0
  784. }
  785. rt.setArbitration(policy, input.Budgets, input.Admission, rt.arbitration.Queue)
  786. return input
  787. }
  788. func (rt *dspRuntime) runRefinement(art *spectrumArtifacts, surv pipeline.SurveillanceResult, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementStep {
  789. input := rt.buildRefinementInput(surv, art.now)
  790. markWorkItemsStatus(input.WorkItems, pipeline.RefinementStatusAdmitted, pipeline.RefinementStatusRunning, pipeline.RefinementReasonRunning)
  791. result := rt.refineSignals(art, input, extractMgr, rec)
  792. markWorkItemsCompleted(input.WorkItems, result.Candidates)
  793. return pipeline.RefinementStep{Input: input, Result: result}
  794. }
  795. func (rt *dspRuntime) refineSignals(art *spectrumArtifacts, input pipeline.RefinementInput, extractMgr *extractionManager, rec *recorder.Manager) pipeline.RefinementResult {
  796. if art == nil || len(art.detailIQ) == 0 || len(input.Scheduled) == 0 {
  797. return pipeline.RefinementResult{}
  798. }
  799. policy := pipeline.PolicyFromConfig(rt.cfg)
  800. selectedCandidates := make([]pipeline.Candidate, 0, len(input.Scheduled))
  801. selectedSignals := make([]detector.Signal, 0, len(input.Scheduled))
  802. for _, sc := range input.Scheduled {
  803. selectedCandidates = append(selectedCandidates, sc.Candidate)
  804. selectedSignals = append(selectedSignals, detector.Signal{
  805. ID: sc.Candidate.ID,
  806. FirstBin: sc.Candidate.FirstBin,
  807. LastBin: sc.Candidate.LastBin,
  808. CenterHz: sc.Candidate.CenterHz,
  809. BWHz: sc.Candidate.BandwidthHz,
  810. PeakDb: sc.Candidate.PeakDb,
  811. SNRDb: sc.Candidate.SNRDb,
  812. NoiseDb: sc.Candidate.NoiseDb,
  813. })
  814. }
  815. sampleRate := input.SampleRate
  816. fftSize := input.FFTSize
  817. centerHz := input.CenterHz
  818. if sampleRate <= 0 {
  819. sampleRate = rt.cfg.SampleRate
  820. }
  821. if fftSize <= 0 {
  822. fftSize = rt.cfg.FFTSize
  823. }
  824. if centerHz == 0 {
  825. centerHz = rt.cfg.CenterHz
  826. }
  827. snips, snipRates := extractSignalIQBatch(extractMgr, art.detailIQ, sampleRate, centerHz, selectedSignals)
  828. refined := pipeline.RefineCandidates(selectedCandidates, input.Windows, art.detailSpectrum, sampleRate, fftSize, snips, snipRates, classifier.ClassifierMode(rt.cfg.ClassifierMode))
  829. signals := make([]detector.Signal, 0, len(refined))
  830. decisions := make([]pipeline.SignalDecision, 0, len(refined))
  831. for i, ref := range refined {
  832. sig := ref.Signal
  833. signals = append(signals, sig)
  834. cls := sig.Class
  835. snipRate := ref.SnippetRate
  836. decision := pipeline.DecideSignalAction(policy, ref.Candidate, cls)
  837. decisions = append(decisions, decision)
  838. if cls != nil {
  839. if cls.ModType == classifier.ClassWFM {
  840. cls.ModType = classifier.ClassWFMStereo
  841. signals[i].PlaybackMode = string(classifier.ClassWFMStereo)
  842. signals[i].DemodName = string(classifier.ClassWFMStereo)
  843. signals[i].StereoState = "searching"
  844. }
  845. pll := classifier.PLLResult{}
  846. if i < len(snips) && snips[i] != nil && len(snips[i]) > 256 {
  847. pll = classifier.EstimateExactFrequency(snips[i], snipRate, signals[i].CenterHz, cls.ModType)
  848. cls.PLL = &pll
  849. signals[i].PLL = &pll
  850. if cls.ModType == classifier.ClassWFMStereo {
  851. if pll.Stereo {
  852. signals[i].StereoState = "locked"
  853. } else if signals[i].StereoState == "" {
  854. signals[i].StereoState = "searching"
  855. }
  856. signals[i].PlaybackMode = string(classifier.ClassWFMStereo)
  857. signals[i].DemodName = string(classifier.ClassWFMStereo)
  858. }
  859. }
  860. if cls.ModType == classifier.ClassWFMStereo && rec != nil {
  861. rt.updateRDS(art.now, rec, &signals[i], cls)
  862. if signals[i].PLL != nil && signals[i].PLL.RDSStation != "" {
  863. signals[i].StereoState = "locked"
  864. }
  865. }
  866. }
  867. }
  868. budget := input.Budgets
  869. queueStats := rt.arbiter.ApplyDecisions(decisions, budget, art.now, policy)
  870. rt.setArbitration(policy, budget, input.Admission, queueStats)
  871. summary := summarizeDecisions(decisions)
  872. if rec != nil {
  873. if summary.RecordEnabled > 0 {
  874. rt.cfg.Recorder.Enabled = true
  875. }
  876. if summary.DecodeEnabled > 0 {
  877. rt.cfg.Recorder.AutoDecode = true
  878. }
  879. }
  880. rt.det.UpdateClasses(signals)
  881. return pipeline.RefinementResult{Level: input.Level, Signals: signals, Decisions: decisions, Candidates: selectedCandidates}
  882. }
  883. func (rt *dspRuntime) updateRDS(now time.Time, rec *recorder.Manager, sig *detector.Signal, cls *classifier.Classification) {
  884. if sig == nil || cls == nil {
  885. return
  886. }
  887. keyHz := sig.CenterHz
  888. if sig.PLL != nil && sig.PLL.ExactHz != 0 {
  889. keyHz = sig.PLL.ExactHz
  890. }
  891. key := int64(math.Round(keyHz / 25000.0))
  892. st := rt.rdsMap[key]
  893. if st == nil {
  894. st = &rdsState{}
  895. rt.rdsMap[key] = st
  896. }
  897. if now.Sub(st.lastDecode) >= 4*time.Second && atomic.LoadInt32(&st.busy) == 0 {
  898. st.lastDecode = now
  899. atomic.StoreInt32(&st.busy, 1)
  900. go func(st *rdsState, sigHz float64) {
  901. defer atomic.StoreInt32(&st.busy, 0)
  902. ringIQ, ringSR, ringCenter := rec.SliceRecent(4.0)
  903. if len(ringIQ) < ringSR || ringSR <= 0 {
  904. return
  905. }
  906. offset := sigHz - ringCenter
  907. shifted := dsp.FreqShift(ringIQ, ringSR, offset)
  908. decim1 := ringSR / 1000000
  909. if decim1 < 1 {
  910. decim1 = 1
  911. }
  912. lp1 := dsp.LowpassFIR(float64(ringSR/decim1)/2.0*0.8, ringSR, 51)
  913. f1 := dsp.ApplyFIR(shifted, lp1)
  914. d1 := dsp.Decimate(f1, decim1)
  915. rate1 := ringSR / decim1
  916. decim2 := rate1 / 250000
  917. if decim2 < 1 {
  918. decim2 = 1
  919. }
  920. lp2 := dsp.LowpassFIR(float64(rate1/decim2)/2.0*0.8, rate1, 101)
  921. f2 := dsp.ApplyFIR(d1, lp2)
  922. decimated := dsp.Decimate(f2, decim2)
  923. actualRate := rate1 / decim2
  924. rdsBase := demod.RDSBasebandComplex(decimated, actualRate)
  925. if len(rdsBase.Samples) == 0 {
  926. return
  927. }
  928. st.mu.Lock()
  929. result := st.dec.Decode(rdsBase.Samples, rdsBase.SampleRate)
  930. if result.PS != "" {
  931. st.result = result
  932. }
  933. st.mu.Unlock()
  934. }(st, sig.CenterHz)
  935. }
  936. st.mu.Lock()
  937. ps := st.result.PS
  938. st.mu.Unlock()
  939. if ps != "" && sig.PLL != nil {
  940. sig.PLL.RDSStation = strings.TrimSpace(ps)
  941. cls.PLL = sig.PLL
  942. }
  943. }
  944. func (rt *dspRuntime) maintenance(displaySignals []detector.Signal, rec *recorder.Manager) {
  945. if len(rt.rdsMap) > 0 {
  946. activeIDs := make(map[int64]bool, len(displaySignals))
  947. for _, s := range displaySignals {
  948. keyHz := s.CenterHz
  949. if s.PLL != nil && s.PLL.ExactHz != 0 {
  950. keyHz = s.PLL.ExactHz
  951. }
  952. activeIDs[int64(math.Round(keyHz/25000.0))] = true
  953. }
  954. for id := range rt.rdsMap {
  955. if !activeIDs[id] {
  956. delete(rt.rdsMap, id)
  957. }
  958. }
  959. }
  960. if len(rt.streamPhaseState) > 0 {
  961. sigIDs := make(map[int64]bool, len(displaySignals))
  962. for _, s := range displaySignals {
  963. sigIDs[s.ID] = true
  964. }
  965. for id := range rt.streamPhaseState {
  966. if !sigIDs[id] {
  967. delete(rt.streamPhaseState, id)
  968. }
  969. }
  970. }
  971. if rec != nil && len(displaySignals) > 0 {
  972. aqCfg := extractionConfig{firTaps: rt.cfg.Recorder.ExtractionTaps, bwMult: rt.cfg.Recorder.ExtractionBwMult}
  973. _ = aqCfg
  974. }
  975. }
  976. func spanForPolicy(policy pipeline.Policy, fallback float64) float64 {
  977. if policy.MonitorSpanHz > 0 {
  978. return policy.MonitorSpanHz
  979. }
  980. if len(policy.MonitorWindows) > 0 {
  981. maxSpan := 0.0
  982. for _, w := range policy.MonitorWindows {
  983. if w.SpanHz > maxSpan {
  984. maxSpan = w.SpanHz
  985. }
  986. }
  987. if maxSpan > 0 {
  988. return maxSpan
  989. }
  990. }
  991. if policy.MonitorStartHz != 0 && policy.MonitorEndHz != 0 && policy.MonitorEndHz > policy.MonitorStartHz {
  992. return policy.MonitorEndHz - policy.MonitorStartHz
  993. }
  994. return fallback
  995. }
  996. func windowSpanBounds(windows []pipeline.RefinementWindow) (float64, float64, bool) {
  997. minSpan := 0.0
  998. maxSpan := 0.0
  999. ok := false
  1000. for _, w := range windows {
  1001. if w.SpanHz <= 0 {
  1002. continue
  1003. }
  1004. if !ok || w.SpanHz < minSpan {
  1005. minSpan = w.SpanHz
  1006. }
  1007. if !ok || w.SpanHz > maxSpan {
  1008. maxSpan = w.SpanHz
  1009. }
  1010. ok = true
  1011. }
  1012. return minSpan, maxSpan, ok
  1013. }
  1014. func analysisLevel(name, role, truth string, sampleRate int, fftSize int, centerHz float64, spanHz float64, source string, decimation int, baseRate int) pipeline.AnalysisLevel {
  1015. level := pipeline.AnalysisLevel{
  1016. Name: name,
  1017. Role: role,
  1018. Truth: truth,
  1019. SampleRate: sampleRate,
  1020. FFTSize: fftSize,
  1021. CenterHz: centerHz,
  1022. SpanHz: spanHz,
  1023. Source: source,
  1024. }
  1025. if level.SampleRate > 0 && level.FFTSize > 0 {
  1026. level.BinHz = float64(level.SampleRate) / float64(level.FFTSize)
  1027. }
  1028. if decimation > 0 {
  1029. level.Decimation = decimation
  1030. } else if baseRate > 0 && level.SampleRate > 0 && baseRate%level.SampleRate == 0 {
  1031. level.Decimation = baseRate / level.SampleRate
  1032. }
  1033. return level
  1034. }
  1035. func (rt *dspRuntime) buildSurveillancePlan(policy pipeline.Policy) surveillancePlan {
  1036. baseRate := rt.cfg.SampleRate
  1037. baseFFT := rt.cfg.Surveillance.AnalysisFFTSize
  1038. if baseFFT <= 0 {
  1039. baseFFT = rt.cfg.FFTSize
  1040. }
  1041. span := spanForPolicy(policy, float64(baseRate))
  1042. detectionPolicy := pipeline.SurveillanceDetectionPolicyFromPolicy(policy)
  1043. primary := analysisLevel("surveillance", pipeline.RoleSurveillancePrimary, "surveillance", baseRate, baseFFT, rt.cfg.CenterHz, span, "baseband", 1, baseRate)
  1044. levels := []pipeline.AnalysisLevel{primary}
  1045. specs := []surveillanceLevelSpec{{Level: primary, Decim: 1, AllowGPU: true}}
  1046. context := pipeline.AnalysisContext{Surveillance: primary}
  1047. derivedLevels := make([]pipeline.AnalysisLevel, 0, 2)
  1048. supportLevels := make([]pipeline.AnalysisLevel, 0, 2)
  1049. strategy := strings.ToLower(strings.TrimSpace(policy.SurveillanceStrategy))
  1050. switch strategy {
  1051. case "multi-res", "multi-resolution", "multi", "multi_res":
  1052. decim := 2
  1053. derivedRate := baseRate / decim
  1054. derivedFFT := baseFFT / decim
  1055. if derivedRate >= 200000 && derivedFFT >= 256 {
  1056. derivedSpan := spanForPolicy(policy, float64(derivedRate))
  1057. role := pipeline.RoleSurveillanceSupport
  1058. if detectionPolicy.DerivedDetectionEnabled {
  1059. role = pipeline.RoleSurveillanceDerived
  1060. }
  1061. derived := analysisLevel("surveillance-lowres", role, "surveillance", derivedRate, derivedFFT, rt.cfg.CenterHz, derivedSpan, "decimated", decim, baseRate)
  1062. if detectionPolicy.DerivedDetectionEnabled {
  1063. levels = append(levels, derived)
  1064. derivedLevels = append(derivedLevels, derived)
  1065. } else {
  1066. supportLevels = append(supportLevels, derived)
  1067. }
  1068. specs = append(specs, surveillanceLevelSpec{Level: derived, Decim: decim, AllowGPU: false})
  1069. context.Derived = append(context.Derived, derived)
  1070. }
  1071. }
  1072. presentation := analysisLevel("presentation", pipeline.RolePresentation, "presentation", baseRate, rt.cfg.Surveillance.DisplayBins, rt.cfg.CenterHz, span, "display", 1, baseRate)
  1073. context.Presentation = presentation
  1074. if len(derivedLevels) == 0 && detectionPolicy.DerivedDetectionEnabled {
  1075. detectionPolicy.DerivedDetectionEnabled = false
  1076. detectionPolicy.DerivedDetectionReason = "levels"
  1077. }
  1078. switch {
  1079. case len(derivedLevels) > 0:
  1080. detectionPolicy.DerivedDetectionMode = "detection"
  1081. case len(supportLevels) > 0:
  1082. detectionPolicy.DerivedDetectionMode = "support"
  1083. default:
  1084. detectionPolicy.DerivedDetectionMode = "disabled"
  1085. }
  1086. levelSet := pipeline.SurveillanceLevelSet{
  1087. Primary: primary,
  1088. Derived: append([]pipeline.AnalysisLevel(nil), derivedLevels...),
  1089. Support: append([]pipeline.AnalysisLevel(nil), supportLevels...),
  1090. Presentation: presentation,
  1091. }
  1092. detectionLevels := make([]pipeline.AnalysisLevel, 0, 1+len(derivedLevels))
  1093. detectionLevels = append(detectionLevels, primary)
  1094. detectionLevels = append(detectionLevels, derivedLevels...)
  1095. levelSet.Detection = detectionLevels
  1096. allLevels := make([]pipeline.AnalysisLevel, 0, 1+len(derivedLevels)+len(supportLevels)+1)
  1097. allLevels = append(allLevels, primary)
  1098. allLevels = append(allLevels, derivedLevels...)
  1099. allLevels = append(allLevels, supportLevels...)
  1100. if presentation.Name != "" {
  1101. allLevels = append(allLevels, presentation)
  1102. }
  1103. levelSet.All = allLevels
  1104. return surveillancePlan{
  1105. Primary: primary,
  1106. Levels: levels,
  1107. LevelSet: levelSet,
  1108. Presentation: presentation,
  1109. Context: context,
  1110. DetectionPolicy: detectionPolicy,
  1111. Specs: specs,
  1112. }
  1113. }
  1114. func sameIQBuffer(a []complex64, b []complex64) bool {
  1115. if len(a) != len(b) {
  1116. return false
  1117. }
  1118. if len(a) == 0 {
  1119. return true
  1120. }
  1121. return &a[0] == &b[0]
  1122. }
  1123. func markWorkItemsStatus(items []pipeline.RefinementWorkItem, from string, to string, reason string) {
  1124. for i := range items {
  1125. if items[i].Status != from {
  1126. continue
  1127. }
  1128. items[i].Status = to
  1129. if reason != "" {
  1130. items[i].Reason = reason
  1131. }
  1132. }
  1133. }
  1134. func markWorkItemsCompleted(items []pipeline.RefinementWorkItem, candidates []pipeline.Candidate) {
  1135. if len(items) == 0 || len(candidates) == 0 {
  1136. return
  1137. }
  1138. done := map[int64]struct{}{}
  1139. for _, cand := range candidates {
  1140. if cand.ID != 0 {
  1141. done[cand.ID] = struct{}{}
  1142. }
  1143. }
  1144. for i := range items {
  1145. if _, ok := done[items[i].Candidate.ID]; !ok {
  1146. continue
  1147. }
  1148. items[i].Status = pipeline.RefinementStatusCompleted
  1149. items[i].Reason = pipeline.RefinementReasonCompleted
  1150. }
  1151. }
  1152. func (rt *dspRuntime) setArbitration(policy pipeline.Policy, budget pipeline.BudgetModel, admission pipeline.RefinementAdmission, queue pipeline.DecisionQueueStats) {
  1153. rt.arbitration = pipeline.BuildArbitrationState(policy, budget, admission, queue)
  1154. }