-
-
Notifications
You must be signed in to change notification settings - Fork 444
/
session_map.go
376 lines (288 loc) · 10.4 KB
/
session_map.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
371
372
373
374
375
376
package deej
import (
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/omriharel/deej/util"
"github.com/thoas/go-funk"
"go.uber.org/zap"
)
type sessionMap struct {
deej *Deej
logger *zap.SugaredLogger
m map[string][]Session
lock sync.Locker
sessionFinder SessionFinder
lastSessionRefresh time.Time
unmappedSessions []Session
}
const (
masterSessionName = "master" // master device volume
systemSessionName = "system" // system sounds volume
inputSessionName = "mic" // microphone input level
// some targets need to be transformed before their correct audio sessions can be accessed.
// this prefix identifies those targets to ensure they don't contradict with another similarly-named process
specialTargetTransformPrefix = "deej."
// targets the currently active window (Windows-only, experimental)
specialTargetCurrentWindow = "current"
// targets all currently unmapped sessions (experimental)
specialTargetAllUnmapped = "unmapped"
// this threshold constant assumes that re-acquiring all sessions is a kind of expensive operation,
// and needs to be limited in some manner. this value was previously user-configurable through a config
// key "process_refresh_frequency", but exposing this type of implementation detail seems wrong now
minTimeBetweenSessionRefreshes = time.Second * 5
// determines whether the map should be refreshed when a slider moves.
// this is a bit greedy but allows us to ensure sessions are always re-acquired, which is
// especially important for process groups (because you can have one ongoing session
// always preventing lookup of other processes bound to its slider, which forces the user
// to manually refresh sessions). a cleaner way to do this down the line is by registering to notifications
// whenever a new session is added, but that's too hard to justify for how easy this solution is
maxTimeBetweenSessionRefreshes = time.Second * 45
)
// this matches friendly device names (on Windows), e.g. "Headphones (Realtek Audio)"
var deviceSessionKeyPattern = regexp.MustCompile(`^.+ \(.+\)$`)
func newSessionMap(deej *Deej, logger *zap.SugaredLogger, sessionFinder SessionFinder) (*sessionMap, error) {
logger = logger.Named("sessions")
m := &sessionMap{
deej: deej,
logger: logger,
m: make(map[string][]Session),
lock: &sync.Mutex{},
sessionFinder: sessionFinder,
}
logger.Debug("Created session map instance")
return m, nil
}
func (m *sessionMap) initialize() error {
if err := m.getAndAddSessions(); err != nil {
m.logger.Warnw("Failed to get all sessions during session map initialization", "error", err)
return fmt.Errorf("get all sessions during init: %w", err)
}
m.setupOnConfigReload()
m.setupOnSliderMove()
return nil
}
func (m *sessionMap) release() error {
if err := m.sessionFinder.Release(); err != nil {
m.logger.Warnw("Failed to release session finder during session map release", "error", err)
return fmt.Errorf("release session finder during release: %w", err)
}
return nil
}
// assumes the session map is clean!
// only call on a new session map or as part of refreshSessions which calls reset
func (m *sessionMap) getAndAddSessions() error {
// mark that we're refreshing before anything else
m.lastSessionRefresh = time.Now()
m.unmappedSessions = nil
sessions, err := m.sessionFinder.GetAllSessions()
if err != nil {
m.logger.Warnw("Failed to get sessions from session finder", "error", err)
return fmt.Errorf("get sessions from SessionFinder: %w", err)
}
for _, session := range sessions {
m.add(session)
if !m.sessionMapped(session) {
m.logger.Debugw("Tracking unmapped session", "session", session)
m.unmappedSessions = append(m.unmappedSessions, session)
}
}
m.logger.Infow("Got all audio sessions successfully", "sessionMap", m)
return nil
}
func (m *sessionMap) setupOnConfigReload() {
configReloadedChannel := m.deej.config.SubscribeToChanges()
go func() {
for {
select {
case <-configReloadedChannel:
m.logger.Info("Detected config reload, attempting to re-acquire all audio sessions")
m.refreshSessions(false)
}
}
}()
}
func (m *sessionMap) setupOnSliderMove() {
sliderEventsChannel := m.deej.serial.SubscribeToSliderMoveEvents()
go func() {
for {
select {
case event := <-sliderEventsChannel:
m.handleSliderMoveEvent(event)
}
}
}()
}
// performance: explain why force == true at every such use to avoid unintended forced refresh spams
func (m *sessionMap) refreshSessions(force bool) {
// make sure enough time passed since the last refresh, unless force is true in which case always clear
if !force && m.lastSessionRefresh.Add(minTimeBetweenSessionRefreshes).After(time.Now()) {
return
}
// clear and release sessions first
m.clear()
if err := m.getAndAddSessions(); err != nil {
m.logger.Warnw("Failed to re-acquire all audio sessions", "error", err)
} else {
m.logger.Debug("Re-acquired sessions successfully")
}
}
// returns true if a session is not currently mapped to any slider, false otherwise
// special sessions (master, system, mic) and device-specific sessions always count as mapped,
// even when absent from the config. this makes sense for every current feature that uses "unmapped sessions"
func (m *sessionMap) sessionMapped(session Session) bool {
// count master/system/mic as mapped
if funk.ContainsString([]string{masterSessionName, systemSessionName, inputSessionName}, session.Key()) {
return true
}
// count device sessions as mapped
if deviceSessionKeyPattern.MatchString(session.Key()) {
return true
}
matchFound := false
// look through the actual mappings
m.deej.config.SliderMapping.iterate(func(sliderIdx int, targets []string) {
for _, target := range targets {
// ignore special transforms
if m.targetHasSpecialTransform(target) {
continue
}
// safe to assume this has a single element because we made sure there's no special transform
target = m.resolveTarget(target)[0]
if target == session.Key() {
matchFound = true
return
}
}
})
return matchFound
}
func (m *sessionMap) handleSliderMoveEvent(event SliderMoveEvent) {
// first of all, ensure our session map isn't moldy
if m.lastSessionRefresh.Add(maxTimeBetweenSessionRefreshes).Before(time.Now()) {
m.logger.Debug("Stale session map detected on slider move, refreshing")
m.refreshSessions(true)
}
// get the targets mapped to this slider from the config
targets, ok := m.deej.config.SliderMapping.get(event.SliderID)
// if slider not found in config, silently ignore
if !ok {
return
}
targetFound := false
adjustmentFailed := false
// for each possible target for this slider...
for _, target := range targets {
// resolve the target name by cleaning it up and applying any special transformations.
// depending on the transformation applied, this can result in more than one target name
resolvedTargets := m.resolveTarget(target)
// for each resolved target...
for _, resolvedTarget := range resolvedTargets {
// check the map for matching sessions
sessions, ok := m.get(resolvedTarget)
// no sessions matching this target - move on
if !ok {
continue
}
targetFound = true
// iterate all matching sessions and adjust the volume of each one
for _, session := range sessions {
if session.GetVolume() != event.PercentValue {
if err := session.SetVolume(event.PercentValue); err != nil {
m.logger.Warnw("Failed to set target session volume", "error", err)
adjustmentFailed = true
}
}
}
}
}
// if we still haven't found a target or the volume adjustment failed, maybe look for the target again.
// processes could've opened since the last time this slider moved.
// if they haven't, the cooldown will take care to not spam it up
if !targetFound {
m.refreshSessions(false)
} else if adjustmentFailed {
// performance: the reason that forcing a refresh here is okay is that we'll only get here
// when a session's SetVolume call errored, such as in the case of a stale master session
// (or another, more catastrophic failure happens)
m.refreshSessions(true)
}
}
func (m *sessionMap) targetHasSpecialTransform(target string) bool {
return strings.HasPrefix(target, specialTargetTransformPrefix)
}
func (m *sessionMap) resolveTarget(target string) []string {
// start by ignoring the case
target = strings.ToLower(target)
// look for any special targets first, by examining the prefix
if m.targetHasSpecialTransform(target) {
return m.applyTargetTransform(strings.TrimPrefix(target, specialTargetTransformPrefix))
}
return []string{target}
}
func (m *sessionMap) applyTargetTransform(specialTargetName string) []string {
// select the transformation based on its name
switch specialTargetName {
// get current active window
case specialTargetCurrentWindow:
currentWindowProcessNames, err := util.GetCurrentWindowProcessNames()
// silently ignore errors here, as this is on deej's "hot path" (and it could just mean the user's running linux)
if err != nil {
return nil
}
// we could have gotten a non-lowercase names from that, so let's ensure we return ones that are lowercase
for targetIdx, target := range currentWindowProcessNames {
currentWindowProcessNames[targetIdx] = strings.ToLower(target)
}
// remove dupes
return funk.UniqString(currentWindowProcessNames)
// get currently unmapped sessions
case specialTargetAllUnmapped:
targetKeys := make([]string, len(m.unmappedSessions))
for sessionIdx, session := range m.unmappedSessions {
targetKeys[sessionIdx] = session.Key()
}
return targetKeys
}
return nil
}
func (m *sessionMap) add(value Session) {
m.lock.Lock()
defer m.lock.Unlock()
key := value.Key()
existing, ok := m.m[key]
if !ok {
m.m[key] = []Session{value}
} else {
m.m[key] = append(existing, value)
}
}
func (m *sessionMap) get(key string) ([]Session, bool) {
m.lock.Lock()
defer m.lock.Unlock()
value, ok := m.m[key]
return value, ok
}
func (m *sessionMap) clear() {
m.lock.Lock()
defer m.lock.Unlock()
m.logger.Debug("Releasing and clearing all audio sessions")
for key, sessions := range m.m {
for _, session := range sessions {
session.Release()
}
delete(m.m, key)
}
m.logger.Debug("Session map cleared")
}
func (m *sessionMap) String() string {
m.lock.Lock()
defer m.lock.Unlock()
sessionCount := 0
for _, value := range m.m {
sessionCount += len(value)
}
return fmt.Sprintf("<%d audio sessions>", sessionCount)
}