-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathopendj.go
340 lines (282 loc) · 8.14 KB
/
opendj.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
package opendj
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/sync/errgroup"
)
var ErrorEmptyQueue = errors.New("can't pop from empty queue")
// Dj stores the queue and handlers
type Dj struct {
waitingQueue queue
currentEntry QueueEntry
handlers handlers
songStarted time.Time
}
type handlers struct {
newSongHandler func(QueueEntry)
endOfSongHandler func(QueueEntry, error)
errorHander func(error)
}
// Media represents a video or song that can be streamed.
//
// this can be anything youtube-dl supports.
type Media struct {
Title string
URL string
Duration time.Duration
}
// A QueueEntry represents media and metadata the can be ented into a queue.
type QueueEntry struct {
Media Media
Owner string
Dedication string
}
type queue struct {
Items []QueueEntry
sync.Mutex
}
// NewDj initializes and returns a new Dj struct.
func NewDj(queue []QueueEntry) (dj *Dj) {
_, err := exec.LookPath("yt-dlp")
if err != nil {
panic(err)
}
_, err = exec.LookPath("ffmpeg")
if err != nil {
panic(err)
}
dj = &Dj{}
dj.waitingQueue.Items = queue
return dj
}
// AddNewSongHandler adds a function that will be called every time a new song starts playing.
func (dj *Dj) AddNewSongHandler(f func(QueueEntry)) {
dj.handlers.newSongHandler = f
}
// AddEndOfSongHandler adds a function that will be called every time a song stops playing.
// It gets passed the QueueEntry that finished playing and any errors encountered during playback.
func (dj *Dj) AddEndOfSongHandler(f func(QueueEntry, error)) {
dj.handlers.endOfSongHandler = f
}
// AddPlaybackErrorHandler adds a function that will be called every time an error occurs during playback.
//
// In effect this mean it will be called every time ffmpeg or yt-dlp exit with an error.
// Sometimes ffmpeg can exit with code 1 even though the song was streamed successfully.
func (dj *Dj) AddPlaybackErrorHandler(f func(error)) {
dj.handlers.errorHander = f
}
// Queue return the current queue as a list of queue entries.
func (dj *Dj) Queue() []QueueEntry {
return dj.waitingQueue.Items
}
// AddEntry adds the passed QueueEntry at the end of the queue.
func (dj *Dj) AddEntry(newEntry QueueEntry) {
dj.waitingQueue.Lock()
dj.waitingQueue.Items = append(dj.waitingQueue.Items, newEntry)
dj.waitingQueue.Unlock()
}
// InsertEntry inserts the passed QueueEntry into the queue at the given index.
//
// if the index is too high it has the same effect as AddEntry().
// returns an error if the index is < 0.
func (dj *Dj) InsertEntry(newEntry QueueEntry, index int) error {
dj.waitingQueue.Lock()
defer dj.waitingQueue.Unlock()
if index < 0 {
return errors.New("index out of range")
} else if index >= len(dj.waitingQueue.Items) {
dj.waitingQueue.Items = append(dj.waitingQueue.Items, newEntry)
return nil
}
dj.waitingQueue.Items = append(dj.waitingQueue.Items, QueueEntry{})
copy(dj.waitingQueue.Items[index+1:], dj.waitingQueue.Items[index:])
dj.waitingQueue.Items[index] = newEntry
return nil
}
// RemoveIndex removes the element the given index from the queue
//
// returns an error if the index is out of range.
func (dj *Dj) RemoveIndex(index int) error {
dj.waitingQueue.Lock()
defer dj.waitingQueue.Unlock()
if index >= len(dj.waitingQueue.Items) || index < 0 {
return errors.New("index out of range")
}
dj.waitingQueue.Items = append(dj.waitingQueue.Items[:index], dj.waitingQueue.Items[index+1:]...)
return nil
}
// ChangeIndex swaps the QueueEntry the index for the provided one
//
// returns an error if the index is out of range
func (dj *Dj) ChangeIndex(newEntry QueueEntry, index int) error {
dj.waitingQueue.Lock()
defer dj.waitingQueue.Unlock()
if index < 0 || index >= len(dj.waitingQueue.Items) {
return errors.New("index out of range")
}
dj.waitingQueue.Items[index] = newEntry
return nil
}
func (dj *Dj) pop() (QueueEntry, error) {
dj.waitingQueue.Lock()
defer dj.waitingQueue.Unlock()
if len(dj.waitingQueue.Items) < 1 {
return QueueEntry{}, ErrorEmptyQueue
}
entry := dj.waitingQueue.Items[0]
dj.waitingQueue.Items = dj.waitingQueue.Items[1:]
return entry, nil
}
// EntryAtIndex returns the QueueEntry at the given index or error if the index is out of range
func (dj *Dj) EntryAtIndex(index int) (QueueEntry, error) {
dj.waitingQueue.Lock()
defer dj.waitingQueue.Unlock()
if index >= len(dj.waitingQueue.Items) || index < 0 {
return QueueEntry{}, errors.New("index out of range")
}
entry := dj.waitingQueue.Items[index]
return entry, nil
}
// Play starts the playback to the given RTMP server.
//
// If nothing is in the playlist it waits for new content to be added.
// Any encoutered errors are handled by the errorHandler.
func (dj *Dj) Play(rtmpServer string) {
const fifoPath = "/tmp/opendj-fifo"
_ = os.Remove(fifoPath)
if err := syscall.Mkfifo(fifoPath, 0o0644); err != nil {
panic(err)
}
eg := errgroup.Group{}
eg.Go(func() error {
emptyStreamCounter := 0
fifo, err := os.OpenFile(fifoPath, os.O_CREATE|os.O_WRONLY, os.ModeNamedPipe)
if err != nil {
return err
}
defer fifo.Close()
for {
entry, err := dj.pop()
if err != nil {
dj.currentEntry = QueueEntry{}
// In the case that the queue is empty, input 15 seconds of
// silence into the pipe up to 4 consecutive times before
// returning
if errors.Is(err, ErrorEmptyQueue) {
if emptyStreamCounter >= 4 {
break
}
if err = writeToFIFO(
fifo,
"-re",
"-t", "00:00:15",
"-f", "lavfi",
"-i", "anullsrc",
); err != nil {
return err
}
emptyStreamCounter++
continue
}
return err
}
dj.currentEntry = entry
output, err := exec.Command("yt-dlp", "-f", "bestaudio", "-g", entry.Media.URL).Output()
if err != nil {
return err
}
audioURL := strings.TrimSpace(string(output))
if dj.handlers.newSongHandler != nil {
dj.handlers.newSongHandler(entry)
}
dj.songStarted = time.Now()
if err = writeToFIFO(
fifo,
"-reconnect", "1",
"-i", audioURL,
"-af", "apad=pad_dur=5",
); err != nil {
return err
}
if dj.handlers.endOfSongHandler != nil {
dj.handlers.endOfSongHandler(entry, err)
}
}
return nil
})
eg.Go(func() error {
time.Sleep(5 * time.Second)
cmd := exec.Command(
"ffmpeg",
"-re",
"-i", fifoPath,
"-c", "copy",
"-f", "flv",
rtmpServer,
)
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to stream from fifo: %w", err)
}
return nil
})
if err := eg.Wait(); err != nil {
if dj.handlers.errorHander != nil {
dj.handlers.errorHander(err)
}
}
}
// UserPosition returns a slice of all the position in the queue that belong to the given user.
func (dj *Dj) UserPosition(nick string) (positions []int) {
dj.waitingQueue.Lock()
defer dj.waitingQueue.Unlock()
for i, content := range dj.waitingQueue.Items {
if content.Owner == nick {
positions = append(positions, i)
}
}
return positions
}
// DurationUntilUser returns a slice of all the durations to the songs in the queue that belong to the given user.
func (dj *Dj) DurationUntilUser(nick string) (durations []time.Duration) {
dj.waitingQueue.Lock()
defer dj.waitingQueue.Unlock()
dur := dj.currentEntry.Media.Duration - time.Since(dj.songStarted)
for _, content := range dj.waitingQueue.Items {
if content.Owner == nick {
durations = append(durations, dur)
}
dur += content.Media.Duration
}
return durations
}
// CurrentlyPlaying returns the song that is currently being played and for how long it has been playing.
//
// Returns an error if there is nothing playing.
func (dj *Dj) CurrentlyPlaying() (entry QueueEntry, progress time.Duration, err error) {
if dj.currentEntry.Media == (Media{}) {
err = errors.New("there is no song being played")
}
return dj.currentEntry, time.Since(dj.songStarted), err
}
func writeToFIFO(fifo *os.File, args ...string) error {
args = append(args, []string{
"-c:a", "aac",
"-strict", "-2",
"-ar", "44100",
"-b:a", "160k",
"-ac", "2",
"-f", "mpegts", "pipe:1",
}...)
cmd := exec.Command("ffmpeg", args...)
cmd.Stdout = fifo
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to write to pipe: %w", err)
}
return nil
}