-
Notifications
You must be signed in to change notification settings - Fork 1
/
reader.go
665 lines (627 loc) · 18.4 KB
/
reader.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
package m3u8
/*
Part of M3U8 parser & generator library.
This file defines functions related to playlist parsing.
Copyleft 2013-2015 Alexander I.Grafov aka Axel <[email protected]>
Copyleft 2013-2015 library authors (see AUTHORS file).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
ॐ तारे तुत्तारे तुरे स्व
*/
import (
"bytes"
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"time"
)
var reKeyValue = regexp.MustCompile(`([a-zA-Z_-]+)=("[^"]+"|[^",]+)`)
// Parse master playlist from the buffer.
// If `strict` parameter is true then return first syntax error.
func (p *MasterPlaylist) Decode(data bytes.Buffer, strict bool) error {
return p.decode(&data, strict)
}
// Parse master playlist from the io.Reader stream.
// If `strict` parameter is true then return first syntax error.
func (p *MasterPlaylist) DecodeFrom(reader io.Reader, strict bool) error {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(reader)
if err != nil {
return err
}
return p.decode(buf, strict)
}
// Parse master playlist. Internal function.
func (p *MasterPlaylist) decode(buf *bytes.Buffer, strict bool) error {
var eof bool
state := new(decodingState)
for !eof {
line, err := buf.ReadString('\n')
if err == io.EOF {
eof = true
} else if err != nil {
break
}
err = decodeLineOfMasterPlaylist(p, state, line, strict)
if strict && err != nil {
return err
}
}
if strict && !state.m3u {
return errors.New("#EXTM3U absent")
}
return nil
}
// Parse media playlist from the buffer.
// If `strict` parameter is true then return first syntax error.
func (p *MediaPlaylist) Decode(data bytes.Buffer, strict bool) error {
return p.decode(&data, strict)
}
// Parse media playlist from the io.Reader stream.
// If `strict` parameter is true then return first syntax error.
func (p *MediaPlaylist) DecodeFrom(reader io.Reader, strict bool) error {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(reader)
if err != nil {
return err
}
return p.decode(buf, strict)
}
func (p *MediaPlaylist) decode(buf *bytes.Buffer, strict bool) error {
var eof bool
var line string
var err error
state := new(decodingState)
wv := new(WV)
for !eof {
if line, err = buf.ReadString('\n'); err == io.EOF {
eof = true
} else if err != nil {
break
}
err = decodeLineOfMediaPlaylist(p, wv, state, line, strict)
if strict && err != nil {
return err
}
}
if state.tagWV {
p.WV = wv
}
if strict && !state.m3u {
return errors.New("#EXTM3U absent")
}
return nil
}
// Detect playlist type and decode it from the buffer.
func Decode(data bytes.Buffer, strict bool) (Playlist, ListType, error) {
return decode(&data, strict)
}
// Detect playlist type and decode it from input stream.
func DecodeFrom(reader io.Reader, strict bool) (Playlist, ListType, error) {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(reader)
if err != nil {
return nil, 0, err
}
return decode(buf, strict)
}
// Detect playlist type and decode it. May be used as decoder for both master and media playlists.
func decode(buf *bytes.Buffer, strict bool) (Playlist, ListType, error) {
var eof bool
var line string
var master *MasterPlaylist
var media *MediaPlaylist
var listType ListType
var err error
state := new(decodingState)
wv := new(WV)
master = NewMasterPlaylist()
media, err = NewMediaPlaylist(8, 1024) // Winsize for VoD will become 0, capacity auto extends
if err != nil {
return nil, 0, fmt.Errorf("Create media playlist failed: %s", err)
}
for !eof {
if line, err = buf.ReadString('\n'); err == io.EOF {
eof = true
} else if err != nil {
break
}
// fixes the issues https://github.com/grafov/m3u8/issues/25
// TODO: the same should be done in decode functions of both Master- and MediaPlaylists
// so some DRYing would be needed.
if len(line) < 1 || line == "\r" {
continue
}
err = decodeLineOfMasterPlaylist(master, state, line, strict)
if strict && err != nil {
return master, state.listType, err
}
err = decodeLineOfMediaPlaylist(media, wv, state, line, strict)
if strict && err != nil {
return media, state.listType, err
}
}
if state.listType == MEDIA && state.tagWV {
media.WV = wv
}
if strict && !state.m3u {
return nil, listType, errors.New("#EXTM3U absent")
}
switch state.listType {
case MASTER:
return master, MASTER, nil
case MEDIA:
if media.Closed || media.MediaType == EVENT {
// VoD and Event's should show the entire playlist
media.SetWinSize(0)
}
return media, MEDIA, nil
default:
return nil, state.listType, errors.New("Can't detect playlist type")
}
return nil, state.listType, errors.New("This return is impossible. Saved for compatibility with go 1.0")
}
func decodeParamsLine(line string) map[string]string {
out := make(map[string]string)
for _, kv := range reKeyValue.FindAllStringSubmatch(line, -1) {
k, v := kv[1], kv[2]
out[k] = strings.Trim(v, ` "`)
}
return out
}
// Parse one line of master playlist.
func decodeLineOfMasterPlaylist(p *MasterPlaylist, state *decodingState, line string, strict bool) error {
var err error
line = strings.TrimSpace(line)
switch {
case line == "#EXTM3U": // start tag first
state.m3u = true
case strings.HasPrefix(line, "#EXT-X-VERSION:"): // version tag
state.listType = MASTER
_, err = fmt.Sscanf(line, "#EXT-X-VERSION:%d", &p.ver)
if strict && err != nil {
return err
}
case strings.HasPrefix(line, "#EXT-X-SESSION-KEY:"):
state.listType = MASTER
state.xsessionkey = new(Key)
for k, v := range decodeParamsLine(line[19:]) {
switch k {
case "METHOD":
state.xsessionkey.Method = v
case "URI":
state.xsessionkey.URI = v
case "IV":
state.xsessionkey.IV = v
case "KEYFORMAT":
state.xsessionkey.Keyformat = v
case "KEYFORMATVERSIONS":
state.xsessionkey.Keyformatversions = v
}
}
p.SessionKey = state.xsessionkey
case strings.HasPrefix(line, "#EXT-X-MEDIA:"):
var alt Alternative
state.listType = MASTER
for k, v := range decodeParamsLine(line[13:]) {
switch k {
case "TYPE":
alt.Type = v
case "GROUP-ID":
alt.GroupId = v
case "LANGUAGE":
alt.Language = v
case "NAME":
alt.Name = v
case "DEFAULT":
if strings.ToUpper(v) == "YES" {
alt.Default = true
} else if strings.ToUpper(v) == "NO" {
alt.Default = false
} else if strict {
return errors.New("value must be YES or NO")
}
case "AUTOSELECT":
alt.Autoselect = v
case "FORCED":
alt.Forced = v
case "CHARACTERISTICS":
alt.Characteristics = v
case "SUBTITLES":
alt.Subtitles = v
case "URI":
alt.URI = v
}
}
state.alternatives = append(state.alternatives, &alt)
case !state.tagStreamInf && strings.HasPrefix(line, "#EXT-X-STREAM-INF:"):
state.tagStreamInf = true
state.listType = MASTER
state.variant = new(Variant)
if len(state.alternatives) > 0 {
state.variant.Alternatives = state.alternatives
state.alternatives = nil
}
p.Variants = append(p.Variants, state.variant)
for k, v := range decodeParamsLine(line[18:]) {
switch k {
case "PROGRAM-ID":
var val int
val, err = strconv.Atoi(v)
if strict && err != nil {
return err
}
state.variant.ProgramId = uint32(val)
case "BANDWIDTH":
var val int
val, err = strconv.Atoi(v)
if strict && err != nil {
return err
}
state.variant.Bandwidth = uint32(val)
case "CODECS":
state.variant.Codecs = v
case "RESOLUTION":
state.variant.Resolution = v
case "AUDIO":
state.variant.Audio = v
case "VIDEO":
state.variant.Video = v
case "SUBTITLES":
state.variant.Subtitles = v
case "CLOSED-CAPTIONS":
state.variant.Captions = v
case "NAME":
state.variant.Name = v
}
}
case state.tagStreamInf && !strings.HasPrefix(line, "#"):
state.tagStreamInf = false
state.variant.URI = line
case strings.HasPrefix(line, "#EXT-X-I-FRAME-STREAM-INF:"):
state.listType = MASTER
state.variant = new(Variant)
state.variant.Iframe = true
if len(state.alternatives) > 0 {
state.variant.Alternatives = state.alternatives
state.alternatives = nil
}
p.Variants = append(p.Variants, state.variant)
for k, v := range decodeParamsLine(line[26:]) {
switch k {
case "URI":
state.variant.URI = v
case "PROGRAM-ID":
var val int
val, err = strconv.Atoi(v)
if strict && err != nil {
return err
}
state.variant.ProgramId = uint32(val)
case "BANDWIDTH":
var val int
val, err = strconv.Atoi(v)
if strict && err != nil {
return err
}
state.variant.Bandwidth = uint32(val)
case "CODECS":
state.variant.Codecs = v
case "RESOLUTION":
state.variant.Resolution = v
case "AUDIO":
state.variant.Audio = v
case "VIDEO":
state.variant.Video = v
}
}
case strings.HasPrefix(line, "#"): // unknown tags treated as comments
return err
}
return err
}
// Parse one line of media playlist.
func decodeLineOfMediaPlaylist(p *MediaPlaylist, wv *WV, state *decodingState, line string, strict bool) error {
var err error
line = strings.TrimSpace(line)
switch {
case !state.tagInf && strings.HasPrefix(line, "#EXTINF:"):
state.tagInf = true
state.listType = MEDIA
sepIndex := strings.Index(line, ",")
if sepIndex == -1 {
break
}
duration := line[8:sepIndex]
if len(duration) > 0 {
if state.duration, err = strconv.ParseFloat(duration, 64); strict && err != nil {
return fmt.Errorf("Duration parsing error: %s", err)
}
}
if len(line) > sepIndex {
state.title = line[sepIndex+1:]
}
case !strings.HasPrefix(line, "#"):
if state.tagInf {
err := p.Append(line, state.duration, state.title)
if err == ErrPlaylistFull {
// Extend playlist by doubling size, reset internal state, try again.
// If the second Append fails, the if err block will handle it.
// Retrying instead of being recursive was chosen as the state maybe
// modified non-idempotently.
p.Segments = append(p.Segments, make([]*MediaSegment, p.Count())...)
p.capacity = uint(len(p.Segments))
p.tail = p.count
err = p.Append(line, state.duration, state.title)
}
// Check err for first or subsequent Append()
if err != nil {
return err
}
state.tagInf = false
}
if state.tagRange {
if err = p.SetRange(state.limit, state.offset); strict && err != nil {
return err
}
state.tagRange = false
}
if state.tagSCTE35 {
state.tagSCTE35 = false
scte := *state.scte
if err = p.SetSCTE(scte.Cue, scte.ID, scte.Time); strict && err != nil {
return err
}
}
if state.tagDiscontinuity {
state.tagDiscontinuity = false
if err = p.SetDiscontinuity(); strict && err != nil {
return err
}
}
if state.tagProgramDateTime {
state.tagProgramDateTime = false
if err = p.SetProgramDateTime(state.programDateTime); strict && err != nil {
return err
}
}
// If EXT-X-KEY appeared before reference to segment (EXTINF) then it linked to this segment
if state.tagKey {
p.Segments[p.last()].Key = &Key{state.xkey.Method, state.xkey.URI, state.xkey.IV, state.xkey.Keyformat, state.xkey.Keyformatversions}
// First EXT-X-KEY may appeared in the header of the playlist and linked to first segment
// but for convenient playlist generation it also linked as default playlist key
if p.Key == nil {
p.Key = state.xkey
}
state.tagKey = false
}
// If EXT-X-MAP appeared before reference to segment (EXTINF) then it linked to this segment
if state.tagMap {
p.Segments[p.last()].Map = &Map{state.xmap.URI, state.xmap.Limit, state.xmap.Offset}
// First EXT-X-MAP may appeared in the header of the playlist and linked to first segment
// but for convenient playlist generation it also linked as default playlist map
if p.Map == nil {
p.Map = state.xmap
}
state.tagMap = false
}
// start tag first
case line == "#EXTM3U":
state.m3u = true
case line == "#EXT-X-ENDLIST":
state.listType = MEDIA
p.Closed = true
case strings.HasPrefix(line, "#EXT-X-VERSION:"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#EXT-X-VERSION:%d", &p.ver); strict && err != nil {
return err
}
case strings.HasPrefix(line, "#EXT-X-TARGETDURATION:"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#EXT-X-TARGETDURATION:%f", &p.TargetDuration); strict && err != nil {
return err
}
case strings.HasPrefix(line, "#EXT-X-MEDIA-SEQUENCE:"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#EXT-X-MEDIA-SEQUENCE:%d", &p.SeqNo); strict && err != nil {
return err
}
case strings.HasPrefix(line, "#EXT-X-PLAYLIST-TYPE:"):
state.listType = MEDIA
var playlistType string
_, err = fmt.Sscanf(line, "#EXT-X-PLAYLIST-TYPE:%s", &playlistType)
if err != nil {
if strict {
return err
}
} else {
switch playlistType {
case "EVENT":
p.MediaType = EVENT
case "VOD":
p.MediaType = VOD
}
}
case strings.HasPrefix(line, "#EXT-X-KEY:"):
state.listType = MEDIA
state.xkey = new(Key)
for k, v := range decodeParamsLine(line[11:]) {
switch k {
case "METHOD":
state.xkey.Method = v
case "URI":
state.xkey.URI = v
case "IV":
state.xkey.IV = v
case "KEYFORMAT":
state.xkey.Keyformat = v
case "KEYFORMATVERSIONS":
state.xkey.Keyformatversions = v
}
}
state.tagKey = true
case strings.HasPrefix(line, "#EXT-X-MAP:"):
state.listType = MEDIA
state.xmap = new(Map)
for k, v := range decodeParamsLine(line[11:]) {
switch k {
case "URI":
state.xmap.URI = v
case "BYTERANGE":
if _, err = fmt.Sscanf(v, "%d@%d", &state.xmap.Limit, &state.xmap.Offset); strict && err != nil {
return fmt.Errorf("Byterange sub-range length value parsing error: %s", err)
}
}
}
state.tagMap = true
case !state.tagProgramDateTime && strings.HasPrefix(line, "#EXT-X-PROGRAM-DATE-TIME:"):
state.tagProgramDateTime = true
state.listType = MEDIA
if state.programDateTime, err = time.Parse(DATETIME, line[25:]); strict && err != nil {
return err
}
case !state.tagRange && strings.HasPrefix(line, "#EXT-X-BYTERANGE:"):
state.tagRange = true
state.listType = MEDIA
state.offset = 0
params := strings.SplitN(line[17:], "@", 2)
if state.limit, err = strconv.ParseInt(params[0], 10, 64); strict && err != nil {
return fmt.Errorf("Byterange sub-range length value parsing error: %s", err)
}
if len(params) > 1 {
if state.offset, err = strconv.ParseInt(params[1], 10, 64); strict && err != nil {
return fmt.Errorf("Byterange sub-range offset value parsing error: %s", err)
}
}
case !state.tagSCTE35 && strings.HasPrefix(line, "#EXT-SCTE35:"):
state.tagSCTE35 = true
state.listType = MEDIA
state.scte = new(SCTE)
for attribute, value := range decodeParamsLine(line[12:]) {
switch attribute {
case "CUE":
state.scte.Cue = value
case "ID":
state.scte.ID = value
case "TIME":
state.scte.Time, _ = strconv.ParseFloat(value, 64)
}
}
case !state.tagDiscontinuity && strings.HasPrefix(line, "#EXT-X-DISCONTINUITY"):
state.tagDiscontinuity = true
state.listType = MEDIA
case strings.HasPrefix(line, "#EXT-X-I-FRAMES-ONLY"):
state.listType = MEDIA
p.Iframe = true
case strings.HasPrefix(line, "#WV-AUDIO-CHANNELS"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-AUDIO-CHANNELS %d", &wv.AudioChannels); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-AUDIO-FORMAT"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-AUDIO-FORMAT %d", &wv.AudioFormat); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-AUDIO-PROFILE-IDC"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-AUDIO-PROFILE-IDC %d", &wv.AudioProfileIDC); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-AUDIO-SAMPLE-SIZE"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-AUDIO-SAMPLE-SIZE %d", &wv.AudioSampleSize); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-AUDIO-SAMPLING-FREQUENCY"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-AUDIO-SAMPLING-FREQUENCY %d", &wv.AudioSamplingFrequency); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-CYPHER-VERSION"):
state.listType = MEDIA
wv.CypherVersion = line[19:]
state.tagWV = true
case strings.HasPrefix(line, "#WV-ECM"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-ECM %s", &wv.ECM); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-VIDEO-FORMAT"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-VIDEO-FORMAT %d", &wv.VideoFormat); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-VIDEO-FRAME-RATE"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-VIDEO-FRAME-RATE %d", &wv.VideoFrameRate); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-VIDEO-LEVEL-IDC"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-VIDEO-LEVEL-IDC %d", &wv.VideoLevelIDC); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-VIDEO-PROFILE-IDC"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-VIDEO-PROFILE-IDC %d", &wv.VideoProfileIDC); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#WV-VIDEO-RESOLUTION"):
state.listType = MEDIA
wv.VideoResolution = line[21:]
state.tagWV = true
case strings.HasPrefix(line, "#WV-VIDEO-SAR"):
state.listType = MEDIA
if _, err = fmt.Sscanf(line, "#WV-VIDEO-SAR %s", &wv.VideoSAR); strict && err != nil {
return err
}
if err == nil {
state.tagWV = true
}
case strings.HasPrefix(line, "#"): // unknown tags treated as comments
return err
}
return err
}