forked from luckfox-eng29/kvm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative_audio.go
More file actions
279 lines (232 loc) · 6.67 KB
/
native_audio.go
File metadata and controls
279 lines (232 loc) · 6.67 KB
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
package kvm
import (
"encoding/json"
"errors"
"fmt"
"net"
"os"
"os/exec"
"sync"
"time"
)
var (
audioCmd *exec.Cmd
audioCmdLock = &sync.Mutex{}
)
var audioSocketConn net.Conn
var audioOngoingRequests = make(map[int32]chan *CtrlResponse)
var audioLock = &sync.Mutex{}
func CallAudioCtrlAction(action string, params map[string]interface{}) (*CtrlResponse, error) {
audioLock.Lock()
defer audioLock.Unlock()
ctrlAction := CtrlAction{
Action: action,
Seq: seq,
Params: params,
}
responseChan := make(chan *CtrlResponse)
audioOngoingRequests[seq] = responseChan
seq++
jsonData, err := json.Marshal(ctrlAction)
if err != nil {
delete(audioOngoingRequests, ctrlAction.Seq)
return nil, fmt.Errorf("error marshaling ctrl action: %w", err)
}
scopedLogger := audioLogger.With().
Str("action", ctrlAction.Action).
Interface("params", ctrlAction.Params).Logger()
scopedLogger.Debug().Msg("sending audio ctrl action")
err = WriteAudioCtrlMessage(jsonData)
if err != nil {
delete(audioOngoingRequests, ctrlAction.Seq)
return nil, ErrorfL(&scopedLogger, "error writing audio ctrl message", err)
}
select {
case response := <-responseChan:
delete(audioOngoingRequests, seq)
if response.Error != "" {
return nil, ErrorfL(
&scopedLogger,
"error audio response: %s",
errors.New(response.Error),
)
}
return response, nil
case <-time.After(5 * time.Second):
close(responseChan)
delete(audioOngoingRequests, seq)
return nil, ErrorfL(&scopedLogger, "timeout waiting for response", nil)
}
}
func WriteAudioCtrlMessage(message []byte) error {
if audioSocketConn == nil {
return fmt.Errorf("audio socket not conn ected")
}
_, err := audioSocketConn.Write(message)
return err
}
var audioCtrlSocketListener net.Listener
var audioCtrlClientConnected = make(chan struct{})
func waitAudioCtrlClientConnected() {
<-audioCtrlClientConnected
}
func StartAudioSocketServer(socketPath string, handleClient func(net.Conn), isCtrl bool) net.Listener {
scopedLogger := audioLogger.With().
Str("socket_path", socketPath).
Logger()
// Remove the socket file if it already exists
if _, err := os.Stat(socketPath); err == nil {
if err := os.Remove(socketPath); err != nil {
scopedLogger.Warn().Err(err).Msg("failed to remove existing socket file")
os.Exit(1)
}
}
listener, err := net.Listen("unixpacket", socketPath)
if err != nil {
scopedLogger.Warn().Err(err).Msg("failed to start server")
os.Exit(1)
}
scopedLogger.Info().Msg("server listening")
go func() {
for {
conn, err := listener.Accept()
if err != nil {
scopedLogger.Warn().Err(err).Msg("failed to accept socket")
continue
}
if isCtrl {
// check if the channel is closed
select {
case <-audioCtrlClientConnected:
scopedLogger.Debug().Msg("audio ctrl client reconnected")
default:
close(audioCtrlClientConnected)
scopedLogger.Debug().Msg("first audio ctrl socket client connected")
}
}
//conn.Write([]byte("[handleAudioCtrlClient]audio sock test"))
go handleClient(conn)
}
}()
return listener
}
func StartAudioCtrlSocketServer() {
audioCtrlSocketListener = StartAudioSocketServer("/var/run/kvm_audio.sock", handleAudioCtrlClient, true)
audioLogger.Debug().Msg("audio ctrl sock started")
}
func handleAudioCtrlClient(conn net.Conn) {
defer conn.Close()
scopedLogger := audioLogger.With().
Str("addr", conn.RemoteAddr().String()).
Str("type", "audio_ctrl").
Logger()
scopedLogger.Info().Msg("audio socket client connected")
if audioSocketConn != nil {
scopedLogger.Debug().Msg("closing existing audio socket connection")
audioSocketConn.Close()
}
audioSocketConn = conn
readBuf := make([]byte, 4096)
for {
n, err := conn.Read(readBuf)
if err != nil {
scopedLogger.Warn().Err(err).Msg("error reading from audio sock")
break
}
readMsg := string(readBuf[:n])
audioResp := CtrlResponse{}
err = json.Unmarshal([]byte(readMsg), &audioResp)
if err != nil {
scopedLogger.Warn().Err(err).Str("data", readMsg).Msg("error parsing audio sock msg")
continue
}
scopedLogger.Trace().Interface("data", audioResp).Msg("audio sock msg")
if audioResp.Seq != 0 {
responseChan, ok := audioOngoingRequests[audioResp.Seq]
if ok {
responseChan <- &audioResp
}
}
switch audioResp.Event {
case "audio_input_state":
HandleAudioStateMessage(audioResp)
}
}
scopedLogger.Debug().Msg("audio sock disconnected")
}
func startAudioBinaryWithLock(binaryPath string) (*exec.Cmd, error) {
audioCmdLock.Lock()
defer audioCmdLock.Unlock()
cmd, err := startAudioBinary(binaryPath)
if err != nil {
return nil, err
}
audioCmd = cmd
return cmd, nil
}
func restartAudioBinary(binaryPath string) error {
time.Sleep(10 * time.Second)
// restart the binary
audioLogger.Info().Msg("restarting audio_video binary")
cmd, err := startAudioBinary(binaryPath)
if err != nil {
audioLogger.Warn().Err(err).Msg("failed to restart binary")
}
audioCmd = cmd
return err
}
func superviseAudioBinary(binaryPath string) error {
audioCmdLock.Lock()
defer audioCmdLock.Unlock()
if audioCmd == nil || audioCmd.Process == nil {
return restartAudioBinary(binaryPath)
}
err := audioCmd.Wait()
if err == nil {
audioLogger.Info().Err(err).Msg("kvm_audio binary exited with no error")
} else if exiterr, ok := err.(*exec.ExitError); ok {
audioLogger.Warn().Int("exit_code", exiterr.ExitCode()).Msg("kvm_audio binary exited with error")
} else {
audioLogger.Warn().Err(err).Msg("kvm_audio binary exited with unknown error")
}
return restartAudioBinary(binaryPath)
}
func ExtractAndRunAudioBin() error {
binaryPath := "/userdata/picokvm/bin/kvm_audio"
// Make the binary executable
if err := os.Chmod(binaryPath, 0755); err != nil {
return fmt.Errorf("failed to make binary executable: %w", err)
}
// Run the binary in the background
cmd, err := startAudioBinaryWithLock(binaryPath)
if err != nil {
return fmt.Errorf("failed to start binary: %w", err)
}
// check if the binary is still running every 10 seconds
go func() {
for {
select {
case <-appCtx.Done():
audioLogger.Info().Msg("stopping audio binary supervisor")
return
default:
err := superviseAudioBinary(binaryPath)
if err != nil {
audioLogger.Warn().Err(err).Msg("failed to supervise audio binary")
time.Sleep(1 * time.Second) // Add a short delay to prevent rapid successive calls
}
}
}
}()
go func() {
<-appCtx.Done()
audioLogger.Info().Int("pid", cmd.Process.Pid).Msg("killing process")
err := cmd.Process.Kill()
if err != nil {
audioLogger.Warn().Err(err).Msg("failed to kill process")
return
}
}()
audioLogger.Info().Int("pid", cmd.Process.Pid).Msg("kvm_audio binary started")
return nil
}