forked from grafov/m3u8
-
Notifications
You must be signed in to change notification settings - Fork 1
/
writer.go
1119 lines (1034 loc) · 31.9 KB
/
writer.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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package m3u8
/*
Part of M3U8 parser & generator library.
This file defines functions related to playlist generation.
Copyright 2013-2019 The Project Developers.
See the AUTHORS and LICENSE files at the top-level directory of this distribution
and at https://github.com/grafov/m3u8/
ॐ तारे तुत्तारे तुरे स्व
*/
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
)
// ErrPlaylistFull declares the playlist error.
var ErrPlaylistFull = errors.New("playlist is full")
// Set version of the playlist accordingly with section 7
func version(ver *uint8, newver uint8) {
if *ver < newver {
*ver = newver
}
}
func strver(ver uint8) string {
return strconv.FormatUint(uint64(ver), 10)
}
// NewMasterPlaylist creates a new empty master playlist. Master
// playlist consists of variants.
func NewMasterPlaylist() *MasterPlaylist {
p := new(MasterPlaylist)
p.ver = minver
return p
}
// Append appends a variant to master playlist. This operation does
// reset playlist cache.
func (p *MasterPlaylist) Append(uri string, chunklist *MediaPlaylist, params VariantParams) {
v := new(Variant)
v.URI = uri
v.Chunklist = chunklist
v.VariantParams = params
p.Variants = append(p.Variants, v)
if len(v.Alternatives) > 0 {
// From section 7:
// The EXT-X-MEDIA tag and the AUDIO, VIDEO and SUBTITLES attributes of
// the EXT-X-STREAM-INF tag are backward compatible to protocol version
// 1, but playback on older clients may not be desirable. A server MAY
// consider indicating a EXT-X-VERSION of 4 or higher in the Master
// Playlist but is not required to do so.
version(&p.ver, 4) // so it is optional and in theory may be set to ver.1
// but more tests required
}
p.buf.Reset()
}
// ResetCache resetes the playlist' cache.
func (p *MasterPlaylist) ResetCache() {
p.buf.Reset()
}
// Encode generates the output in M3U8 format.
func (p *MasterPlaylist) Encode() *bytes.Buffer {
if p.buf.Len() > 0 {
return &p.buf
}
p.buf.WriteString("#EXTM3U\n")
if p.Twitch == "" {
p.buf.WriteString("#EXT-X-VERSION:")
p.buf.WriteString(strver(p.ver))
p.buf.WriteRune('\n')
}
for _, c := range p.Comments {
p.buf.WriteString(c)
p.buf.WriteRune('\n')
}
if p.IndependentSegments() {
p.buf.WriteString("#EXT-X-INDEPENDENT-SEGMENTS\n")
}
// Write custom twitch tags
if p.Twitch != "" {
p.buf.WriteString(string(p.Twitch))
p.buf.WriteRune('\n')
}
// Write any custom master tags
if p.Custom != nil {
for _, v := range p.Custom {
if customBuf := v.Encode(); customBuf != nil {
p.buf.WriteString(customBuf.String())
p.buf.WriteRune('\n')
}
}
}
// write alternatives first in order of Type
p.encodeAlternatives("VIDEO")
p.encodeAlternatives("AUDIO")
p.encodeAlternatives("SUBTITLES")
p.encodeAlternatives("CLOSED-CAPTIONS")
for _, pl := range p.Variants {
if pl.Iframe {
p.buf.WriteString("#EXT-X-I-FRAME-STREAM-INF:PROGRAM-ID=")
p.buf.WriteString(strconv.FormatUint(uint64(pl.ProgramId), 10))
p.buf.WriteString(",BANDWIDTH=")
p.buf.WriteString(strconv.FormatUint(uint64(pl.Bandwidth), 10))
if pl.AverageBandwidth != 0 {
p.buf.WriteString(",AVERAGE-BANDWIDTH=")
p.buf.WriteString(strconv.FormatUint(uint64(pl.AverageBandwidth), 10))
}
if pl.Codecs != "" {
p.buf.WriteString(",CODECS=\"")
p.buf.WriteString(pl.Codecs)
p.buf.WriteRune('"')
}
if pl.SupplementalCodecs != "" {
p.buf.WriteString(",SUPPLEMENTAL-CODECS=\"")
p.buf.WriteString(pl.SupplementalCodecs)
p.buf.WriteRune('"')
}
if pl.Resolution != "" {
p.buf.WriteString(",RESOLUTION=") // Resolution should not be quoted
p.buf.WriteString(pl.Resolution)
}
if pl.Video != "" {
p.buf.WriteString(",VIDEO=\"")
p.buf.WriteString(pl.Video)
p.buf.WriteRune('"')
}
if pl.VideoRange != "" {
p.buf.WriteString(",VIDEO-RANGE=")
p.buf.WriteString(pl.VideoRange)
}
if pl.HDCPLevel != "" {
p.buf.WriteString(",HDCP-LEVEL=")
p.buf.WriteString(pl.HDCPLevel)
}
if pl.URI != "" {
p.buf.WriteString(",URI=\"")
p.buf.WriteString(pl.URI)
p.buf.WriteRune('"')
}
p.buf.WriteRune('\n')
} else if pl.ImageStream {
p.buf.WriteString("#EXT-X-IMAGE-STREAM-INF:BANDWIDTH=")
p.buf.WriteString(strconv.FormatUint(uint64(pl.Bandwidth), 10))
if pl.Resolution != "" {
p.buf.WriteString(",RESOLUTION=") // Resolution should not be quoted
p.buf.WriteString(pl.Resolution)
}
if pl.Codecs != "" {
p.buf.WriteString(",CODECS=\"")
p.buf.WriteString(pl.Codecs)
p.buf.WriteRune('"')
}
if pl.URI != "" {
p.buf.WriteString(",URI=\"")
p.buf.WriteString(pl.URI)
p.buf.WriteRune('"')
}
p.buf.WriteRune('\n')
} else {
p.buf.WriteString("#EXT-X-STREAM-INF:PROGRAM-ID=")
p.buf.WriteString(strconv.FormatUint(uint64(pl.ProgramId), 10))
p.buf.WriteString(",BANDWIDTH=")
p.buf.WriteString(strconv.FormatUint(uint64(pl.Bandwidth), 10))
if pl.AverageBandwidth != 0 {
p.buf.WriteString(",AVERAGE-BANDWIDTH=")
p.buf.WriteString(strconv.FormatUint(uint64(pl.AverageBandwidth), 10))
}
if pl.Codecs != "" {
p.buf.WriteString(",CODECS=\"")
p.buf.WriteString(pl.Codecs)
p.buf.WriteRune('"')
}
if pl.SupplementalCodecs != "" {
p.buf.WriteString(",SUPPLEMENTAL-CODECS=\"")
p.buf.WriteString(pl.SupplementalCodecs)
p.buf.WriteRune('"')
}
if pl.Resolution != "" {
p.buf.WriteString(",RESOLUTION=") // Resolution should not be quoted
p.buf.WriteString(pl.Resolution)
}
if pl.Audio != "" {
p.buf.WriteString(",AUDIO=\"")
p.buf.WriteString(pl.Audio)
p.buf.WriteRune('"')
}
if pl.Video != "" {
p.buf.WriteString(",VIDEO=\"")
p.buf.WriteString(pl.Video)
p.buf.WriteRune('"')
}
if pl.Captions != "" {
p.buf.WriteString(",CLOSED-CAPTIONS=")
if pl.Captions == "NONE" {
p.buf.WriteString(pl.Captions) // CC should not be quoted when eq NONE
} else {
p.buf.WriteRune('"')
p.buf.WriteString(pl.Captions)
p.buf.WriteRune('"')
}
}
if pl.Subtitles != "" {
p.buf.WriteString(",SUBTITLES=\"")
p.buf.WriteString(pl.Subtitles)
p.buf.WriteRune('"')
}
if pl.Name != "" {
p.buf.WriteString(",NAME=\"")
p.buf.WriteString(pl.Name)
p.buf.WriteRune('"')
}
if pl.FrameRate != 0 {
p.buf.WriteString(",FRAME-RATE=")
p.buf.WriteString(strconv.FormatFloat(pl.FrameRate, 'f', 3, 64))
}
if pl.VideoRange != "" {
p.buf.WriteString(",VIDEO-RANGE=")
p.buf.WriteString(pl.VideoRange)
}
if pl.HDCPLevel != "" {
p.buf.WriteString(",HDCP-LEVEL=")
p.buf.WriteString(pl.HDCPLevel)
}
p.buf.WriteRune('\n')
p.buf.WriteString(pl.URI)
if p.Args != "" {
if strings.Contains(pl.URI, "?") {
p.buf.WriteRune('&')
} else {
p.buf.WriteRune('?')
}
p.buf.WriteString(p.Args)
}
p.buf.WriteRune('\n')
}
}
return &p.buf
}
func (p *MasterPlaylist) encodeAlternatives(altType string) {
var altsWritten = make(map[string]bool)
orderedAlts := []*Alternative{}
for _, pl := range p.Variants {
if pl.Alternatives == nil {
continue
}
for _, alt := range pl.Alternatives {
// Make sure that we only write out an alternative once
altKey := fmt.Sprintf("%s-%s-%s-%s", alt.Type, alt.GroupId, alt.Name, alt.Language)
if altsWritten[altKey] || alt.Type != altType {
continue
}
altsWritten[altKey] = true
orderedAlts = append(orderedAlts, alt)
}
}
sort.SliceStable(orderedAlts, func(i, j int) bool {
return orderedAlts[i].Index < orderedAlts[j].Index
})
for _, alt := range orderedAlts {
p.buf.WriteString("#EXT-X-MEDIA:")
if alt.Type != "" {
p.buf.WriteString("TYPE=") // Type should not be quoted
p.buf.WriteString(alt.Type)
}
if alt.GroupId != "" {
p.buf.WriteString(",GROUP-ID=\"")
p.buf.WriteString(alt.GroupId)
p.buf.WriteRune('"')
}
if alt.Name != "" {
p.buf.WriteString(",NAME=\"")
p.buf.WriteString(alt.Name)
p.buf.WriteRune('"')
}
p.buf.WriteString(",DEFAULT=")
if alt.Default {
p.buf.WriteString("YES")
} else {
p.buf.WriteString("NO")
}
if alt.Autoselect != "" {
p.buf.WriteString(",AUTOSELECT=")
p.buf.WriteString(alt.Autoselect)
}
if alt.Language != "" {
p.buf.WriteString(",LANGUAGE=\"")
p.buf.WriteString(alt.Language)
p.buf.WriteRune('"')
}
if alt.Forced != "" {
p.buf.WriteString(",FORCED=")
p.buf.WriteString(alt.Forced)
}
if alt.Characteristics != "" {
p.buf.WriteString(",CHARACTERISTICS=\"")
p.buf.WriteString(alt.Characteristics)
p.buf.WriteRune('"')
}
if alt.Subtitles != "" {
p.buf.WriteString(",SUBTITLES=\"")
p.buf.WriteString(alt.Subtitles)
p.buf.WriteRune('"')
}
if alt.Channels != "" {
p.buf.WriteString(",CHANNELS=\"")
p.buf.WriteString(alt.Channels)
p.buf.WriteRune('"')
}
if alt.URI != "" {
p.buf.WriteString(",URI=\"")
p.buf.WriteString(alt.URI)
p.buf.WriteRune('"')
}
if alt.InstreamID != "" {
p.buf.WriteString(",INSTREAM-ID=\"")
p.buf.WriteString(alt.InstreamID)
p.buf.WriteRune('"')
}
p.buf.WriteRune('\n')
}
}
// SetCustomTag sets the provided tag on the master playlist for its TagName
func (p *MasterPlaylist) SetCustomTag(tag CustomTag) {
if p.Custom == nil {
p.Custom = make(map[string]CustomTag)
}
p.Custom[tag.TagName()] = tag
}
// Version returns the current playlist version number
func (p *MasterPlaylist) Version() uint8 {
return p.ver
}
// SetVersion sets the playlist version number, note the version maybe changed
// automatically by other Set methods.
func (p *MasterPlaylist) SetVersion(ver uint8) {
p.ver = ver
}
// IndependentSegments returns true if all media samples in a segment can be
// decoded without information from other segments.
func (p *MasterPlaylist) IndependentSegments() bool {
return p.independentSegments
}
// SetIndependentSegments sets whether all media samples in a segment can be
// decoded without information from other segments.
func (p *MasterPlaylist) SetIndependentSegments(b bool) {
p.independentSegments = b
}
// String here for compatibility with Stringer interface. For example
// fmt.Printf("%s", sampleMediaList) will encode playist and print its
// string representation.
func (p *MasterPlaylist) String() string {
return p.Encode().String()
}
// NewMediaPlaylist creates a new media playlist structure. Winsize
// defines how much items will displayed on playlist generation.
// Capacity is total size of a playlist.
func NewMediaPlaylist(winsize uint, capacity uint) (*MediaPlaylist, error) {
p := new(MediaPlaylist)
p.ver = minver
p.capacity = capacity
if err := p.SetWinSize(winsize); err != nil {
return nil, err
}
p.Segments = make([]*MediaSegment, capacity)
return p, nil
}
// last returns the previously written segment's index
func (p *MediaPlaylist) last() uint {
if p.tail == 0 {
return p.capacity - 1
}
return p.tail - 1
}
// Remove current segment from the head of chunk slice form a media playlist. Useful for sliding playlists.
// This operation does reset playlist cache.
func (p *MediaPlaylist) Remove() (err error) {
if p.count == 0 {
return errors.New("playlist is empty")
}
p.head = (p.head + 1) % p.capacity
p.count--
if !p.Closed {
p.SeqNo++
}
p.buf.Reset()
return nil
}
// Append general chunk to the tail of chunk slice for a media playlist.
// This operation does reset playlist cache.
func (p *MediaPlaylist) Append(uri string, duration float64, title string) error {
seg := new(MediaSegment)
seg.URI = uri
seg.Duration = duration
seg.Title = title
return p.AppendSegment(seg)
}
// AppendSegment appends a MediaSegment to the tail of chunk slice for
// a media playlist. This operation does reset playlist cache.
func (p *MediaPlaylist) AppendSegment(seg *MediaSegment) error {
if p.head == p.tail && p.count > 0 {
return ErrPlaylistFull
}
seg.SeqId = p.SeqNo
if p.count > 0 {
seg.SeqId = p.Segments[(p.capacity+p.tail-1)%p.capacity].SeqId + 1
}
p.Segments[p.tail] = seg
p.tail = (p.tail + 1) % p.capacity
p.count++
if p.TargetDuration < seg.Duration {
p.TargetDuration = math.Ceil(seg.Duration)
}
p.buf.Reset()
return nil
}
// Slide combines two operations: firstly it removes one chunk from
// the head of chunk slice and move pointer to next chunk. Secondly it
// appends one chunk to the tail of chunk slice. Useful for sliding
// playlists. This operation does reset cache.
func (p *MediaPlaylist) Slide(uri string, duration float64, title string) {
if !p.Closed && p.count >= p.winsize {
p.Remove()
}
p.Append(uri, duration, title)
}
// ResetCache resets playlist cache. Next called Encode() will
// regenerate playlist from the chunk slice.
func (p *MediaPlaylist) ResetCache() {
p.buf.Reset()
}
// Encode generates output in M3U8 format. Marshal `winsize` elements
// from bottom of the `segments` queue.
func (p *MediaPlaylist) Encode() *bytes.Buffer {
if p.buf.Len() > 0 {
return &p.buf
}
p.buf.WriteString("#EXTM3U\n#EXT-X-VERSION:")
p.buf.WriteString(strver(p.ver))
p.buf.WriteRune('\n')
// Write any custom master tags
if p.Custom != nil {
for _, v := range p.Custom {
if customBuf := v.Encode(); customBuf != nil {
p.buf.WriteString(customBuf.String())
p.buf.WriteRune('\n')
}
}
}
// default key (workaround for Widevine)
if p.Key != nil {
p.buf.WriteString("#EXT-X-KEY:")
p.buf.WriteString("METHOD=")
p.buf.WriteString(p.Key.Method)
if p.Key.Method != "NONE" {
p.buf.WriteString(",URI=\"")
p.buf.WriteString(p.Key.URI)
p.buf.WriteRune('"')
if p.Key.IV != "" {
p.buf.WriteString(",IV=")
p.buf.WriteString(p.Key.IV)
}
if p.Key.Keyformat != "" {
p.buf.WriteString(",KEYFORMAT=\"")
p.buf.WriteString(p.Key.Keyformat)
p.buf.WriteRune('"')
}
if p.Key.Keyformatversions != "" {
p.buf.WriteString(",KEYFORMATVERSIONS=\"")
p.buf.WriteString(p.Key.Keyformatversions)
p.buf.WriteRune('"')
}
if p.Key.KeyID != "" {
p.buf.WriteString(",KEYID=\"")
p.buf.WriteString(p.Key.KeyID)
p.buf.WriteRune('"')
}
}
p.buf.WriteRune('\n')
}
for _, key := range p.Keys {
p.buf.WriteString("#EXT-X-KEY:")
p.buf.WriteString("METHOD=")
p.buf.WriteString(key.Method)
if key.Method != "NONE" {
p.buf.WriteString(",URI=\"")
p.buf.WriteString(key.URI)
p.buf.WriteRune('"')
if key.IV != "" {
p.buf.WriteString(",IV=")
p.buf.WriteString(key.IV)
}
if key.Keyformat != "" {
p.buf.WriteString(",KEYFORMAT=\"")
p.buf.WriteString(key.Keyformat)
p.buf.WriteRune('"')
}
if key.Keyformatversions != "" {
p.buf.WriteString(",KEYFORMATVERSIONS=\"")
p.buf.WriteString(key.Keyformatversions)
p.buf.WriteRune('"')
}
if key.KeyID != "" {
p.buf.WriteString(",KEYID=\"")
p.buf.WriteString(key.KeyID)
p.buf.WriteRune('"')
}
}
p.buf.WriteRune('\n')
}
if p.Map != nil {
p.buf.WriteString("#EXT-X-MAP:")
p.buf.WriteString("URI=\"")
p.buf.WriteString(p.Map.URI)
p.buf.WriteRune('"')
if p.Map.Limit > 0 {
p.buf.WriteString(",BYTERANGE=\"")
p.buf.WriteString(strconv.FormatInt(p.Map.Limit, 10))
p.buf.WriteRune('@')
p.buf.WriteString(strconv.FormatInt(p.Map.Offset, 10))
p.buf.WriteRune('"')
}
p.buf.WriteRune('\n')
}
if p.MediaType > 0 {
p.buf.WriteString("#EXT-X-PLAYLIST-TYPE:")
switch p.MediaType {
case EVENT:
p.buf.WriteString("EVENT\n")
p.buf.WriteString("#EXT-X-ALLOW-CACHE:NO\n")
case VOD:
p.buf.WriteString("VOD\n")
}
}
p.buf.WriteString("#EXT-X-MEDIA-SEQUENCE:")
p.buf.WriteString(strconv.FormatUint(p.SeqNo, 10))
p.buf.WriteRune('\n')
p.buf.WriteString("#EXT-X-TARGETDURATION:")
p.buf.WriteString(strconv.FormatInt(int64(math.Ceil(p.TargetDuration)), 10)) // due section 3.4.2 of M3U8 specs EXT-X-TARGETDURATION must be integer
p.buf.WriteRune('\n')
if p.Twitch != nil {
for _, v := range p.Twitch {
p.buf.WriteString(string(v))
p.buf.WriteRune('\n')
}
}
if p.StartTime > 0.0 {
p.buf.WriteString("#EXT-X-START:TIME-OFFSET=")
p.buf.WriteString(strconv.FormatFloat(p.StartTime, 'f', -1, 64))
if p.StartTimePrecise {
p.buf.WriteString(",PRECISE=YES")
}
p.buf.WriteRune('\n')
}
if p.DiscontinuitySeq != 0 {
p.buf.WriteString("#EXT-X-DISCONTINUITY-SEQUENCE:")
p.buf.WriteString(strconv.FormatUint(uint64(p.DiscontinuitySeq), 10))
p.buf.WriteRune('\n')
}
if p.Iframe {
p.buf.WriteString("#EXT-X-I-FRAMES-ONLY\n")
}
// Tag used to create Images playlist for DELIVER-2169
if p.Images {
p.buf.WriteString("#EXT-X-IMAGES-ONLY\n")
}
// Widevine tags
if p.WV != nil {
if p.WV.AudioChannels != 0 {
p.buf.WriteString("#WV-AUDIO-CHANNELS ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioChannels), 10))
p.buf.WriteRune('\n')
}
if p.WV.AudioFormat != 0 {
p.buf.WriteString("#WV-AUDIO-FORMAT ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioFormat), 10))
p.buf.WriteRune('\n')
}
if p.WV.AudioProfileIDC != 0 {
p.buf.WriteString("#WV-AUDIO-PROFILE-IDC ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioProfileIDC), 10))
p.buf.WriteRune('\n')
}
if p.WV.AudioSampleSize != 0 {
p.buf.WriteString("#WV-AUDIO-SAMPLE-SIZE ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioSampleSize), 10))
p.buf.WriteRune('\n')
}
if p.WV.AudioSamplingFrequency != 0 {
p.buf.WriteString("#WV-AUDIO-SAMPLING-FREQUENCY ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioSamplingFrequency), 10))
p.buf.WriteRune('\n')
}
if p.WV.CypherVersion != "" {
p.buf.WriteString("#WV-CYPHER-VERSION ")
p.buf.WriteString(p.WV.CypherVersion)
p.buf.WriteRune('\n')
}
if p.WV.ECM != "" {
p.buf.WriteString("#WV-ECM ")
p.buf.WriteString(p.WV.ECM)
p.buf.WriteRune('\n')
}
if p.WV.VideoFormat != 0 {
p.buf.WriteString("#WV-VIDEO-FORMAT ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoFormat), 10))
p.buf.WriteRune('\n')
}
if p.WV.VideoFrameRate != 0 {
p.buf.WriteString("#WV-VIDEO-FRAME-RATE ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoFrameRate), 10))
p.buf.WriteRune('\n')
}
if p.WV.VideoLevelIDC != 0 {
p.buf.WriteString("#WV-VIDEO-LEVEL-IDC")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoLevelIDC), 10))
p.buf.WriteRune('\n')
}
if p.WV.VideoProfileIDC != 0 {
p.buf.WriteString("#WV-VIDEO-PROFILE-IDC ")
p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoProfileIDC), 10))
p.buf.WriteRune('\n')
}
if p.WV.VideoResolution != "" {
p.buf.WriteString("#WV-VIDEO-RESOLUTION ")
p.buf.WriteString(p.WV.VideoResolution)
p.buf.WriteRune('\n')
}
if p.WV.VideoSAR != "" {
p.buf.WriteString("#WV-VIDEO-SAR ")
p.buf.WriteString(p.WV.VideoSAR)
p.buf.WriteRune('\n')
}
}
var (
seg *MediaSegment
durationCache = make(map[float64]string)
)
head := p.head
count := p.count
for i := uint(0); (i < p.winsize || p.winsize == 0) && count > 0; count-- {
seg = p.Segments[head]
head = (head + 1) % p.capacity
if seg == nil { // protection from badly filled chunklists
continue
}
if p.winsize > 0 { // skip for VOD playlists, where winsize = 0
i++
}
if seg.SCTE != nil {
switch seg.SCTE.Syntax {
case SCTE35_67_2014:
p.buf.WriteString("#EXT-SCTE35:")
p.buf.WriteString("CUE=\"")
p.buf.WriteString(seg.SCTE.Cue)
p.buf.WriteRune('"')
if seg.SCTE.ID != "" {
p.buf.WriteString(",ID=\"")
p.buf.WriteString(seg.SCTE.ID)
p.buf.WriteRune('"')
}
if seg.SCTE.Time != 0 {
p.buf.WriteString(",TIME=")
p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Time, 'f', -1, 64))
}
p.buf.WriteRune('\n')
case SCTE35_OATCLS:
switch seg.SCTE.CueType {
case SCTE35Cue_Start:
p.buf.WriteString("#EXT-OATCLS-SCTE35:")
p.buf.WriteString(seg.SCTE.Cue)
if seg.SCTE.CAID != "" {
p.buf.WriteRune('\n')
p.buf.WriteString("#EXT-X-ASSET:")
p.buf.WriteString(seg.SCTE.CAID)
}
p.buf.WriteRune('\n')
p.buf.WriteString("#EXT-X-CUE-OUT:")
p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Time, 'f', -1, 64))
p.buf.WriteRune('\n')
case SCTE35Cue_Mid:
p.buf.WriteString("#EXT-X-CUE-OUT-CONT:")
if seg.SCTE.CAID != "" {
p.buf.WriteString("CAID=")
p.buf.WriteString(seg.SCTE.CAID)
p.buf.WriteString(",")
}
p.buf.WriteString("ElapsedTime=")
p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Elapsed, 'f', -1, 64))
p.buf.WriteString(",Duration=")
p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Time, 'f', -1, 64))
p.buf.WriteString(",SCTE35=")
p.buf.WriteString(seg.SCTE.Cue)
p.buf.WriteRune('\n')
case SCTE35Cue_End:
if len(seg.SCTE.Cue) > 0 {
// while CUE-IN tags should not have OATCLS tags or any ads metadata,
// we want to pass these values through to honor the source manifest
p.buf.WriteString("#EXT-OATCLS-SCTE35:")
p.buf.WriteString(seg.SCTE.Cue)
p.buf.WriteRune('\n')
}
p.buf.WriteString("#EXT-X-CUE-IN")
p.buf.WriteRune('\n')
}
case SCTE35_SIMPLECUES:
switch seg.SCTE.CueType {
case SCTE35Cue_Start:
p.buf.WriteString("#EXT-X-CUE-OUT:DURATION=")
p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Time, 'f', -1, 64))
p.buf.WriteRune('\n')
case SCTE35Cue_End:
p.buf.WriteString("#EXT-X-CUE-IN")
p.buf.WriteRune('\n')
}
}
}
// check for key change
if seg.Key != nil && p.Key != seg.Key {
p.buf.WriteString("#EXT-X-KEY:")
p.buf.WriteString("METHOD=")
p.buf.WriteString(seg.Key.Method)
if seg.Key.Method != "NONE" {
p.buf.WriteString(",URI=\"")
p.buf.WriteString(seg.Key.URI)
p.buf.WriteRune('"')
if seg.Key.IV != "" {
p.buf.WriteString(",IV=")
p.buf.WriteString(seg.Key.IV)
}
if seg.Key.Keyformat != "" {
p.buf.WriteString(",KEYFORMAT=\"")
p.buf.WriteString(seg.Key.Keyformat)
p.buf.WriteRune('"')
}
if seg.Key.Keyformatversions != "" {
p.buf.WriteString(",KEYFORMATVERSIONS=\"")
p.buf.WriteString(seg.Key.Keyformatversions)
p.buf.WriteRune('"')
}
if seg.Key.KeyID != "" {
p.buf.WriteString(",KEYID=\"")
p.buf.WriteString(seg.Key.KeyID)
p.buf.WriteRune('"')
}
}
p.buf.WriteRune('\n')
}
if seg.Discontinuity {
p.buf.WriteString("#EXT-X-DISCONTINUITY\n")
}
// ignore segment Map if default playlist Map is present
if p.Map == nil && seg.Map != nil {
p.buf.WriteString("#EXT-X-MAP:")
p.buf.WriteString("URI=\"")
p.buf.WriteString(seg.Map.URI)
p.buf.WriteRune('"')
if seg.Map.Limit > 0 {
p.buf.WriteString(",BYTERANGE=\"")
p.buf.WriteString(strconv.FormatInt(seg.Map.Limit, 10))
p.buf.WriteRune('@')
p.buf.WriteString(strconv.FormatInt(seg.Map.Offset, 10))
p.buf.WriteRune('"')
}
p.buf.WriteRune('\n')
}
// add if default map exists and playlist has discontinuities
if p.Map != nil && seg.Discontinuity && seg.Map != nil {
p.buf.WriteString("#EXT-X-MAP:")
p.buf.WriteString("URI=\"")
p.buf.WriteString(seg.Map.URI)
p.buf.WriteRune('"')
if seg.Map.Limit > 0 {
p.buf.WriteString(",BYTERANGE=\"")
p.buf.WriteString(strconv.FormatInt(seg.Map.Limit, 10))
p.buf.WriteRune('@')
p.buf.WriteString(strconv.FormatInt(seg.Map.Offset, 10))
p.buf.WriteRune('"')
}
p.buf.WriteRune('\n')
}
if !seg.ProgramDateTime.IsZero() {
p.buf.WriteString("#EXT-X-PROGRAM-DATE-TIME:")
p.buf.WriteString(seg.ProgramDateTime.Format(DATETIME))
p.buf.WriteRune('\n')
}
if seg.Limit > 0 {
p.buf.WriteString("#EXT-X-BYTERANGE:")
p.buf.WriteString(strconv.FormatInt(seg.Limit, 10))
p.buf.WriteRune('@')
p.buf.WriteString(strconv.FormatInt(seg.Offset, 10))
p.buf.WriteRune('\n')
}
// Add Custom Segment Tags here
if seg.Custom != nil {
for _, v := range seg.Custom {
if customBuf := v.Encode(); customBuf != nil {
p.buf.WriteString(customBuf.String())
p.buf.WriteRune('\n')
}
}
}
p.buf.WriteString("#EXTINF:")
if str, ok := durationCache[seg.Duration]; ok {
p.buf.WriteString(str)
} else {
if p.durationAsInt {
// Old Android players has problems with non integer Duration.
durationCache[seg.Duration] = strconv.FormatInt(int64(math.Ceil(seg.Duration)), 10)
} else {
// Wowza Mediaserver and some others prefer floats.
durationCache[seg.Duration] = strconv.FormatFloat(seg.Duration, 'f', 3, 32)
}
p.buf.WriteString(durationCache[seg.Duration])
}
p.buf.WriteRune(',')
p.buf.WriteString(seg.Title)
p.buf.WriteRune('\n')
// Adds custom tag under #EXTINF
if seg.CustomSubTag != nil {
if customBuf := seg.CustomSubTag.Encode(); customBuf != nil {
p.buf.WriteString(customBuf.String())
p.buf.WriteRune('\n')
}
}
p.buf.WriteString(seg.URI)
if p.Args != "" {
p.buf.WriteRune('?')
p.buf.WriteString(p.Args)
}
p.buf.WriteRune('\n')
}
if p.Closed {
p.buf.WriteString("#EXT-X-ENDLIST\n")
}
return &p.buf
}
// String here for compatibility with Stringer interface For example
// fmt.Printf("%s", sampleMediaList) will encode playist and print its
// string representation.
func (p *MediaPlaylist) String() string {
return p.Encode().String()
}
// DurationAsInt represents the duration as the integer in encoded playlist.
func (p *MediaPlaylist) DurationAsInt(yes bool) {
if yes {
// duration must be integers if protocol version is less than 3
version(&p.ver, 3)
}
p.durationAsInt = yes
}
// Count tells us the number of items that are currently in the media
// playlist.
func (p *MediaPlaylist) Count() uint {
return p.count
}
// Close sliding playlist and make them fixed.
func (p *MediaPlaylist) Close() {
if p.buf.Len() > 0 {
p.buf.WriteString("#EXT-X-ENDLIST\n")
}
p.Closed = true
}
// SetDefaultKey sets encryption key appeared once in header of the
// playlist (pointer to MediaPlaylist.Key). It useful when keys not
// changed during playback. Set tag for the whole list.
// Deprecated: Use AddDefaultKey instead.
func (p *MediaPlaylist) SetDefaultKey(method, uri, iv, keyformat, keyformatversions, id string) error {
// A Media Playlist MUST indicate a EXT-X-VERSION of 5 or higher if it
// contains:
// - The KEYFORMAT and KEYFORMATVERSIONS attributes of the EXT-X-KEY tag.
if keyformat != "" || keyformatversions != "" {
version(&p.ver, 5)
}
p.Key = &Key{Method: method, URI: uri, IV: iv, Keyformat: keyformat, Keyformatversions: keyformatversions, KeyID: id}
return nil
}
// AddDefaultKey adds encryption key appeared once in header of the
// playlist (pointer to MediaPlaylist.Key). It useful when keys not
// changed during playback. Set tag for the whole list.
func (p *MediaPlaylist) AddDefaultKey(method, uri, iv, keyformat, keyformatversions, id string) error {
// A Media Playlist MUST indicate a EXT-X-VERSION of 5 or higher if it
// contains:
// - The KEYFORMAT and KEYFORMATVERSIONS attributes of the EXT-X-KEY tag.
if keyformat != "" || keyformatversions != "" {
version(&p.ver, 5)
}
p.Keys = append(p.Keys, &Key{Method: method, URI: uri, IV: iv, Keyformat: keyformat, Keyformatversions: keyformatversions, KeyID: id})
return nil
}
// SetDefaultMap sets default Media Initialization Section values for
// playlist (pointer to MediaPlaylist.Map). Set EXT-X-MAP tag for the
// whole playlist.
func (p *MediaPlaylist) SetDefaultMap(uri string, limit, offset int64) {
version(&p.ver, 5) // due section 4
p.Map = &Map{uri, limit, offset}
}
// SetIframeOnly marks medialist as consists of only I-frames (Intra
// frames). Set tag for the whole list.
func (p *MediaPlaylist) SetIframeOnly() {
version(&p.ver, 4) // due section 4.3.3
p.Iframe = true
}
// SetKey sets encryption key for the current segment of media playlist
// (pointer to Segment.Key).
// Deprecated: Use AddKey instead.
func (p *MediaPlaylist) SetKey(method, uri, iv, keyformat, keyformatversions, id string) error {
if p.count == 0 {
return errors.New("playlist is empty")
}
// A Media Playlist MUST indicate a EXT-X-VERSION of 5 or higher if it
// contains:
// - The KEYFORMAT and KEYFORMATVERSIONS attributes of the EXT-X-KEY tag.
if keyformat != "" || keyformatversions != "" {
version(&p.ver, 5)
}
p.Segments[p.last()].Key = &Key{Method: method, URI: uri, IV: iv, Keyformat: keyformat, Keyformatversions: keyformatversions, KeyID: id}
return nil
}
// AddKey adds encryption key for the current segment of media playlist
func (p *MediaPlaylist) AddKey(method, uri, iv, keyformat, keyformatversions, id string) error {
if p.count == 0 {
return errors.New("playlist is empty")
}
// A Media Playlist MUST indicate a EXT-X-VERSION of 5 or higher if it
// contains:
// - The KEYFORMAT and KEYFORMATVERSIONS attributes of the EXT-X-KEY tag.
if keyformat != "" || keyformatversions != "" {
version(&p.ver, 5)
}
p.Segments[p.last()].Keys = append(p.Segments[p.last()].Keys, &Key{Method: method, URI: uri, IV: iv, Keyformat: keyformat, Keyformatversions: keyformatversions, KeyID: id})
return nil