-
Notifications
You must be signed in to change notification settings - Fork 341
Expand file tree
/
Copy pathaudio.go
More file actions
194 lines (171 loc) · 4.72 KB
/
audio.go
File metadata and controls
194 lines (171 loc) · 4.72 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
package kvm
import (
"context"
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/jetkvm/kvm/internal/audio"
"github.com/pion/webrtc/v4"
"github.com/pion/webrtc/v4/pkg/media"
)
var (
audioCancel context.CancelFunc
audioStopped chan struct{}
audioTrack *webrtc.TrackLocalStaticSample
audioMu sync.Mutex
)
func startAudio(track *webrtc.TrackLocalStaticSample) {
audioMu.Lock()
defer audioMu.Unlock()
stopAudioLocked()
ctx, cancel := context.WithCancel(context.Background())
audioCancel = cancel
audioStopped = make(chan struct{})
audioTrack = track
go runAudioCapture(ctx, track, audioStopped)
}
func stopAudio() {
audioMu.Lock()
defer audioMu.Unlock()
stopAudioLocked()
}
// stopAudioIfOwner stops the audio capture only if it is currently bound to
// track. Used on session teardown so capture doesn't keep writing samples to
// a track whose peer connection has closed.
func stopAudioIfOwner(track *webrtc.TrackLocalStaticSample) {
audioMu.Lock()
defer audioMu.Unlock()
if audioTrack != track {
return
}
stopAudioLocked()
}
func stopAudioLocked() {
if audioCancel == nil {
return
}
audioCancel()
<-audioStopped
audioCancel = nil
audioStopped = nil
audioTrack = nil
}
// reopenThreshold is the number of consecutive non-idle read errors that
// triggers a close+reopen of the ALSA handle. The C-side already recovers
// EPIPE/ESTRPIPE; errors that surface here (EBADFD, ENODEV, …) usually mean
// the handle is dead — typically a USB gadget rebuild or host reattach.
const reopenThreshold = 5
func runAudioCapture(ctx context.Context, track *webrtc.TrackLocalStaticSample, stopped chan<- struct{}) {
defer close(stopped)
codec := audio.CodecPCMU
if strings.EqualFold(track.Codec().MimeType, webrtc.MimeTypeG722) {
codec = audio.CodecG722
}
capture, err := openCaptureWithBackoff(ctx)
if err != nil {
return
}
defer func() { capture.Close() }()
audioLogger.Info().Str("codec", codec.String()).Msg("audio capture started")
defer audioLogger.Info().Msg("audio capture stopped")
sample := media.Sample{Duration: 20 * time.Millisecond}
consecutiveErrors := 0
for {
select {
case <-ctx.Done():
return
default:
}
payload, err := capture.ReadEncoded(codec)
if err != nil {
if errors.Is(err, audio.ErrNoAudioData) {
// Partial period or idle ALSA — back off ~half a frame so we
// don't spin while the buffer fills.
select {
case <-ctx.Done():
return
case <-time.After(10 * time.Millisecond):
}
continue
}
consecutiveErrors++
audioLogger.Warn().Err(err).Int("errs", consecutiveErrors).Msg("audio capture read failed")
if consecutiveErrors >= reopenThreshold {
capture.Close()
next, err := openCaptureWithBackoff(ctx)
if err != nil {
return
}
capture = next
consecutiveErrors = 0
continue
}
time.Sleep(100 * time.Millisecond)
continue
}
consecutiveErrors = 0
if len(payload) == 0 {
continue
}
sample.Data = payload
if err := track.WriteSample(sample); err != nil {
audioLogger.Warn().Err(err).Msg("audio sample write failed")
time.Sleep(100 * time.Millisecond)
}
}
}
// openCaptureWithBackoff opens the ALSA capture device, retrying with
// exponential backoff (capped at 2 s) until success or ctx cancellation.
// Re-resolves the card on every attempt so a USB re-enumeration that hands
// the gadget a new card number is picked up automatically.
func openCaptureWithBackoff(ctx context.Context) (*audio.ALSACapture, error) {
backoff := 100 * time.Millisecond
for {
device := alsaCaptureDevice()
capture, err := audio.OpenALSACapture(device)
if err == nil {
audioLogger.Info().Str("device", device).Msg("audio capture opened")
return capture, nil
}
audioLogger.Warn().Err(err).Str("device", device).Dur("retry_in", backoff).Msg("audio capture open failed")
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(backoff):
}
if backoff *= 2; backoff > 2*time.Second {
backoff = 2 * time.Second
}
}
}
// alsaCaptureDevice returns the ALSA device for the UAC1 gadget card.
func alsaCaptureDevice() string {
if card, ok := findALSACard("UAC1Gadget"); ok {
return "hw:" + strconv.Itoa(card) + ",0"
}
return "hw:1,0"
}
func findALSACard(cardID string) (int, bool) {
entries, err := os.ReadDir("/sys/class/sound")
if err != nil {
return 0, false
}
for _, entry := range entries {
name := entry.Name()
if !strings.HasPrefix(name, "card") {
continue
}
id, err := os.ReadFile(filepath.Join("/sys/class/sound", name, "id"))
if err != nil || strings.TrimSpace(string(id)) != cardID {
continue
}
if card, err := strconv.Atoi(strings.TrimPrefix(name, "card")); err == nil {
return card, true
}
}
return 0, false
}