package audio import ( "errors" "fmt" "io" "os" "github.com/sirupsen/logrus" "github.com/BeatGlow/beatglow/config" ) func init() { Register("file", openReader) Register("fifo", openReader) } // Source of audio samples. type Source interface { io.Reader String() string // Channels is the number of channels. Channels() int // Format of the source. Format() Format // SampleRate of the source. SampleRate() Rate } // NotFound signals the reader type can not be found. type NotFound struct { Type string } func (err NotFound) Error() string { return fmt.Sprintf("audio source %q not available", err.Type) } // SourceOpener can open an audio stream source. type SourceOpener func(config.Audio) (Source, error) var drivers = make(map[string]SourceOpener) func Register(name string, opener SourceOpener) { if _, dupe := drivers[name]; dupe { panic(fmt.Sprintf("audio source %q already registered", name)) } drivers[name] = opener } func NewSource(config config.Audio) (Source, error) { opener, ok := drivers[config.Type] if ok { return opener(config) } return nil, NotFound{Type: config.Type} } type ReaderSource struct { io.ReadCloser // Name of the reader (path). Name string // Ch is the number of channels. Ch int // Format is the audio format. Fmt Format // Rate is the sample rate. Rate Rate // Opener is a function that can be called if the reader is closed. Opener func() (io.ReadCloser, error) } func openReader(config config.Audio) (Source, error) { var ( ch = config.Channels bits = config.Bits rate = Rate(config.Rate) ) if ch == 0 { ch = 2 } if bits == 0 { bits = 16 } if rate == 0 { rate = 44100 } return &ReaderSource{ Name: config.Path, Ch: ch, Fmt: makeFormat(bits), Rate: rate, Opener: func() (io.ReadCloser, error) { return os.Open(config.Path) }, }, nil } func (s *ReaderSource) String() string { return "reader:" + s.Name } func (s *ReaderSource) Channels() int { return s.Ch } func (s *ReaderSource) Format() Format { return s.Fmt } func (s *ReaderSource) SampleRate() Rate { return s.Rate } func (r *ReaderSource) Read(b []byte) (int, error) { var err error if r.ReadCloser == nil { if r.ReadCloser, err = r.Opener(); err != nil { return 0, err } } var n int if n, err = r.ReadCloser.Read(b); err != nil { logrus.WithError(err).Warn("source failed to read; closing") if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { _ = r.ReadCloser.Close() r.ReadCloser = nil } } return n, err } type SamplesReader interface { // ReadSamples reads samples, it returns the number of samples read. ReadSamples(samples [][]Sample) (int, error) }