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

221 řádky
6.5KB

  1. package offline
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "path/filepath"
  7. "time"
  8. "github.com/jan/fm-rds-tx/internal/audio"
  9. cfgpkg "github.com/jan/fm-rds-tx/internal/config"
  10. "github.com/jan/fm-rds-tx/internal/dsp"
  11. "github.com/jan/fm-rds-tx/internal/mpx"
  12. "github.com/jan/fm-rds-tx/internal/output"
  13. "github.com/jan/fm-rds-tx/internal/rds"
  14. "github.com/jan/fm-rds-tx/internal/stereo"
  15. )
  16. type frameSource interface {
  17. NextFrame() audio.Frame
  18. }
  19. // PreEmphasizedSource wraps an audio source and applies pre-emphasis.
  20. // The source is expected to already output at composite rate (resampled
  21. // upstream). Pre-emphasis is applied per-sample at that rate.
  22. type PreEmphasizedSource struct {
  23. src frameSource
  24. preL *dsp.PreEmphasis
  25. preR *dsp.PreEmphasis
  26. gain float64
  27. }
  28. func NewPreEmphasizedSource(src frameSource, tauUS, sampleRate, gain float64) *PreEmphasizedSource {
  29. p := &PreEmphasizedSource{src: src, gain: gain}
  30. if tauUS > 0 {
  31. p.preL = dsp.NewPreEmphasis(tauUS, sampleRate)
  32. p.preR = dsp.NewPreEmphasis(tauUS, sampleRate)
  33. }
  34. return p
  35. }
  36. func (p *PreEmphasizedSource) NextFrame() audio.Frame {
  37. f := p.src.NextFrame()
  38. l := float64(f.L) * p.gain
  39. r := float64(f.R) * p.gain
  40. if p.preL != nil {
  41. l = p.preL.Process(l)
  42. r = p.preR.Process(r)
  43. }
  44. return audio.NewFrame(audio.Sample(l), audio.Sample(r))
  45. }
  46. type SourceInfo struct {
  47. Kind string
  48. SampleRate float64
  49. Detail string
  50. }
  51. type Generator struct {
  52. cfg cfgpkg.Config
  53. // Persistent DSP state across GenerateFrame calls
  54. source *PreEmphasizedSource
  55. stereoEncoder stereo.StereoEncoder
  56. rdsEnc *rds.Encoder
  57. combiner mpx.DefaultCombiner
  58. limiter *dsp.MPXLimiter
  59. fmMod *dsp.FMModulator
  60. sampleRate float64
  61. initialized bool
  62. frameSeq uint64
  63. }
  64. func NewGenerator(cfg cfgpkg.Config) *Generator {
  65. return &Generator{cfg: cfg}
  66. }
  67. func (g *Generator) init() {
  68. if g.initialized {
  69. return
  70. }
  71. g.sampleRate = float64(g.cfg.FM.CompositeRateHz)
  72. if g.sampleRate <= 0 {
  73. g.sampleRate = 228000
  74. }
  75. rawSource, _ := g.sourceFor(g.sampleRate)
  76. g.source = NewPreEmphasizedSource(rawSource, g.cfg.FM.PreEmphasisTauUS, g.sampleRate, g.cfg.Audio.Gain)
  77. g.stereoEncoder = stereo.NewStereoEncoder(g.sampleRate)
  78. g.combiner = mpx.DefaultCombiner{
  79. MonoGain: 1.0, StereoGain: 1.0,
  80. PilotGain: g.cfg.FM.PilotLevel, RDSGain: g.cfg.FM.RDSInjection,
  81. }
  82. if g.cfg.RDS.Enabled {
  83. piCode, _ := cfgpkg.ParsePI(g.cfg.RDS.PI)
  84. g.rdsEnc, _ = rds.NewEncoder(rds.RDSConfig{
  85. PI: piCode, PS: g.cfg.RDS.PS, RT: g.cfg.RDS.RadioText,
  86. PTY: uint8(g.cfg.RDS.PTY), SampleRate: g.sampleRate,
  87. })
  88. }
  89. ceiling := g.cfg.FM.LimiterCeiling
  90. if ceiling <= 0 { ceiling = 1.0 }
  91. if g.cfg.FM.LimiterEnabled {
  92. g.limiter = dsp.NewMPXLimiter(ceiling, 0.1, 50, g.sampleRate)
  93. }
  94. if g.cfg.FM.FMModulationEnabled {
  95. g.fmMod = dsp.NewFMModulator(g.sampleRate)
  96. if g.cfg.FM.MaxDeviationHz > 0 { g.fmMod.MaxDeviation = g.cfg.FM.MaxDeviationHz }
  97. }
  98. g.initialized = true
  99. }
  100. func (g *Generator) sourceFor(sampleRate float64) (frameSource, SourceInfo) {
  101. if g.cfg.Audio.InputPath != "" {
  102. if src, err := audio.LoadWAVSource(g.cfg.Audio.InputPath); err == nil {
  103. return audio.NewResampledSource(src, sampleRate), SourceInfo{Kind: "wav", SampleRate: float64(src.SampleRate), Detail: g.cfg.Audio.InputPath}
  104. }
  105. return audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude), SourceInfo{Kind: "tone-fallback", SampleRate: sampleRate, Detail: g.cfg.Audio.InputPath}
  106. }
  107. return audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude), SourceInfo{Kind: "tones", SampleRate: sampleRate, Detail: "generated"}
  108. }
  109. func (g *Generator) GenerateFrame(duration time.Duration) *output.CompositeFrame {
  110. g.init()
  111. samples := int(duration.Seconds() * g.sampleRate)
  112. if samples <= 0 { samples = int(g.sampleRate / 10) }
  113. g.frameSeq++
  114. frame := &output.CompositeFrame{
  115. Samples: make([]output.IQSample, samples),
  116. SampleRateHz: g.sampleRate,
  117. Timestamp: time.Now().UTC(),
  118. Sequence: g.frameSeq,
  119. }
  120. ceiling := g.cfg.FM.LimiterCeiling
  121. if ceiling <= 0 { ceiling = 1.0 }
  122. for i := 0; i < samples; i++ {
  123. in := g.source.NextFrame()
  124. comps := g.stereoEncoder.Encode(in)
  125. if !g.cfg.FM.StereoEnabled {
  126. comps.Stereo = 0; comps.Pilot = 0
  127. }
  128. rdsValue := 0.0
  129. if g.rdsEnc != nil {
  130. rdsCarrier := g.stereoEncoder.RDSCarrier()
  131. rdsValue = g.rdsEnc.NextSampleWithCarrier(rdsCarrier)
  132. }
  133. composite := g.combiner.Combine(comps.Mono, comps.Stereo, comps.Pilot, rdsValue)
  134. composite *= g.cfg.FM.OutputDrive
  135. if g.limiter != nil {
  136. composite = g.limiter.Process(composite)
  137. composite = dsp.HardClip(composite, ceiling)
  138. }
  139. if g.fmMod != nil {
  140. iq_i, iq_q := g.fmMod.Modulate(composite)
  141. frame.Samples[i] = output.IQSample{I: float32(iq_i), Q: float32(iq_q)}
  142. } else {
  143. frame.Samples[i] = output.IQSample{I: float32(composite), Q: 0}
  144. }
  145. }
  146. return frame
  147. }
  148. func (g *Generator) WriteFile(path string, duration time.Duration) error {
  149. if path == "" {
  150. path = g.cfg.Backend.OutputPath
  151. }
  152. if path == "" {
  153. path = filepath.Join("build", "offline", "composite.iqf32")
  154. }
  155. backend, err := output.NewFileBackend(path, binary.LittleEndian, output.BackendInfo{
  156. Name: "offline-file",
  157. Description: "offline composite file backend",
  158. })
  159. if err != nil {
  160. return err
  161. }
  162. defer backend.Close(context.Background())
  163. if err := backend.Configure(context.Background(), output.BackendConfig{
  164. SampleRateHz: float64(g.cfg.FM.CompositeRateHz),
  165. Channels: 2,
  166. IQLevel: float32(g.cfg.FM.OutputDrive),
  167. }); err != nil {
  168. return err
  169. }
  170. frame := g.GenerateFrame(duration)
  171. if _, err := backend.Write(context.Background(), frame); err != nil {
  172. return err
  173. }
  174. return backend.Flush(context.Background())
  175. }
  176. func (g *Generator) Summary(duration time.Duration) string {
  177. sampleRate := float64(g.cfg.FM.CompositeRateHz)
  178. if sampleRate <= 0 {
  179. sampleRate = 228000
  180. }
  181. _, info := g.sourceFor(sampleRate)
  182. preemph := "off"
  183. if g.cfg.FM.PreEmphasisTauUS > 0 {
  184. preemph = fmt.Sprintf("%.0fµs", g.cfg.FM.PreEmphasisTauUS)
  185. }
  186. modMode := "composite"
  187. if g.cfg.FM.FMModulationEnabled {
  188. modMode = fmt.Sprintf("FM-IQ(±%.0fHz)", g.cfg.FM.MaxDeviationHz)
  189. }
  190. 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",
  191. g.cfg.FM.FrequencyMHz, g.cfg.FM.CompositeRateHz, duration.String(),
  192. g.cfg.FM.OutputDrive, g.cfg.FM.StereoEnabled, g.cfg.RDS.Enabled,
  193. preemph, g.cfg.FM.LimiterEnabled, modMode, info.Kind, info.Detail)
  194. }