-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream_test.go
274 lines (239 loc) · 5.81 KB
/
stream_test.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
package audiostream_test
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/davidae/audiostream"
)
func TestStreamingToTwoListenersWithNoMetadata(t *testing.T) {
data := "123456789 101112131415161718192021222324252627"
s := audiostream.NewStream(audiostream.WithFramzeSize(2))
c1, err := audiostream.NewListener()
noError(err, t)
c2, err := audiostream.NewListener()
noError(err, t)
s.AddListener(c1, c2)
s.AppendAudio(&audiostream.Audio{
Artist: "Foo ft. Bar",
Title: "Hello world",
Data: strings.NewReader(data),
SampleRate: 44100,
})
go func() {
// ignore error return here, not testing that.
s.Start()
}()
var outc1, outc2 string
end := false
for {
select {
case msg := <-c1.Stream():
outc1 += string(msg)
case msg := <-c2.Stream():
outc2 += string(msg)
case <-time.After(time.Second):
end = true
}
if end {
break
}
}
s.Stop()
if outc1 != data {
t.Errorf("expected client 1 to have streamed %q, but got %q", data, outc1)
}
if outc2 != data {
t.Errorf("expected client 2 to have streamed %q, but got %q", data, outc2)
}
}
func TestStreamingToListenerWithMultipleFiles(t *testing.T) {
data := "123456789 101112131415161718192021222324252627"
s := audiostream.NewStream(audiostream.WithFramzeSize(2))
c1, err := audiostream.NewListener()
noError(err, t)
s.AddListener(c1)
audio := &audiostream.Audio{
Artist: "Foo ft. Bar",
Title: "Hello world",
Data: strings.NewReader(data),
SampleRate: 44100,
}
s.AppendAudio(audio)
s.AppendAudio(audio)
s.AppendAudio(audio)
go func() {
s.Start()
}()
dequeueComplete := false
go func() {
q := <-s.Dequeued()
if q != 2 {
t.Errorf("expected queue to be 2, got %d", q)
}
q = <-s.Dequeued()
if q != 1 {
t.Errorf("expected queue to be 1, got %d", q)
}
q = <-s.Dequeued()
if q != 0 {
t.Errorf("expected queue to be 0, got %d", q)
}
dequeueComplete = true
}()
var outc1 string
end := false
for {
select {
case msg := <-c1.Stream():
outc1 += string(msg)
case <-time.After(time.Second):
end = true
}
if end {
break
}
}
s.Stop()
if outc1 != data {
t.Errorf("expected client 1 to have streamed %q, but got %q", data, outc1)
}
if !dequeueComplete {
t.Errorf("expected to listen and receive from dequeue channel")
}
}
func TestStreamingMetadataWithInterval(t *testing.T) {
data := "123456789 101112131415161718192021222324252627"
expectedStreamTitle := "Foo ft. Bar - Hello world"
s := audiostream.NewStream(
audiostream.WithFramzeSize(len(data)),
)
s.AppendAudio(&audiostream.Audio{
Artist: "Foo ft. Bar",
Title: "Hello world",
Data: strings.NewReader(data),
})
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
panic(errors.New("need a flusher for keep alive"))
}
w.Header().Set("Connection", "Keep-Alive")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Content-Type", "audio/mpeg")
w.Header().Set("icy-metadata", "1")
w.Header().Set("icy-metaint", "10")
w.Header().Set("icy-name", "hello world")
client, err := audiostream.NewListener(audiostream.WithIcyMetadataSupport(10))
noError(err, t)
s.AddListener(client)
endLoop := false
for !endLoop {
select {
case <-time.After(time.Second * 2):
endLoop = true
case out, ok := <-client.Stream():
if !ok {
endLoop = true
break
}
binary.Write(w, binary.BigEndian, out)
flusher.Flush()
}
}
s.RemoveListener(client)
}))
defer ts.Close()
go func() {
s, err := GetStreamTitle(ts.URL)
if err != nil {
t.Errorf("unexpected error: %s", err)
}
if s != expectedStreamTitle {
t.Errorf("expected stream title %s, but got %s", expectedStreamTitle, s)
}
}()
time.Sleep(time.Second)
go func() {
// ignore error return here, not testing that.
s.Start()
}()
time.Sleep(time.Second)
s.Stop()
}
// BORROWED FROM https://gist.github.com/jucrouzet/3e59877c0b4352966e6220034f2b84ac
// GetStreamTitle get the current song/show in an Icecast stream
func GetStreamTitle(streamUrl string) (string, error) {
m, err := getStreamMetas(streamUrl)
if err != nil {
return "", err
}
// Should be at least "StreamTitle=' '"
if len(m) < 15 {
return "", nil
}
// Split meta by ';', trim it and search for StreamTitle
for _, m := range bytes.Split(m, []byte(";")) {
m = bytes.Trim(m, " \t")
if bytes.Compare(m[0:13], []byte("StreamTitle='")) != 0 {
continue
}
return string(m[13 : len(m)-1]), nil
}
return "", nil
}
// get stream metadatas
func getStreamMetas(streamUrl string) ([]byte, error) {
client := &http.Client{}
req, _ := http.NewRequest("GET", streamUrl, nil)
req.Header.Set("Icy-MetaData", "1")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
// We sent "Icy-MetaData", we should have a "icy-metaint" in return
ih := resp.Header.Get("icy-metaint")
if ih == "" {
return nil, fmt.Errorf("no metadata")
}
// "icy-metaint" is how often (in bytes) should we receive the meta
ib, err := strconv.Atoi(ih)
if err != nil {
return nil, err
}
reader := bufio.NewReader(resp.Body)
// skip the first mp3 frame
c, err := reader.Discard(ib)
if err != nil {
return nil, err
}
// If we didn't received ib bytes, the stream is ended
if c != ib {
return nil, fmt.Errorf("stream ended prematurally")
}
// get the size byte, that is the metadata length in bytes / 16
sb, err := reader.ReadByte()
if err != nil {
return nil, err
}
ms := int(sb * 16)
// read the ms first bytes it will contain metadata
m, err := reader.Peek(ms)
if err != nil {
return nil, err
}
return m, nil
}
func noError(err error, t *testing.T) {
if err != nil {
t.Errorf("unexpected error: %s", err)
}
}