forked from spezifisch/stmps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent_loop.go
271 lines (238 loc) · 8.1 KB
/
event_loop.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
// Copyright 2023 The STMPS Authors
// SPDX-License-Identifier: GPL-3.0-only
package main
import (
"sort"
"time"
"github.com/spezifisch/stmps/mpvplayer"
)
type eventLoop struct {
// scrobbles are handled by background loop
scrobbleNowPlaying chan string
scrobbleSubmissionTimer *time.Timer
}
func (ui *Ui) initEventLoops() {
el := &eventLoop{
scrobbleNowPlaying: make(chan string, 5),
}
ui.eventLoop = el
// create reused timer to scrobble after delay
el.scrobbleSubmissionTimer = time.NewTimer(0)
if !el.scrobbleSubmissionTimer.Stop() {
<-el.scrobbleSubmissionTimer.C
}
}
func (ui *Ui) runEventLoops() {
go ui.logEventLoops()
go ui.guiEventLoop()
go ui.backgroundEventLoop()
}
// logEventLoops processes log events
// This may look weird: why this way? Why not in guiEventLoop()? Why fork a
// goroutine for every message? Because, my friend, if we fill up the log chan,
// everything hangs, and we can't be *certain* the application won't generate
// more log messages in one UI tick than the chan size. We _could_ make the chan
// size really, absurdly large, but this still wouldn't be a guarantee. This may
// not be the most efficient implementation, but it ensures that the application
// will never hang because of chatty logging (as during DEBUG). This problem is
// particular to stmps because of how much threading is going on in this
// application, and in particular, because logPage.Print does UI stuff, which
// could hang trying to log too many things during this single Print() call.
func (ui *Ui) logEventLoops() {
for {
msg := <-ui.logger.Prints
// handle log page output
go ui.logPage.Print(msg)
}
}
// handle ui updates
func (ui *Ui) guiEventLoop() {
ui.addStarredToList()
events := 0.0
fpsTimer := time.NewTimer(0)
for {
events++
select {
case <-fpsTimer.C:
fpsTimer.Reset(10 * time.Second)
// ui.logger.Printf("guiEventLoop: %f events per second", events/10.0)
events = 0
case mpvEvent := <-ui.mpvEvents:
events++
// handle events from mpv wrapper
switch mpvEvent.Type {
case mpvplayer.EventStatus:
if mpvEvent.Data == nil {
continue
}
// TODO (E) is mpvEvent.Data thread-safe? maybe we need a copy
statusData := mpvEvent.Data.(mpvplayer.StatusData)
if ui.scanning {
scanning, err := ui.connection.ScanStatus()
if err != nil {
ui.logger.PrintError("ScanStatus", err)
}
ui.scanning = scanning.Scanning
}
ui.app.QueueUpdateDraw(func() {
txt := formatPlayerStatus(ui.scanning, statusData.Volume, statusData.Position, statusData.Duration)
ui.playerStatus.SetText(txt)
if ui.queuePage.lyrics != nil {
cl := ui.queuePage.currentLyrics.Lines
lcl := len(cl)
if lcl == 0 {
ui.queuePage.lyrics.SetText("\n[::i]No lyrics[-:-:-]")
} else {
// We only get an update every second or so, and Position is truncated
// to seconds. Make sure that, by the time our tick comes, we're already showing
// the lyric that's being sung. Do this by pretending that we're a half-second
// in the future
p := statusData.Position*1000 + 500
_, _, _, fh := ui.queuePage.lyrics.GetInnerRect()
i := sort.Search(len(cl), func(i int) bool {
return p < cl[i].Start
})
if i < lcl && p < cl[i].Start {
txt := ""
if i > 1 {
txt = cl[i-2].Value + "\n"
}
if i > 0 {
txt += "[::b]" + cl[i-1].Value + "[-:-:-]\n"
}
for k := i; k < lcl && k-i < fh; k++ {
txt += cl[k].Value + "\n"
}
ui.queuePage.lyrics.SetText(txt)
}
}
}
})
case mpvplayer.EventStopped:
ui.logger.Print("mpvEvent: stopped")
ui.app.QueueUpdateDraw(func() {
ui.startStopStatus.SetText("[red::b]Stopped[::-]")
if ui.queuePage.lyrics != nil {
ui.queuePage.lyrics.SetText("")
}
ui.queuePage.updateQueue()
})
case mpvplayer.EventPlaying:
ui.logger.Print("mpvEvent: playing")
statusText := "[green::b]Playing[::-]"
var currentSong mpvplayer.QueueItem
if mpvEvent.Data != nil {
// TODO (E) is mpvEvent.Data thread safe? maybe we need a copy
currentSong = mpvEvent.Data.(mpvplayer.QueueItem)
statusText += formatSongForStatusBar(¤tSong)
// Update MprisPlayer with new track info
if ui.mprisPlayer != nil {
ui.mprisPlayer.OnSongChange(currentSong)
}
lyrics := ui.queuePage.lyricsCache.Get(currentSong.Id)
if len(lyrics) > 0 {
ui.queuePage.currentLyrics = lyrics[0]
}
if ui.connection.Scrobble {
// scrobble "now playing" event (delegate to background event loop)
ui.eventLoop.scrobbleNowPlaying <- currentSong.Id
// scrobble "submission" after song has been playing a bit
// see: https://www.last.fm/api/scrobbling
// A track should only be scrobbled when the following conditions have been met:
// The track must be longer than 30 seconds. And the track has been played for
// at least half its duration, or for 4 minutes (whichever occurs earlier.)
if currentSong.Duration > 30 {
scrobbleDelay := currentSong.Duration / 2
if scrobbleDelay > 240 {
scrobbleDelay = 240
}
scrobbleDuration := time.Duration(scrobbleDelay) * time.Second
ui.eventLoop.scrobbleSubmissionTimer.Reset(scrobbleDuration)
ui.logger.Printf("scrobbler: timer started, %v", scrobbleDuration)
} else {
ui.logger.Printf("scrobbler: track too short")
}
}
}
ui.app.QueueUpdateDraw(func() {
ui.startStopStatus.SetText(statusText)
ui.queuePage.updateQueue()
if ui.queuePage.lyrics != nil {
if len(ui.queuePage.currentLyrics.Lines) == 0 {
ui.queuePage.lyrics.SetText("\n[::i]No lyrics[-:-:-]")
} else {
ui.queuePage.lyrics.SetText("")
}
}
})
case mpvplayer.EventPaused:
ui.logger.Print("mpvEvent: paused")
statusText := "[yellow::b]Paused[::-]"
var currentSong mpvplayer.QueueItem
if mpvEvent.Data != nil {
// TODO mpvEvent.Data thread safe? maybe we need a copy
currentSong = mpvEvent.Data.(mpvplayer.QueueItem)
statusText += formatSongForStatusBar(¤tSong)
}
ui.app.QueueUpdateDraw(func() {
ui.startStopStatus.SetText(statusText)
})
case mpvplayer.EventUnpaused:
ui.logger.Print("mpvEvent: unpaused")
statusText := "[green::b]Playing[::-]"
var currentSong mpvplayer.QueueItem
if mpvEvent.Data != nil {
// TODO is mpvEvent.Data thread safe? maybe we need a copy
currentSong = mpvEvent.Data.(mpvplayer.QueueItem)
statusText += formatSongForStatusBar(¤tSong)
}
ui.app.QueueUpdateDraw(func() {
ui.startStopStatus.SetText(statusText)
})
default:
ui.logger.Printf("guiEventLoop: unhandled mpvEvent %v", mpvEvent)
}
}
}
}
// loop for blocking background tasks that would otherwise block the ui
func (ui *Ui) backgroundEventLoop() {
for {
select {
case songId := <-ui.eventLoop.scrobbleNowPlaying:
// scrobble now playing
if _, err := ui.connection.ScrobbleSubmission(songId, false); err != nil {
ui.logger.PrintError("scrobble nowplaying", err)
}
case <-ui.eventLoop.scrobbleSubmissionTimer.C:
// scrobble submission delay elapsed
if currentSong, err := ui.player.GetPlayingTrack(); err != nil {
// user paused/stopped
ui.logger.Printf("not scrobbling: %v", err)
} else {
// it's still playing
ui.logger.Printf("scrobbling: %s", currentSong.Id)
if _, err := ui.connection.ScrobbleSubmission(currentSong.Id, true); err != nil {
ui.logger.PrintError("scrobble submission", err)
}
}
}
}
}
func (ui *Ui) addStarredToList() {
starred, err := ui.connection.GetStarred()
if err != nil {
ui.logger.PrintError("addStarredToList", err)
}
for _, e := range starred.Songs {
// We're storing empty struct as values as we only want the indexes
// It's faster having direct index access instead of looping through array values
ui.starIdList[e.Id] = struct{}{}
}
for _, e := range starred.Albums {
ui.starIdList[e.Id] = struct{}{}
}
for _, e := range starred.Artists {
ui.starIdList[e.Id] = struct{}{}
}
}