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
|
package downloader
import (
"time"
"github.com/bwmarrin/discordgo"
)
type DlMessage int
const (
Clear DlMessage = iota
Pause
Resume
)
type connUpdate int
const (
attach connUpdate = iota
detach
)
type DownloadManager struct {
conn *discordgo.VoiceConnection
session *discordgo.Session
dls chan *Downloader
PlayState chan DlMessage
playStateChan chan DlMessage
proxyStateChan chan DlMessage
connUpdate chan connUpdate
proxyChan chan []byte
}
const proxyBufSize = 512
func NewManager(s *discordgo.Session) *DownloadManager {
dm := &DownloadManager{
session: s,
dls: make(chan *Downloader),
connUpdate: make(chan connUpdate, 1),
PlayState: make(chan DlMessage),
playStateChan: make(chan DlMessage),
proxyStateChan: make(chan DlMessage),
proxyChan: make(chan []byte, proxyBufSize),
}
go dm.teeStateMessages()
go dm.proxyOpusPackets()
go dm.playFromQueue()
return dm
}
func (m *DownloadManager) teeStateMessages() {
for msg := range m.PlayState {
m.playStateChan <- msg
m.proxyStateChan <- msg
}
}
func (m *DownloadManager) proxyOpusPackets() {
attachState := detach
playState := Resume
clear := false
loop:
for {
if playState == Pause {
select {
case playState = <-m.proxyStateChan:
continue loop
}
}
select { // first check if we have a state update message coming in
case playState = <-m.proxyStateChan:
continue loop
default:
}
// if we're clearing, empty
if clear {
for {
select {
case <-m.proxyChan:
case playState = <-m.proxyStateChan:
continue loop
default:
}
}
}
select {
case upd := <-m.connUpdate:
attachState = upd
default:
}
if attachState == attach {
select {
case upd := <-m.connUpdate:
attachState = upd
case m.conn.OpusSend <- <-m.proxyChan:
}
} else {
select {
case upd := <-m.connUpdate:
attachState = upd
}
}
}
}
func (m *DownloadManager) playFromQueue() {
loop:
for {
select {
case dl := <-m.dls:
dl.SendOn(m.proxyChan)
select {
case <-dl.done:
continue loop
case upd:=<-m.playStateChan:
}
}
}
}
func (m *DownloadManager) Enqueue(url string, startTime, endTime time.Duration) error {
dl, err := NewDownload(url, startTime, endTime)
if err != nil {
return err
}
m.dls <- dl
return nil
}
|