Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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