Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

237 строки
5.5KB

  1. package recorder
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "sync"
  9. "time"
  10. "sdr-visual-suite/internal/demod/gpudemod"
  11. "sdr-visual-suite/internal/detector"
  12. )
  13. type Policy struct {
  14. Enabled bool `yaml:"enabled" json:"enabled"`
  15. MinSNRDb float64 `yaml:"min_snr_db" json:"min_snr_db"`
  16. MinDuration time.Duration `yaml:"min_duration" json:"min_duration"`
  17. MaxDuration time.Duration `yaml:"max_duration" json:"max_duration"`
  18. PrerollMs int `yaml:"preroll_ms" json:"preroll_ms"`
  19. RecordIQ bool `yaml:"record_iq" json:"record_iq"`
  20. RecordAudio bool `yaml:"record_audio" json:"record_audio"`
  21. AutoDemod bool `yaml:"auto_demod" json:"auto_demod"`
  22. AutoDecode bool `yaml:"auto_decode" json:"auto_decode"`
  23. MaxDiskMB int `yaml:"max_disk_mb" json:"max_disk_mb"`
  24. OutputDir string `yaml:"output_dir" json:"output_dir"`
  25. ClassFilter []string `yaml:"class_filter" json:"class_filter"`
  26. RingSeconds int `yaml:"ring_seconds" json:"ring_seconds"`
  27. }
  28. type Manager struct {
  29. mu sync.RWMutex
  30. policy Policy
  31. ring *Ring
  32. sampleRate int
  33. blockSize int
  34. centerHz float64
  35. decodeCommands map[string]string
  36. queue chan detector.Event
  37. gpuDemod *gpudemod.Engine
  38. closed bool
  39. closeOnce sync.Once
  40. workerWG sync.WaitGroup
  41. }
  42. func New(sampleRate int, blockSize int, policy Policy, centerHz float64, decodeCommands map[string]string) *Manager {
  43. if policy.OutputDir == "" {
  44. policy.OutputDir = "data/recordings"
  45. }
  46. if policy.RingSeconds <= 0 {
  47. policy.RingSeconds = 8
  48. }
  49. m := &Manager{policy: policy, ring: NewRing(sampleRate, blockSize, policy.RingSeconds), sampleRate: sampleRate, blockSize: blockSize, centerHz: centerHz, decodeCommands: decodeCommands, queue: make(chan detector.Event, 64)}
  50. m.initGPUDemod(sampleRate, blockSize)
  51. m.workerWG.Add(1)
  52. go m.worker()
  53. return m
  54. }
  55. func (m *Manager) Update(sampleRate int, blockSize int, policy Policy, centerHz float64, decodeCommands map[string]string) {
  56. m.mu.Lock()
  57. defer m.mu.Unlock()
  58. m.policy = policy
  59. m.sampleRate = sampleRate
  60. m.blockSize = blockSize
  61. m.centerHz = centerHz
  62. m.decodeCommands = decodeCommands
  63. m.initGPUDemodLocked(sampleRate, blockSize)
  64. if m.ring == nil {
  65. m.ring = NewRing(sampleRate, blockSize, policy.RingSeconds)
  66. return
  67. }
  68. m.ring.Reset(sampleRate, blockSize, policy.RingSeconds)
  69. }
  70. func (m *Manager) Ingest(t0 time.Time, samples []complex64) {
  71. if m == nil {
  72. return
  73. }
  74. m.mu.RLock()
  75. ring := m.ring
  76. m.mu.RUnlock()
  77. if ring == nil {
  78. return
  79. }
  80. ring.Push(t0, samples)
  81. }
  82. func (m *Manager) OnEvents(events []detector.Event) {
  83. if m == nil || len(events) == 0 {
  84. return
  85. }
  86. m.mu.RLock()
  87. enabled := m.policy.Enabled
  88. closed := m.closed
  89. m.mu.RUnlock()
  90. if !enabled || closed {
  91. return
  92. }
  93. for _, ev := range events {
  94. select {
  95. case m.queue <- ev:
  96. default:
  97. // drop if queue full
  98. }
  99. }
  100. }
  101. func (m *Manager) worker() {
  102. defer m.workerWG.Done()
  103. for ev := range m.queue {
  104. _ = m.recordEvent(ev)
  105. }
  106. }
  107. func (m *Manager) initGPUDemod(sampleRate int, blockSize int) {
  108. m.mu.Lock()
  109. defer m.mu.Unlock()
  110. m.initGPUDemodLocked(sampleRate, blockSize)
  111. }
  112. func (m *Manager) initGPUDemodLocked(sampleRate int, blockSize int) {
  113. if m.gpuDemod != nil {
  114. m.gpuDemod.Close()
  115. m.gpuDemod = nil
  116. }
  117. if !gpudemod.Available() {
  118. return
  119. }
  120. eng, err := gpudemod.New(blockSize, sampleRate)
  121. if err != nil {
  122. return
  123. }
  124. m.gpuDemod = eng
  125. }
  126. func (m *Manager) Close() {
  127. if m == nil {
  128. return
  129. }
  130. m.closeOnce.Do(func() {
  131. m.mu.Lock()
  132. m.closed = true
  133. if m.queue != nil {
  134. close(m.queue)
  135. }
  136. gpu := m.gpuDemod
  137. m.gpuDemod = nil
  138. m.mu.Unlock()
  139. m.workerWG.Wait()
  140. if gpu != nil {
  141. gpu.Close()
  142. }
  143. })
  144. }
  145. func (m *Manager) recordEvent(ev detector.Event) error {
  146. m.mu.RLock()
  147. policy := m.policy
  148. ring := m.ring
  149. sampleRate := m.sampleRate
  150. centerHz := m.centerHz
  151. m.mu.RUnlock()
  152. if !policy.Enabled {
  153. return nil
  154. }
  155. if ev.SNRDb < policy.MinSNRDb {
  156. return nil
  157. }
  158. dur := ev.End.Sub(ev.Start)
  159. if policy.MinDuration > 0 && dur < policy.MinDuration {
  160. return nil
  161. }
  162. if policy.MaxDuration > 0 && dur > policy.MaxDuration {
  163. return nil
  164. }
  165. if len(policy.ClassFilter) > 0 && ev.Class != nil {
  166. match := false
  167. for _, c := range policy.ClassFilter {
  168. if strings.EqualFold(c, string(ev.Class.ModType)) {
  169. match = true
  170. break
  171. }
  172. }
  173. if !match {
  174. return nil
  175. }
  176. }
  177. if !policy.RecordIQ && !policy.RecordAudio {
  178. return nil
  179. }
  180. start := ev.Start.Add(-time.Duration(policy.PrerollMs) * time.Millisecond)
  181. end := ev.End
  182. if start.After(end) {
  183. return errors.New("invalid event window")
  184. }
  185. if ring == nil {
  186. return errors.New("no ring buffer")
  187. }
  188. segment := ring.Slice(start, end)
  189. if len(segment) == 0 {
  190. return errors.New("no iq in ring")
  191. }
  192. dir := filepath.Join(policy.OutputDir, fmt.Sprintf("%s_%0.fHz_evt%d", ev.Start.Format("2006-01-02T15-04-05"), ev.CenterHz, ev.ID))
  193. if err := os.MkdirAll(dir, 0o755); err != nil {
  194. return err
  195. }
  196. files := map[string]any{}
  197. var iqPath string
  198. if policy.RecordIQ {
  199. iqPath = filepath.Join(dir, "signal.cf32")
  200. if err := writeCF32(iqPath, segment); err != nil {
  201. return err
  202. }
  203. files["iq"] = "signal.cf32"
  204. files["iq_format"] = "cf32"
  205. files["iq_sample_rate"] = sampleRate
  206. }
  207. if policy.RecordAudio && policy.AutoDemod && ev.Class != nil {
  208. if err := m.demodAndWrite(dir, ev, segment, files); err != nil {
  209. return err
  210. }
  211. }
  212. if policy.AutoDecode && iqPath != "" && ev.Class != nil {
  213. m.runDecodeIfConfigured(string(ev.Class.ModType), iqPath, sampleRate, files, dir)
  214. }
  215. _ = centerHz
  216. return writeMeta(dir, ev, sampleRate, files)
  217. }