-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
108 lines (90 loc) · 2.26 KB
/
main.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
package main
// #cgo LDFLAGS: -lX11
// #include <X11/Xlib.h>
// #include <X11/X.h>
// #include <stdlib.h>
import "C"
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"time"
"unsafe"
"github.com/jfreymuth/pulse"
"github.com/jfreymuth/pulse/proto"
)
// Play a sound when coming out of idle.
// Directly mute / unmute.
const idleTimeout = time.Minute * 10
func main() {
micIndexFlag := flag.Int("mic-index", -1, "Source index of mic.")
micNameFlag := flag.String("mic-name", "", "Source name of mic.")
keyCodeFlag := flag.Int("key-code", 134, "Key code of PTT key.")
flag.Parse()
micIndex := *micIndexFlag
micName := *micNameFlag
keyCode := *keyCodeFlag
if (micIndex == -1 && micName == "") || (micIndex != -1 && micName != "") {
fmt.Println("Must specify one of --mic-index or --mic-name.")
os.Exit(-1)
}
var err error
execDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
soundPath := fmt.Sprintf("%s/%s", execDir, "ptt.wav")
pulseClient, err := pulse.NewClient()
if err != nil {
log.Fatal(err)
}
var muteReq proto.SetSourceMute
if micIndex != -1 {
muteReq.SourceIndex = uint32(micIndex)
} else {
muteReq.SourceName = micName
}
muted := false
setMute := func(mute bool) {
if mute != muted {
muteReq.Mute = mute
err := pulseClient.RawRequest(&muteReq, nil)
if err != nil {
log.Println(err)
}
cmd := exec.Command("aplay", soundPath)
cmd.Run()
muted = mute
}
}
watchForKey(keyCode, setMute)
}
func watchForKey(pttKey int, callback func(bool)) {
display := C.XOpenDisplay(nil)
pttKeyByte := pttKey / 8
pttKeyBit := pttKey % 8
pttKeyMask := byte(1 << uint(pttKeyBit))
keys := [32]C.char{}
activePollingInterval := time.Millisecond * 10
idlePollingInterval := time.Millisecond * 500
pollingInterval := activePollingInterval
lastPush := time.Now()
for {
C.XQueryKeymap(display, &keys[0])
keyArr := C.GoBytes(unsafe.Pointer(&keys), 32)
if (pttKeyMask & keyArr[pttKeyByte]) == pttKeyMask {
callback(false)
lastPush = time.Now()
pollingInterval = activePollingInterval
} else {
callback(true)
}
if time.Now().Sub(lastPush).Milliseconds() > idleTimeout.Milliseconds() {
pollingInterval = idlePollingInterval
}
time.Sleep(pollingInterval)
}
}