/
play.go
289 lines (238 loc) · 7.82 KB
/
play.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
package player
import (
"fmt"
"io"
"sync"
"time"
"github.com/gookit/slog"
"github.com/keshon/melodix-discord-player/internal/config"
"github.com/keshon/melodix-discord-player/music/history"
"github.com/keshon/melodix-discord-player/music/pkg/dca"
"github.com/keshon/melodix-discord-player/music/utils"
)
// Play starts playing the current or specified song.
func (p *Player) Play(startAt int, song *Song) {
var cleanupDone sync.WaitGroup
// Listen for skip signal
if p.handleSkipSignal() {
return
}
// Get current song (from queue or as arg)
p.setupCurrentSong(startAt, song)
// Setup encoding
options, err := p.createEncodeOptions(startAt)
if err != nil {
slog.Fatalf("Failed to create encode options: %v", err)
}
// Start encoding
var encodeSessionError error
p.EncodingSession, encodeSessionError = dca.EncodeFile(p.CurrentSong.DownloadURL, options)
defer func() {
p.EncodingSession.Cleanup()
cleanupDone.Wait()
}()
// Connect to Discord channel and be ready
p.setupVoiceConnection()
// Send encoding to Discord stream
done := make(chan error, 1)
p.StreamingSession = dca.NewStream(p.EncodingSession, p.VoiceConnection, done)
// Set player status
p.CurrentStatus = StatusPlaying
// Setup history
h := history.NewHistory()
// Add current track to history
p.addSongToHistory(h)
// Add current song playback duration stat to history
p.addSongPlaybackStats(h)
// Handle done signal (finished or with error)
p.handleDoneSignal(done, h, encodeSessionError, &cleanupDone)
}
func (p *Player) handleSkipSignal() bool {
select {
case <-p.SkipInterrupt:
slog.Info("Song is interrupted for skip, stopping playback")
if p.VoiceConnection != nil {
p.VoiceConnection.Speaking(false)
}
p.EncodingSession.Cleanup()
return true
default:
// No skip signal, continue with playback
return false
}
}
func (p *Player) setupCurrentSong(startAt int, song *Song) {
if song != nil {
p.CurrentSong = song
} else {
if len(p.GetSongQueue()) > 0 {
var err error
p.CurrentSong, err = p.Dequeue()
if err != nil {
slog.Info("queue is empty")
}
}
}
if p.CurrentSong == nil {
slog.Info("No songs in queue")
return
}
}
func (p *Player) createEncodeOptions(startAt int) (*dca.EncodeOptions, error) {
config, err := config.NewConfig()
if err != nil {
return nil, fmt.Errorf("error loading config: %v", err)
}
return &dca.EncodeOptions{
Volume: 1.0,
FrameDuration: config.DcaFrameDuration,
Bitrate: config.DcaBitrate,
PacketLoss: config.DcaPacketLoss,
RawOutput: config.DcaRawOutput,
Application: config.DcaApplication,
CompressionLevel: config.DcaCompressionLevel,
BufferedFrames: config.DcaBufferedFrames,
VBR: config.DcaVBR,
StartTime: startAt,
ReconnectAtEOF: config.DcaReconnectAtEOF,
ReconnectStreamed: config.DcaReconnectStreamed,
ReconnectOnNetworkError: config.DcaReconnectOnNetworkError,
ReconnectOnHttpError: config.DcaReconnectOnHttpError,
ReconnectDelayMax: config.DcaReconnectDelayMax,
FfmpegBinaryPath: config.DcaFfmpegBinaryPath,
EncodingLineLog: config.DcaEncodingLineLog,
UserAgent: config.DcaUserAgent,
}, nil
}
func (p *Player) setupEncodingSession(options *dca.EncodeOptions) error {
var errEnc error
p.EncodingSession, errEnc = dca.EncodeFile(p.CurrentSong.DownloadURL, options)
return errEnc
}
func (p *Player) setupVoiceConnection() {
for p.VoiceConnection == nil || !p.VoiceConnection.Ready {
time.Sleep(100 * time.Millisecond)
}
err := p.VoiceConnection.Speaking(true)
if err != nil {
slog.Errorf("Error connecting to Discord voice: %v", err)
p.VoiceConnection.Speaking(false)
}
}
func (p *Player) addSongToHistory(h history.IHistory) {
historySong := &history.Song{
Name: p.CurrentSong.Title,
UserURL: p.CurrentSong.UserURL,
DownloadURL: p.CurrentSong.DownloadURL,
Duration: p.CurrentSong.Duration,
ID: p.CurrentSong.ID,
Thumbnail: history.Thumbnail(p.CurrentSong.Thumbnail),
}
h.AddTrackToHistory(p.VoiceConnection.GuildID, historySong)
}
func (p *Player) addSongPlaybackStats(h history.IHistory) {
interval := 2 * time.Second
ticker := time.NewTicker(interval)
defer ticker.Stop()
tickerDone := make(chan bool)
go func() {
for {
select {
case <-ticker.C:
if p.VoiceConnection != nil && p.StreamingSession != nil && p.CurrentSong != nil {
if !p.StreamingSession.Paused() {
err := h.AddPlaybackDurationStats(p.VoiceConnection.GuildID, p.CurrentSong.ID, float64(interval.Seconds()))
if err != nil {
slog.Warnf("Error adding playback duration stats to history: %v", err)
}
}
}
case <-tickerDone:
return
}
}
}()
tickerDone <- true
}
func (p *Player) handleDoneSignal(done chan error, h history.IHistory, errEnc error, cleanupDone *sync.WaitGroup) {
defer cleanupDone.Done()
select {
case <-done:
if errEnc != nil && errEnc != io.EOF {
p.handleError(errEnc)
return
}
if p.VoiceConnection == nil || p.StreamingSession == nil || p.CurrentSong == nil {
return
}
if p.CurrentSong.Source != SourceStream {
p.handleSongCompletion()
} else {
p.handleUnfinishedSong(0)
}
p.handlePlaybackCountStats(h)
}
}
func (p *Player) handleSongCompletion() {
if p.CurrentStatus != StatusPlaying {
return
}
songDuration, songPosition := p.getSongMetrics(p.EncodingSession, p.StreamingSession, p.CurrentSong)
if p.EncodingSession.Stats().Duration.Seconds() > 0 && songPosition.Seconds() > 0 && songPosition < songDuration {
p.handleUnfinishedSong(int(songPosition.Seconds()))
}
}
func (p *Player) handleUnfinishedSong(startAt int) {
slog.Warn("Song is done but still unfinished. Restarting from interrupted position...")
p.EncodingSession.Cleanup()
p.VoiceConnection.Speaking(false)
p.Play(startAt, p.CurrentSong)
}
func (p *Player) handlePlaybackCountStats(h history.IHistory) {
if err := h.AddPlaybackCountStats(p.VoiceConnection.GuildID, p.CurrentSong.ID); err != nil {
slog.Warnf("Error adding stats count stats to history: %v", err)
}
}
func (p *Player) handleError(err error) {
slog.Warnf("Song is done but an unexpected error occurred: %v", err)
time.Sleep(250 * time.Millisecond)
if p.VoiceConnection != nil {
p.VoiceConnection.Speaking(false)
}
p.CurrentStatus = StatusResting
p.EncodingSession.Cleanup()
}
// getSongMetrics calculates playback metrics for a song.
func (p *Player) getSongMetrics(encoding *dca.EncodeSession, streaming *dca.StreamingSession, song *Song) (songDuration, songPosition time.Duration) {
encodingDuration := encoding.Stats().Duration
encodingStartTime := time.Duration(encoding.Options().StartTime) * time.Second
streamingPosition := streaming.PlaybackPosition()
delay := encodingDuration - streamingPosition
params, err := utils.ParseQueryParamsFromURL(song.DownloadURL)
if err != nil {
slog.Warnf("Failed to parse download URL parameters: %v", err)
}
// Convert duration string to time.Duration
duration, err := time.ParseDuration(params["duration"])
if err != nil {
slog.Errorf("Error parsing duration:", err)
}
songDuration = time.Duration(duration) * time.Second
songPosition = encodingStartTime + streamingPosition + delay
slog.Infof("Total duration: %s, Stopped at: %s", songDuration, songPosition)
slog.Infof("Encoding ahead of streaming: %s, Encoding started time: %s", delay, encodingStartTime)
return songDuration, songPosition
}
func (p *Player) logPlayingInfo() {
slog.Warnf("Current status: %s", p.GetCurrentStatus())
if p.GetCurrentSong() != nil {
slog.Warn("Current song: %s", p.GetCurrentSong().Title)
} else {
slog.Warn("Current song is null")
}
slog.Warn("Song queue:")
for _, elem := range p.GetSongQueue() {
slog.Warn(elem.Title)
}
slog.Warn("Playlist count is ", len(p.GetSongQueue()))
}