2019-11-11 09:25:47 +03:00
|
|
|
/*
|
|
|
|
NAME
|
2019-11-12 05:58:53 +03:00
|
|
|
alsa.go
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
AUTHOR
|
|
|
|
Alan Noble <alan@ausocean.org>
|
|
|
|
Trek Hopton <trek@ausocean.org>
|
|
|
|
|
|
|
|
LICENSE
|
|
|
|
This file is Copyright (C) 2019 the Australian Ocean Lab (AusOcean)
|
|
|
|
|
|
|
|
It is free software: you can redistribute it and/or modify them
|
|
|
|
under the terms of the GNU General Public License as published by the
|
|
|
|
Free Software Foundation, either version 3 of the License, or (at your
|
|
|
|
option) any later version.
|
|
|
|
|
|
|
|
It is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
|
|
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
|
|
for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License in gpl.txt.
|
2019-11-12 08:34:16 +03:00
|
|
|
If not, see http://www.gnu.org/licenses.
|
2019-11-11 09:25:47 +03:00
|
|
|
*/
|
|
|
|
|
2019-11-12 05:58:53 +03:00
|
|
|
// Package alsa provides access to input from ALSA audio devices.
|
|
|
|
package alsa
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2022-01-27 04:20:45 +03:00
|
|
|
"io"
|
2024-04-11 03:51:07 +03:00
|
|
|
"os"
|
2019-11-11 09:25:47 +03:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2019-11-12 05:58:53 +03:00
|
|
|
yalsa "github.com/yobert/alsa"
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
"bitbucket.org/ausocean/av/codec/adpcm"
|
|
|
|
"bitbucket.org/ausocean/av/codec/codecutil"
|
|
|
|
"bitbucket.org/ausocean/av/codec/pcm"
|
|
|
|
"bitbucket.org/ausocean/av/device"
|
|
|
|
"bitbucket.org/ausocean/av/revid/config"
|
2022-05-27 09:12:52 +03:00
|
|
|
"bitbucket.org/ausocean/utils/logging"
|
2021-05-17 04:33:41 +03:00
|
|
|
"bitbucket.org/ausocean/utils/pool"
|
2019-11-11 09:25:47 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2020-08-11 05:13:17 +03:00
|
|
|
pkg = "alsa: "
|
|
|
|
rbTimeout = 100 * time.Millisecond
|
|
|
|
rbNextTimeout = 2000 * time.Millisecond
|
|
|
|
rbLen = 200
|
2019-11-11 09:25:47 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// "running" means the input goroutine is reading from the ALSA device and writing to the ringbuffer.
|
|
|
|
// "paused" means the input routine is sleeping until unpaused or stopped.
|
|
|
|
// "stopped" means the input routine is stopped and the ALSA device is closed.
|
|
|
|
const (
|
|
|
|
running = iota + 1
|
|
|
|
paused
|
|
|
|
stopped
|
|
|
|
)
|
|
|
|
|
2020-08-11 05:13:17 +03:00
|
|
|
const (
|
|
|
|
defaultSampleRate = 48000
|
|
|
|
defaultBitDepth = 16
|
|
|
|
defaultChannels = 1
|
|
|
|
defaultRecPeriod = 1.0
|
|
|
|
defaultCodec = codecutil.PCM
|
|
|
|
)
|
|
|
|
|
|
|
|
// Configuration field errors.
|
|
|
|
var (
|
|
|
|
errInvalidSampleRate = errors.New("invalid sample rate, defaulting")
|
|
|
|
errInvalidChannels = errors.New("invalid number of channels, defaulting")
|
|
|
|
errInvalidBitDepth = errors.New("invalid bitdepth, defaulting")
|
|
|
|
errInvalidRecPeriod = errors.New("invalid record period, defaulting")
|
|
|
|
errInvalidCodec = errors.New("invalid audio codec, defaulting")
|
|
|
|
)
|
|
|
|
|
2019-11-11 15:10:13 +03:00
|
|
|
// An ALSA device holds everything we need to know about the audio input stream and implements io.Reader and device.AVDevice.
|
2019-11-11 14:56:53 +03:00
|
|
|
type ALSA struct {
|
2022-11-06 09:55:28 +03:00
|
|
|
l logging.Logger // Logger for device's routines to log to.
|
|
|
|
mode uint8 // Operating mode, either running, paused, or stopped.
|
|
|
|
mu sync.Mutex // Provides synchronisation when changing modes concurrently.
|
|
|
|
title string // Name of audio title, or empty for the default title.
|
|
|
|
dev *yalsa.Device // ALSA device's Audio input device.
|
|
|
|
pb pcm.Buffer // Buffer to contain the direct audio from ALSA.
|
|
|
|
buf *pool.Buffer // Ring buffer to contain processed audio ready to be read.
|
|
|
|
Config // Configuration parameters for this device.
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2019-11-11 15:10:13 +03:00
|
|
|
// Config provides parameters used by the ALSA device.
|
2019-11-11 09:25:47 +03:00
|
|
|
type Config struct {
|
2020-05-02 06:55:13 +03:00
|
|
|
SampleRate uint
|
|
|
|
Channels uint
|
|
|
|
BitDepth uint
|
2019-11-11 09:25:47 +03:00
|
|
|
RecPeriod float64
|
2021-02-22 07:45:30 +03:00
|
|
|
Codec string
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2019-11-13 12:26:13 +03:00
|
|
|
// New initializes and returns an ALSA device which has its logger set as the given logger.
|
2022-05-27 09:12:52 +03:00
|
|
|
func New(l logging.Logger) *ALSA { return &ALSA{l: l} }
|
2019-11-11 09:25:47 +03:00
|
|
|
|
2019-11-22 03:25:13 +03:00
|
|
|
// Name returns the name of the device.
|
|
|
|
func (d *ALSA) Name() string {
|
|
|
|
return "ALSA"
|
|
|
|
}
|
|
|
|
|
2020-08-13 08:58:59 +03:00
|
|
|
// Setup will take a Config struct, check the validity of the relevant fields
|
2020-08-13 09:53:19 +03:00
|
|
|
// and then perform any configuration necessary. If fields are not valid,
|
2019-11-11 09:25:47 +03:00
|
|
|
// an error is added to the multiError and a default value is used.
|
2019-11-11 15:10:13 +03:00
|
|
|
// It then initialises the ALSA device which can then be started, read from, and stopped.
|
2020-08-13 08:58:59 +03:00
|
|
|
func (d *ALSA) Setup(c config.Config) error {
|
2019-11-11 09:25:47 +03:00
|
|
|
var errs device.MultiError
|
|
|
|
if c.SampleRate <= 0 {
|
2020-08-11 05:13:17 +03:00
|
|
|
errs = append(errs, errInvalidSampleRate)
|
|
|
|
c.SampleRate = defaultSampleRate
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
if c.Channels <= 0 {
|
2020-08-11 05:13:17 +03:00
|
|
|
errs = append(errs, errInvalidChannels)
|
|
|
|
c.Channels = defaultChannels
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
if c.BitDepth <= 0 {
|
2020-08-11 05:13:17 +03:00
|
|
|
errs = append(errs, errInvalidBitDepth)
|
|
|
|
c.BitDepth = defaultBitDepth
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
if c.RecPeriod <= 0 {
|
2020-08-11 05:13:17 +03:00
|
|
|
errs = append(errs, errInvalidRecPeriod)
|
|
|
|
c.RecPeriod = defaultRecPeriod
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
2020-08-11 05:13:17 +03:00
|
|
|
if c.InputCodec != codecutil.ADPCM && c.InputCodec != codecutil.PCM {
|
|
|
|
errs = append(errs, errInvalidCodec)
|
|
|
|
c.InputCodec = defaultCodec
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
d.Config = Config{
|
|
|
|
SampleRate: c.SampleRate,
|
|
|
|
Channels: c.Channels,
|
|
|
|
BitDepth: c.BitDepth,
|
|
|
|
RecPeriod: c.RecPeriod,
|
|
|
|
Codec: c.InputCodec,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Open the requested audio device.
|
|
|
|
err := d.open()
|
|
|
|
if err != nil {
|
2020-08-19 10:25:35 +03:00
|
|
|
return fmt.Errorf("failed to open device: %w", err)
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2024-04-04 05:26:24 +03:00
|
|
|
// Create a buffer of 1 minute for continuous recordings.
|
|
|
|
ab := d.dev.NewBufferDuration(time.Minute)
|
2019-11-12 13:54:08 +03:00
|
|
|
sf, err := pcm.SFFromString(ab.Format.SampleFormat.String())
|
|
|
|
if err != nil {
|
2020-08-19 10:25:35 +03:00
|
|
|
return fmt.Errorf("unable to get sample format from string: %w", err)
|
2019-11-12 13:54:08 +03:00
|
|
|
}
|
2019-11-13 09:24:41 +03:00
|
|
|
cf := pcm.BufferFormat{
|
2019-11-12 13:54:08 +03:00
|
|
|
SFormat: sf,
|
2020-05-02 06:55:13 +03:00
|
|
|
Channels: uint(ab.Format.Channels),
|
|
|
|
Rate: uint(ab.Format.Rate),
|
2019-11-12 13:54:08 +03:00
|
|
|
}
|
2019-11-13 09:41:35 +03:00
|
|
|
d.pb = pcm.Buffer{
|
2019-11-12 13:54:08 +03:00
|
|
|
Format: cf,
|
|
|
|
Data: ab.Data,
|
|
|
|
}
|
2019-11-11 09:25:47 +03:00
|
|
|
|
2021-05-17 04:33:41 +03:00
|
|
|
// Create pool buffer with appropriate chunk size.
|
2020-12-24 03:25:44 +03:00
|
|
|
cs := d.DataSize()
|
2021-05-17 04:33:41 +03:00
|
|
|
d.buf = pool.NewBuffer(rbLen, cs, rbTimeout)
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
// Start device in paused mode.
|
|
|
|
d.mode = paused
|
|
|
|
go d.input()
|
|
|
|
|
2021-07-23 06:24:34 +03:00
|
|
|
if len(errs) != 0 {
|
2020-09-03 10:14:22 +03:00
|
|
|
return errs
|
|
|
|
}
|
2020-08-21 08:04:13 +03:00
|
|
|
return nil
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2020-08-13 08:58:59 +03:00
|
|
|
// Set exists to satisfy the implementation of the Device interface that revid uses.
|
|
|
|
// Everything that would usually be in Set is in the Setup function.
|
|
|
|
// This is because an ALSA device is different to other devices in that it
|
|
|
|
// outputs binary non-packetised data and it requires a different configuration procedure.
|
|
|
|
func (d *ALSA) Set(c config.Config) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-11-11 09:25:47 +03:00
|
|
|
// Start will start recording audio and writing to the ringbuffer.
|
2019-11-11 15:10:13 +03:00
|
|
|
// Once an ALSA device has been stopped it cannot be started again. This is likely to change in future.
|
2019-11-11 14:56:53 +03:00
|
|
|
func (d *ALSA) Start() error {
|
2019-11-11 09:25:47 +03:00
|
|
|
d.mu.Lock()
|
|
|
|
mode := d.mode
|
|
|
|
d.mu.Unlock()
|
|
|
|
switch mode {
|
|
|
|
case paused:
|
|
|
|
d.mu.Lock()
|
|
|
|
d.mode = running
|
|
|
|
d.mu.Unlock()
|
|
|
|
return nil
|
|
|
|
case stopped:
|
|
|
|
// TODO(Trek): Make this reopen device and start recording.
|
|
|
|
return errors.New("device is stopped")
|
|
|
|
case running:
|
|
|
|
return nil
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("invalid mode: %d", mode)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop will stop recording audio and close the device.
|
2019-11-11 15:10:13 +03:00
|
|
|
// Once an ALSA device has been stopped it cannot be started again. This is likely to change in future.
|
2019-11-12 08:34:07 +03:00
|
|
|
func (d *ALSA) Stop() error {
|
2019-11-11 09:25:47 +03:00
|
|
|
d.mu.Lock()
|
|
|
|
d.mode = stopped
|
|
|
|
d.mu.Unlock()
|
2019-11-12 08:34:07 +03:00
|
|
|
return nil
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// open the recording device with the given name and prepare it to record.
|
|
|
|
// If name is empty, the first recording device is used.
|
2019-11-11 14:56:53 +03:00
|
|
|
func (d *ALSA) open() error {
|
2019-11-11 09:25:47 +03:00
|
|
|
// Close any existing device.
|
|
|
|
if d.dev != nil {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("closing device", "title", d.title)
|
2019-11-11 09:25:47 +03:00
|
|
|
d.dev.Close()
|
|
|
|
d.dev = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Open sound card and open recording device.
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("opening sound card")
|
2019-11-12 05:58:53 +03:00
|
|
|
cards, err := yalsa.OpenCards()
|
2019-11-11 09:25:47 +03:00
|
|
|
if err != nil {
|
2020-12-14 08:26:33 +03:00
|
|
|
return err
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
2019-11-12 05:58:53 +03:00
|
|
|
defer yalsa.CloseCards(cards)
|
2019-11-11 09:25:47 +03:00
|
|
|
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("finding audio device")
|
2019-11-11 09:25:47 +03:00
|
|
|
for _, card := range cards {
|
|
|
|
devices, err := card.Devices()
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for _, dev := range devices {
|
2019-11-12 05:58:53 +03:00
|
|
|
if dev.Type != yalsa.PCM || !dev.Record {
|
2019-11-11 09:25:47 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if dev.Title == d.title || d.title == "" {
|
|
|
|
d.dev = dev
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if d.dev == nil {
|
2020-12-14 08:26:33 +03:00
|
|
|
return errors.New("no ALSA device found")
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("opening ALSA device", "title", d.dev.Title)
|
2019-11-11 09:25:47 +03:00
|
|
|
err = d.dev.Open()
|
|
|
|
if err != nil {
|
2020-12-14 08:26:33 +03:00
|
|
|
return err
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2020-08-21 07:43:15 +03:00
|
|
|
// Try to configure device with chosen channels.
|
|
|
|
channels, err := d.dev.NegotiateChannels(int(d.Channels))
|
|
|
|
if err != nil && d.Channels == 1 {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Info("device is unable to record in mono, trying stereo", "error", err)
|
2020-08-21 07:43:15 +03:00
|
|
|
channels, err = d.dev.NegotiateChannels(2)
|
|
|
|
}
|
2019-11-11 09:25:47 +03:00
|
|
|
if err != nil {
|
2020-12-14 08:26:33 +03:00
|
|
|
return fmt.Errorf("device is unable to record with requested number of channels: %w", err)
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("alsa device channels set", "channels", channels)
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
// Try to negotiate a rate to record in that is divisible by the wanted rate
|
|
|
|
// so that it can be easily downsampled to the wanted rate.
|
|
|
|
// rates is a slice of common sample rates including the standard for CD (44100Hz) and standard for professional audio recording (48000Hz).
|
|
|
|
// Note: if a card thinks it can record at a rate but can't actually, this can cause a failure.
|
|
|
|
// Eg. the audioinjector sound card is supposed to record at 8000Hz and 16000Hz but it can't due to a firmware issue,
|
|
|
|
// a fix for this is to remove 8000 and 16000 from the rates slice.
|
|
|
|
var rates = [8]int{8000, 16000, 32000, 44100, 48000, 88200, 96000, 192000}
|
|
|
|
|
|
|
|
var rate int
|
|
|
|
foundRate := false
|
2024-02-13 03:08:40 +03:00
|
|
|
for _, r := range rates {
|
2020-05-02 06:55:13 +03:00
|
|
|
if r < int(d.SampleRate) {
|
2019-11-11 09:25:47 +03:00
|
|
|
continue
|
|
|
|
}
|
2020-05-02 06:55:13 +03:00
|
|
|
if r%int(d.SampleRate) == 0 {
|
2019-11-11 09:25:47 +03:00
|
|
|
rate, err = d.dev.NegotiateRate(r)
|
|
|
|
if err == nil {
|
|
|
|
foundRate = true
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("alsa device sample rate set", "rate", rate)
|
2019-11-11 09:25:47 +03:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If no easily divisible rate is found, then use the default rate.
|
|
|
|
if !foundRate {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Warning("unable to sample at requested rate, default used.", "rateRequested", d.SampleRate)
|
2019-11-11 09:25:47 +03:00
|
|
|
rate, err = d.dev.NegotiateRate(defaultSampleRate)
|
|
|
|
if err != nil {
|
2020-12-14 08:26:33 +03:00
|
|
|
return err
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("alsa device sample rate set", "rate", rate)
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2019-11-12 05:58:53 +03:00
|
|
|
var aFmt yalsa.FormatType
|
2019-11-11 09:25:47 +03:00
|
|
|
switch d.BitDepth {
|
|
|
|
case 16:
|
2019-11-12 05:58:53 +03:00
|
|
|
aFmt = yalsa.S16_LE
|
2019-11-11 09:25:47 +03:00
|
|
|
case 32:
|
2019-11-12 05:58:53 +03:00
|
|
|
aFmt = yalsa.S32_LE
|
2019-11-11 09:25:47 +03:00
|
|
|
default:
|
2020-12-14 08:26:33 +03:00
|
|
|
return fmt.Errorf("unsupported sample bits %v", d.BitDepth)
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
devFmt, err := d.dev.NegotiateFormat(aFmt)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
var bitdepth int
|
|
|
|
switch devFmt {
|
2019-11-12 05:58:53 +03:00
|
|
|
case yalsa.S16_LE:
|
2019-11-11 09:25:47 +03:00
|
|
|
bitdepth = 16
|
2019-11-12 05:58:53 +03:00
|
|
|
case yalsa.S32_LE:
|
2019-11-11 09:25:47 +03:00
|
|
|
bitdepth = 32
|
|
|
|
default:
|
2020-12-14 08:26:33 +03:00
|
|
|
return fmt.Errorf("unsupported sample bits %v", d.BitDepth)
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("alsa device bit depth set", "bitdepth", bitdepth)
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
// A 50ms period is a sensible value for low-ish latency. (this could be made configurable if needed)
|
|
|
|
// Some devices only accept even period sizes while others want powers of 2.
|
|
|
|
// So we will find the closest power of 2 to the desired period size.
|
|
|
|
const wantPeriod = 0.05 //seconds
|
|
|
|
bytesPerSecond := rate * channels * (bitdepth / 8)
|
|
|
|
wantPeriodSize := int(float64(bytesPerSecond) * wantPeriod)
|
|
|
|
nearWantPeriodSize := nearestPowerOfTwo(wantPeriodSize)
|
2024-04-11 03:51:07 +03:00
|
|
|
periodSize, err := d.dev.NegotiatePeriodSize(nearWantPeriodSize)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
d.l.Debug("alsa device period size set", "periodsize", periodSize)
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
// At least two period sizes should fit within the buffer.
|
2024-04-11 03:51:07 +03:00
|
|
|
bufSize, err := d.dev.NegotiateBufferSize(periodSize * 4)
|
2019-11-11 09:25:47 +03:00
|
|
|
if err != nil {
|
2020-12-14 08:26:33 +03:00
|
|
|
return err
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("alsa device buffer size set", "buffersize", bufSize)
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
if err = d.dev.Prepare(); err != nil {
|
2020-12-14 08:26:33 +03:00
|
|
|
return err
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("successfully negotiated device params")
|
2019-11-11 09:25:47 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// input continously records audio and writes it to the ringbuffer.
|
2019-11-11 15:10:13 +03:00
|
|
|
// Re-opens the device and tries again if the ASLA device returns an error.
|
2019-11-11 14:56:53 +03:00
|
|
|
func (d *ALSA) input() {
|
2024-04-04 05:26:24 +03:00
|
|
|
// Make a channel to communicate betwen continuous recording and processing.
|
|
|
|
// The channel has a capacity of 5 minutes of audio, which it should never reach.
|
|
|
|
ch := make(chan []byte, int(5*60/d.RecPeriod))
|
|
|
|
|
|
|
|
// Read audio in 1 minute sections.
|
|
|
|
go chunkingRead(d, ch)
|
2024-04-11 03:51:07 +03:00
|
|
|
// Sleep for 1 minute before the first attempt to read.
|
|
|
|
d.l.Debug("Sleeping before read", "sleep time", "1 minute")
|
|
|
|
time.Sleep(time.Minute)
|
2024-04-04 05:26:24 +03:00
|
|
|
|
2019-11-11 09:25:47 +03:00
|
|
|
for {
|
|
|
|
// Check mode.
|
|
|
|
d.mu.Lock()
|
|
|
|
mode := d.mode
|
|
|
|
d.mu.Unlock()
|
|
|
|
switch mode {
|
|
|
|
case paused:
|
|
|
|
time.Sleep(time.Duration(d.RecPeriod) * time.Second)
|
|
|
|
continue
|
|
|
|
case stopped:
|
|
|
|
if d.dev != nil {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("closing ALSA device", "title", d.title)
|
2019-11-11 09:25:47 +03:00
|
|
|
d.dev.Close()
|
|
|
|
d.dev = nil
|
|
|
|
}
|
2022-02-18 02:43:16 +03:00
|
|
|
err := d.buf.Close()
|
|
|
|
if err != nil {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Error("unable to close pool buffer", "error", err)
|
2022-02-18 02:43:16 +03:00
|
|
|
}
|
2019-11-11 09:25:47 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-04-11 03:51:07 +03:00
|
|
|
// Read audio chunk from channel.
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("recording audio for period", "seconds", d.RecPeriod)
|
2024-04-11 03:51:07 +03:00
|
|
|
d.pb.Data = <-ch
|
|
|
|
d.l.Debug("read audio from channel", "length read", len(d.pb.Data))
|
|
|
|
d.l.Debug("first bytes of audio", "bytes [0:32]", fmt.Sprintf("%x", d.pb.Data[0:4]))
|
2019-11-11 09:25:47 +03:00
|
|
|
|
|
|
|
// Process audio.
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("processing audio")
|
2019-11-11 09:25:47 +03:00
|
|
|
toWrite := d.formatBuffer()
|
|
|
|
|
|
|
|
// Write audio to ringbuffer.
|
2021-05-17 04:33:41 +03:00
|
|
|
n, err := d.buf.Write(toWrite.Data)
|
2019-11-11 09:25:47 +03:00
|
|
|
switch err {
|
|
|
|
case nil:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug("wrote audio to ringbuffer", "length", n)
|
2021-05-17 04:33:41 +03:00
|
|
|
case pool.ErrDropped:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Warning("old audio data overwritten")
|
2019-11-11 09:25:47 +03:00
|
|
|
default:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Error("unexpected ringbuffer error", "error", err.Error())
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-04 05:26:24 +03:00
|
|
|
// chunkingRead reads continuously from the ALSA buffer in 1 minute sections. The
|
|
|
|
// audio is then chunked into the recording period set by d.RecPeriod and sent over
|
|
|
|
// the channel.
|
|
|
|
func chunkingRead(d *ALSA, ch chan []byte) {
|
2024-04-11 03:51:07 +03:00
|
|
|
d.l.Debug("Datasize of recperiod", "datasize", d.DataSize())
|
|
|
|
for {
|
|
|
|
buf := d.dev.NewBufferDuration(time.Minute)
|
|
|
|
// Read audio in 1 minute sections.
|
|
|
|
d.l.Debug("Reading audio for 1 minute")
|
|
|
|
err := d.dev.Read(buf.Data)
|
|
|
|
if err != nil {
|
|
|
|
d.l.Debug("read failed", "error", err.Error())
|
|
|
|
err = d.open() // re-open
|
|
|
|
if err != nil {
|
|
|
|
d.l.Fatal("reopening device failed", "error", err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2024-04-04 05:26:24 +03:00
|
|
|
|
2024-04-11 03:51:07 +03:00
|
|
|
file, err := os.Create("formatted.pcm")
|
|
|
|
if err != nil {
|
|
|
|
d.l.Error("unable to create output file", "error", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
_, err = file.Write(buf.Data)
|
|
|
|
if err != nil {
|
|
|
|
d.l.Error("unable to write formatted audio to file", "error", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Chunk the audio into length of RecPeriod.
|
|
|
|
for i := 0; i < len(buf.Data); i += d.DataSize() {
|
|
|
|
ch <- buf.Data[i:(i + d.DataSize())]
|
|
|
|
}
|
2024-04-04 05:26:24 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-11 09:25:47 +03:00
|
|
|
// Read reads from the ringbuffer, returning the number of bytes read upon success.
|
2019-11-11 14:56:53 +03:00
|
|
|
func (d *ALSA) Read(p []byte) (int, error) {
|
2019-11-11 09:25:47 +03:00
|
|
|
// Ready ringbuffer for read.
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug(pkg + "getting next chunk ready")
|
2022-02-09 07:30:04 +03:00
|
|
|
_, err := d.buf.Next(rbNextTimeout)
|
2019-11-11 09:25:47 +03:00
|
|
|
if err != nil {
|
2022-01-27 04:20:45 +03:00
|
|
|
switch err {
|
2022-02-18 02:43:16 +03:00
|
|
|
case io.EOF:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug(pkg + "EOF from Next")
|
2022-02-14 07:14:35 +03:00
|
|
|
return 0, err
|
2022-01-27 04:20:45 +03:00
|
|
|
case pool.ErrTimeout:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug(pkg + "pool buffer timeout")
|
2022-02-18 02:40:01 +03:00
|
|
|
return 0, err
|
2022-01-27 04:20:45 +03:00
|
|
|
default:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Error(pkg+"unexpected error from Next", "error", err.Error())
|
2022-02-18 02:40:01 +03:00
|
|
|
return 0, err
|
2022-01-27 04:20:45 +03:00
|
|
|
}
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
2021-05-17 04:33:41 +03:00
|
|
|
// Read from pool buffer.
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug(pkg + "reading from buffer")
|
2022-01-27 04:20:45 +03:00
|
|
|
n, err := d.buf.Read(p)
|
|
|
|
if err != nil {
|
|
|
|
switch err {
|
2022-02-18 02:43:16 +03:00
|
|
|
case io.EOF:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug(pkg + "EOF from Read")
|
2022-02-09 09:08:10 +03:00
|
|
|
return n, err
|
2022-01-27 04:20:45 +03:00
|
|
|
default:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Error(pkg+"unexpected error from Read", "error", err.Error())
|
2022-02-18 02:40:01 +03:00
|
|
|
return n, err
|
2022-01-27 04:20:45 +03:00
|
|
|
}
|
|
|
|
}
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Debug(fmt.Sprintf("%v read %v bytes", pkg, n))
|
2022-01-27 04:20:45 +03:00
|
|
|
return n, nil
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// formatBuffer returns audio that has been converted to the desired format.
|
2019-11-13 09:24:41 +03:00
|
|
|
func (d *ALSA) formatBuffer() pcm.Buffer {
|
2019-11-11 09:25:47 +03:00
|
|
|
var err error
|
|
|
|
|
|
|
|
// If nothing needs to be changed, return the original.
|
2019-11-13 09:41:35 +03:00
|
|
|
if d.pb.Format.Channels == d.Channels && d.pb.Format.Rate == d.SampleRate {
|
2024-04-11 03:51:07 +03:00
|
|
|
d.l.Debug("doing nothing in formatBuffer")
|
2019-11-13 09:41:35 +03:00
|
|
|
return d.pb
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
2019-11-13 09:24:41 +03:00
|
|
|
var formatted pcm.Buffer
|
2019-11-13 09:41:35 +03:00
|
|
|
if d.pb.Format.Channels != d.Channels {
|
2019-11-11 09:25:47 +03:00
|
|
|
// Convert channels.
|
|
|
|
// TODO(Trek): Make this work for conversions other than stereo to mono.
|
2019-11-13 09:41:35 +03:00
|
|
|
if d.pb.Format.Channels == 2 && d.Channels == 1 {
|
|
|
|
formatted, err = pcm.StereoToMono(d.pb)
|
2019-11-11 09:25:47 +03:00
|
|
|
if err != nil {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Fatal("channel conversion failed", "error", err.Error())
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-13 09:41:35 +03:00
|
|
|
if d.pb.Format.Rate != d.SampleRate {
|
2019-11-11 09:25:47 +03:00
|
|
|
// Convert rate.
|
|
|
|
formatted, err = pcm.Resample(formatted, d.SampleRate)
|
|
|
|
if err != nil {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Fatal("rate conversion failed", "error", err.Error())
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch d.Codec {
|
|
|
|
case codecutil.PCM:
|
|
|
|
case codecutil.ADPCM:
|
|
|
|
b := bytes.NewBuffer(make([]byte, 0, adpcm.EncBytes(len(formatted.Data))))
|
|
|
|
enc := adpcm.NewEncoder(b)
|
|
|
|
_, err = enc.Write(formatted.Data)
|
|
|
|
if err != nil {
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Fatal("unable to encode", "error", err.Error())
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
formatted.Data = b.Bytes()
|
|
|
|
default:
|
2022-11-06 09:55:28 +03:00
|
|
|
d.l.Error("unhandled audio codec")
|
2019-11-11 09:25:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return formatted
|
|
|
|
}
|
|
|
|
|
2020-08-13 09:12:28 +03:00
|
|
|
// DataSize returns the size in bytes of the data ALSA device d will
|
|
|
|
// output in the duration of a single recording period.
|
2020-08-11 13:47:52 +03:00
|
|
|
func (d *ALSA) DataSize() int {
|
2020-12-24 03:25:44 +03:00
|
|
|
s := pcm.DataSize(d.SampleRate, d.Channels, d.BitDepth, d.RecPeriod)
|
|
|
|
if d.Codec == codecutil.ADPCM {
|
|
|
|
s = adpcm.EncBytes(s)
|
|
|
|
}
|
|
|
|
return s
|
2020-08-11 13:47:52 +03:00
|
|
|
}
|
|
|
|
|
2019-11-11 09:25:47 +03:00
|
|
|
// nearestPowerOfTwo finds and returns the nearest power of two to the given integer.
|
|
|
|
// If the lower and higher power of two are the same distance, it returns the higher power.
|
|
|
|
// For negative values, 1 is returned.
|
|
|
|
// Source: https://stackoverflow.com/a/45859570
|
|
|
|
func nearestPowerOfTwo(n int) int {
|
|
|
|
if n <= 0 {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
if n == 1 {
|
|
|
|
return 2
|
|
|
|
}
|
|
|
|
v := n
|
|
|
|
v--
|
|
|
|
v |= v >> 1
|
|
|
|
v |= v >> 2
|
|
|
|
v |= v >> 4
|
|
|
|
v |= v >> 8
|
|
|
|
v |= v >> 16
|
|
|
|
v++ // higher power of 2
|
|
|
|
x := v >> 1 // lower power of 2
|
|
|
|
if (v - n) > (n - x) {
|
|
|
|
return x
|
|
|
|
}
|
|
|
|
return v
|
|
|
|
}
|
2020-01-28 09:22:46 +03:00
|
|
|
|
|
|
|
// IsRunning is used to determine if the ALSA device is running.
|
|
|
|
func (d *ALSA) IsRunning() bool {
|
2020-01-30 03:52:24 +03:00
|
|
|
return d.mode == running
|
2020-01-28 09:22:46 +03:00
|
|
|
}
|