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

218 строки
6.4KB

  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 at the
  20. // audio input rate, before upsampling to composite rate. This is more
  21. // efficient than filtering at composite rate and is the correct signal path.
  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. }
  63. func NewGenerator(cfg cfgpkg.Config) *Generator {
  64. return &Generator{cfg: cfg}
  65. }
  66. func (g *Generator) init() {
  67. if g.initialized {
  68. return
  69. }
  70. g.sampleRate = float64(g.cfg.FM.CompositeRateHz)
  71. if g.sampleRate <= 0 {
  72. g.sampleRate = 228000
  73. }
  74. rawSource, _ := g.sourceFor(g.sampleRate)
  75. g.source = NewPreEmphasizedSource(rawSource, g.cfg.FM.PreEmphasisTauUS, g.sampleRate, g.cfg.Audio.Gain)
  76. g.stereoEncoder = stereo.NewStereoEncoder(g.sampleRate)
  77. g.combiner = mpx.DefaultCombiner{
  78. MonoGain: 1.0, StereoGain: 1.0,
  79. PilotGain: g.cfg.FM.PilotLevel, RDSGain: g.cfg.FM.RDSInjection,
  80. }
  81. if g.cfg.RDS.Enabled {
  82. piCode, _ := cfgpkg.ParsePI(g.cfg.RDS.PI)
  83. g.rdsEnc, _ = rds.NewEncoder(rds.RDSConfig{
  84. PI: piCode, PS: g.cfg.RDS.PS, RT: g.cfg.RDS.RadioText,
  85. PTY: uint8(g.cfg.RDS.PTY), SampleRate: g.sampleRate,
  86. })
  87. }
  88. ceiling := g.cfg.FM.LimiterCeiling
  89. if ceiling <= 0 { ceiling = 1.0 }
  90. if g.cfg.FM.LimiterEnabled {
  91. g.limiter = dsp.NewMPXLimiter(ceiling, 0.1, 50, g.sampleRate)
  92. }
  93. if g.cfg.FM.FMModulationEnabled {
  94. g.fmMod = dsp.NewFMModulator(g.sampleRate)
  95. if g.cfg.FM.MaxDeviationHz > 0 { g.fmMod.MaxDeviation = g.cfg.FM.MaxDeviationHz }
  96. }
  97. g.initialized = true
  98. }
  99. func (g *Generator) sourceFor(sampleRate float64) (frameSource, SourceInfo) {
  100. if g.cfg.Audio.InputPath != "" {
  101. if src, err := audio.LoadWAVSource(g.cfg.Audio.InputPath); err == nil {
  102. return audio.NewResampledSource(src, sampleRate), SourceInfo{Kind: "wav", SampleRate: float64(src.SampleRate), Detail: g.cfg.Audio.InputPath}
  103. }
  104. 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}
  105. }
  106. return audio.NewConfiguredToneSource(sampleRate, g.cfg.Audio.ToneLeftHz, g.cfg.Audio.ToneRightHz, g.cfg.Audio.ToneAmplitude), SourceInfo{Kind: "tones", SampleRate: sampleRate, Detail: "generated"}
  107. }
  108. func (g *Generator) GenerateFrame(duration time.Duration) *output.CompositeFrame {
  109. g.init()
  110. samples := int(duration.Seconds() * g.sampleRate)
  111. if samples <= 0 { samples = int(g.sampleRate / 10) }
  112. frame := &output.CompositeFrame{
  113. Samples: make([]output.IQSample, samples),
  114. SampleRateHz: g.sampleRate,
  115. Timestamp: time.Now().UTC(),
  116. Sequence: 1,
  117. }
  118. ceiling := g.cfg.FM.LimiterCeiling
  119. if ceiling <= 0 { ceiling = 1.0 }
  120. for i := 0; i < samples; i++ {
  121. in := g.source.NextFrame()
  122. comps := g.stereoEncoder.Encode(in)
  123. if !g.cfg.FM.StereoEnabled {
  124. comps.Stereo = 0; comps.Pilot = 0
  125. }
  126. rdsValue := 0.0
  127. if g.rdsEnc != nil {
  128. rdsValue = g.rdsEnc.NextSample()
  129. }
  130. composite := g.combiner.Combine(comps.Mono, comps.Stereo, comps.Pilot, rdsValue)
  131. composite *= g.cfg.FM.OutputDrive
  132. if g.limiter != nil {
  133. composite = g.limiter.Process(composite)
  134. composite = dsp.HardClip(composite, ceiling)
  135. }
  136. if g.fmMod != nil {
  137. iq_i, iq_q := g.fmMod.Modulate(composite)
  138. frame.Samples[i] = output.IQSample{I: float32(iq_i), Q: float32(iq_q)}
  139. } else {
  140. frame.Samples[i] = output.IQSample{I: float32(composite), Q: 0}
  141. }
  142. }
  143. return frame
  144. }
  145. func (g *Generator) WriteFile(path string, duration time.Duration) error {
  146. if path == "" {
  147. path = g.cfg.Backend.OutputPath
  148. }
  149. if path == "" {
  150. path = filepath.Join("build", "offline", "composite.iqf32")
  151. }
  152. backend, err := output.NewFileBackend(path, binary.LittleEndian, output.BackendInfo{
  153. Name: "offline-file",
  154. Description: "offline composite file backend",
  155. })
  156. if err != nil {
  157. return err
  158. }
  159. defer backend.Close(context.Background())
  160. if err := backend.Configure(context.Background(), output.BackendConfig{
  161. SampleRateHz: float64(g.cfg.FM.CompositeRateHz),
  162. Channels: 2,
  163. IQLevel: float32(g.cfg.FM.OutputDrive),
  164. }); err != nil {
  165. return err
  166. }
  167. frame := g.GenerateFrame(duration)
  168. if _, err := backend.Write(context.Background(), frame); err != nil {
  169. return err
  170. }
  171. return backend.Flush(context.Background())
  172. }
  173. func (g *Generator) Summary(duration time.Duration) string {
  174. sampleRate := float64(g.cfg.FM.CompositeRateHz)
  175. if sampleRate <= 0 {
  176. sampleRate = 228000
  177. }
  178. _, info := g.sourceFor(sampleRate)
  179. preemph := "off"
  180. if g.cfg.FM.PreEmphasisTauUS > 0 {
  181. preemph = fmt.Sprintf("%.0fµs", g.cfg.FM.PreEmphasisTauUS)
  182. }
  183. modMode := "composite"
  184. if g.cfg.FM.FMModulationEnabled {
  185. modMode = fmt.Sprintf("FM-IQ(±%.0fHz)", g.cfg.FM.MaxDeviationHz)
  186. }
  187. 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",
  188. g.cfg.FM.FrequencyMHz, g.cfg.FM.CompositeRateHz, duration.String(),
  189. g.cfg.FM.OutputDrive, g.cfg.FM.StereoEnabled, g.cfg.RDS.Enabled,
  190. preemph, g.cfg.FM.LimiterEnabled, modMode, info.Kind, info.Detail)
  191. }