-
Notifications
You must be signed in to change notification settings - Fork 28
/
muxer.go
656 lines (563 loc) · 14.2 KB
/
muxer.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
package gohlslib
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"github.com/bluenviron/gohlslib/v2/pkg/codecs"
"github.com/bluenviron/gohlslib/v2/pkg/playlist"
"github.com/bluenviron/gohlslib/v2/pkg/storage"
)
const (
fmp4StartDTS = 10 * time.Second
mpegtsSegmentMinAUCount = 100
multivariantPlaylistMaxAge = "30"
initMaxAge = "30"
segmentMaxAge = "3600"
)
func boolPtr(v bool) *bool {
return &v
}
func parseMSNPart(msn string, part string) (uint64, uint64, error) {
var msnint uint64
if msn != "" {
var err error
msnint, err = strconv.ParseUint(msn, 10, 64)
if err != nil {
return 0, 0, err
}
}
var partint uint64
if part != "" {
var err error
partint, err = strconv.ParseUint(part, 10, 64)
if err != nil {
return 0, 0, err
}
}
return msnint, partint, nil
}
func bandwidth(segments []muxerSegment) (int, int) {
if len(segments) == 0 {
return 0, 0
}
var maxBandwidth uint64
var sizes uint64
var durations time.Duration
for _, seg := range segments {
if _, ok := seg.(*muxerGap); !ok {
bandwidth := 8 * seg.getSize() * uint64(time.Second) / uint64(seg.getDuration())
if bandwidth > maxBandwidth {
maxBandwidth = bandwidth
}
sizes += seg.getSize()
durations += seg.getDuration()
}
}
averageBandwidth := 8 * sizes * uint64(time.Second) / uint64(durations)
return int(maxBandwidth), int(averageBandwidth)
}
func queryVal(q url.Values, key string) string {
vals, ok := q[key]
if ok && len(vals) >= 1 {
return vals[0]
}
return ""
}
func isVideo(codec codecs.Codec) bool {
switch codec.(type) {
case *codecs.AV1, *codecs.VP9, *codecs.H265, *codecs.H264:
return true
}
return false
}
// a prefix is needed to prevent usage of cached segments
// from previous muxing sessions.
func generatePrefix() (string, error) {
var buf [6]byte
_, err := rand.Read(buf[:])
if err != nil {
return "", err
}
return hex.EncodeToString(buf[:]), nil
}
func mediaPlaylistPath(streamID string) string {
return streamID + "_stream.m3u8"
}
func initFilePath(prefix string, streamID string) string {
return prefix + "_" + streamID + "_init.mp4"
}
func segmentPath(prefix string, streamID string, segmentID uint64, mp4 bool) string {
if mp4 {
return prefix + "_" + streamID + "_seg" + strconv.FormatUint(segmentID, 10) + ".mp4"
}
return prefix + "_" + streamID + "_seg" + strconv.FormatUint(segmentID, 10) + ".ts"
}
func partPath(prefix string, streamID string, partID uint64) string {
return prefix + "_" + streamID + "_part" + strconv.FormatUint(partID, 10) + ".mp4"
}
func fmp4TimeScale(c codecs.Codec) uint32 {
switch codec := c.(type) {
case *codecs.MPEG4Audio:
return uint32(codec.SampleRate)
case *codecs.Opus:
return 48000
}
return 90000
}
type switchableWriter struct {
w io.Writer
}
func (w *switchableWriter) Write(p []byte) (int, error) {
return w.w.Write(p)
}
// MuxerOnEncodeErrorFunc is the prototype of Muxer.OnEncodeError.
type MuxerOnEncodeErrorFunc func(err error)
// Muxer is a HLS muxer.
type Muxer struct {
//
// parameters (all optional except Tracks).
//
// tracks.
Tracks []*Track
// Variant to use.
// It defaults to MuxerVariantLowLatency
Variant MuxerVariant
// Number of HLS segments to keep on the server.
// Segments allow to seek through the stream.
// Their number doesn't influence latency.
// It defaults to 7.
SegmentCount int
// Minimum duration of each segment.
// This is adjusted in order to include at least one IDR frame in each segment.
// A player usually puts 3 segments in a buffer before reproducing the stream.
// It defaults to 1sec.
SegmentMinDuration time.Duration
// Minimum duration of each part.
// Parts are used in Low-Latency HLS in place of segments.
// This is adjusted in order to produce segments with a similar duration.
// A player usually puts 3 parts in a buffer before reproducing the stream.
// It defaults to 200ms.
PartMinDuration time.Duration
// Maximum size of each segment.
// This prevents RAM exhaustion.
// It defaults to 50MB.
SegmentMaxSize uint64
// Directory in which to save segments.
// This decreases performance, since saving segments on disk is less performant
// than saving them on RAM, but allows to preserve RAM.
Directory string
//
// callbacks (all optional)
//
// called when a non-fatal encode error occurs.
OnEncodeError MuxerOnEncodeErrorFunc
//
// private
//
mutex sync.Mutex
cond *sync.Cond
mtracks []*muxerTrack
mtracksByTrack map[*Track]*muxerTrack
streams []*muxerStream
leadingStream *muxerStream
prefix string
storageFactory storage.Factory
segmenter *muxerSegmenter
server *muxerServer
closed bool
}
// Start initializes the muxer.
func (m *Muxer) Start() error {
if m.Variant == 0 {
m.Variant = MuxerVariantLowLatency
}
if m.SegmentCount == 0 {
m.SegmentCount = 7
}
if m.SegmentMinDuration == 0 {
m.SegmentMinDuration = 1 * time.Second
}
if m.PartMinDuration == 0 {
m.PartMinDuration = 200 * time.Millisecond
}
if m.SegmentMaxSize == 0 {
m.SegmentMaxSize = 50 * 1024 * 1024
}
if m.OnEncodeError == nil {
m.OnEncodeError = func(e error) {
log.Printf("%v", e)
}
}
if len(m.Tracks) == 0 {
return fmt.Errorf("at least one track must be provided")
}
hasVideo := false
hasAudio := false
if m.Variant == MuxerVariantMPEGTS {
for _, track := range m.Tracks {
if isVideo(track.Codec) {
if hasVideo {
return fmt.Errorf("the MPEG-TS variant of HLS supports a single video track only")
}
if _, ok := track.Codec.(*codecs.H264); !ok {
return fmt.Errorf(
"the MPEG-TS variant of HLS supports H264 video only")
}
hasVideo = true
} else {
if hasAudio {
return fmt.Errorf("the MPEG-TS variant of HLS supports a single audio track only")
}
if _, ok := track.Codec.(*codecs.MPEG4Audio); !ok {
return fmt.Errorf(
"the MPEG-TS variant of HLS supports MPEG-4 Audio only")
}
hasAudio = true
}
}
} else {
for _, track := range m.Tracks {
if isVideo(track.Codec) {
if hasVideo {
return fmt.Errorf("only one video track is currently supported")
}
hasVideo = true
} else {
hasAudio = true //nolint:ineffassign,wastedassign
}
}
}
hasDefaultAudio := false
for _, track := range m.Tracks {
if !isVideo(track.Codec) && track.IsDefault {
if hasDefaultAudio {
return fmt.Errorf("multiple default audio tracks are not supported")
}
hasDefaultAudio = true
}
}
switch m.Variant {
case MuxerVariantLowLatency:
if m.SegmentCount < 7 {
return fmt.Errorf("Low-Latency HLS requires at least 7 segments")
}
default:
if m.SegmentCount < 3 {
return fmt.Errorf("the minimum number of HLS segments is 3")
}
}
m.cond = sync.NewCond(&m.mutex)
m.mtracksByTrack = make(map[*Track]*muxerTrack)
m.segmenter = &muxerSegmenter{
variant: m.Variant,
segmentMinDuration: m.SegmentMinDuration,
partMinDuration: m.PartMinDuration,
parent: m,
}
m.segmenter.initialize()
m.server = &muxerServer{}
m.server.initialize()
m.server.registerPath("index.m3u8", m.handleMultivariantPlaylist)
for i, track := range m.Tracks {
mtrack := &muxerTrack{
Track: track,
variant: m.Variant,
isLeading: isVideo(track.Codec) || (!hasVideo && i == 0),
}
mtrack.initialize()
m.mtracks = append(m.mtracks, mtrack)
m.mtracksByTrack[track] = mtrack
}
var err error
m.prefix, err = generatePrefix()
if err != nil {
return err
}
if m.Directory != "" {
m.storageFactory = storage.NewFactoryDisk(m.Directory)
} else {
m.storageFactory = storage.NewFactoryRAM()
}
// add initial gaps, required by iOS LL-HLS
nextSegmentID := uint64(0)
if m.Variant == MuxerVariantLowLatency {
nextSegmentID = 7
}
switch {
case m.Variant == MuxerVariantMPEGTS:
stream := &muxerStream{
isLeading: true,
variant: m.Variant,
segmentMaxSize: m.SegmentMaxSize,
segmentCount: m.SegmentCount,
onEncodeError: m.OnEncodeError,
mutex: &m.mutex,
cond: m.cond,
prefix: m.prefix,
storageFactory: m.storageFactory,
server: m.server,
tracks: m.mtracks,
id: "main",
nextSegmentID: nextSegmentID,
}
stream.initialize()
m.streams = append(m.streams, stream)
default:
defaultAudioChosen := false
for i, track := range m.mtracks {
var id string
if isVideo(track.Codec) {
id = "video" + strconv.FormatInt(int64(i+1), 10)
} else {
id = "audio" + strconv.FormatInt(int64(i+1), 10)
}
isRendition := !track.isLeading || (!isVideo(track.Codec) && len(m.Tracks) > 1)
isDefault := false
name := ""
if isRendition {
if !hasDefaultAudio {
if !defaultAudioChosen {
defaultAudioChosen = true
isDefault = true
}
} else {
isDefault = track.IsDefault
}
if track.Name != "" {
name = track.Name
} else {
name = id
}
}
stream := &muxerStream{
variant: m.Variant,
segmentMaxSize: m.SegmentMaxSize,
segmentCount: m.SegmentCount,
onEncodeError: m.OnEncodeError,
mutex: &m.mutex,
cond: m.cond,
prefix: m.prefix,
storageFactory: m.storageFactory,
server: m.server,
tracks: []*muxerTrack{track},
id: id,
isLeading: track.isLeading,
isRendition: isRendition,
name: name,
language: track.Language,
isDefault: isDefault,
nextSegmentID: nextSegmentID,
}
stream.initialize()
m.streams = append(m.streams, stream)
}
}
m.leadingStream = func() *muxerStream {
for _, stream := range m.streams {
if stream.isLeading {
return stream
}
}
return nil
}()
return nil
}
// Close closes a Muxer.
func (m *Muxer) Close() {
m.mutex.Lock()
m.closed = true
m.mutex.Unlock()
m.cond.Broadcast()
for _, stream := range m.streams {
stream.close()
}
}
// WriteAV1 writes an AV1 temporal unit.
func (m *Muxer) WriteAV1(
track *Track,
ntp time.Time,
pts int64,
tu [][]byte,
) error {
return m.segmenter.writeAV1(m.mtracksByTrack[track], ntp, pts, tu)
}
// WriteVP9 writes a VP9 frame.
func (m *Muxer) WriteVP9(
track *Track,
ntp time.Time,
pts int64,
frame []byte,
) error {
return m.segmenter.writeVP9(m.mtracksByTrack[track], ntp, pts, frame)
}
// WriteH265 writes an H265 access unit.
func (m *Muxer) WriteH265(
track *Track,
ntp time.Time,
pts int64,
au [][]byte,
) error {
return m.segmenter.writeH265(m.mtracksByTrack[track], ntp, pts, au)
}
// WriteH264 writes an H264 access unit.
func (m *Muxer) WriteH264(
track *Track,
ntp time.Time,
pts int64,
au [][]byte,
) error {
return m.segmenter.writeH264(m.mtracksByTrack[track], ntp, pts, au)
}
// WriteOpus writes Opus packets.
func (m *Muxer) WriteOpus(
track *Track,
ntp time.Time,
pts int64,
packets [][]byte,
) error {
return m.segmenter.writeOpus(m.mtracksByTrack[track], ntp, pts, packets)
}
// WriteMPEG4Audio writes MPEG-4 Audio access units.
func (m *Muxer) WriteMPEG4Audio(
track *Track,
ntp time.Time,
pts int64,
aus [][]byte,
) error {
return m.segmenter.writeMPEG4Audio(m.mtracksByTrack[track], ntp, pts, aus)
}
// Handle handles a HTTP request.
func (m *Muxer) Handle(w http.ResponseWriter, r *http.Request) {
m.server.handle(w, r)
}
func (m *Muxer) createFirstSegment(nextDTS time.Duration, nextNTP time.Time) error {
for _, stream := range m.streams {
err := stream.createFirstSegment(nextDTS, nextNTP)
if err != nil {
return err
}
}
return nil
}
func (m *Muxer) rotateParts(nextDTS time.Duration) error {
m.mutex.Lock()
err := m.rotatePartsInner(nextDTS)
m.mutex.Unlock()
if err != nil {
return err
}
m.cond.Broadcast()
return nil
}
func (m *Muxer) rotatePartsInner(nextDTS time.Duration) error {
err := m.leadingStream.rotateParts(nextDTS, true)
if err != nil {
return err
}
for _, stream := range m.streams {
if !stream.isLeading {
err := stream.rotateParts(nextDTS, true)
if err != nil {
return err
}
stream.partTargetDuration = m.leadingStream.partTargetDuration
}
}
return nil
}
func (m *Muxer) rotateSegments(
nextDTS time.Duration,
nextNTP time.Time,
force bool,
) error {
m.mutex.Lock()
err := m.rotateSegmentsInner(nextDTS, nextNTP, force)
m.mutex.Unlock()
if err != nil {
return err
}
m.cond.Broadcast()
return nil
}
func (m *Muxer) rotateSegmentsInner(
nextDTS time.Duration,
nextNTP time.Time,
force bool,
) error {
err := m.leadingStream.rotateSegments(nextDTS, nextNTP, force)
if err != nil {
return err
}
for _, stream := range m.streams {
if !stream.isLeading {
err := stream.rotateSegments(nextDTS, nextNTP, force)
if err != nil {
return err
}
stream.targetDuration = m.leadingStream.targetDuration
stream.partTargetDuration = m.leadingStream.partTargetDuration
}
}
return nil
}
func (m *Muxer) handleMultivariantPlaylist(w http.ResponseWriter, r *http.Request) {
buf := func() []byte {
m.mutex.Lock()
defer m.mutex.Unlock()
for {
if m.closed {
return nil
}
if m.streams[0].hasContent() {
break
}
m.cond.Wait()
}
buf, err := m.generateMultivariantPlaylist(r.URL.RawQuery)
if err != nil {
return nil
}
return buf
}()
if buf == nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
// allow caching but use a small period in order to
// allow a stream to change tracks or bitrate
w.Header().Set("Cache-Control", "max-age="+multivariantPlaylistMaxAge)
w.Header().Set("Content-Type", `application/vnd.apple.mpegurl`)
w.WriteHeader(http.StatusOK)
w.Write(buf)
}
func (m *Muxer) generateMultivariantPlaylist(rawQuery string) ([]byte, error) {
// TODO: consider segments in all streams
maxBandwidth, averageBandwidth := bandwidth(m.streams[0].segments)
pl := &playlist.Multivariant{
Version: func() int {
if m.Variant == MuxerVariantMPEGTS {
return 3
}
return 9
}(),
IndependentSegments: true,
Variants: []*playlist.MultivariantVariant{{
Bandwidth: maxBandwidth,
AverageBandwidth: &averageBandwidth,
}},
}
for _, stream := range m.streams {
err := stream.populateMultivariantPlaylist(pl, rawQuery)
if err != nil {
return nil, err
}
}
return pl.Marshal()
}