Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

421 lines
14KB

  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 (i.e. before init).
  108. func (g *Generator) SetExternalSource(src frameSource) {
  109. g.externalSource = src
  110. }
  111. // UpdateLive hot-swaps DSP parameters. Thread-safe — called from control API,
  112. // applied at the next chunk boundary by the DSP goroutine.
  113. func (g *Generator) UpdateLive(p LiveParams) {
  114. g.liveParams.Store(&p)
  115. }
  116. // CurrentLiveParams returns the current live parameter snapshot.
  117. // Used by Engine.UpdateConfig to do read-modify-write on the params.
  118. func (g *Generator) CurrentLiveParams() LiveParams {
  119. if lp := g.liveParams.Load(); lp != nil {
  120. return *lp
  121. }
  122. return LiveParams{OutputDrive: 1.0, LimiterCeiling: 1.0, MpxGain: 1.0}
  123. }
  124. // RDSEncoder returns the live RDS encoder, or nil if RDS is disabled.
  125. // Used by the Engine to forward text updates.
  126. func (g *Generator) RDSEncoder() *rds.Encoder {
  127. return g.rdsEnc
  128. }
  129. func (g *Generator) init() {
  130. if g.initialized {
  131. return
  132. }
  133. g.sampleRate = float64(g.cfg.FM.CompositeRateHz)
  134. if g.sampleRate <= 0 {
  135. g.sampleRate = 228000
  136. }
  137. rawSource, _ := g.sourceFor(g.sampleRate)
  138. g.source = NewPreEmphasizedSource(rawSource, g.cfg.FM.PreEmphasisTauUS, g.sampleRate, g.cfg.Audio.Gain)
  139. g.stereoEncoder = stereo.NewStereoEncoder(g.sampleRate)
  140. g.combiner = mpx.DefaultCombiner{
  141. MonoGain: 1.0, StereoGain: 1.0,
  142. PilotGain: g.cfg.FM.PilotLevel, RDSGain: g.cfg.FM.RDSInjection,
  143. }
  144. if g.cfg.RDS.Enabled {
  145. piCode, _ := cfgpkg.ParsePI(g.cfg.RDS.PI)
  146. g.rdsEnc, _ = rds.NewEncoder(rds.RDSConfig{
  147. PI: piCode, PS: g.cfg.RDS.PS, RT: g.cfg.RDS.RadioText,
  148. PTY: uint8(g.cfg.RDS.PTY), SampleRate: g.sampleRate,
  149. })
  150. }
  151. ceiling := g.cfg.FM.LimiterCeiling
  152. if ceiling <= 0 { ceiling = 1.0 }
  153. // Broadcast clip-filter-clip chain:
  154. // Pre-clip: 14kHz LPF (8th-order) + 19kHz double-notch (per channel)
  155. g.audioLPF_L = dsp.NewAudioLPF(g.sampleRate)
  156. g.audioLPF_R = dsp.NewAudioLPF(g.sampleRate)
  157. g.pilotNotchL = dsp.NewPilotNotch(g.sampleRate)
  158. g.pilotNotchR = dsp.NewPilotNotch(g.sampleRate)
  159. // Slow compressor: 5ms attack / 200ms release. Brings average level UP.
  160. // The clips after it catch the peaks the limiter's attack time misses.
  161. // This is the "slow-to-fast progression" from broadcast processing:
  162. // slow limiter → fast clips.
  163. g.limiter = dsp.NewStereoLimiter(ceiling, 5, 200, g.sampleRate)
  164. // Post-clip cleanup: second 14kHz LPF pass (removes clip harmonics)
  165. g.cleanupLPF_L = dsp.NewAudioLPF(g.sampleRate)
  166. g.cleanupLPF_R = dsp.NewAudioLPF(g.sampleRate)
  167. // Composite clipper protection: double-notch at 19kHz + 57kHz
  168. g.mpxNotch19, g.mpxNotch57 = dsp.NewCompositeProtection(g.sampleRate)
  169. // BS.412 MPX power limiter (EU/CH requirement for licensed FM)
  170. if g.cfg.FM.BS412Enabled {
  171. chunkSec := 0.05 // 50ms chunks (matches engine default)
  172. g.bs412 = dsp.NewBS412Limiter(
  173. g.cfg.FM.BS412ThresholdDBr,
  174. g.cfg.FM.PilotLevel,
  175. g.cfg.FM.RDSInjection,
  176. chunkSec,
  177. )
  178. }
  179. if g.cfg.FM.FMModulationEnabled {
  180. g.fmMod = dsp.NewFMModulator(g.sampleRate)
  181. maxDev := g.cfg.FM.MaxDeviationHz
  182. if maxDev > 0 {
  183. if g.cfg.FM.MpxGain > 0 && g.cfg.FM.MpxGain != 1.0 {
  184. maxDev *= g.cfg.FM.MpxGain
  185. }
  186. g.fmMod.MaxDeviation = maxDev
  187. }
  188. }
  189. // Seed initial live params from config
  190. g.liveParams.Store(&LiveParams{
  191. OutputDrive: g.cfg.FM.OutputDrive,
  192. StereoEnabled: g.cfg.FM.StereoEnabled,
  193. PilotLevel: g.cfg.FM.PilotLevel,
  194. RDSInjection: g.cfg.FM.RDSInjection,
  195. RDSEnabled: g.cfg.RDS.Enabled,
  196. LimiterEnabled: g.cfg.FM.LimiterEnabled,
  197. LimiterCeiling: ceiling,
  198. MpxGain: g.cfg.FM.MpxGain,
  199. })
  200. g.initialized = true
  201. }
  202. func (g *Generator) sourceFor(sampleRate float64) (frameSource, SourceInfo) {
  203. if g.externalSource != nil {
  204. return g.externalSource, SourceInfo{Kind: "stream", SampleRate: sampleRate, Detail: "live audio"}
  205. }
  206. if g.cfg.Audio.InputPath != "" {
  207. if src, err := audio.LoadWAVSource(g.cfg.Audio.InputPath); err == nil {
  208. return audio.NewResampledSource(src, sampleRate), SourceInfo{Kind: "wav", SampleRate: float64(src.SampleRate), Detail: g.cfg.Audio.InputPath}
  209. }
  210. 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}
  211. }
  212. return audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude), SourceInfo{Kind: "tones", SampleRate: sampleRate, Detail: "generated"}
  213. }
  214. func (g *Generator) GenerateFrame(duration time.Duration) *output.CompositeFrame {
  215. g.init()
  216. samples := int(duration.Seconds() * g.sampleRate)
  217. if samples <= 0 { samples = int(g.sampleRate / 10) }
  218. // Reuse buffer — grow only if needed, never shrink
  219. if g.frameBuf == nil || g.bufCap < samples {
  220. g.frameBuf = &output.CompositeFrame{
  221. Samples: make([]output.IQSample, samples),
  222. }
  223. g.bufCap = samples
  224. }
  225. frame := g.frameBuf
  226. frame.Samples = frame.Samples[:samples]
  227. frame.SampleRateHz = g.sampleRate
  228. frame.Timestamp = time.Now().UTC()
  229. g.frameSeq++
  230. frame.Sequence = g.frameSeq
  231. // Load live params once per chunk — single atomic read, zero per-sample cost
  232. lp := g.liveParams.Load()
  233. if lp == nil {
  234. // Fallback: should never happen after init(), but be safe
  235. lp = &LiveParams{OutputDrive: 1.0, LimiterCeiling: 1.0, MpxGain: 1.0}
  236. }
  237. // Broadcast clip-filter-clip FM MPX signal chain:
  238. //
  239. // Audio L/R → PreEmphasis
  240. // → LPF₁ (14kHz, 8th-order) → 19kHz Notch (double)
  241. // → × OutputDrive → HardClip₁ (ceiling)
  242. // → LPF₂ (14kHz, 8th-order) [removes clip₁ harmonics]
  243. // → HardClip₂ (ceiling) [catches LPF₂ overshoots]
  244. // → Stereo Encode
  245. // Audio MPX (mono + stereo sub)
  246. // → HardClip₃ (ceiling) [composite deviation control]
  247. // → 19kHz Notch (double) [protect pilot band]
  248. // → 57kHz Notch (double) [protect RDS band]
  249. // + Pilot 19kHz (fixed, NEVER clipped)
  250. // + RDS 57kHz (fixed, NEVER clipped)
  251. // → FM Modulator
  252. //
  253. // Guard band depth at 19kHz: LPF₁(-21dB) + Notch(-60dB) + LPF₂(-21dB)
  254. // + CompNotch(-60dB) → broadband floor -42dB, exact 19kHz >-90dB
  255. ceiling := lp.LimiterCeiling
  256. if ceiling <= 0 { ceiling = 1.0 }
  257. // Pilot and RDS are FIXED injection levels, independent of OutputDrive.
  258. // Config values directly represent percentage of ±75kHz deviation:
  259. // pilotLevel: 0.09 = 9% = ±6.75kHz (ITU standard)
  260. // rdsInjection: 0.04 = 4% = ±3.0kHz (typical)
  261. pilotAmp := lp.PilotLevel
  262. rdsAmp := lp.RDSInjection
  263. // BS.412 MPX power limiter: uses previous chunk's measurement to set gain.
  264. // Power is measured during this chunk and fed back at the end.
  265. bs412Gain := 1.0
  266. var bs412PowerAccum float64
  267. if g.bs412 != nil {
  268. bs412Gain = g.bs412.CurrentGain()
  269. }
  270. for i := 0; i < samples; i++ {
  271. in := g.source.NextFrame()
  272. // --- Stage 1: Band-limit pre-emphasized audio ---
  273. l := g.audioLPF_L.Process(float64(in.L))
  274. l = g.pilotNotchL.Process(l)
  275. r := g.audioLPF_R.Process(float64(in.R))
  276. r = g.pilotNotchR.Process(r)
  277. // --- Stage 2: Drive + Compress + Clip₁ ---
  278. l *= lp.OutputDrive
  279. r *= lp.OutputDrive
  280. if g.limiter != nil {
  281. l, r = g.limiter.Process(l, r)
  282. }
  283. l = dsp.HardClip(l, ceiling)
  284. r = dsp.HardClip(r, ceiling)
  285. // --- Stage 3: Cleanup LPF + Clip₂ (overshoot compensator) ---
  286. l = g.cleanupLPF_L.Process(l)
  287. r = g.cleanupLPF_R.Process(r)
  288. l = dsp.HardClip(l, ceiling)
  289. r = dsp.HardClip(r, ceiling)
  290. // --- Stage 4: Stereo encode ---
  291. limited := audio.NewFrame(audio.Sample(l), audio.Sample(r))
  292. comps := g.stereoEncoder.Encode(limited)
  293. // --- Stage 5: Composite clip + protection ---
  294. audioMPX := float64(comps.Mono)
  295. if lp.StereoEnabled {
  296. audioMPX += float64(comps.Stereo)
  297. }
  298. audioMPX = dsp.HardClip(audioMPX, ceiling)
  299. audioMPX = g.mpxNotch19.Process(audioMPX)
  300. audioMPX = g.mpxNotch57.Process(audioMPX)
  301. // BS.412: apply gain and measure power
  302. if bs412Gain < 1.0 {
  303. audioMPX *= bs412Gain
  304. }
  305. bs412PowerAccum += audioMPX * audioMPX
  306. // --- Stage 6: Add protected components ---
  307. composite := audioMPX
  308. if lp.StereoEnabled {
  309. composite += pilotAmp * comps.Pilot
  310. }
  311. if g.rdsEnc != nil && lp.RDSEnabled {
  312. rdsCarrier := g.stereoEncoder.RDSCarrier()
  313. rdsValue := g.rdsEnc.NextSampleWithCarrier(rdsCarrier)
  314. composite += rdsAmp * rdsValue
  315. }
  316. if g.fmMod != nil {
  317. iq_i, iq_q := g.fmMod.Modulate(composite)
  318. frame.Samples[i] = output.IQSample{I: float32(iq_i), Q: float32(iq_q)}
  319. } else {
  320. frame.Samples[i] = output.IQSample{I: float32(composite), Q: 0}
  321. }
  322. }
  323. // BS.412: feed this chunk's average audio power for next chunk's gain calculation
  324. if g.bs412 != nil && samples > 0 {
  325. g.bs412.ProcessChunk(bs412PowerAccum / float64(samples))
  326. }
  327. return frame
  328. }
  329. func (g *Generator) WriteFile(path string, duration time.Duration) error {
  330. if path == "" {
  331. path = g.cfg.Backend.OutputPath
  332. }
  333. if path == "" {
  334. path = filepath.Join("build", "offline", "composite.iqf32")
  335. }
  336. backend, err := output.NewFileBackend(path, binary.LittleEndian, output.BackendInfo{
  337. Name: "offline-file",
  338. Description: "offline composite file backend",
  339. })
  340. if err != nil {
  341. return err
  342. }
  343. defer backend.Close(context.Background())
  344. if err := backend.Configure(context.Background(), output.BackendConfig{
  345. SampleRateHz: float64(g.cfg.FM.CompositeRateHz),
  346. Channels: 2,
  347. IQLevel: float32(g.cfg.FM.OutputDrive),
  348. }); err != nil {
  349. return err
  350. }
  351. frame := g.GenerateFrame(duration)
  352. if _, err := backend.Write(context.Background(), frame); err != nil {
  353. return err
  354. }
  355. return backend.Flush(context.Background())
  356. }
  357. func (g *Generator) Summary(duration time.Duration) string {
  358. sampleRate := float64(g.cfg.FM.CompositeRateHz)
  359. if sampleRate <= 0 {
  360. sampleRate = 228000
  361. }
  362. _, info := g.sourceFor(sampleRate)
  363. preemph := "off"
  364. if g.cfg.FM.PreEmphasisTauUS > 0 {
  365. preemph = fmt.Sprintf("%.0fµs", g.cfg.FM.PreEmphasisTauUS)
  366. }
  367. modMode := "composite"
  368. if g.cfg.FM.FMModulationEnabled {
  369. modMode = fmt.Sprintf("FM-IQ(±%.0fHz)", g.cfg.FM.MaxDeviationHz)
  370. }
  371. 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",
  372. g.cfg.FM.FrequencyMHz, g.cfg.FM.CompositeRateHz, duration.String(),
  373. g.cfg.FM.OutputDrive, g.cfg.FM.StereoEnabled, g.cfg.RDS.Enabled,
  374. preemph, g.cfg.FM.LimiterEnabled, modMode, info.Kind, info.Detail)
  375. }