audio: naming

This commit is contained in:
Trek H 2019-06-06 02:41:17 +09:30
parent 96c1b51173
commit 34fc64383e
1 changed files with 96 additions and 96 deletions

View File

@ -98,47 +98,47 @@ type Logger interface {
// NewDevice initializes and returns an Device which can be started, read from, and stopped. // NewDevice initializes and returns an Device which can be started, read from, and stopped.
func NewDevice(cfg *Config, l Logger) (*Device, error) { func NewDevice(cfg *Config, l Logger) (*Device, error) {
a := &Device{} d := &Device{}
a.Config = cfg d.Config = cfg
a.l = l d.l = l
// Open the requested audio device. // Open the requested audio device.
err := a.open() err := d.open()
if err != nil { if err != nil {
a.l.Log(logger.Error, pkg+"failed to open audio device", "error", err.Error()) d.l.Log(logger.Error, pkg+"failed to open audio device", "error", err.Error())
return nil, errors.New("failed to open audio device") return nil, errors.New("failed to open audio device")
} }
// Setup ring buffer to capture audio in periods of a.RecPeriod seconds and buffer rbDuration seconds in total. // Setup ring buffer to capture audio in periods of d.RecPeriod seconds and buffer rbDuration seconds in total.
a.ab = a.dev.NewBufferDuration(time.Duration(a.RecPeriod * float64(time.Second))) d.ab = d.dev.NewBufferDuration(time.Duration(d.RecPeriod * float64(time.Second)))
cs := (float64((len(a.ab.Data)/a.dev.BufferFormat().Channels)*a.Channels) / float64(a.dev.BufferFormat().Rate)) * float64(a.SampleRate) cs := (float64((len(d.ab.Data)/d.dev.BufferFormat().Channels)*d.Channels) / float64(d.dev.BufferFormat().Rate)) * float64(d.SampleRate)
if cs < 1 { if cs < 1 {
a.l.Log(logger.Error, pkg+"given Config parameters are too small", "error", err.Error()) d.l.Log(logger.Error, pkg+"given Config parameters are too small", "error", err.Error())
return nil, errors.New("given Config parameters are too small") return nil, errors.New("given Config parameters are too small")
} }
if a.Codec == codecutil.ADPCM { if d.Codec == codecutil.ADPCM {
a.chunkSize = adpcm.EncBytes(int(cs)) d.chunkSize = adpcm.EncBytes(int(cs))
} else { } else {
a.chunkSize = int(cs) d.chunkSize = int(cs)
} }
a.rb = ring.NewBuffer(rbLen, a.chunkSize, rbTimeout) d.rb = ring.NewBuffer(rbLen, d.chunkSize, rbTimeout)
a.mode = paused d.mode = paused
go a.input() go d.input()
return a, nil return d, nil
} }
// Start will start recording audio and writing to the ringbuffer. // Start will start recording audio and writing to the ringbuffer.
func (a *Device) Start() error { func (d *Device) Start() error {
a.mu.Lock() d.mu.Lock()
mode := a.mode mode := d.mode
a.mu.Unlock() d.mu.Unlock()
switch mode { switch mode {
case paused: case paused:
a.mu.Lock() d.mu.Lock()
a.mode = running d.mode = running
a.mu.Unlock() d.mu.Unlock()
return nil return nil
case stopped: case stopped:
// TODO(Trek): Make this reopen device and start recording. // TODO(Trek): Make this reopen device and start recording.
@ -151,37 +151,37 @@ func (a *Device) Start() error {
} }
// Stop will stop recording audio and close the device. // Stop will stop recording audio and close the device.
func (a *Device) Stop() { func (d *Device) Stop() {
a.mu.Lock() d.mu.Lock()
a.mode = stopped d.mode = stopped
a.mu.Unlock() d.mu.Unlock()
} }
// ChunkSize returns the number of bytes written to the ringbuffer per a.RecPeriod. // ChunkSize returns the number of bytes written to the ringbuffer per d.RecPeriod.
func (a *Device) ChunkSize() int { func (d *Device) ChunkSize() int {
return a.chunkSize return d.chunkSize
} }
// open the recording device with the given name and prepare it to record. // open the recording device with the given name and prepare it to record.
// If name is empty, the first recording device is used. // If name is empty, the first recording device is used.
func (a *Device) open() error { func (d *Device) open() error {
// Close any existing device. // Close any existing device.
if a.dev != nil { if d.dev != nil {
a.l.Log(logger.Debug, pkg+"closing device", "title", a.title) d.l.Log(logger.Debug, pkg+"closing device", "title", d.title)
a.dev.Close() d.dev.Close()
a.dev = nil d.dev = nil
} }
// Open sound card and open recording device. // Open sound card and open recording device.
a.l.Log(logger.Debug, pkg+"opening sound card") d.l.Log(logger.Debug, pkg+"opening sound card")
cards, err := alsa.OpenCards() cards, err := alsa.OpenCards()
if err != nil { if err != nil {
a.l.Log(logger.Debug, pkg+"failed to open sound card") d.l.Log(logger.Debug, pkg+"failed to open sound card")
return err return err
} }
defer alsa.CloseCards(cards) defer alsa.CloseCards(cards)
a.l.Log(logger.Debug, pkg+"finding audio device") d.l.Log(logger.Debug, pkg+"finding audio device")
for _, card := range cards { for _, card := range cards {
devices, err := card.Devices() devices, err := card.Devices()
if err != nil { if err != nil {
@ -191,27 +191,27 @@ func (a *Device) open() error {
if dev.Type != alsa.PCM || !dev.Record { if dev.Type != alsa.PCM || !dev.Record {
continue continue
} }
if dev.Title == a.title || a.title == "" { if dev.Title == d.title || d.title == "" {
a.dev = dev d.dev = dev
break break
} }
} }
} }
if a.dev == nil { if d.dev == nil {
a.l.Log(logger.Debug, pkg+"failed to find audio device") d.l.Log(logger.Debug, pkg+"failed to find audio device")
return errors.New("no audio device found") return errors.New("no audio device found")
} }
a.l.Log(logger.Debug, pkg+"opening audio device", "title", a.dev.Title) d.l.Log(logger.Debug, pkg+"opening audio device", "title", d.dev.Title)
err = a.dev.Open() err = d.dev.Open()
if err != nil { if err != nil {
a.l.Log(logger.Debug, pkg+"failed to open audio device") d.l.Log(logger.Debug, pkg+"failed to open audio device")
return err return err
} }
// 2 channels is what most devices need to record in. If mono is requested, // 2 channels is what most devices need to record in. If mono is requested,
// the recording will be converted in formatBuffer(). // the recording will be converted in formatBuffer().
_, err = a.dev.NegotiateChannels(2) _, err = d.dev.NegotiateChannels(2)
if err != nil { if err != nil {
return err return err
} }
@ -223,111 +223,111 @@ func (a *Device) open() error {
// a fix for this is to remove 8000 and 16000 from the Rates slice. // a fix for this is to remove 8000 and 16000 from the Rates slice.
foundRate := false foundRate := false
for i := 0; i < len(Rates) && !foundRate; i++ { for i := 0; i < len(Rates) && !foundRate; i++ {
if Rates[i] < a.SampleRate { if Rates[i] < d.SampleRate {
continue continue
} }
if Rates[i]%a.SampleRate == 0 { if Rates[i]%d.SampleRate == 0 {
_, err = a.dev.NegotiateRate(Rates[i]) _, err = d.dev.NegotiateRate(Rates[i])
if err == nil { if err == nil {
foundRate = true foundRate = true
a.l.Log(logger.Debug, pkg+"Sample rate set", "rate", Rates[i]) d.l.Log(logger.Debug, pkg+"Sample rate set", "rate", Rates[i])
} }
} }
} }
// If no easily divisible rate is found, then use the default rate. // If no easily divisible rate is found, then use the default rate.
if !foundRate { if !foundRate {
a.l.Log(logger.Warning, pkg+"Unable to sample at requested rate, default used.", "rateRequested", a.SampleRate) d.l.Log(logger.Warning, pkg+"Unable to sample at requested rate, default used.", "rateRequested", d.SampleRate)
_, err = a.dev.NegotiateRate(defaultSampleRate) _, err = d.dev.NegotiateRate(defaultSampleRate)
if err != nil { if err != nil {
return err return err
} }
a.l.Log(logger.Debug, pkg+"Sample rate set", "rate", defaultSampleRate) d.l.Log(logger.Debug, pkg+"Sample rate set", "rate", defaultSampleRate)
} }
var aFmt alsa.FormatType var aFmt alsa.FormatType
switch a.BitDepth { switch d.BitDepth {
case 16: case 16:
aFmt = alsa.S16_LE aFmt = alsa.S16_LE
case 32: case 32:
aFmt = alsa.S32_LE aFmt = alsa.S32_LE
default: default:
return fmt.Errorf("unsupported sample bits %v", a.BitDepth) return fmt.Errorf("unsupported sample bits %v", d.BitDepth)
} }
_, err = a.dev.NegotiateFormat(aFmt) _, err = d.dev.NegotiateFormat(aFmt)
if err != nil { if err != nil {
return err return err
} }
// Either 8192 or 16384 bytes is a reasonable ALSA buffer size. // Either 8192 or 16384 bytes is a reasonable ALSA buffer size.
_, err = a.dev.NegotiateBufferSize(8192, 16384) _, err = d.dev.NegotiateBufferSize(8192, 16384)
if err != nil { if err != nil {
return err return err
} }
if err = a.dev.Prepare(); err != nil { if err = d.dev.Prepare(); err != nil {
return err return err
} }
a.l.Log(logger.Debug, pkg+"Successfully negotiated ALSA params") d.l.Log(logger.Debug, pkg+"Successfully negotiated ALSA params")
return nil return nil
} }
// input continously records audio and writes it to the ringbuffer. // input continously records audio and writes it to the ringbuffer.
// Re-opens the device and tries again if ASLA returns an error. // Re-opens the device and tries again if ASLA returns an error.
func (a *Device) input() { func (d *Device) input() {
for { for {
// Check mode. // Check mode.
a.mu.Lock() d.mu.Lock()
mode := a.mode mode := d.mode
a.mu.Unlock() d.mu.Unlock()
switch mode { switch mode {
case paused: case paused:
time.Sleep(time.Duration(a.RecPeriod) * time.Second) time.Sleep(time.Duration(d.RecPeriod) * time.Second)
continue continue
case stopped: case stopped:
if a.dev != nil { if d.dev != nil {
a.l.Log(logger.Debug, pkg+"closing audio device", "title", a.title) d.l.Log(logger.Debug, pkg+"closing audio device", "title", d.title)
a.dev.Close() d.dev.Close()
a.dev = nil d.dev = nil
} }
return return
} }
// Read from audio device. // Read from audio device.
a.l.Log(logger.Debug, pkg+"recording audio for period", "seconds", a.RecPeriod) d.l.Log(logger.Debug, pkg+"recording audio for period", "seconds", d.RecPeriod)
err := a.dev.Read(a.ab.Data) err := d.dev.Read(d.ab.Data)
if err != nil { if err != nil {
a.l.Log(logger.Debug, pkg+"read failed", "error", err.Error()) d.l.Log(logger.Debug, pkg+"read failed", "error", err.Error())
err = a.open() // re-open err = d.open() // re-open
if err != nil { if err != nil {
a.l.Log(logger.Fatal, pkg+"reopening device failed", "error", err.Error()) d.l.Log(logger.Fatal, pkg+"reopening device failed", "error", err.Error())
return return
} }
continue continue
} }
// Process audio. // Process audio.
a.l.Log(logger.Debug, "processing audio") d.l.Log(logger.Debug, "processing audio")
toWrite := a.formatBuffer() toWrite := d.formatBuffer()
// Write audio to ringbuffer. // Write audio to ringbuffer.
n, err := a.rb.Write(toWrite.Data) n, err := d.rb.Write(toWrite.Data)
switch err { switch err {
case nil: case nil:
a.l.Log(logger.Debug, pkg+"wrote audio to ringbuffer", "length", n) d.l.Log(logger.Debug, pkg+"wrote audio to ringbuffer", "length", n)
case ring.ErrDropped: case ring.ErrDropped:
a.l.Log(logger.Warning, pkg+"old audio data overwritten") d.l.Log(logger.Warning, pkg+"old audio data overwritten")
default: default:
a.l.Log(logger.Error, pkg+"unexpected ringbuffer error", "error", err.Error()) d.l.Log(logger.Error, pkg+"unexpected ringbuffer error", "error", err.Error())
return return
} }
} }
} }
// Read reads from the ringbuffer, returning the number of bytes read upon success. // Read reads from the ringbuffer, returning the number of bytes read upon success.
func (a *Device) Read(p []byte) (n int, err error) { func (d *Device) Read(p []byte) (n int, err error) {
// Ready ringbuffer for read. // Ready ringbuffer for read.
_, err = a.rb.Next(rbNextTimeout) _, err = d.rb.Next(rbNextTimeout)
switch err { switch err {
case nil: case nil:
case ring.ErrTimeout: case ring.ErrTimeout:
@ -337,7 +337,7 @@ func (a *Device) Read(p []byte) (n int, err error) {
} }
// Read from ring buffer. // Read from ring buffer.
n, err = a.rb.Read(p) n, err = d.rb.Read(p)
switch err { switch err {
case nil: case nil:
case io.EOF: case io.EOF:
@ -350,46 +350,46 @@ func (a *Device) Read(p []byte) (n int, err error) {
} }
// formatBuffer returns audio that has been converted to the desired format. // formatBuffer returns audio that has been converted to the desired format.
func (a *Device) formatBuffer() alsa.Buffer { func (d *Device) formatBuffer() alsa.Buffer {
var err error var err error
// If nothing needs to be changed, return the original. // If nothing needs to be changed, return the original.
if a.ab.Format.Channels == a.Channels && a.ab.Format.Rate == a.SampleRate { if d.ab.Format.Channels == d.Channels && d.ab.Format.Rate == d.SampleRate {
return a.ab return d.ab
} }
formatted := alsa.Buffer{Format: a.ab.Format, Data: a.ab.Data} formatted := alsa.Buffer{Format: d.ab.Format, Data: d.ab.Data}
if a.ab.Format.Channels != a.Channels { if d.ab.Format.Channels != d.Channels {
// Convert channels. // Convert channels.
// TODO(Trek): Make this work for conversions other than stereo to mono. // TODO(Trek): Make this work for conversions other than stereo to mono.
if a.ab.Format.Channels == 2 && a.Channels == 1 { if d.ab.Format.Channels == 2 && d.Channels == 1 {
formatted.Data, err = pcm.StereoToMono(a.ab) formatted.Data, err = pcm.StereoToMono(d.ab)
if err != nil { if err != nil {
a.l.Log(logger.Fatal, pkg+"channel conversion failed", "error", err.Error()) d.l.Log(logger.Fatal, pkg+"channel conversion failed", "error", err.Error())
} }
} }
} }
if a.ab.Format.Rate != a.SampleRate { if d.ab.Format.Rate != d.SampleRate {
// Convert rate. // Convert rate.
formatted.Data, err = pcm.Resample(formatted, a.SampleRate) formatted.Data, err = pcm.Resample(formatted, d.SampleRate)
if err != nil { if err != nil {
a.l.Log(logger.Fatal, pkg+"rate conversion failed", "error", err.Error()) d.l.Log(logger.Fatal, pkg+"rate conversion failed", "error", err.Error())
} }
} }
switch a.Codec { switch d.Codec {
case codecutil.PCM: case codecutil.PCM:
case codecutil.ADPCM: case codecutil.ADPCM:
b := bytes.NewBuffer(make([]byte, 0, adpcm.EncBytes(len(formatted.Data)))) b := bytes.NewBuffer(make([]byte, 0, adpcm.EncBytes(len(formatted.Data))))
enc := adpcm.NewEncoder(b) enc := adpcm.NewEncoder(b)
_, err = enc.Write(formatted.Data) _, err = enc.Write(formatted.Data)
if err != nil { if err != nil {
a.l.Log(logger.Fatal, pkg+"unable to encode", "error", err.Error()) d.l.Log(logger.Fatal, pkg+"unable to encode", "error", err.Error())
} }
formatted.Data = b.Bytes() formatted.Data = b.Bytes()
default: default:
a.l.Log(logger.Error, pkg+"unhandled audio codec") d.l.Log(logger.Error, pkg+"unhandled audio codec")
} }
return formatted return formatted