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.

518 line
17KB

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