Go-based FM stereo transmitter with RDS, Windows-first and cross-platform
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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