Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

597 строки
20KB

  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. g.rdsEnc, _ = rds.NewEncoder(rds.RDSConfig{
  185. PI: piCode, PS: g.cfg.RDS.PS, RT: g.cfg.RDS.RadioText,
  186. PTY: uint8(g.cfg.RDS.PTY), SampleRate: g.sampleRate,
  187. })
  188. }
  189. ceiling := g.cfg.FM.LimiterCeiling
  190. if ceiling <= 0 { ceiling = 1.0 }
  191. // Broadcast clip-filter-clip chain:
  192. // Pre-clip: 14kHz LPF (8th-order) + 19kHz double-notch (per channel)
  193. g.audioLPF_L = dsp.NewAudioLPF(g.sampleRate)
  194. g.audioLPF_R = dsp.NewAudioLPF(g.sampleRate)
  195. g.pilotNotchL = dsp.NewPilotNotch(g.sampleRate)
  196. g.pilotNotchR = dsp.NewPilotNotch(g.sampleRate)
  197. // Slow compressor: 5ms attack / 200ms release. Brings average level UP.
  198. // The clips after it catch the peaks the limiter's attack time misses.
  199. // This is the "slow-to-fast progression" from broadcast processing:
  200. // slow limiter → fast clips.
  201. // Burst-masking-optimized limiter (Bonello, JAES 2007):
  202. // 2ms attack lets initial transient peaks clip for <5ms (burst-masked).
  203. // 150ms release avoids audible pumping on sustained passages.
  204. g.limiter = dsp.NewStereoLimiter(ceiling, 2, 150, g.sampleRate)
  205. // Post-clip cleanup: second 14kHz LPF pass (removes clip harmonics)
  206. g.cleanupLPF_L = dsp.NewAudioLPF(g.sampleRate)
  207. g.cleanupLPF_R = dsp.NewAudioLPF(g.sampleRate)
  208. // Composite clipper protection: double-notch at 19kHz + 57kHz
  209. g.mpxNotch19, g.mpxNotch57 = dsp.NewCompositeProtection(g.sampleRate)
  210. // ITU-R SM.1268 iterative composite clipper (optional, replaces simple clip+notch)
  211. // Always created so it can be live-toggled via CompositeClipperEnabled.
  212. g.compositeClip = dsp.NewCompositeClipper(dsp.CompositeClipperConfig{
  213. Ceiling: ceiling,
  214. Iterations: g.cfg.FM.CompositeClipper.Iterations,
  215. SoftKnee: g.cfg.FM.CompositeClipper.SoftKnee,
  216. LookaheadMs: g.cfg.FM.CompositeClipper.LookaheadMs,
  217. SampleRate: g.sampleRate,
  218. })
  219. // BS.412 MPX power limiter (EU/CH requirement for licensed FM)
  220. if g.cfg.FM.BS412Enabled {
  221. // chunkSec is not known at init time (Engine.chunkDuration may differ).
  222. // Pass 0 here; GenerateFrame computes the actual chunk duration from
  223. // the real sample count and updates BS.412 accordingly.
  224. g.bs412 = dsp.NewBS412Limiter(
  225. g.cfg.FM.BS412ThresholdDBr,
  226. g.cfg.FM.PilotLevel,
  227. g.cfg.FM.RDSInjection,
  228. 0,
  229. )
  230. }
  231. if g.cfg.FM.FMModulationEnabled {
  232. g.fmMod = dsp.NewFMModulator(g.sampleRate)
  233. maxDev := g.cfg.FM.MaxDeviationHz
  234. if maxDev > 0 {
  235. if g.cfg.FM.MpxGain > 0 && g.cfg.FM.MpxGain != 1.0 {
  236. maxDev *= g.cfg.FM.MpxGain
  237. }
  238. g.fmMod.MaxDeviation = maxDev
  239. }
  240. }
  241. // Seed initial live params from config
  242. g.liveParams.Store(&LiveParams{
  243. OutputDrive: g.cfg.FM.OutputDrive,
  244. StereoEnabled: g.cfg.FM.StereoEnabled,
  245. StereoMode: g.cfg.FM.StereoMode,
  246. PilotLevel: g.cfg.FM.PilotLevel,
  247. RDSInjection: g.cfg.FM.RDSInjection,
  248. RDSEnabled: g.cfg.RDS.Enabled,
  249. LimiterEnabled: g.cfg.FM.LimiterEnabled,
  250. LimiterCeiling: ceiling,
  251. MpxGain: g.cfg.FM.MpxGain,
  252. ToneLeftHz: g.cfg.Audio.ToneLeftHz,
  253. ToneRightHz: g.cfg.Audio.ToneRightHz,
  254. ToneAmplitude: g.cfg.Audio.ToneAmplitude,
  255. AudioGain: g.cfg.Audio.Gain,
  256. CompositeClipperEnabled: g.cfg.FM.CompositeClipper.Enabled,
  257. })
  258. if g.licenseState != nil {
  259. frames, err := license.LoadJingleFrames(license.JingleWAV(), g.sampleRate)
  260. if err != nil {
  261. log.Printf("license: jingle load failed: %v", err)
  262. } else {
  263. g.jingleFrames = frames
  264. }
  265. }
  266. // STFT watermark: anti-alias LPF for decimation to WMRate (12 kHz).
  267. // Nyquist at 12 kHz = 6 kHz. Cut at 5.5 kHz with margin.
  268. if g.stftEmbedder != nil {
  269. g.wmDecimLPF = dsp.NewLPF4(5500, g.sampleRate)
  270. g.wmInterpLPF = dsp.NewLPF4(5500, g.sampleRate) // separate instance for upsample
  271. }
  272. g.initialized = true
  273. }
  274. func (g *Generator) sourceFor(sampleRate float64) (frameSource, SourceInfo) {
  275. if g.externalSource != nil {
  276. return g.externalSource, SourceInfo{Kind: "stream", SampleRate: sampleRate, Detail: "live audio"}
  277. }
  278. if g.cfg.Audio.InputPath != "" {
  279. if src, err := audio.LoadWAVSource(g.cfg.Audio.InputPath); err == nil {
  280. return audio.NewResampledSource(src, sampleRate), SourceInfo{Kind: "wav", SampleRate: float64(src.SampleRate), Detail: g.cfg.Audio.InputPath}
  281. }
  282. ts := audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude)
  283. g.toneSource = ts
  284. return ts, SourceInfo{Kind: "tone-fallback", SampleRate: sampleRate, Detail: g.cfg.Audio.InputPath}
  285. }
  286. ts := audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude)
  287. g.toneSource = ts
  288. return ts, SourceInfo{Kind: "tones", SampleRate: sampleRate, Detail: "generated"}
  289. }
  290. func (g *Generator) GenerateFrame(duration time.Duration) *output.CompositeFrame {
  291. g.init()
  292. samples := int(duration.Seconds() * g.sampleRate)
  293. if samples <= 0 { samples = int(g.sampleRate / 10) }
  294. // Reuse buffer — grow only if needed, never shrink
  295. if g.frameBuf == nil || g.bufCap < samples {
  296. g.frameBuf = &output.CompositeFrame{
  297. Samples: make([]output.IQSample, samples),
  298. }
  299. g.bufCap = samples
  300. }
  301. frame := g.frameBuf
  302. frame.Samples = frame.Samples[:samples]
  303. frame.SampleRateHz = g.sampleRate
  304. frame.Timestamp = time.Now().UTC()
  305. g.frameSeq++
  306. frame.Sequence = g.frameSeq
  307. // L/R buffers for two-pass processing (STFT watermark between stages 3 and 4)
  308. lBuf := make([]float64, samples)
  309. rBuf := make([]float64, samples)
  310. // Load live params once per chunk — single atomic read, zero per-sample cost
  311. lp := g.liveParams.Load()
  312. if lp == nil {
  313. // Fallback: should never happen after init(), but be safe
  314. lp = &LiveParams{OutputDrive: 1.0, LimiterCeiling: 1.0, MpxGain: 1.0}
  315. }
  316. // Apply live tone and gain updates each chunk. GenerateFrame runs on a
  317. // single goroutine so these field writes are safe without additional locking.
  318. if g.toneSource != nil {
  319. g.toneSource.LeftFreq = lp.ToneLeftHz
  320. g.toneSource.RightFreq = lp.ToneRightHz
  321. g.toneSource.Amplitude = lp.ToneAmplitude
  322. }
  323. if g.source != nil {
  324. g.source.gain = lp.AudioGain
  325. }
  326. // Broadcast clip-filter-clip FM MPX signal chain:
  327. //
  328. // Audio L/R → PreEmphasis
  329. // → LPF₁ (14kHz, 8th-order) → 19kHz Notch (double)
  330. // → × OutputDrive → HardClip₁ (ceiling)
  331. // → LPF₂ (14kHz, 8th-order) [removes clip₁ harmonics]
  332. // → HardClip₂ (ceiling) [catches LPF₂ overshoots]
  333. // → Stereo Encode
  334. // Audio MPX (mono + stereo sub)
  335. // → HardClip₃ (ceiling) [composite deviation control]
  336. // → 19kHz Notch (double) [protect pilot band]
  337. // → 57kHz Notch (double) [protect RDS band]
  338. // + Pilot 19kHz (fixed, NEVER clipped)
  339. // + RDS 57kHz (fixed, NEVER clipped)
  340. // → FM Modulator
  341. //
  342. // Guard band depth at 19kHz: LPF₁(-21dB) + Notch(-60dB) + LPF₂(-21dB)
  343. // + CompNotch(-60dB) → broadband floor -42dB, exact 19kHz >-90dB
  344. ceiling := lp.LimiterCeiling
  345. if ceiling <= 0 { ceiling = 1.0 }
  346. // Pilot and RDS are FIXED injection levels, independent of OutputDrive.
  347. // Config values directly represent percentage of ±75kHz deviation:
  348. // pilotLevel: 0.09 = 9% = ±6.75kHz (ITU standard)
  349. // rdsInjection: 0.04 = 4% = ±3.0kHz (typical)
  350. pilotAmp := lp.PilotLevel
  351. rdsAmp := lp.RDSInjection
  352. // BS.412 MPX power limiter: uses previous chunk's measurement to set gain.
  353. // Power is measured during this chunk and fed back at the end.
  354. bs412Gain := 1.0
  355. var bs412PowerAccum float64
  356. if g.bs412 != nil {
  357. bs412Gain = g.bs412.CurrentGain()
  358. }
  359. if g.licenseState != nil {
  360. g.licenseState.Tick()
  361. }
  362. for i := 0; i < samples; i++ {
  363. in := g.source.NextFrame()
  364. // --- Stage 1: Band-limit pre-emphasized audio ---
  365. l := g.audioLPF_L.Process(float64(in.L))
  366. l = g.pilotNotchL.Process(l)
  367. r := g.audioLPF_R.Process(float64(in.R))
  368. r = g.pilotNotchR.Process(r)
  369. // --- Stage 2: Drive + Compress + Clip₁ ---
  370. l *= lp.OutputDrive
  371. r *= lp.OutputDrive
  372. if g.limiter != nil {
  373. l, r = g.limiter.Process(l, r)
  374. }
  375. l = dsp.HardClip(l, ceiling)
  376. r = dsp.HardClip(r, ceiling)
  377. // --- Stage 3: Cleanup LPF + Clip₂ (overshoot compensator) ---
  378. l = g.cleanupLPF_L.Process(l)
  379. r = g.cleanupLPF_R.Process(r)
  380. l = dsp.HardClip(l, ceiling)
  381. r = dsp.HardClip(r, ceiling)
  382. lBuf[i] = l
  383. rBuf[i] = r
  384. }
  385. // --- STFT Watermark: decimate → embed → upsample → add to L/R ---
  386. if g.stftEmbedder != nil {
  387. decimFactor := int(g.sampleRate) / watermark.WMRate // 228000/12000 = 19
  388. if decimFactor < 1 {
  389. decimFactor = 1
  390. }
  391. nDown := samples / decimFactor
  392. // Anti-alias: LPF ALL composite-rate samples, THEN decimate.
  393. // The LPF must see every sample for correct IIR state update.
  394. mono12k := make([]float64, nDown)
  395. lpfState := 0.0
  396. decimCount := 0
  397. outIdx := 0
  398. for i := 0; i < samples && outIdx < nDown; i++ {
  399. mono := (lBuf[i] + rBuf[i]) / 2
  400. if g.wmDecimLPF != nil {
  401. lpfState = g.wmDecimLPF.Process(mono)
  402. } else {
  403. lpfState = mono
  404. }
  405. decimCount++
  406. if decimCount >= decimFactor {
  407. decimCount = 0
  408. mono12k[outIdx] = lpfState
  409. outIdx++
  410. }
  411. }
  412. // STFT embed at 12 kHz
  413. embedded := g.stftEmbedder.ProcessBlock(mono12k)
  414. // Extract watermark signal (difference) and upsample via ZOH + LPF.
  415. // ZOH creates spectral images at 12k, 24k, 36k... Hz.
  416. // The interpolation LPF removes these, keeping only 0-5.5 kHz.
  417. // Without this, the images leak into pilot (19k) and stereo sub (38k).
  418. for i := 0; i < samples; i++ {
  419. wmIdx := i / decimFactor
  420. if wmIdx >= nDown {
  421. wmIdx = nDown - 1
  422. }
  423. wmSig := embedded[wmIdx] - mono12k[wmIdx]
  424. if g.wmInterpLPF != nil {
  425. wmSig = g.wmInterpLPF.Process(wmSig)
  426. }
  427. lBuf[i] += wmSig
  428. rBuf[i] += wmSig
  429. }
  430. }
  431. // --- Pass 2: Stereo encode + composite processing ---
  432. for i := 0; i < samples; i++ {
  433. l := lBuf[i]
  434. r := rBuf[i]
  435. // --- Stage 4: Stereo encode ---
  436. limited := audio.NewFrame(audio.Sample(l), audio.Sample(r))
  437. comps := g.stereoEncoder.Encode(limited)
  438. // --- Stage 5: Composite clip + protection ---
  439. audioMPX := float64(comps.Mono)
  440. if lp.StereoEnabled {
  441. audioMPX += float64(comps.Stereo)
  442. }
  443. if lp.CompositeClipperEnabled && g.compositeClip != nil {
  444. // ITU-R SM.1268 iterative clipper: look-ahead + N×(clip→notch→notch) + final clip
  445. audioMPX = g.compositeClip.Process(audioMPX)
  446. } else {
  447. // Legacy single-pass: one clip, then notch, no final safety clip
  448. audioMPX = dsp.HardClip(audioMPX, ceiling)
  449. audioMPX = g.mpxNotch19.Process(audioMPX)
  450. audioMPX = g.mpxNotch57.Process(audioMPX)
  451. }
  452. // BS.412: apply gain and measure power
  453. if bs412Gain < 1.0 {
  454. audioMPX *= bs412Gain
  455. }
  456. bs412PowerAccum += audioMPX * audioMPX
  457. // --- Stage 6: Add protected components ---
  458. composite := audioMPX
  459. if lp.StereoEnabled {
  460. composite += pilotAmp * comps.Pilot
  461. }
  462. if g.rdsEnc != nil && lp.RDSEnabled {
  463. rdsCarrier := g.stereoEncoder.RDSCarrier()
  464. rdsValue := g.rdsEnc.NextSampleWithCarrier(rdsCarrier)
  465. composite += rdsAmp * rdsValue
  466. }
  467. // Jingle: injected when unlicensed, bypasses drive/gain controls.
  468. if g.licenseState != nil && len(g.jingleFrames) > 0 {
  469. composite += g.licenseState.NextSample(g.jingleFrames)
  470. }
  471. if g.fmMod != nil {
  472. iq_i, iq_q := g.fmMod.Modulate(composite)
  473. frame.Samples[i] = output.IQSample{I: float32(iq_i), Q: float32(iq_q)}
  474. } else {
  475. frame.Samples[i] = output.IQSample{I: float32(composite), Q: 0}
  476. }
  477. }
  478. // BS.412: feed this chunk's actual duration and average audio power for
  479. // the next chunk's gain calculation. Using the real sample count avoids
  480. // the error that occurred when chunkSec was hardcoded to 0.05 — any
  481. // SetChunkDuration() call from the engine would silently miscalibrate
  482. // the ITU-R BS.412 power measurement window.
  483. if g.bs412 != nil && samples > 0 {
  484. chunkSec := float64(samples) / g.sampleRate
  485. g.bs412.UpdateChunkDuration(chunkSec)
  486. g.bs412.ProcessChunk(bs412PowerAccum / float64(samples))
  487. }
  488. return frame
  489. }
  490. func (g *Generator) WriteFile(path string, duration time.Duration) error {
  491. if path == "" {
  492. path = g.cfg.Backend.OutputPath
  493. }
  494. if path == "" {
  495. path = filepath.Join("build", "offline", "composite.iqf32")
  496. }
  497. backend, err := output.NewFileBackend(path, binary.LittleEndian, output.BackendInfo{
  498. Name: "offline-file",
  499. Description: "offline composite file backend",
  500. })
  501. if err != nil {
  502. return err
  503. }
  504. defer backend.Close(context.Background())
  505. if err := backend.Configure(context.Background(), output.BackendConfig{
  506. SampleRateHz: float64(g.cfg.FM.CompositeRateHz),
  507. Channels: 2,
  508. IQLevel: float32(g.cfg.FM.OutputDrive),
  509. }); err != nil {
  510. return err
  511. }
  512. frame := g.GenerateFrame(duration)
  513. if _, err := backend.Write(context.Background(), frame); err != nil {
  514. return err
  515. }
  516. return backend.Flush(context.Background())
  517. }
  518. func (g *Generator) Summary(duration time.Duration) string {
  519. sampleRate := float64(g.cfg.FM.CompositeRateHz)
  520. if sampleRate <= 0 {
  521. sampleRate = 228000
  522. }
  523. _, info := g.sourceFor(sampleRate)
  524. preemph := "off"
  525. if g.cfg.FM.PreEmphasisTauUS > 0 {
  526. preemph = fmt.Sprintf("%.0fµs", g.cfg.FM.PreEmphasisTauUS)
  527. }
  528. modMode := "composite"
  529. if g.cfg.FM.FMModulationEnabled {
  530. modMode = fmt.Sprintf("FM-IQ(±%.0fHz)", g.cfg.FM.MaxDeviationHz)
  531. }
  532. 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",
  533. g.cfg.FM.FrequencyMHz, g.cfg.FM.CompositeRateHz, duration.String(),
  534. g.cfg.FM.OutputDrive, g.cfg.FM.StereoEnabled, g.cfg.RDS.Enabled,
  535. preemph, g.cfg.FM.LimiterEnabled, modMode, info.Kind, info.Detail)
  536. }