-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjack-peak-meter.go
370 lines (308 loc) · 8.61 KB
/
jack-peak-meter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"unsafe"
"github.com/xthexder/go-jack"
)
const (
disableCursor = "\033[?25l"
enableCursor = "\033[?25h"
moveCursorUp = "\033[F"
)
var (
counter int
)
var fillBlocks = []string{" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"}
type portStrings []string
func (p *portStrings) String() string {
return strings.Join(*p, ",")
}
func (p *portStrings) Set(value string) error {
*p = append(*p, value)
return nil
}
type visualizer struct {
channels int // Amount of input channels
offset int // Number of matching channels to skip over
buffer int // Smoothing graph with last n printed samples, set 1 to disable
amplifer float64 // Compensate weak audio signal with this ultimate amplifier value
printValues bool
printChnIdx bool
printNames bool
verbose bool
portMatches portStrings // Array of port match patterns used for input bindings
additionalBuffer int
avg float32
avgMain []float32
lastValues [][]float32
client *jack.Client
PortsIn []*jack.Port
srcPortNames portStrings
}
func (v *visualizer) Start() error {
var status int
var clientName string
// trying to establish JACK client
for i := 0; i < 1000; i++ {
clientName = fmt.Sprintf("spectrum analyser %d", i)
v.client, status = jack.ClientOpen(clientName, jack.NoStartServer)
if status == 0 {
break
}
}
if status != 0 {
return fmt.Errorf("failed to initialize client, errcode: %d", status)
}
defer v.client.Close()
// registering JACK callback
if code := v.client.SetProcessCallback(v.process); code != 0 {
return fmt.Errorf("failed to set process callback: %d", code)
}
v.client.OnShutdown(v.shutdown)
// Activating client
if code := v.client.Activate(); code != 0 {
return fmt.Errorf("failed to activate client: %d", code)
}
// find jack input ports
for i := range v.portMatches {
foundNames := v.client.GetPorts(v.portMatches[i], "", jack.PortIsOutput)
if len(foundNames) == 0 {
return fmt.Errorf("failed to find matching jack ports: %s", v.portMatches[i])
}
for n := range foundNames {
v.srcPortNames = append(v.srcPortNames, foundNames[n])
}
}
// adjust for offset, if any
if v.offset > 0 {
if v.offset >= len(v.srcPortNames) {
return fmt.Errorf("offset exceeds number of matching jack ports: %d >= %d", v.offset, len(v.srcPortNames))
}
v.srcPortNames = v.srcPortNames[v.offset:]
}
// print warning if # channels < # found
if v.channels < len(v.srcPortNames) {
fmt.Printf(">> Capturing the first %d channels of %d found <<\r", v.channels, len(v.srcPortNames))
}
// registering audio channels inputs and connecting them automatically to system monitor output
for i := 1; i <= v.channels && i <= len(v.srcPortNames); i++ {
portName := fmt.Sprintf("input_%d", i)
port := v.client.PortRegister(portName, jack.DEFAULT_AUDIO_TYPE, jack.PortIsInput, 0)
v.PortsIn = append(v.PortsIn, port)
srcPortName := v.srcPortNames[i-1]
dstPortName := fmt.Sprintf("%s:input_%d", clientName, i)
code := v.client.Connect(srcPortName, dstPortName)
if code != 0 {
return fmt.Errorf("Failed connecting port \"%s\" to \"%s\"\n", srcPortName, dstPortName)
}
if v.verbose {
fmt.Printf("connected port \"%s\" to \"%s\"\n", srcPortName, dstPortName)
}
}
fmt.Print(disableCursor) // disablingCursorblink
fmt.Print("\n")
interrupted := make(chan bool)
// signal handler
sigChan := make(chan os.Signal, 2)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigChan
v.shutdown()
interrupted <- true
}()
buffer := int(v.client.GetBufferSize())
v.additionalBuffer = v.calculateAdditionalBuffer(buffer)
<-interrupted
return nil
}
func getHighestSpread(samples []jack.AudioSample) jack.AudioSample {
var winner jack.AudioSample
for _, s := range samples {
if s < 0 {
s = -s
}
if s > winner {
winner = s
}
}
return winner
}
// JACK callback
func (v *visualizer) process(nframes uint32) int {
counter += 1
for i, port := range v.PortsIn {
samples := port.GetBuffer(nframes)
highest := float32(getHighestSpread(samples))
highest *= float32(v.amplifer)
v.avgMain[i] += highest
if counter >= v.additionalBuffer {
value := v.avgMain[i] / float32(v.additionalBuffer)
v.updateCache(value, i)
termWidth, termHeight := getTermWidthHeight()
if termHeight < v.channels {
fmt.Printf(">> Not sufficient space for bars <<\r")
} else {
v.printBar(v.getAvg(i), termWidth, i)
if i+1 != v.channels { // do not print newline for last bar
fmt.Print("\n")
}
v.avgMain[i] = 0
}
}
}
if counter >= v.additionalBuffer {
counter = 0
for i := 1; i < v.channels; i++ {
fmt.Print(moveCursorUp)
}
}
return 0
}
// JACK callback
func (v *visualizer) shutdown() {
fmt.Print(enableCursor + "\n")
v.client.Close()
}
func newVisualizer(channels, offset, buffer int, amplifier float64, portMatches portStrings, verbose, printValues, printChnIdx, printNames bool) visualizer {
var lastValues [][]float32
var avgMin []float32
// preparing fixed-size lastValues struct
for channel := 0; channel < channels; channel++ {
var tmp []float32
for frame := 0; frame < buffer; frame++ {
tmp = append(tmp, 0.0)
}
lastValues = append(lastValues, tmp)
avgMin = append(avgMin, 0.0)
}
// set default input ports pattern, if none provided
if len(portMatches) == 0 {
portMatches = portStrings{"system:(capture|monitor)_"}
}
return visualizer{
channels,
offset,
buffer,
amplifier,
printValues,
printChnIdx,
printNames,
verbose,
portMatches,
1,
0.0,
avgMin,
lastValues,
nil,
[]*jack.Port{},
portStrings{},
}
}
func (v *visualizer) updateCache(value float32, channel int) {
l := v.buffer - 1
for i := l; i > 0; i-- {
v.lastValues[channel][i] = v.lastValues[channel][i-1]
}
v.lastValues[channel][0] = value
}
func (v *visualizer) getAvg(channel int) float32 {
var avg float32
for _, v := range v.lastValues[channel] {
avg += v
}
avg = avg / float32(v.buffer)
if avg > 1 {
avg = 1
}
return avg
}
func (v *visualizer) calculateAdditionalBuffer(frameSize int) int {
if frameSize > 512 {
return 1
}
return 512 / frameSize
}
func (v *visualizer) printBar(value float32, width, chanNumber int) {
var bar = ""
if v.printValues {
width -= 10
bar = fmt.Sprintf(" %.3f |", value)
} else {
width -= 4
bar = " |"
}
if v.printNames {
width -= 26
bar = fmt.Sprintf(" %25s%s", v.srcPortNames[chanNumber], bar)
}
if v.printChnIdx {
width -= 4
bar = fmt.Sprintf(" %3d%s", chanNumber, bar)
}
bar = "\r" + bar
fullBlocks := int(float32(width) * value)
for i := 0; i < fullBlocks; i++ {
bar += fillBlocks[8] // full block fill
}
if fullBlocks < width {
fillBlockIdx := int((float32(width)*value - float32(fullBlocks)) * 8)
bar += fillBlocks[fillBlockIdx] // transition block fill
}
for i := 0; i <= width-fullBlocks-2; i++ {
bar += fillBlocks[0] // empty block fill
}
fmt.Print(bar + "| ")
}
type winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
func getTermWidthHeight() (x, y int) {
ws := &winsize{}
retCode, _, errno := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdin),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws)))
if int(retCode) == -1 {
panic(errno)
}
x = int(ws.Col)
y = int(ws.Row)
return
}
func main() {
var (
verbose *bool
printValues *bool
printChnIdx *bool
printNames *bool
flagChannels *int
flagOffset *int
flagBuffer *int
flagAmplifier *float64
portMatches portStrings
)
verbose = flag.Bool("verbose", false, "Print verbose messages for troubleshooting")
printValues = flag.Bool("values", false, "Print value before each channel of visualizer")
printChnIdx = flag.Bool("index", false, "Print channel index before each channel of visualizer")
printNames = flag.Bool("names", false, "Print channel names before each channel of visualizer")
flagChannels = flag.Int("channels", 2, "Maximum amount of input channels to meter")
flagOffset = flag.Int("offset", 0, "Number of matching channels to skip over")
flagBuffer = flag.Int("buffer", 10, "Smoothing graph with last n printed samples, set 1 to disable")
flagAmplifier = flag.Float64("amplify", 3.5, "Compensate weak audio signal with this ultimate amplifier value")
flag.Var(&portMatches, "port", "Name or regex pattern matching one or more jack ports.")
flag.Parse()
visualizer := newVisualizer(*flagChannels, *flagOffset, *flagBuffer, *flagAmplifier, portMatches, *verbose, *printValues, *printChnIdx, *printNames)
err := visualizer.Start()
if err != nil {
panic(err)
}
fmt.Println("Bye!")
}