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) } }