package audio import ( "encoding/binary" "errors" "math" "go.maze.io/harmon/internal/calc" ) var ErrFormat = errors.New("invalid audio format") type Format uint // Audio format. const ( ByteFormat Format = iota Int8Format Int16LEFormat Int16BEFormat Int32LEFormat Int32BEFormat Float32LEFormat Float32BEFormat invalidFormat ) func (f Format) Order() binary.ByteOrder { switch f { case Int16LEFormat, Int32LEFormat, Float32LEFormat: return binary.LittleEndian case Int16BEFormat, Int32BEFormat, Float32BEFormat: return binary.BigEndian default: return nil } } func (f Format) BytesPerSample() int { switch f { case ByteFormat, Int8Format: return 8 case Int16LEFormat, Int16BEFormat: return 16 case Int32LEFormat, Int32BEFormat, Float32LEFormat, Float32BEFormat: return 32 default: return 0 } } func (f Format) NewBuffer(size, channels int) Buffer { switch f { case Int8Format: return NewInt8Buffer(size, channels) case Int16LEFormat, Int16BEFormat: return NewInt16Buffer(size, channels, f.Order()) case Int32LEFormat, Int32BEFormat: return NewInt32Buffer(size, channels, f.Order()) case Float32LEFormat, Float32BEFormat: return NewFloat32Buffer(size, channels, f.Order()) default: return nil } } func Min(samples []float32) (min float32) { if len(samples) == 0 { return 0 } min = math.MaxFloat32 for _, sample := range samples { if sample < min { min = sample } } return } func abs(v float32) float32 { if v < 0 { return -v } return v } func Max(samples []float32) (max float32) { if len(samples) == 0 { return 0 } max = -math.MaxFloat32 for _, sample := range samples { if sample > max { max = sample } } return } func Abs(samples []float32) { if len(samples) == 0 { return } for i, sample := range samples { samples[i] = abs(sample) } } func Normalize(samples []float32) { if len(samples) == 0 { return } var max float32 for _, sample := range samples { if abs := abs(sample); abs > max { max = abs } } if max != 0 { for i := range samples { samples[i] /= max } } } func Clamp(sample float32) float32 { if sample < -1 { return -1 } if sample > +1 { return +1 } return sample } func RMS(samples []float32, channel, channels int) float64 { if channels == 1 { return calc.RMS(samples) } return calc.RMSOffset(samples, channel, channels) }