audio: added validate functions for device config

This commit is contained in:
Trek H 2019-06-18 18:35:45 +09:30
parent ba67d6d43d
commit 2d5ba8cd8f
2 changed files with 38 additions and 0 deletions

View File

@ -24,7 +24,13 @@ LICENSE
package codecutil
import "fmt"
// numCodecs is the number of entries in the list of codecs.
const numCodecs = 5
// A global list containing all available codecs for reference in any application.
// When adding or removing a codec from this list, the numCodecs const must be updated.
const (
PCM = iota
ADPCM
@ -32,3 +38,11 @@ const (
H265
MJPEG
)
// Validate recieves an int representing a codec and checks if it is valid.
func Validate(codec uint8) error {
if codec < 0 || codec >= numCodecs {
return fmt.Errorf("invalid codec")
}
return nil
}

View File

@ -93,6 +93,9 @@ type OpenError error
// NewDevice initializes and returns an Device which can be started, read from, and stopped.
func NewDevice(cfg *Config, l Logger) (*Device, error) {
validate(cfg)
d := &Device{
Config: cfg,
l: l,
@ -169,6 +172,27 @@ func (d *Device) ChunkSize() int {
return d.chunkSize
}
// validate checks if Config parameters are valid and returns an error if they are not.
func validate(c *Config) error {
if c.SampleRate <= 0 {
return fmt.Errorf("invalid sample rate: %v", c.SampleRate)
}
if c.Channels <= 0 {
return fmt.Errorf("invalid number of channels: %v", c.Channels)
}
if c.BitDepth <= 0 {
return fmt.Errorf("invalid bitdepth: %v", c.BitDepth)
}
if c.RecPeriod <= 0 {
return fmt.Errorf("invalid recording period: %v", c.RecPeriod)
}
err := codecutil.Validate(c.Codec)
if err != nil {
return err
}
return nil
}
// open the recording device with the given name and prepare it to record.
// If name is empty, the first recording device is used.
func (d *Device) open() error {