From 3a378435c36ccca76092f8192f44ad69b9e10dc5 Mon Sep 17 00:00:00 2001 From: Wijnand Modderman-Lenstra Date: Thu, 29 Oct 2026 17:28:14 +0100 Subject: [PATCH] Log audio source throughput and stalls --- sound/registry.go | 6 +- sound/source.go | 1 + sound/source_log.go | 182 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 sound/source_log.go diff --git a/sound/registry.go b/sound/registry.go index 7568dfb..346fc44 100644 --- a/sound/registry.go +++ b/sound/registry.go @@ -20,7 +20,11 @@ func Register(name string, opener Opener) { func New(config *config.Audio) (Source, error) { opener, ok := drivers[config.Type] if ok { - return opener(config) + source, err := opener(config) + if err != nil { + return nil, err + } + return NewLogger(source, nil, 0), nil } return nil, fmt.Errorf("sound: no %q driver was found", config.Type) } diff --git a/sound/source.go b/sound/source.go index fb4c6b4..62dd8f6 100644 --- a/sound/source.go +++ b/sound/source.go @@ -32,6 +32,7 @@ type Source interface { SampleRate() int } +// Reader of samples from a file/fifo. type Reader struct { io.ReadCloser diff --git a/sound/source_log.go b/sound/source_log.go new file mode 100644 index 0000000..bcf3e1e --- /dev/null +++ b/sound/source_log.go @@ -0,0 +1,182 @@ +package sound + +import ( + "fmt" + "sync" + "sync/atomic" + "time" + + "github.com/sirupsen/logrus" + + "github.com/BeatGlow/audio" +) + +type LoggingSource struct { + src Source + log *logrus.Logger + interval time.Duration + + startOnce sync.Once + done chan struct{} + closeOnce sync.Once + + samplesRead atomic.Uint64 + lastActive atomic.Int64 + + startedAt time.Time +} + +// NewLogger wraps src and reports stats/stalls to log every 15s. +// A nil logger falls back to logrus.StandardLogger(). A non-positive +// interval falls back to 15s. +func NewLogger(src Source, log *logrus.Logger, interval time.Duration) *LoggingSource { + if log == nil { + log = logrus.StandardLogger() + } + if interval <= 0 { + interval = 15 * time.Second + } + return &LoggingSource{ + src: src, + log: log, + interval: interval, + done: make(chan struct{}), + } +} + +func (l *LoggingSource) String() string { return l.src.String() } +func (l *LoggingSource) Channels() int { return l.src.Channels() } +func (l *LoggingSource) BitDepth() int { return l.src.BitDepth() } +func (l *LoggingSource) SampleRate() int { return l.src.SampleRate() } + +func (l *LoggingSource) ReadBuffer(buf audio.Buffer[float64]) (int, error) { + l.start() + + n, err := l.src.ReadBuffer(buf) + + if n > 0 { + l.samplesRead.Add(uint64(n)) + l.lastActive.Store(time.Now().UnixNano()) + } + + if err != nil { + l.logFinal(err) + l.Stop() + } + + return n, err +} + +func (l *LoggingSource) Stop() { + l.closeOnce.Do(func() { close(l.done) }) +} + +func (l *LoggingSource) start() { + l.startOnce.Do(func() { + l.startedAt = time.Now() + l.lastActive.Store(l.startedAt.UnixNano()) + go l.watch() + }) +} + +func (l *LoggingSource) bytesPerSample() int { + if bits := l.BitDepth(); bits > 0 { + return bits / 8 + } + return 0 +} + +func (l *LoggingSource) watch() { + ticker := time.NewTicker(l.interval) + defer ticker.Stop() + + var ( + lastSamples uint64 + lastTime = time.Now() + ) + bytesPerSample := l.bytesPerSample() + + for { + select { + case <-l.done: + return + case now := <-ticker.C: + totalSamples := l.samplesRead.Load() + deltaSamples := totalSamples - lastSamples + window := now.Sub(lastTime) + + lastSamples = totalSamples + lastTime = now + + deltaBytes := deltaSamples * uint64(bytesPerSample) + totalBytes := totalSamples * uint64(bytesPerSample) + + var byteRate, sampleRate float64 + if secs := window.Seconds(); secs > 0 { + byteRate = float64(deltaBytes) / secs + sampleRate = float64(deltaSamples) / secs + } + + lastActive := time.Unix(0, l.lastActive.Load()) + stalled := now.Sub(lastActive) + + fields := logrus.Fields{ + "source": l.String(), + "channels": l.Channels(), + "bit_depth": l.BitDepth(), + "sample_rate": l.SampleRate(), + "total_bytes": totalBytes, + "delta_bytes": deltaBytes, + "data_rate_bps": formatBytes(byteRate) + "/s", + "sample_rate_actual": int64(sampleRate), + "audio_sec": audioSeconds(totalSamples, l.SampleRate()), + "elapsed": now.Sub(l.startedAt).Truncate(time.Second).String(), + } + + switch { + case deltaSamples == 0: + fields["stalled_for"] = stalled.Truncate(time.Second).String() + l.log.WithFields(fields).Warn("audio source stalled: no data flowing") + default: + l.log.WithFields(fields).Info("audio source stats") + } + } + } +} + +func (l *LoggingSource) logFinal(err error) { + bytesPerSample := l.bytesPerSample() + total := l.samplesRead.Load() + fields := logrus.Fields{ + "source": l.String(), + "total_bytes": total * uint64(bytesPerSample), + "total_samples": total, + "audio_sec": audioSeconds(total, l.SampleRate()), + "elapsed": time.Since(l.startedAt).Truncate(time.Second).String(), + } + if err != nil { + fields["err"] = err.Error() + } + l.log.WithFields(fields).Info("audio source finished") +} + +func audioSeconds(samples uint64, rate int) float64 { + if rate <= 0 { + return 0 + } + return float64(samples) / float64(rate) +} + +func formatBytes(b float64) string { + const unit = 1024 + switch { + case b >= unit*unit*unit: + return fmt.Sprintf("%.2f GiB", b/(unit*unit*unit)) + case b >= unit*unit: + return fmt.Sprintf("%.2f MiB", b/(unit*unit)) + case b >= unit: + return fmt.Sprintf("%.2f KiB", b/unit) + default: + return fmt.Sprintf("%.0f B", b) + } +}