package audio import ( "image" "image/color" "image/draw" "math" "sort" "git.maze.io/go/bragi/audio" "periph.io/x/conn/v3/physic" ) var ( spriteLeft = []uint8{ 0x08, /* width */ 0x05, /* height */ 0b10000, 0b10000, 0b10000, 0b10000, 0b11110, } spriteRight = []uint8{ 0x08, /* width */ 0x05, /* height */ 0b11110, 0b10001, 0b11110, 0b10100, 0b10010, } ) type Peak struct { rate physic.Frequency channels int level audio.Float64 peaks []audio.Float64 } func NewPeak(sampleRate physic.Frequency, channels int, keep int) *Peak { if channels < 1 { channels = 1 } else if channels > 2 { channels = 2 } v := &Peak{ rate: sampleRate, channels: channels, level: make(audio.Float64, channels), } if keep > 0 { for i := 0; i < channels; i++ { v.peaks = append(v.peaks, make(audio.Float64, keep)) } } return v } func (v *Peak) Process(samples audio.Slice) { sum := make([]float64, v.channels) for i, l := 0, samples.Len(); i < l; i++ { k := samples.At(i) if k < 0 { k = -k } if k > 1 { k = 1 } n := i % v.channels sum[n] += math.Pow(k, 2) } //log.Printf("max: %+v", max) for n, k := range sum { l := math.Sqrt(k / float64(samples.Len())) v.level[n] = l if v.peaks != nil { copy(v.peaks[n][1:], v.peaks[n]) v.peaks[n][0] = l //sortSlice(v.peaks[n], true) } } } func (v *Peak) Render(dst draw.Image, origin image.Point, c color.Color) { var ( r = image.Rect(0, 0, 64, 11) scale = 1.0 / float64(r.Dx()-6) ) // Clear buffer draw.Draw(dst, r.Add(origin), image.Black, image.Point{}, draw.Src) ox, oy := origin.X, origin.Y // Draw sprites drawSprite(dst, ox-3, oy+0, spriteLeft[:], c) drawSprite(dst, ox-3, oy+6, spriteRight[:], c) // Draw line ox += 6 drawLine(dst, ox, oy+2, ox+r.Dx()-6, oy+2, c) drawLine(dst, ox, oy+8, ox+r.Dx()-6, oy+8, c) // Draw bar lw := int(v.level[0] / scale) rw := lw if v.channels > 1 { rw = int(v.level[1] / scale) } drawLine(dst, ox, oy+1, ox+lw, oy+1, c) drawLine(dst, ox, oy+3, ox+lw, oy+3, c) drawLine(dst, ox, oy+7, ox+rw, oy+7, c) drawLine(dst, ox, oy+9, ox+rw, oy+9, c) if v.peaks != nil { lw = int(audio.Max(v.peaks[0]) / scale) //int(v.peaks[0][0] / scale) rw = lw if v.channels > 1 { rw = int(audio.Max(v.peaks[1]) / scale) //int(v.peaks[1][0] / scale) } drawLine(dst, ox+lw, oy+1, ox+lw, oy+3, c) drawLine(dst, ox+rw, oy+7, ox+rw, oy+9, c) } } func sortSlice(s audio.Float64, reverse bool) { sort.Slice(s, func(i, j int) bool { if reverse { return s[i] > s[j] } return s[i] < s[j] }) } var _ Visualizer = (*Peak)(nil)