Files
beatglow/audio/stream.go
T
2026-10-29 17:29:41 +01:00

279 lines
5.3 KiB
Go

package audio
import (
"errors"
"fmt"
"io"
"os"
"time"
"github.com/sirupsen/logrus"
"go.maze.io/harmon/config"
"go.maze.io/harmon/hardware"
"periph.io/x/conn/v3/physic"
)
const streamBuffers = 16
type Stream interface {
hardware.Driver
// Channels is the number of channels.
Channels() int
// SampleRate is the audio sampling rate.
SampleRate() physic.Frequency
// Samples is a channel of interleaved audio samples.
Samples(size int) <-chan Buffer
}
type Processor interface {
Process(Buffer)
}
type StreamReader struct {
Opener func() (io.Reader, error)
// Format is the audio sample format.
Format Format
// Ch is the number of channels.
Ch int
// Rate is the sampling rate.
Rate physic.Frequency
// quit signal channel.
quit chan struct{}
}
func NewStreamReader(open func() (io.Reader, error), f Format, ch int, rate physic.Frequency) Stream {
return &StreamReader{
Opener: open,
Format: f,
Ch: ch,
Rate: rate,
quit: make(chan struct{}),
}
}
func (r *StreamReader) Halt() error {
if r.quit != nil {
close(r.quit)
r.quit = nil
}
return nil
}
func (r *StreamReader) Type() string {
return "stream"
}
func (r *StreamReader) Channels() int {
return r.Ch
}
func (r *StreamReader) SampleRate() physic.Frequency {
return r.Rate
}
func (r *StreamReader) Samples(size int) <-chan Buffer {
samples := make(chan Buffer, streamBuffers)
go r.stream(samples, size)
return samples
}
func (r *StreamReader) stream(samples chan<- Buffer, size int) {
defer close(samples)
var (
log = logrus.WithField("audio", "stream")
ring [streamBuffers]Buffer
curr int
)
for i := 0; i < streamBuffers; i++ {
ring[i] = r.Format.NewBuffer(size*r.Ch, r.Ch)
}
log.Debug("starting with %d buffers", streamBuffers)
for {
log.Debug("opening stream")
f, err := r.Opener()
if err != nil {
log.WithError(err).Warn("opening stream failed, retrying...")
time.Sleep(time.Second)
continue
}
for {
n, err := ring[curr].ReadFrom(f)
if err != nil {
log.WithError(err).Warn("stream closed, retrying...")
break
}
log.WithField("samples", n).Trace("stream samples")
select {
case <-r.quit:
if c, ok := f.(io.Closer); ok {
if err = c.Close(); err != nil {
log.WithError(err).Warn("closing stream failed")
}
}
return
case samples <- ring[curr]:
default:
log.Warn("dropped samples, buffer overrun")
}
curr = (curr + 1) % streamBuffers
}
}
}
/*
type Reader struct {
io.Reader
// Format is the audio sample format.
Format Format
// Ch is the number of channels.
Ch int
// Rate is the sampling rate.
Rate physic.Frequency
}
func NewReader(r io.Reader, f Format, ch int, rate physic.Frequency) Stream {
return &Reader{
Reader: r,
Format: f,
Ch: ch,
Rate: rate,
}
}
func (r Reader) Type() string {
return "file"
}
func (r Reader) Halt() error {
if c, ok := r.Reader.(io.Closer); ok {
return c.Close()
}
return nil
}
func (r Reader) Channels() int {
return r.Ch
}
func (r Reader) SampleRate() physic.Frequency {
return r.Rate
}
func (r *Reader) Read(b Buffer) (n int, err error) {
return b.ReadFrom(r.Reader)
}
const numBuf = 16
func (r *Reader) stream(send chan Buffer, rate physic.Frequency) {
var (
b = r.Format.NewBuffer(int(rate/physic.Hertz), r.Ch) //NewBuffer(int(rate/physic.Hertz), r.Ch, r.Format)
buf [numBuf]Buffer
n int
)
logrus.WithFields(logrus.Fields{
"buffers": numBuf,
"rate_in": r.Rate,
"rate_out": rate,
}).Info("audio stream starting")
for {
if _, err := r.Read(b); err != nil {
logrus.WithError(err).Warn("audio stream interrupted")
close(send)
return
}
//samples, err := b.Decode(buf[n], order)
samples, err := b.ReadFrom(r.Reader)
if err != nil {
logrus.WithError(err).Warn("samples decode failed")
continue
}
select {
case send <- buf[n]:
default:
logrus.WithField("samples", samples).Warn("samples dropped, buffer overrun")
}
n = (n + 1) % numBuf
}
}
func (r *Reader) Samples(rate physic.Frequency) <-chan Buffer {
samples := make(chan Buffer, numBuf)
go r.stream(samples, rate)
return samples
}
*/
// Open a stream backed by a file (or a FIFO).
func Open(name string, f Format, ch int, rate physic.Frequency) Stream {
/*
r, err := os.OpenFile(name, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
return NewReader(r, f, ch, rate), nil
*/
return NewStreamReader(func() (io.Reader, error) {
return os.OpenFile(name, os.O_RDONLY, 0)
}, f, ch, rate)
}
func openFile(config config.Audio) (Stream, error) {
if config.Rate <= 0 {
return nil, errors.New("audio rate not configured")
}
if config.Channels <= 0 {
return nil, errors.New("audio chanels not configured")
}
if config.Bits == 0 {
return nil, errors.New("audio bits not configured")
}
var (
rate = physic.Frequency(config.Rate) * physic.Hertz
f Format
)
switch config.Bits {
case 8:
f = Int8Format
case 16:
f = Int16LEFormat
case 32:
f = Int32LEFormat
default:
return nil, fmt.Errorf("audio bits should be 8, 16 or 32, got %d", config.Bits)
}
logrus.WithFields(logrus.Fields{
"type": config.Type,
"bits": config.Bits,
"channels": config.Channels,
"rate": rate,
}).Debug("open audio driver")
return Open(config.Path, f, config.Channels, rate), nil
}
func init() {
Register("file", openFile)
Register("fifo", openFile)
}