-
Notifications
You must be signed in to change notification settings - Fork 27
/
client_primary_downloader.go
327 lines (282 loc) · 8 KB
/
client_primary_downloader.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
package gohlslib
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/bluenviron/gohlslib/v2/pkg/playlist"
)
func checkSupport(codecs []string) bool {
for _, codec := range codecs {
if !strings.HasPrefix(codec, "avc1.") &&
!strings.HasPrefix(codec, "hvc1.") &&
!strings.HasPrefix(codec, "hev1.") &&
!strings.HasPrefix(codec, "mp4a.") &&
codec != "opus" {
return false
}
}
return true
}
func cloneURL(ur *url.URL) *url.URL {
return &url.URL{
Scheme: ur.Scheme,
Opaque: ur.Opaque,
User: ur.User,
Host: ur.Host,
Path: ur.Path,
RawPath: ur.RawPath,
OmitHost: ur.OmitHost,
ForceQuery: ur.ForceQuery,
RawQuery: ur.RawQuery,
Fragment: ur.Fragment,
RawFragment: ur.RawFragment,
}
}
func clientDownloadPlaylist(
ctx context.Context,
httpClient *http.Client,
onRequest ClientOnRequestFunc,
ur *url.URL,
) (playlist.Playlist, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ur.String(), nil)
if err != nil {
return nil, err
}
onRequest(req)
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad status code: %d", res.StatusCode)
}
byts, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
return playlist.Unmarshal(byts)
}
func pickLeadingPlaylist(variants []*playlist.MultivariantVariant) *playlist.MultivariantVariant {
var candidates []*playlist.MultivariantVariant //nolint:prealloc
for _, v := range variants {
if !checkSupport(v.Codecs) {
continue
}
candidates = append(candidates, v)
}
if candidates == nil {
return nil
}
// pick the variant with the greatest bandwidth
var leadingPlaylist *playlist.MultivariantVariant
for _, v := range candidates {
if leadingPlaylist == nil ||
v.Bandwidth > leadingPlaylist.Bandwidth {
leadingPlaylist = v
}
}
return leadingPlaylist
}
func pickAudioPlaylist(alternatives []*playlist.MultivariantRendition, groupID string) *playlist.MultivariantRendition {
candidates := func() []*playlist.MultivariantRendition {
var ret []*playlist.MultivariantRendition
for _, alt := range alternatives {
if alt.GroupID == groupID {
ret = append(ret, alt)
}
}
return ret
}()
if candidates == nil {
return nil
}
// pick the default audio playlist
for _, alt := range candidates {
if alt.Default {
return alt
}
}
// alternatively, pick the first one
return candidates[0]
}
type streamTracksEntry struct {
isLeading bool
tracks []*Track
}
type clientPrimaryDownloader struct {
primaryPlaylistURL *url.URL
httpClient *http.Client
onRequest ClientOnRequestFunc
onDownloadPrimaryPlaylist ClientOnDownloadPrimaryPlaylistFunc
onDownloadStreamPlaylist ClientOnDownloadStreamPlaylistFunc
onDownloadSegment ClientOnDownloadSegmentFunc
onDownloadPart ClientOnDownloadPartFunc
onDecodeError ClientOnDecodeErrorFunc
rp *clientRoutinePool
setTracks func([]*Track) (map[*Track]*clientTrack, error)
setLeadingTimeConv func(ts clientTimeConv)
getLeadingTimeConv func(ctx context.Context) (clientTimeConv, bool)
clientTracks map[*Track]*clientTrack
// in
chStreamTracks chan streamTracksEntry
chStreamEnded chan struct{}
// out
startStreaming chan struct{}
}
func (d *clientPrimaryDownloader) initialize() {
d.chStreamTracks = make(chan streamTracksEntry)
d.chStreamEnded = make(chan struct{})
d.startStreaming = make(chan struct{})
}
func (d *clientPrimaryDownloader) run(ctx context.Context) error {
d.onDownloadPrimaryPlaylist(d.primaryPlaylistURL.String())
pl, err := clientDownloadPlaylist(ctx, d.httpClient, d.onRequest, d.primaryPlaylistURL)
if err != nil {
return err
}
streamCount := 0
switch plt := pl.(type) {
case *playlist.Media:
ds := &clientStreamDownloader{
isLeading: true,
httpClient: d.httpClient,
onRequest: d.onRequest,
onDownloadStreamPlaylist: d.onDownloadStreamPlaylist,
onDownloadSegment: d.onDownloadSegment,
onDownloadPart: d.onDownloadPart,
onDecodeError: d.onDecodeError,
playlistURL: d.primaryPlaylistURL,
firstPlaylist: plt,
rp: d.rp,
setStreamTracks: d.setStreamTracks,
setStreamEnded: d.setStreamEnded,
setLeadingTimeConv: d.setLeadingTimeConv,
getLeadingTimeConv: d.getLeadingTimeConv,
}
d.rp.add(ds)
streamCount++
case *playlist.Multivariant:
leadingPlaylist := pickLeadingPlaylist(plt.Variants)
if leadingPlaylist == nil {
return fmt.Errorf("no variants with supported codecs found")
}
var u *url.URL
u, err = clientAbsoluteURL(d.primaryPlaylistURL, leadingPlaylist.URI)
if err != nil {
return err
}
ds := &clientStreamDownloader{
isLeading: true,
httpClient: d.httpClient,
onRequest: d.onRequest,
onDownloadStreamPlaylist: d.onDownloadStreamPlaylist,
onDownloadSegment: d.onDownloadSegment,
onDownloadPart: d.onDownloadPart,
onDecodeError: d.onDecodeError,
playlistURL: u,
firstPlaylist: nil,
rp: d.rp,
setStreamTracks: d.setStreamTracks,
setStreamEnded: d.setStreamEnded,
setLeadingTimeConv: d.setLeadingTimeConv,
getLeadingTimeConv: d.getLeadingTimeConv,
}
d.rp.add(ds)
streamCount++
if leadingPlaylist.Audio != "" {
audioPlaylist := pickAudioPlaylist(plt.Renditions, leadingPlaylist.Audio)
if audioPlaylist == nil {
return fmt.Errorf("audio playlist with id \"%s\" not found", leadingPlaylist.Audio)
}
if audioPlaylist.URI != nil {
u, err = clientAbsoluteURL(d.primaryPlaylistURL, *audioPlaylist.URI)
if err != nil {
return err
}
ds := &clientStreamDownloader{
isLeading: false,
onRequest: d.onRequest,
httpClient: d.httpClient,
onDownloadStreamPlaylist: d.onDownloadStreamPlaylist,
onDownloadSegment: d.onDownloadSegment,
onDownloadPart: d.onDownloadPart,
onDecodeError: d.onDecodeError,
playlistURL: u,
firstPlaylist: nil,
rp: d.rp,
setStreamTracks: d.setStreamTracks,
setLeadingTimeConv: d.setLeadingTimeConv,
getLeadingTimeConv: d.getLeadingTimeConv,
setStreamEnded: d.setStreamEnded,
}
d.rp.add(ds)
streamCount++
}
}
default:
return fmt.Errorf("invalid playlist")
}
var tracks []*Track
for i := 0; i < streamCount; i++ {
select {
case entry := <-d.chStreamTracks:
if entry.isLeading {
tracks = append(append([]*Track(nil), entry.tracks...), tracks...)
} else {
tracks = append(tracks, entry.tracks...)
}
case <-ctx.Done():
return fmt.Errorf("terminated")
}
}
if len(tracks) == 0 {
return fmt.Errorf("no supported tracks found")
}
d.clientTracks, err = d.setTracks(tracks)
if err != nil {
return err
}
close(d.startStreaming)
for i := 0; i < streamCount; i++ {
select {
case <-d.chStreamEnded:
case <-ctx.Done():
return fmt.Errorf("terminated")
}
}
return ErrClientEOS
}
func (d *clientPrimaryDownloader) setStreamTracks(
ctx context.Context,
isLeading bool,
tracks []*Track,
) ([]*clientTrack, bool) {
select {
case d.chStreamTracks <- streamTracksEntry{
isLeading: isLeading,
tracks: tracks,
}:
case <-ctx.Done():
return nil, false
}
select {
case <-d.startStreaming:
case <-ctx.Done():
return nil, false
}
streamClientTracks := make([]*clientTrack, len(tracks))
for i, track := range tracks {
streamClientTracks[i] = d.clientTracks[track]
}
return streamClientTracks, true
}
func (d *clientPrimaryDownloader) setStreamEnded(ctx context.Context) {
select {
case d.chStreamEnded <- struct{}{}:
case <-ctx.Done():
}
}