Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

436 řádky
15KB

  1. package offline
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "path/filepath"
  7. "sync/atomic"
  8. "time"
  9. "github.com/jan/fm-rds-tx/internal/audio"
  10. cfgpkg "github.com/jan/fm-rds-tx/internal/config"
  11. "github.com/jan/fm-rds-tx/internal/dsp"
  12. "github.com/jan/fm-rds-tx/internal/mpx"
  13. "github.com/jan/fm-rds-tx/internal/output"
  14. "github.com/jan/fm-rds-tx/internal/rds"
  15. "github.com/jan/fm-rds-tx/internal/stereo"
  16. )
  17. type frameSource interface {
  18. NextFrame() audio.Frame
  19. }
  20. // LiveParams carries DSP parameters that can be hot-swapped at runtime.
  21. // Loaded once per chunk via atomic pointer — zero per-sample overhead.
  22. type LiveParams struct {
  23. OutputDrive float64
  24. StereoEnabled bool
  25. PilotLevel float64
  26. RDSInjection float64
  27. RDSEnabled bool
  28. LimiterEnabled bool
  29. LimiterCeiling float64
  30. MpxGain float64 // hardware calibration factor for composite output
  31. }
  32. // PreEmphasizedSource wraps an audio source and applies pre-emphasis.
  33. // The source is expected to already output at composite rate (resampled
  34. // upstream). Pre-emphasis is applied per-sample at that rate.
  35. type PreEmphasizedSource struct {
  36. src frameSource
  37. preL *dsp.PreEmphasis
  38. preR *dsp.PreEmphasis
  39. gain float64
  40. }
  41. func NewPreEmphasizedSource(src frameSource, tauUS, sampleRate, gain float64) *PreEmphasizedSource {
  42. p := &PreEmphasizedSource{src: src, gain: gain}
  43. if tauUS > 0 {
  44. p.preL = dsp.NewPreEmphasis(tauUS, sampleRate)
  45. p.preR = dsp.NewPreEmphasis(tauUS, sampleRate)
  46. }
  47. return p
  48. }
  49. func (p *PreEmphasizedSource) NextFrame() audio.Frame {
  50. f := p.src.NextFrame()
  51. l := float64(f.L) * p.gain
  52. r := float64(f.R) * p.gain
  53. if p.preL != nil {
  54. l = p.preL.Process(l)
  55. r = p.preR.Process(r)
  56. }
  57. return audio.NewFrame(audio.Sample(l), audio.Sample(r))
  58. }
  59. type SourceInfo struct {
  60. Kind string
  61. SampleRate float64
  62. Detail string
  63. }
  64. type Generator struct {
  65. cfg cfgpkg.Config
  66. // Persistent DSP state across GenerateFrame calls
  67. source *PreEmphasizedSource
  68. stereoEncoder stereo.StereoEncoder
  69. rdsEnc *rds.Encoder
  70. combiner mpx.DefaultCombiner
  71. fmMod *dsp.FMModulator
  72. sampleRate float64
  73. initialized bool
  74. frameSeq uint64
  75. // Broadcast-standard clip-filter-clip chain (per channel L/R):
  76. //
  77. // PreEmph → LPF₁(14kHz) → Notch(19kHz) → ×Drive
  78. // → StereoLimiter (slow AGC: raises average level)
  79. // → Clip₁ → LPF₂(14kHz) [cleanup] → Clip₂ [catches LPF overshoots]
  80. // → Stereo Encode → Composite Clip → Notch₁₉ → Notch₅₇
  81. // → + Pilot → + RDS → FM
  82. //
  83. audioLPF_L *dsp.FilterChain // 14kHz 8th-order (pre-clip)
  84. audioLPF_R *dsp.FilterChain
  85. pilotNotchL *dsp.FilterChain // 19kHz double-notch (guard band)
  86. pilotNotchR *dsp.FilterChain
  87. limiter *dsp.StereoLimiter // slow compressor (raises average, clips catch peaks)
  88. cleanupLPF_L *dsp.FilterChain // 14kHz 8th-order (post-clip cleanup)
  89. cleanupLPF_R *dsp.FilterChain
  90. mpxNotch19 *dsp.FilterChain // composite clipper protection
  91. mpxNotch57 *dsp.FilterChain
  92. bs412 *dsp.BS412Limiter // ITU-R BS.412 MPX power limiter (optional)
  93. // Pre-allocated frame buffer — reused every GenerateFrame call.
  94. frameBuf *output.CompositeFrame
  95. bufCap int
  96. // Live-updatable DSP parameters — written by control API, read per chunk.
  97. liveParams atomic.Pointer[LiveParams]
  98. // Optional external audio source (e.g. StreamResampler for live audio).
  99. // When set, takes priority over WAV/tones in sourceFor().
  100. externalSource frameSource
  101. }
  102. func NewGenerator(cfg cfgpkg.Config) *Generator {
  103. return &Generator{cfg: cfg}
  104. }
  105. // SetExternalSource sets a live audio source (e.g. StreamResampler) that
  106. // takes priority over WAV/tone sources. Must be called before the first
  107. // GenerateFrame() call; calling it after init() has no effect because
  108. // g.source is already wired to the old source.
  109. func (g *Generator) SetExternalSource(src frameSource) {
  110. if g.initialized {
  111. // init() already called sourceFor() and wired g.source. Updating
  112. // g.externalSource here would have no effect on the live DSP chain.
  113. // This is a programming error — log loudly rather than silently break.
  114. panic("generator: SetExternalSource called after GenerateFrame; call it before the engine starts")
  115. }
  116. g.externalSource = src
  117. }
  118. // UpdateLive hot-swaps DSP parameters. Thread-safe — called from control API,
  119. // applied at the next chunk boundary by the DSP goroutine.
  120. func (g *Generator) UpdateLive(p LiveParams) {
  121. g.liveParams.Store(&p)
  122. }
  123. // CurrentLiveParams returns the current live parameter snapshot.
  124. // Used by Engine.UpdateConfig to do read-modify-write on the params.
  125. func (g *Generator) CurrentLiveParams() LiveParams {
  126. if lp := g.liveParams.Load(); lp != nil {
  127. return *lp
  128. }
  129. return LiveParams{OutputDrive: 1.0, LimiterCeiling: 1.0, MpxGain: 1.0}
  130. }
  131. // RDSEncoder returns the live RDS encoder, or nil if RDS is disabled.
  132. // Used by the Engine to forward text updates.
  133. func (g *Generator) RDSEncoder() *rds.Encoder {
  134. return g.rdsEnc
  135. }
  136. func (g *Generator) init() {
  137. if g.initialized {
  138. return
  139. }
  140. g.sampleRate = float64(g.cfg.FM.CompositeRateHz)
  141. if g.sampleRate <= 0 {
  142. g.sampleRate = 228000
  143. }
  144. rawSource, _ := g.sourceFor(g.sampleRate)
  145. g.source = NewPreEmphasizedSource(rawSource, g.cfg.FM.PreEmphasisTauUS, g.sampleRate, g.cfg.Audio.Gain)
  146. g.stereoEncoder = stereo.NewStereoEncoder(g.sampleRate)
  147. g.combiner = mpx.DefaultCombiner{
  148. MonoGain: 1.0, StereoGain: 1.0,
  149. PilotGain: g.cfg.FM.PilotLevel, RDSGain: g.cfg.FM.RDSInjection,
  150. }
  151. if g.cfg.RDS.Enabled {
  152. piCode, _ := cfgpkg.ParsePI(g.cfg.RDS.PI)
  153. g.rdsEnc, _ = rds.NewEncoder(rds.RDSConfig{
  154. PI: piCode, PS: g.cfg.RDS.PS, RT: g.cfg.RDS.RadioText,
  155. PTY: uint8(g.cfg.RDS.PTY), SampleRate: g.sampleRate,
  156. })
  157. }
  158. ceiling := g.cfg.FM.LimiterCeiling
  159. if ceiling <= 0 { ceiling = 1.0 }
  160. // Broadcast clip-filter-clip chain:
  161. // Pre-clip: 14kHz LPF (8th-order) + 19kHz double-notch (per channel)
  162. g.audioLPF_L = dsp.NewAudioLPF(g.sampleRate)
  163. g.audioLPF_R = dsp.NewAudioLPF(g.sampleRate)
  164. g.pilotNotchL = dsp.NewPilotNotch(g.sampleRate)
  165. g.pilotNotchR = dsp.NewPilotNotch(g.sampleRate)
  166. // Slow compressor: 5ms attack / 200ms release. Brings average level UP.
  167. // The clips after it catch the peaks the limiter's attack time misses.
  168. // This is the "slow-to-fast progression" from broadcast processing:
  169. // slow limiter → fast clips.
  170. g.limiter = dsp.NewStereoLimiter(ceiling, 5, 200, g.sampleRate)
  171. // Post-clip cleanup: second 14kHz LPF pass (removes clip harmonics)
  172. g.cleanupLPF_L = dsp.NewAudioLPF(g.sampleRate)
  173. g.cleanupLPF_R = dsp.NewAudioLPF(g.sampleRate)
  174. // Composite clipper protection: double-notch at 19kHz + 57kHz
  175. g.mpxNotch19, g.mpxNotch57 = dsp.NewCompositeProtection(g.sampleRate)
  176. // BS.412 MPX power limiter (EU/CH requirement for licensed FM)
  177. if g.cfg.FM.BS412Enabled {
  178. // chunkSec is not known at init time (Engine.chunkDuration may differ).
  179. // Pass 0 here; GenerateFrame computes the actual chunk duration from
  180. // the real sample count and updates BS.412 accordingly.
  181. g.bs412 = dsp.NewBS412Limiter(
  182. g.cfg.FM.BS412ThresholdDBr,
  183. g.cfg.FM.PilotLevel,
  184. g.cfg.FM.RDSInjection,
  185. 0,
  186. )
  187. }
  188. if g.cfg.FM.FMModulationEnabled {
  189. g.fmMod = dsp.NewFMModulator(g.sampleRate)
  190. maxDev := g.cfg.FM.MaxDeviationHz
  191. if maxDev > 0 {
  192. if g.cfg.FM.MpxGain > 0 && g.cfg.FM.MpxGain != 1.0 {
  193. maxDev *= g.cfg.FM.MpxGain
  194. }
  195. g.fmMod.MaxDeviation = maxDev
  196. }
  197. }
  198. // Seed initial live params from config
  199. g.liveParams.Store(&LiveParams{
  200. OutputDrive: g.cfg.FM.OutputDrive,
  201. StereoEnabled: g.cfg.FM.StereoEnabled,
  202. PilotLevel: g.cfg.FM.PilotLevel,
  203. RDSInjection: g.cfg.FM.RDSInjection,
  204. RDSEnabled: g.cfg.RDS.Enabled,
  205. LimiterEnabled: g.cfg.FM.LimiterEnabled,
  206. LimiterCeiling: ceiling,
  207. MpxGain: g.cfg.FM.MpxGain,
  208. })
  209. g.initialized = true
  210. }
  211. func (g *Generator) sourceFor(sampleRate float64) (frameSource, SourceInfo) {
  212. if g.externalSource != nil {
  213. return g.externalSource, SourceInfo{Kind: "stream", SampleRate: sampleRate, Detail: "live audio"}
  214. }
  215. if g.cfg.Audio.InputPath != "" {
  216. if src, err := audio.LoadWAVSource(g.cfg.Audio.InputPath); err == nil {
  217. return audio.NewResampledSource(src, sampleRate), SourceInfo{Kind: "wav", SampleRate: float64(src.SampleRate), Detail: g.cfg.Audio.InputPath}
  218. }
  219. return audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude), SourceInfo{Kind: "tone-fallback", SampleRate: sampleRate, Detail: g.cfg.Audio.InputPath}
  220. }
  221. return audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude), SourceInfo{Kind: "tones", SampleRate: sampleRate, Detail: "generated"}
  222. }
  223. func (g *Generator) GenerateFrame(duration time.Duration) *output.CompositeFrame {
  224. g.init()
  225. samples := int(duration.Seconds() * g.sampleRate)
  226. if samples <= 0 { samples = int(g.sampleRate / 10) }
  227. // Reuse buffer — grow only if needed, never shrink
  228. if g.frameBuf == nil || g.bufCap < samples {
  229. g.frameBuf = &output.CompositeFrame{
  230. Samples: make([]output.IQSample, samples),
  231. }
  232. g.bufCap = samples
  233. }
  234. frame := g.frameBuf
  235. frame.Samples = frame.Samples[:samples]
  236. frame.SampleRateHz = g.sampleRate
  237. frame.Timestamp = time.Now().UTC()
  238. g.frameSeq++
  239. frame.Sequence = g.frameSeq
  240. // Load live params once per chunk — single atomic read, zero per-sample cost
  241. lp := g.liveParams.Load()
  242. if lp == nil {
  243. // Fallback: should never happen after init(), but be safe
  244. lp = &LiveParams{OutputDrive: 1.0, LimiterCeiling: 1.0, MpxGain: 1.0}
  245. }
  246. // Broadcast clip-filter-clip FM MPX signal chain:
  247. //
  248. // Audio L/R → PreEmphasis
  249. // → LPF₁ (14kHz, 8th-order) → 19kHz Notch (double)
  250. // → × OutputDrive → HardClip₁ (ceiling)
  251. // → LPF₂ (14kHz, 8th-order) [removes clip₁ harmonics]
  252. // → HardClip₂ (ceiling) [catches LPF₂ overshoots]
  253. // → Stereo Encode
  254. // Audio MPX (mono + stereo sub)
  255. // → HardClip₃ (ceiling) [composite deviation control]
  256. // → 19kHz Notch (double) [protect pilot band]
  257. // → 57kHz Notch (double) [protect RDS band]
  258. // + Pilot 19kHz (fixed, NEVER clipped)
  259. // + RDS 57kHz (fixed, NEVER clipped)
  260. // → FM Modulator
  261. //
  262. // Guard band depth at 19kHz: LPF₁(-21dB) + Notch(-60dB) + LPF₂(-21dB)
  263. // + CompNotch(-60dB) → broadband floor -42dB, exact 19kHz >-90dB
  264. ceiling := lp.LimiterCeiling
  265. if ceiling <= 0 { ceiling = 1.0 }
  266. // Pilot and RDS are FIXED injection levels, independent of OutputDrive.
  267. // Config values directly represent percentage of ±75kHz deviation:
  268. // pilotLevel: 0.09 = 9% = ±6.75kHz (ITU standard)
  269. // rdsInjection: 0.04 = 4% = ±3.0kHz (typical)
  270. pilotAmp := lp.PilotLevel
  271. rdsAmp := lp.RDSInjection
  272. // BS.412 MPX power limiter: uses previous chunk's measurement to set gain.
  273. // Power is measured during this chunk and fed back at the end.
  274. bs412Gain := 1.0
  275. var bs412PowerAccum float64
  276. if g.bs412 != nil {
  277. bs412Gain = g.bs412.CurrentGain()
  278. }
  279. for i := 0; i < samples; i++ {
  280. in := g.source.NextFrame()
  281. // --- Stage 1: Band-limit pre-emphasized audio ---
  282. l := g.audioLPF_L.Process(float64(in.L))
  283. l = g.pilotNotchL.Process(l)
  284. r := g.audioLPF_R.Process(float64(in.R))
  285. r = g.pilotNotchR.Process(r)
  286. // --- Stage 2: Drive + Compress + Clip₁ ---
  287. l *= lp.OutputDrive
  288. r *= lp.OutputDrive
  289. if g.limiter != nil {
  290. l, r = g.limiter.Process(l, r)
  291. }
  292. l = dsp.HardClip(l, ceiling)
  293. r = dsp.HardClip(r, ceiling)
  294. // --- Stage 3: Cleanup LPF + Clip₂ (overshoot compensator) ---
  295. l = g.cleanupLPF_L.Process(l)
  296. r = g.cleanupLPF_R.Process(r)
  297. l = dsp.HardClip(l, ceiling)
  298. r = dsp.HardClip(r, ceiling)
  299. // --- Stage 4: Stereo encode ---
  300. limited := audio.NewFrame(audio.Sample(l), audio.Sample(r))
  301. comps := g.stereoEncoder.Encode(limited)
  302. // --- Stage 5: Composite clip + protection ---
  303. audioMPX := float64(comps.Mono)
  304. if lp.StereoEnabled {
  305. audioMPX += float64(comps.Stereo)
  306. }
  307. audioMPX = dsp.HardClip(audioMPX, ceiling)
  308. audioMPX = g.mpxNotch19.Process(audioMPX)
  309. audioMPX = g.mpxNotch57.Process(audioMPX)
  310. // BS.412: apply gain and measure power
  311. if bs412Gain < 1.0 {
  312. audioMPX *= bs412Gain
  313. }
  314. bs412PowerAccum += audioMPX * audioMPX
  315. // --- Stage 6: Add protected components ---
  316. composite := audioMPX
  317. if lp.StereoEnabled {
  318. composite += pilotAmp * comps.Pilot
  319. }
  320. if g.rdsEnc != nil && lp.RDSEnabled {
  321. rdsCarrier := g.stereoEncoder.RDSCarrier()
  322. rdsValue := g.rdsEnc.NextSampleWithCarrier(rdsCarrier)
  323. composite += rdsAmp * rdsValue
  324. }
  325. if g.fmMod != nil {
  326. iq_i, iq_q := g.fmMod.Modulate(composite)
  327. frame.Samples[i] = output.IQSample{I: float32(iq_i), Q: float32(iq_q)}
  328. } else {
  329. frame.Samples[i] = output.IQSample{I: float32(composite), Q: 0}
  330. }
  331. }
  332. // BS.412: feed this chunk's actual duration and average audio power for
  333. // the next chunk's gain calculation. Using the real sample count avoids
  334. // the error that occurred when chunkSec was hardcoded to 0.05 — any
  335. // SetChunkDuration() call from the engine would silently miscalibrate
  336. // the ITU-R BS.412 power measurement window.
  337. if g.bs412 != nil && samples > 0 {
  338. chunkSec := float64(samples) / g.sampleRate
  339. g.bs412.UpdateChunkDuration(chunkSec)
  340. g.bs412.ProcessChunk(bs412PowerAccum / float64(samples))
  341. }
  342. return frame
  343. }
  344. func (g *Generator) WriteFile(path string, duration time.Duration) error {
  345. if path == "" {
  346. path = g.cfg.Backend.OutputPath
  347. }
  348. if path == "" {
  349. path = filepath.Join("build", "offline", "composite.iqf32")
  350. }
  351. backend, err := output.NewFileBackend(path, binary.LittleEndian, output.BackendInfo{
  352. Name: "offline-file",
  353. Description: "offline composite file backend",
  354. })
  355. if err != nil {
  356. return err
  357. }
  358. defer backend.Close(context.Background())
  359. if err := backend.Configure(context.Background(), output.BackendConfig{
  360. SampleRateHz: float64(g.cfg.FM.CompositeRateHz),
  361. Channels: 2,
  362. IQLevel: float32(g.cfg.FM.OutputDrive),
  363. }); err != nil {
  364. return err
  365. }
  366. frame := g.GenerateFrame(duration)
  367. if _, err := backend.Write(context.Background(), frame); err != nil {
  368. return err
  369. }
  370. return backend.Flush(context.Background())
  371. }
  372. func (g *Generator) Summary(duration time.Duration) string {
  373. sampleRate := float64(g.cfg.FM.CompositeRateHz)
  374. if sampleRate <= 0 {
  375. sampleRate = 228000
  376. }
  377. _, info := g.sourceFor(sampleRate)
  378. preemph := "off"
  379. if g.cfg.FM.PreEmphasisTauUS > 0 {
  380. preemph = fmt.Sprintf("%.0fµs", g.cfg.FM.PreEmphasisTauUS)
  381. }
  382. modMode := "composite"
  383. if g.cfg.FM.FMModulationEnabled {
  384. modMode = fmt.Sprintf("FM-IQ(±%.0fHz)", g.cfg.FM.MaxDeviationHz)
  385. }
  386. return fmt.Sprintf("offline frame: freq=%.1fMHz rate=%d duration=%s drive=%.2f stereo=%t rds=%t preemph=%s limiter=%t output=%s source=%s detail=%s",
  387. g.cfg.FM.FrequencyMHz, g.cfg.FM.CompositeRateHz, duration.String(),
  388. g.cfg.FM.OutputDrive, g.cfg.FM.StereoEnabled, g.cfg.RDS.Enabled,
  389. preemph, g.cfg.FM.LimiterEnabled, modMode, info.Kind, info.Detail)
  390. }