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ů.

622 řádky
21KB

  1. package offline
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "log"
  7. "path/filepath"
  8. "sync/atomic"
  9. "time"
  10. "github.com/jan/fm-rds-tx/internal/audio"
  11. cfgpkg "github.com/jan/fm-rds-tx/internal/config"
  12. "github.com/jan/fm-rds-tx/internal/license"
  13. "github.com/jan/fm-rds-tx/internal/watermark"
  14. "github.com/jan/fm-rds-tx/internal/dsp"
  15. "github.com/jan/fm-rds-tx/internal/mpx"
  16. "github.com/jan/fm-rds-tx/internal/output"
  17. "github.com/jan/fm-rds-tx/internal/rds"
  18. "github.com/jan/fm-rds-tx/internal/stereo"
  19. )
  20. type frameSource interface {
  21. NextFrame() audio.Frame
  22. }
  23. // LiveParams carries DSP parameters that can be hot-swapped at runtime.
  24. // Loaded once per chunk via atomic pointer — zero per-sample overhead.
  25. type LiveParams struct {
  26. OutputDrive float64
  27. StereoEnabled bool
  28. StereoMode string
  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. // Composite clipper: live-toggleable without DSP chain reinit.
  41. CompositeClipperEnabled bool
  42. }
  43. // PreEmphasizedSource wraps an audio source and applies pre-emphasis.
  44. // The source is expected to already output at composite rate (resampled
  45. // upstream). Pre-emphasis is applied per-sample at that rate.
  46. type PreEmphasizedSource struct {
  47. src frameSource
  48. preL *dsp.PreEmphasis
  49. preR *dsp.PreEmphasis
  50. gain float64
  51. }
  52. func NewPreEmphasizedSource(src frameSource, tauUS, sampleRate, gain float64) *PreEmphasizedSource {
  53. p := &PreEmphasizedSource{src: src, gain: gain}
  54. if tauUS > 0 {
  55. p.preL = dsp.NewPreEmphasis(tauUS, sampleRate)
  56. p.preR = dsp.NewPreEmphasis(tauUS, sampleRate)
  57. }
  58. return p
  59. }
  60. func (p *PreEmphasizedSource) NextFrame() audio.Frame {
  61. f := p.src.NextFrame()
  62. l := float64(f.L) * p.gain
  63. r := float64(f.R) * p.gain
  64. if p.preL != nil {
  65. l = p.preL.Process(l)
  66. r = p.preR.Process(r)
  67. }
  68. return audio.NewFrame(audio.Sample(l), audio.Sample(r))
  69. }
  70. type SourceInfo struct {
  71. Kind string
  72. SampleRate float64
  73. Detail string
  74. }
  75. type Generator struct {
  76. cfg cfgpkg.Config
  77. // Persistent DSP state across GenerateFrame calls
  78. source *PreEmphasizedSource
  79. stereoEncoder stereo.StereoEncoder
  80. rdsEnc *rds.Encoder
  81. combiner mpx.DefaultCombiner
  82. fmMod *dsp.FMModulator
  83. sampleRate float64
  84. initialized bool
  85. frameSeq uint64
  86. // Broadcast-standard clip-filter-clip chain (per channel L/R):
  87. //
  88. // PreEmph → LPF₁(14kHz) → Notch(19kHz) → ×Drive
  89. // → StereoLimiter (slow AGC: raises average level)
  90. // → Clip₁ → LPF₂(14kHz) [cleanup] → Clip₂ [catches LPF overshoots]
  91. // → Stereo Encode → Composite Clip → Notch₁₉ → Notch₅₇
  92. // → + Pilot → + RDS → FM
  93. //
  94. audioLPF_L *dsp.FilterChain // 14kHz 8th-order (pre-clip)
  95. audioLPF_R *dsp.FilterChain
  96. pilotNotchL *dsp.FilterChain // 19kHz double-notch (guard band)
  97. pilotNotchR *dsp.FilterChain
  98. limiter *dsp.StereoLimiter // slow compressor (raises average, clips catch peaks)
  99. cleanupLPF_L *dsp.FilterChain // 14kHz 8th-order (post-clip cleanup)
  100. cleanupLPF_R *dsp.FilterChain
  101. mpxNotch19 *dsp.FilterChain // composite clipper protection
  102. mpxNotch57 *dsp.FilterChain
  103. bs412 *dsp.BS412Limiter // ITU-R BS.412 MPX power limiter (optional)
  104. compositeClip *dsp.CompositeClipper // ITU-R SM.1268 iterative composite clipper (optional)
  105. // Pre-allocated frame buffer — reused every GenerateFrame call.
  106. frameBuf *output.CompositeFrame
  107. bufCap int
  108. // Live-updatable DSP parameters — written by control API, read per chunk.
  109. liveParams atomic.Pointer[LiveParams]
  110. // Optional external audio source (e.g. StreamResampler for live audio).
  111. // When set, takes priority over WAV/tones in sourceFor().
  112. externalSource frameSource
  113. // Tone source reference — non-nil when a ToneSource is the active audio input.
  114. // Allows live-updating tone parameters via LiveParams each chunk.
  115. toneSource *audio.ToneSource
  116. // License: jingle injection when unlicensed.
  117. licenseState *license.State
  118. jingleFrames []license.JingleFrame
  119. // Watermark: STFT-domain spread-spectrum (Kirovski & Malvar 2003).
  120. stftEmbedder *watermark.STFTEmbedder
  121. wmDecimLPF *dsp.FilterChain // anti-alias LPF for 228k→12k decimation
  122. wmInterpLPF *dsp.FilterChain // image-rejection LPF for 12k→228k upsample
  123. }
  124. func NewGenerator(cfg cfgpkg.Config) *Generator {
  125. return &Generator{cfg: cfg}
  126. }
  127. // SetLicense configures license state (jingle) and creates the STFT watermark
  128. // embedder. Must be called before the first GenerateFrame.
  129. func (g *Generator) SetLicense(state *license.State, key string) {
  130. g.licenseState = state
  131. g.stftEmbedder = watermark.NewSTFTEmbedder(key)
  132. }
  133. // SetExternalSource sets a live audio source (e.g. StreamResampler) that
  134. // takes priority over WAV/tone sources. Must be called before the first
  135. // GenerateFrame() call; calling it after init() has no effect because
  136. // g.source is already wired to the old source.
  137. func (g *Generator) SetExternalSource(src frameSource) error {
  138. if g.initialized {
  139. return fmt.Errorf("generator: SetExternalSource called after GenerateFrame; call it before the engine starts")
  140. }
  141. g.externalSource = src
  142. return nil
  143. }
  144. // UpdateLive hot-swaps DSP parameters. Thread-safe — called from control API,
  145. // applied at the next chunk boundary by the DSP goroutine.
  146. func (g *Generator) UpdateLive(p LiveParams) {
  147. // Detect stereo mode change: requires reconfiguring the encoder's Hilbert filter.
  148. if old := g.liveParams.Load(); old != nil && old.StereoMode != p.StereoMode {
  149. g.stereoEncoder.SetMode(stereo.ParseMode(p.StereoMode), g.sampleRate)
  150. }
  151. g.liveParams.Store(&p)
  152. }
  153. // CurrentLiveParams returns the current live parameter snapshot.
  154. // Used by Engine.UpdateConfig to do read-modify-write on the params.
  155. func (g *Generator) CurrentLiveParams() LiveParams {
  156. if lp := g.liveParams.Load(); lp != nil {
  157. return *lp
  158. }
  159. return LiveParams{OutputDrive: 1.0, LimiterCeiling: 1.0, MpxGain: 1.0}
  160. }
  161. // RDSEncoder returns the live RDS encoder, or nil if RDS is disabled.
  162. // Used by the Engine to forward text updates.
  163. func (g *Generator) RDSEncoder() *rds.Encoder {
  164. return g.rdsEnc
  165. }
  166. func (g *Generator) init() {
  167. if g.initialized {
  168. return
  169. }
  170. g.sampleRate = float64(g.cfg.FM.CompositeRateHz)
  171. if g.sampleRate <= 0 {
  172. g.sampleRate = 228000
  173. }
  174. rawSource, _ := g.sourceFor(g.sampleRate)
  175. g.source = NewPreEmphasizedSource(rawSource, g.cfg.FM.PreEmphasisTauUS, g.sampleRate, g.cfg.Audio.Gain)
  176. g.stereoEncoder = stereo.NewStereoEncoder(g.sampleRate)
  177. g.stereoEncoder.SetMode(stereo.ParseMode(g.cfg.FM.StereoMode), g.sampleRate)
  178. g.combiner = mpx.DefaultCombiner{
  179. MonoGain: 1.0, StereoGain: 1.0,
  180. PilotGain: g.cfg.FM.PilotLevel, RDSGain: g.cfg.FM.RDSInjection,
  181. }
  182. if g.cfg.RDS.Enabled {
  183. piCode, _ := cfgpkg.ParsePI(g.cfg.RDS.PI)
  184. // Build EON entries
  185. var eonEntries []rds.EONEntry
  186. for _, e := range g.cfg.RDS.EON {
  187. eonPI, _ := cfgpkg.ParsePI(e.PI)
  188. eonEntries = append(eonEntries, rds.EONEntry{
  189. PI: eonPI, PS: e.PS, PTY: uint8(e.PTY),
  190. TP: e.TP, TA: e.TA, AF: e.AF,
  191. })
  192. }
  193. sep := g.cfg.RDS.RTPlusSeparator
  194. if sep == "" {
  195. sep = " - "
  196. }
  197. g.rdsEnc, _ = rds.NewEncoder(rds.RDSConfig{
  198. PI: piCode, PS: g.cfg.RDS.PS, RT: g.cfg.RDS.RadioText,
  199. PTY: uint8(g.cfg.RDS.PTY), SampleRate: g.sampleRate,
  200. TP: g.cfg.RDS.TP, TA: g.cfg.RDS.TA,
  201. MS: g.cfg.RDS.MS, DI: g.cfg.RDS.DI,
  202. AF: g.cfg.RDS.AF,
  203. CTEnabled: g.cfg.RDS.CTEnabled,
  204. CTOffsetHalfHours: g.cfg.RDS.CTOffsetHalfHours,
  205. PTYN: g.cfg.RDS.PTYN,
  206. RTPlusEnabled: g.cfg.RDS.RTPlusEnabled,
  207. RTPlusSeparator: sep,
  208. EON: eonEntries,
  209. })
  210. }
  211. ceiling := g.cfg.FM.LimiterCeiling
  212. if ceiling <= 0 { ceiling = 1.0 }
  213. // Broadcast clip-filter-clip chain:
  214. // Pre-clip: 14kHz LPF (8th-order) + 19kHz double-notch (per channel)
  215. g.audioLPF_L = dsp.NewAudioLPF(g.sampleRate)
  216. g.audioLPF_R = dsp.NewAudioLPF(g.sampleRate)
  217. g.pilotNotchL = dsp.NewPilotNotch(g.sampleRate)
  218. g.pilotNotchR = dsp.NewPilotNotch(g.sampleRate)
  219. // Slow compressor: 5ms attack / 200ms release. Brings average level UP.
  220. // The clips after it catch the peaks the limiter's attack time misses.
  221. // This is the "slow-to-fast progression" from broadcast processing:
  222. // slow limiter → fast clips.
  223. // Burst-masking-optimized limiter (Bonello, JAES 2007):
  224. // 2ms attack lets initial transient peaks clip for <5ms (burst-masked).
  225. // 150ms release avoids audible pumping on sustained passages.
  226. g.limiter = dsp.NewStereoLimiter(ceiling, 2, 150, g.sampleRate)
  227. // Post-clip cleanup: second 14kHz LPF pass (removes clip harmonics)
  228. g.cleanupLPF_L = dsp.NewAudioLPF(g.sampleRate)
  229. g.cleanupLPF_R = dsp.NewAudioLPF(g.sampleRate)
  230. // Composite clipper protection: double-notch at 19kHz + 57kHz
  231. g.mpxNotch19, g.mpxNotch57 = dsp.NewCompositeProtection(g.sampleRate)
  232. // ITU-R SM.1268 iterative composite clipper (optional, replaces simple clip+notch)
  233. // Always created so it can be live-toggled via CompositeClipperEnabled.
  234. g.compositeClip = dsp.NewCompositeClipper(dsp.CompositeClipperConfig{
  235. Ceiling: ceiling,
  236. Iterations: g.cfg.FM.CompositeClipper.Iterations,
  237. SoftKnee: g.cfg.FM.CompositeClipper.SoftKnee,
  238. LookaheadMs: g.cfg.FM.CompositeClipper.LookaheadMs,
  239. SampleRate: g.sampleRate,
  240. })
  241. // BS.412 MPX power limiter (EU/CH requirement for licensed FM)
  242. if g.cfg.FM.BS412Enabled {
  243. // chunkSec is not known at init time (Engine.chunkDuration may differ).
  244. // Pass 0 here; GenerateFrame computes the actual chunk duration from
  245. // the real sample count and updates BS.412 accordingly.
  246. g.bs412 = dsp.NewBS412Limiter(
  247. g.cfg.FM.BS412ThresholdDBr,
  248. g.cfg.FM.PilotLevel,
  249. g.cfg.FM.RDSInjection,
  250. 0,
  251. )
  252. }
  253. if g.cfg.FM.FMModulationEnabled {
  254. g.fmMod = dsp.NewFMModulator(g.sampleRate)
  255. maxDev := g.cfg.FM.MaxDeviationHz
  256. if maxDev > 0 {
  257. if g.cfg.FM.MpxGain > 0 && g.cfg.FM.MpxGain != 1.0 {
  258. maxDev *= g.cfg.FM.MpxGain
  259. }
  260. g.fmMod.MaxDeviation = maxDev
  261. }
  262. }
  263. // Seed initial live params from config
  264. g.liveParams.Store(&LiveParams{
  265. OutputDrive: g.cfg.FM.OutputDrive,
  266. StereoEnabled: g.cfg.FM.StereoEnabled,
  267. StereoMode: g.cfg.FM.StereoMode,
  268. PilotLevel: g.cfg.FM.PilotLevel,
  269. RDSInjection: g.cfg.FM.RDSInjection,
  270. RDSEnabled: g.cfg.RDS.Enabled,
  271. LimiterEnabled: g.cfg.FM.LimiterEnabled,
  272. LimiterCeiling: ceiling,
  273. MpxGain: g.cfg.FM.MpxGain,
  274. ToneLeftHz: g.cfg.Audio.ToneLeftHz,
  275. ToneRightHz: g.cfg.Audio.ToneRightHz,
  276. ToneAmplitude: g.cfg.Audio.ToneAmplitude,
  277. AudioGain: g.cfg.Audio.Gain,
  278. CompositeClipperEnabled: g.cfg.FM.CompositeClipper.Enabled,
  279. })
  280. if g.licenseState != nil {
  281. frames, err := license.LoadJingleFrames(license.JingleWAV(), g.sampleRate)
  282. if err != nil {
  283. log.Printf("license: jingle load failed: %v", err)
  284. } else {
  285. g.jingleFrames = frames
  286. }
  287. }
  288. // STFT watermark: anti-alias LPF for decimation to WMRate (12 kHz).
  289. // Nyquist at 12 kHz = 6 kHz. Cut at 5.5 kHz with margin.
  290. if g.stftEmbedder != nil {
  291. g.wmDecimLPF = dsp.NewLPF4(5500, g.sampleRate)
  292. g.wmInterpLPF = dsp.NewLPF4(5500, g.sampleRate) // separate instance for upsample
  293. }
  294. g.initialized = true
  295. }
  296. func (g *Generator) sourceFor(sampleRate float64) (frameSource, SourceInfo) {
  297. if g.externalSource != nil {
  298. return g.externalSource, SourceInfo{Kind: "stream", SampleRate: sampleRate, Detail: "live audio"}
  299. }
  300. if g.cfg.Audio.InputPath != "" {
  301. if src, err := audio.LoadWAVSource(g.cfg.Audio.InputPath); err == nil {
  302. return audio.NewResampledSource(src, sampleRate), SourceInfo{Kind: "wav", SampleRate: float64(src.SampleRate), Detail: g.cfg.Audio.InputPath}
  303. }
  304. ts := audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude)
  305. g.toneSource = ts
  306. return ts, SourceInfo{Kind: "tone-fallback", SampleRate: sampleRate, Detail: g.cfg.Audio.InputPath}
  307. }
  308. ts := audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude)
  309. g.toneSource = ts
  310. return ts, SourceInfo{Kind: "tones", SampleRate: sampleRate, Detail: "generated"}
  311. }
  312. func (g *Generator) GenerateFrame(duration time.Duration) *output.CompositeFrame {
  313. g.init()
  314. samples := int(duration.Seconds() * g.sampleRate)
  315. if samples <= 0 { samples = int(g.sampleRate / 10) }
  316. // Reuse buffer — grow only if needed, never shrink
  317. if g.frameBuf == nil || g.bufCap < samples {
  318. g.frameBuf = &output.CompositeFrame{
  319. Samples: make([]output.IQSample, samples),
  320. }
  321. g.bufCap = samples
  322. }
  323. frame := g.frameBuf
  324. frame.Samples = frame.Samples[:samples]
  325. frame.SampleRateHz = g.sampleRate
  326. frame.Timestamp = time.Now().UTC()
  327. g.frameSeq++
  328. frame.Sequence = g.frameSeq
  329. // L/R buffers for two-pass processing (STFT watermark between stages 3 and 4)
  330. lBuf := make([]float64, samples)
  331. rBuf := make([]float64, samples)
  332. // Load live params once per chunk — single atomic read, zero per-sample cost
  333. lp := g.liveParams.Load()
  334. if lp == nil {
  335. // Fallback: should never happen after init(), but be safe
  336. lp = &LiveParams{OutputDrive: 1.0, LimiterCeiling: 1.0, MpxGain: 1.0}
  337. }
  338. // Apply live tone and gain updates each chunk. GenerateFrame runs on a
  339. // single goroutine so these field writes are safe without additional locking.
  340. if g.toneSource != nil {
  341. g.toneSource.LeftFreq = lp.ToneLeftHz
  342. g.toneSource.RightFreq = lp.ToneRightHz
  343. g.toneSource.Amplitude = lp.ToneAmplitude
  344. }
  345. if g.source != nil {
  346. g.source.gain = lp.AudioGain
  347. }
  348. // Broadcast clip-filter-clip FM MPX signal chain:
  349. //
  350. // Audio L/R → PreEmphasis
  351. // → LPF₁ (14kHz, 8th-order) → 19kHz Notch (double)
  352. // → × OutputDrive → HardClip₁ (ceiling)
  353. // → LPF₂ (14kHz, 8th-order) [removes clip₁ harmonics]
  354. // → HardClip₂ (ceiling) [catches LPF₂ overshoots]
  355. // → Stereo Encode
  356. // Audio MPX (mono + stereo sub)
  357. // → HardClip₃ (ceiling) [composite deviation control]
  358. // → 19kHz Notch (double) [protect pilot band]
  359. // → 57kHz Notch (double) [protect RDS band]
  360. // + Pilot 19kHz (fixed, NEVER clipped)
  361. // + RDS 57kHz (fixed, NEVER clipped)
  362. // → FM Modulator
  363. //
  364. // Guard band depth at 19kHz: LPF₁(-21dB) + Notch(-60dB) + LPF₂(-21dB)
  365. // + CompNotch(-60dB) → broadband floor -42dB, exact 19kHz >-90dB
  366. ceiling := lp.LimiterCeiling
  367. if ceiling <= 0 { ceiling = 1.0 }
  368. // Pilot and RDS are FIXED injection levels, independent of OutputDrive.
  369. // Config values directly represent percentage of ±75kHz deviation:
  370. // pilotLevel: 0.09 = 9% = ±6.75kHz (ITU standard)
  371. // rdsInjection: 0.04 = 4% = ±3.0kHz (typical)
  372. pilotAmp := lp.PilotLevel
  373. rdsAmp := lp.RDSInjection
  374. // BS.412 MPX power limiter: uses previous chunk's measurement to set gain.
  375. // Power is measured during this chunk and fed back at the end.
  376. bs412Gain := 1.0
  377. var bs412PowerAccum float64
  378. if g.bs412 != nil {
  379. bs412Gain = g.bs412.CurrentGain()
  380. }
  381. if g.licenseState != nil {
  382. g.licenseState.Tick()
  383. }
  384. for i := 0; i < samples; i++ {
  385. in := g.source.NextFrame()
  386. // --- Stage 1: Band-limit pre-emphasized audio ---
  387. l := g.audioLPF_L.Process(float64(in.L))
  388. l = g.pilotNotchL.Process(l)
  389. r := g.audioLPF_R.Process(float64(in.R))
  390. r = g.pilotNotchR.Process(r)
  391. // --- Stage 2: Drive + Compress + Clip₁ ---
  392. l *= lp.OutputDrive
  393. r *= lp.OutputDrive
  394. if g.limiter != nil {
  395. l, r = g.limiter.Process(l, r)
  396. }
  397. l = dsp.HardClip(l, ceiling)
  398. r = dsp.HardClip(r, ceiling)
  399. // --- Stage 3: Cleanup LPF + Clip₂ (overshoot compensator) ---
  400. l = g.cleanupLPF_L.Process(l)
  401. r = g.cleanupLPF_R.Process(r)
  402. l = dsp.HardClip(l, ceiling)
  403. r = dsp.HardClip(r, ceiling)
  404. lBuf[i] = l
  405. rBuf[i] = r
  406. }
  407. // --- STFT Watermark: decimate → embed → upsample → add to L/R ---
  408. if g.stftEmbedder != nil {
  409. decimFactor := int(g.sampleRate) / watermark.WMRate // 228000/12000 = 19
  410. if decimFactor < 1 {
  411. decimFactor = 1
  412. }
  413. nDown := samples / decimFactor
  414. // Anti-alias: LPF ALL composite-rate samples, THEN decimate.
  415. // The LPF must see every sample for correct IIR state update.
  416. mono12k := make([]float64, nDown)
  417. lpfState := 0.0
  418. decimCount := 0
  419. outIdx := 0
  420. for i := 0; i < samples && outIdx < nDown; i++ {
  421. mono := (lBuf[i] + rBuf[i]) / 2
  422. if g.wmDecimLPF != nil {
  423. lpfState = g.wmDecimLPF.Process(mono)
  424. } else {
  425. lpfState = mono
  426. }
  427. decimCount++
  428. if decimCount >= decimFactor {
  429. decimCount = 0
  430. mono12k[outIdx] = lpfState
  431. outIdx++
  432. }
  433. }
  434. // STFT embed at 12 kHz
  435. embedded := g.stftEmbedder.ProcessBlock(mono12k)
  436. // Extract watermark signal (difference) and upsample via ZOH + LPF.
  437. // ZOH creates spectral images at 12k, 24k, 36k... Hz.
  438. // The interpolation LPF removes these, keeping only 0-5.5 kHz.
  439. // Without this, the images leak into pilot (19k) and stereo sub (38k).
  440. for i := 0; i < samples; i++ {
  441. wmIdx := i / decimFactor
  442. if wmIdx >= nDown {
  443. wmIdx = nDown - 1
  444. }
  445. wmSig := embedded[wmIdx] - mono12k[wmIdx]
  446. if g.wmInterpLPF != nil {
  447. wmSig = g.wmInterpLPF.Process(wmSig)
  448. }
  449. lBuf[i] += wmSig
  450. rBuf[i] += wmSig
  451. }
  452. }
  453. // --- Pass 2: Stereo encode + composite processing ---
  454. for i := 0; i < samples; i++ {
  455. l := lBuf[i]
  456. r := rBuf[i]
  457. // --- Stage 4: Stereo encode ---
  458. limited := audio.NewFrame(audio.Sample(l), audio.Sample(r))
  459. comps := g.stereoEncoder.Encode(limited)
  460. // --- Stage 5: Composite clip + protection ---
  461. audioMPX := float64(comps.Mono)
  462. if lp.StereoEnabled {
  463. audioMPX += float64(comps.Stereo)
  464. }
  465. if lp.CompositeClipperEnabled && g.compositeClip != nil {
  466. // ITU-R SM.1268 iterative clipper: look-ahead + N×(clip→notch→notch) + final clip
  467. audioMPX = g.compositeClip.Process(audioMPX)
  468. } else {
  469. // Legacy single-pass: one clip, then notch, no final safety clip
  470. audioMPX = dsp.HardClip(audioMPX, ceiling)
  471. audioMPX = g.mpxNotch19.Process(audioMPX)
  472. audioMPX = g.mpxNotch57.Process(audioMPX)
  473. }
  474. // BS.412: apply gain and measure power
  475. if bs412Gain < 1.0 {
  476. audioMPX *= bs412Gain
  477. }
  478. bs412PowerAccum += audioMPX * audioMPX
  479. // --- Stage 6: Add protected components ---
  480. composite := audioMPX
  481. if lp.StereoEnabled {
  482. composite += pilotAmp * comps.Pilot
  483. }
  484. if g.rdsEnc != nil && lp.RDSEnabled {
  485. rdsCarrier := g.stereoEncoder.RDSCarrier()
  486. rdsValue := g.rdsEnc.NextSampleWithCarrier(rdsCarrier)
  487. composite += rdsAmp * rdsValue
  488. }
  489. // Jingle: injected when unlicensed, bypasses drive/gain controls.
  490. if g.licenseState != nil && len(g.jingleFrames) > 0 {
  491. composite += g.licenseState.NextSample(g.jingleFrames)
  492. }
  493. if g.fmMod != nil {
  494. iq_i, iq_q := g.fmMod.Modulate(composite)
  495. frame.Samples[i] = output.IQSample{I: float32(iq_i), Q: float32(iq_q)}
  496. } else {
  497. frame.Samples[i] = output.IQSample{I: float32(composite), Q: 0}
  498. }
  499. }
  500. // BS.412: feed this chunk's actual duration and average audio power for
  501. // the next chunk's gain calculation. Using the real sample count avoids
  502. // the error that occurred when chunkSec was hardcoded to 0.05 — any
  503. // SetChunkDuration() call from the engine would silently miscalibrate
  504. // the ITU-R BS.412 power measurement window.
  505. if g.bs412 != nil && samples > 0 {
  506. chunkSec := float64(samples) / g.sampleRate
  507. g.bs412.UpdateChunkDuration(chunkSec)
  508. g.bs412.ProcessChunk(bs412PowerAccum / float64(samples))
  509. }
  510. return frame
  511. }
  512. func (g *Generator) WriteFile(path string, duration time.Duration) error {
  513. if path == "" {
  514. path = g.cfg.Backend.OutputPath
  515. }
  516. if path == "" {
  517. path = filepath.Join("build", "offline", "composite.iqf32")
  518. }
  519. backend, err := output.NewFileBackend(path, binary.LittleEndian, output.BackendInfo{
  520. Name: "offline-file",
  521. Description: "offline composite file backend",
  522. })
  523. if err != nil {
  524. return err
  525. }
  526. defer backend.Close(context.Background())
  527. if err := backend.Configure(context.Background(), output.BackendConfig{
  528. SampleRateHz: float64(g.cfg.FM.CompositeRateHz),
  529. Channels: 2,
  530. IQLevel: float32(g.cfg.FM.OutputDrive),
  531. }); err != nil {
  532. return err
  533. }
  534. frame := g.GenerateFrame(duration)
  535. if _, err := backend.Write(context.Background(), frame); err != nil {
  536. return err
  537. }
  538. return backend.Flush(context.Background())
  539. }
  540. func (g *Generator) Summary(duration time.Duration) string {
  541. sampleRate := float64(g.cfg.FM.CompositeRateHz)
  542. if sampleRate <= 0 {
  543. sampleRate = 228000
  544. }
  545. _, info := g.sourceFor(sampleRate)
  546. preemph := "off"
  547. if g.cfg.FM.PreEmphasisTauUS > 0 {
  548. preemph = fmt.Sprintf("%.0fµs", g.cfg.FM.PreEmphasisTauUS)
  549. }
  550. modMode := "composite"
  551. if g.cfg.FM.FMModulationEnabled {
  552. modMode = fmt.Sprintf("FM-IQ(±%.0fHz)", g.cfg.FM.MaxDeviationHz)
  553. }
  554. 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",
  555. g.cfg.FM.FrequencyMHz, g.cfg.FM.CompositeRateHz, duration.String(),
  556. g.cfg.FM.OutputDrive, g.cfg.FM.StereoEnabled, g.cfg.RDS.Enabled,
  557. preemph, g.cfg.FM.LimiterEnabled, modMode, info.Kind, info.Detail)
  558. }