-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathmediaserver.go
1654 lines (1527 loc) · 51.1 KB
/
mediaserver.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 server is the place we integrate the Livepeer node with the LPMS media server.
*/
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"path"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/livepeer/go-livepeer/clog"
"github.com/livepeer/go-livepeer/monitor"
"github.com/livepeer/go-livepeer/pm"
"github.com/livepeer/go-tools/drivers"
"github.com/golang/glog"
"github.com/livepeer/go-livepeer/common"
"github.com/livepeer/go-livepeer/core"
lpmscore "github.com/livepeer/lpms/core"
ffmpeg "github.com/livepeer/lpms/ffmpeg"
"github.com/livepeer/lpms/segmenter"
"github.com/livepeer/lpms/stream"
"github.com/livepeer/lpms/vidplayer"
"github.com/livepeer/m3u8"
"github.com/patrickmn/go-cache"
)
var errAlreadyExists = errors.New("StreamAlreadyExists")
var errStorage = errors.New("ErrStorage")
var errDiscovery = errors.New("ErrDiscovery")
var errNoOrchs = errors.New("ErrNoOrchs")
var errUnknownStream = errors.New("ErrUnknownStream")
var errMismatchedParams = errors.New("Mismatched type for stream params")
const HLSWaitInterval = time.Second
const HLSBufferCap = uint(43200) //12 hrs assuming 1s segment
const HLSBufferWindow = uint(5)
const StreamKeyBytes = 6
const SegLen = 2 * time.Second
const BroadcastRetry = 15 * time.Second
var BroadcastJobVideoProfiles = []ffmpeg.VideoProfile{ffmpeg.P240p30fps4x3, ffmpeg.P360p30fps16x9}
var AuthWebhookURL *url.URL
var DetectionWebhookURL *url.URL
var DetectionWhClient = &http.Client{Timeout: 2 * time.Second}
var SelectRandFreq float64
func PixelFormatNone() ffmpeg.PixelFormat {
return ffmpeg.PixelFormat{RawValue: ffmpeg.PixelFormatNone}
}
// For HTTP push watchdog
var httpPushTimeout = 60 * time.Second
var httpPushResetTimer = func() (context.Context, context.CancelFunc) {
sleepDur := time.Duration(int64(float64(httpPushTimeout) * 0.9))
return context.WithTimeout(context.Background(), sleepDur)
}
type rtmpConnection struct {
initializing chan struct{}
mid core.ManifestID
nonce uint64
stream stream.RTMPVideoStream
pl core.PlaylistManager
profile *ffmpeg.VideoProfile
params *core.StreamParameters
sessManager *BroadcastSessionsManager
lastUsed time.Time
sourceBytes uint64
transcodedBytes uint64
}
func (s *LivepeerServer) getActiveRtmpConnectionUnsafe(mid core.ManifestID) (*rtmpConnection, bool) {
cxn, exists := s.rtmpConnections[mid]
if exists {
if cxn.initializing != nil {
<-cxn.initializing
}
}
return cxn, exists
}
type LivepeerServer struct {
RTMPSegmenter lpmscore.RTMPSegmenter
LPMS *lpmscore.LPMS
LivepeerNode *core.LivepeerNode
HTTPMux *http.ServeMux
ExposeCurrentManifest bool
recordingsAuthResponses *cache.Cache
// Thread sensitive fields. All accesses to the
// following fields should be protected by `connectionLock`
rtmpConnections map[core.ManifestID]*rtmpConnection
internalManifests map[core.ManifestID]core.ManifestID
lastHLSStreamID core.StreamID
lastManifestID core.ManifestID
context context.Context
connectionLock *sync.RWMutex
serverLock *sync.RWMutex
}
func (s *LivepeerServer) SetContextFromUnitTest(c context.Context) {
s.context = c
}
type authWebhookResponse struct {
ManifestID string `json:"manifestID"`
StreamID string `json:"streamID"`
SessionID string `json:"sessionID"`
StreamKey string `json:"streamKey"`
Presets []string `json:"presets"`
ObjectStore string `json:"objectStore"`
RecordObjectStore string `json:"recordObjectStore"`
RecordObjectStoreURL string `json:"recordObjectStoreUrl"`
// Same json structure is used in lpms to decode profile from
// files, while here we decode from HTTP
Profiles []ffmpeg.JsonProfile `json:"profiles"`
PreviousSessions []string `json:"previousSessions"`
Detection struct {
// Run detection on 1/freq segments
Freq uint `json:"freq"`
SampleRate uint `json:"sampleRate"`
SceneClassification []struct {
Name string `json:"name"`
} `json:"sceneClassification"`
} `json:"detection"`
VerificationFreq uint `json:"verificationFreq"`
}
func NewLivepeerServer(rtmpAddr string, lpNode *core.LivepeerNode, httpIngest bool, transcodingOptions string) (*LivepeerServer, error) {
opts := lpmscore.LPMSOpts{
RtmpAddr: rtmpAddr,
RtmpDisabled: true,
WorkDir: lpNode.WorkDir,
HttpMux: http.NewServeMux(),
}
switch lpNode.NodeType {
case core.BroadcasterNode:
opts.RtmpDisabled = false
if transcodingOptions != "" {
var profiles []ffmpeg.VideoProfile
content, err := ioutil.ReadFile(transcodingOptions)
if err == nil && len(content) > 0 {
stubResp := &authWebhookResponse{}
err = json.Unmarshal(content, &stubResp.Profiles)
if err != nil {
return nil, err
}
profiles, err = ffmpeg.ParseProfilesFromJsonProfileArray(stubResp.Profiles)
if err != nil {
return nil, err
}
} else {
// check the built-in profiles
profiles = parsePresets(strings.Split(transcodingOptions, ","))
}
if len(profiles) <= 0 {
return nil, fmt.Errorf("No transcoding profiles found")
}
BroadcastJobVideoProfiles = profiles
}
}
server := lpmscore.New(&opts)
ls := &LivepeerServer{RTMPSegmenter: server, LPMS: server, LivepeerNode: lpNode, HTTPMux: opts.HttpMux, connectionLock: &sync.RWMutex{},
serverLock: &sync.RWMutex{},
rtmpConnections: make(map[core.ManifestID]*rtmpConnection),
internalManifests: make(map[core.ManifestID]core.ManifestID),
recordingsAuthResponses: cache.New(time.Hour, 2*time.Hour),
}
if lpNode.NodeType == core.BroadcasterNode && httpIngest {
opts.HttpMux.HandleFunc("/live/", ls.HandlePush)
}
opts.HttpMux.HandleFunc("/recordings/", ls.HandleRecordings)
return ls, nil
}
//StartMediaServer starts the LPMS server
func (s *LivepeerServer) StartMediaServer(ctx context.Context, httpAddr string) error {
glog.V(common.SHORT).Infof("Transcode Job Type: %v", BroadcastJobVideoProfiles)
// Store ctx to later use as cancel signal for watchdog goroutine
s.context = ctx
//LPMS handlers for handling RTMP video
s.LPMS.HandleRTMPPublish(createRTMPStreamIDHandler(ctx, s, nil), gotRTMPStreamHandler(s), endRTMPStreamHandler(s))
s.LPMS.HandleRTMPPlay(getRTMPStreamHandler(s))
//LPMS hanlder for handling HLS video play
s.LPMS.HandleHLSPlay(getHLSMasterPlaylistHandler(s), getHLSMediaPlaylistHandler(s), getHLSSegmentHandler(s))
//Start the LPMS server
lpmsCtx, cancel := context.WithCancel(ctx)
ec := make(chan error, 2)
go func() {
if err := s.LPMS.Start(lpmsCtx); err != nil {
// typically triggered if there's an error with broadcaster LPMS
// transcoder LPMS should return without an error
ec <- s.LPMS.Start(lpmsCtx)
}
}()
if s.LivepeerNode.NodeType == core.BroadcasterNode {
go func() {
glog.V(4).Infof("HTTP Server listening on http://%v", httpAddr)
ec <- http.ListenAndServe(httpAddr, s.HTTPMux)
}()
}
select {
case err := <-ec:
glog.Infof("LPMS Server Error: %v. Quitting...", err)
cancel()
return err
case <-ctx.Done():
cancel()
return ctx.Err()
}
}
//RTMP Publish Handlers
func createRTMPStreamIDHandler(_ctx context.Context, s *LivepeerServer, webhookResponseOverride *authWebhookResponse) func(url *url.URL) (strmID stream.AppData) {
return func(url *url.URL) (strmID stream.AppData) {
//Check HTTP header for ManifestID
//If ManifestID is passed in HTTP header, use that one
//Else check webhook for ManifestID
//If ManifestID is returned from webhook, use it
//Else check URL for ManifestID
//If ManifestID is passed in URL, use that one
//Else create one
var resp *authWebhookResponse
var mid core.ManifestID
var extStreamID, sessionID string
var err error
var key string
var os, ros drivers.OSDriver
var oss, ross drivers.OSSession
profiles := []ffmpeg.VideoProfile{}
detectionConfig := core.DetectionConfig{}
var VerificationFreq uint
nonce := rand.Uint64()
// do not replace captured _ctx variable
ctx := clog.AddNonce(_ctx, nonce)
if resp, err = authenticateStream(AuthWebhookURL, url.String()); err != nil {
clog.Errorf(ctx, "Authentication denied for streamID url=%s err=%q", url.String(), err)
return nil
}
// If we've received auth in header AND callback URL forms then for now, we reject cases where they're
// trying to give us different profiles
if resp != nil && webhookResponseOverride != nil {
if !resp.areProfilesEqual(*webhookResponseOverride) {
clog.Errorf(ctx, "Received auth header with profiles that don't match those in callback URL response")
return nil
}
}
// If we've received a header containing auth values then let those override any from a callback URL
if webhookResponseOverride != nil {
resp = webhookResponseOverride
}
if resp != nil {
mid, key = parseManifestID(resp.ManifestID), resp.StreamKey
extStreamID, sessionID = resp.StreamID, resp.SessionID
if sessionID != "" && extStreamID != "" && sessionID != extStreamID {
ctx = clog.AddSessionID(ctx, sessionID)
}
// Process transcoding options presets
if len(resp.Presets) > 0 {
profiles = parsePresets(resp.Presets)
}
parsedProfiles, err := ffmpeg.ParseProfilesFromJsonProfileArray(resp.Profiles)
if err != nil {
clog.Errorf(ctx, "Failed to parse JSON video profile for streamID url=%s err=%q", url.String(), err)
return nil
}
profiles = append(profiles, parsedProfiles...)
// Only set defaults if user did not specify a preset/profile
if len(resp.Profiles) <= 0 && len(resp.Presets) <= 0 {
profiles = BroadcastJobVideoProfiles
}
// set OS if it was provided
if resp.ObjectStore != "" {
os, err = drivers.ParseOSURL(resp.ObjectStore, false)
if err != nil {
clog.Errorf(ctx, "Failed to parse object store url for streamID url=%s err=%q", url.String(), err)
return nil
}
}
// set Recording OS if it was provided
if resp.RecordObjectStore != "" {
ros, err = drivers.ParseOSURL(resp.RecordObjectStore, true)
if err != nil {
clog.Errorf(ctx, "Failed to parse recording object store url for streamID url=%s err=%q", url.String(), err)
return nil
}
}
// set Detection profile if provided
if resp.Detection.Freq != 0 {
detectionConfig, err = jsonDetectionToDetectionConfig(ctx, resp)
if err != nil {
clog.Errorf(ctx, "Failed to parse detection config from JSON for streamID url=%s err=%q", url.String(), err)
return nil
}
}
VerificationFreq = resp.VerificationFreq
} else {
profiles = BroadcastJobVideoProfiles
}
sid := parseStreamID(url.Path)
extmid := sid.ManifestID
if mid == "" {
mid, key = sid.ManifestID, sid.Rendition
}
if mid == "" {
mid = core.RandomManifestID()
}
// Generate RTMP part of StreamID
if key == "" {
key = common.RandomIDGenerator(StreamKeyBytes)
}
ctx = clog.AddManifestID(ctx, string(mid))
if os != nil {
oss = os.NewSession(string(mid))
}
recordPath := fmt.Sprintf("%s/%s", extmid, monitor.NodeID)
if ros != nil {
ross = ros.NewSession(recordPath)
} else if drivers.RecordStorage != nil {
ross = drivers.RecordStorage.NewSession(recordPath)
}
// Ensure there's no concurrent StreamID with the same name
s.connectionLock.RLock()
defer s.connectionLock.RUnlock()
if core.MaxSessions > 0 && len(s.rtmpConnections) >= core.MaxSessions {
clog.Errorf(ctx, "Too many connections for streamID url=%s err=%q", url.String(), err)
return nil
}
return &core.StreamParameters{
ManifestID: mid,
ExternalStreamID: extStreamID,
SessionID: sessionID,
RtmpKey: key,
// HTTP push mutates `profiles` so make a copy of it
Profiles: append([]ffmpeg.VideoProfile(nil), profiles...),
OS: oss,
RecordOS: ross,
Detection: detectionConfig,
VerificationFreq: VerificationFreq,
Nonce: nonce,
}
}
}
func jsonDetectionToDetectionConfig(ctx context.Context, resp *authWebhookResponse) (core.DetectionConfig, error) {
detection := core.DetectionConfig{
Freq: resp.Detection.Freq,
SelectedClassNames: []string{},
Profiles: []ffmpeg.DetectorProfile{},
}
modelPaths := make(map[string]bool)
for _, class := range resp.Detection.SceneClassification {
c, ok := ffmpeg.SceneClassificationProfileLookup[class.Name]
if !ok {
return detection, errors.New("No detector found for class: " + class.Name)
}
detection.SelectedClassNames = append(detection.SelectedClassNames, class.Name)
if _, ok := modelPaths[c.ModelPath]; ok {
// Skip this profile because we already have a profile with a model that covers this class
continue
}
modelPaths[c.ModelPath] = true
c.SampleRate = resp.Detection.SampleRate
detection.Profiles = append(detection.Profiles, &c)
}
clog.V(common.DEBUG).Infof(ctx, "Configuring detection for classes=%v with segment freq=%v and frame sampleRate=%v",
detection.SelectedClassNames, detection.Freq, resp.Detection.SampleRate)
return detection, nil
}
func streamParams(d stream.AppData) *core.StreamParameters {
p, ok := d.(*core.StreamParameters)
if !ok {
glog.Error("Mismatched type for RTMP app data")
return nil
}
return p
}
func gotRTMPStreamHandler(s *LivepeerServer) func(url *url.URL, rtmpStrm stream.RTMPVideoStream) (err error) {
return func(url *url.URL, rtmpStrm stream.RTMPVideoStream) (err error) {
cxn, err := s.registerConnection(context.Background(), rtmpStrm, nil, PixelFormatNone(), nil)
if err != nil {
return err
}
mid := cxn.mid
nonce := cxn.nonce
startSeq := 0
streamStarted := false
//Segment the stream, insert the segments into the broadcaster
go func(rtmpStrm stream.RTMPVideoStream) {
hid := string(core.RandomManifestID()) // ffmpeg m3u8 output name
hlsStrm := stream.NewBasicHLSVideoStream(hid, stream.DefaultHLSStreamWin)
hlsStrm.SetSubscriber(func(seg *stream.HLSSegment, eof bool) {
if eof {
// XXX update HLS manifest
return
}
if !streamStarted {
streamStarted = true
if monitor.Enabled {
monitor.StreamStarted(nonce)
}
}
go processSegment(context.Background(), cxn, seg, nil)
})
segOptions := segmenter.SegmenterOptions{
StartSeq: startSeq,
SegLength: SegLen,
}
err := s.RTMPSegmenter.SegmentRTMPToHLS(context.Background(), rtmpStrm, hlsStrm, segOptions)
if err != nil {
// Stop the incoming RTMP connection.
// TODO retry segmentation if err != SegmenterTimeout; may be recoverable
rtmpStrm.Close()
}
}(rtmpStrm)
if monitor.Enabled {
monitor.StreamCreated(string(mid), nonce)
}
glog.Infof("\n\nVideo Created With ManifestID: %v\n\n", mid)
return nil
}
}
func endRTMPStreamHandler(s *LivepeerServer) func(url *url.URL, rtmpStrm stream.RTMPVideoStream) error {
return func(url *url.URL, rtmpStrm stream.RTMPVideoStream) error {
params := streamParams(rtmpStrm.AppData())
if params == nil {
return errMismatchedParams
}
//Remove RTMP stream
err := removeRTMPStream(context.Background(), s, params.ManifestID)
if err != nil {
return err
}
return nil
}
}
func (s *LivepeerServer) registerConnection(ctx context.Context, rtmpStrm stream.RTMPVideoStream, actualStreamCodec *ffmpeg.VideoCodec, pixelFormat ffmpeg.PixelFormat, segPar *core.SegmentParameters) (*rtmpConnection, error) {
ctx = clog.Clone(context.Background(), ctx)
// Set up the connection tracking
params := streamParams(rtmpStrm.AppData())
if params == nil {
return nil, errMismatchedParams
}
mid := params.ManifestID
if drivers.NodeStorage == nil {
clog.Errorf(ctx, "Missing node storage")
return nil, errStorage
}
// Build the source video profile from the RTMP stream.
if params.Resolution == "" {
params.Resolution = fmt.Sprintf("%vx%v", rtmpStrm.Width(), rtmpStrm.Height())
}
if params.OS == nil {
params.OS = drivers.NodeStorage.NewSession(string(mid))
}
storage := params.OS
// Generate and set capabilities
if actualStreamCodec != nil {
params.Codec = *actualStreamCodec
}
params.PixelFormat = pixelFormat
caps, err := core.JobCapabilities(params, segPar)
if err != nil {
return nil, err
}
params.Capabilities = caps
recordStorage := params.RecordOS
vProfile := ffmpeg.VideoProfile{
Name: "source",
Resolution: params.Resolution,
Bitrate: "4000k", // Fix this
Format: params.Format,
}
hlsStrmID := core.MakeStreamID(mid, &vProfile)
playlist := core.NewBasicPlaylistManager(mid, storage, recordStorage)
// first, initialize connection without SessionManager, which creates O and T sessions, and may leave
// connectionLock locked for significant amount of time
cxn := &rtmpConnection{
mid: mid,
initializing: make(chan struct{}),
nonce: params.Nonce,
stream: rtmpStrm,
pl: playlist,
profile: &vProfile,
params: params,
lastUsed: time.Now(),
}
s.connectionLock.Lock()
oldCxn, exists := s.getActiveRtmpConnectionUnsafe(mid)
if exists {
// We can only have one concurrent stream per ManifestID
s.connectionLock.Unlock()
return oldCxn, errAlreadyExists
}
s.rtmpConnections[mid] = cxn
// do not obtain this lock again while initializing channel is open, it will cause deadlock if other goroutine already obtained the lock and called getActiveRtmpConnectionUnsafe()
s.connectionLock.Unlock()
// initialize session manager
var stakeRdr stakeReader
if s.LivepeerNode.Eth != nil {
stakeRdr = &storeStakeReader{store: s.LivepeerNode.Database}
}
selFactory := func() BroadcastSessionsSelector {
return NewMinLSSelectorWithRandFreq(stakeRdr, 1.0, SelectRandFreq)
}
// safe, because other goroutines should be waiting on initializing channel
cxn.sessManager = NewSessionManager(ctx, s.LivepeerNode, params, selFactory)
// populate fields and signal initializing channel
s.serverLock.Lock()
s.lastManifestID = mid
s.lastHLSStreamID = hlsStrmID
s.serverLock.Unlock()
// connection is ready, only monitoring below
close(cxn.initializing)
// need lock to access rtmpConnections
s.connectionLock.RLock()
defer s.connectionLock.RUnlock()
sessionsNumber := len(s.rtmpConnections)
fastVerificationEnabled, fastVerificationUsing := countStreamsWithFastVerificationEnabled(s.rtmpConnections)
if monitor.Enabled {
monitor.CurrentSessions(sessionsNumber)
monitor.FastVerificationEnabledAndUsingCurrentSessions(fastVerificationEnabled, fastVerificationUsing)
}
return cxn, nil
}
func countStreamsWithFastVerificationEnabled(rtmpConnections map[core.ManifestID]*rtmpConnection) (int, int) {
var enabled, using int
for _, cxn := range rtmpConnections {
if cxn.params.VerificationFreq > 0 {
enabled++
if cxn.sessManager.usingVerified() {
using++
}
}
}
return enabled, using
}
func removeRTMPStream(ctx context.Context, s *LivepeerServer, extmid core.ManifestID) error {
s.connectionLock.Lock()
defer s.connectionLock.Unlock()
intmid := extmid
if _intmid, exists := s.internalManifests[extmid]; exists {
// Use the internal manifestID that was stored for the provided manifestID
// to index into rtmpConnections
intmid = _intmid
}
cxn, ok := s.getActiveRtmpConnectionUnsafe(intmid)
if !ok || cxn.pl == nil {
clog.Warningf(ctx, "Attempted to end unknown stream with manifestID=%s", extmid)
return errUnknownStream
}
cxn.stream.Close()
cxn.sessManager.cleanup(ctx)
cxn.pl.Cleanup()
clog.Infof(ctx, "Ended stream with manifestID=%s external manifestID=%s", intmid, extmid)
delete(s.rtmpConnections, intmid)
delete(s.internalManifests, extmid)
if monitor.Enabled {
monitor.StreamEnded(ctx, cxn.nonce)
monitor.CurrentSessions(len(s.rtmpConnections))
monitor.FastVerificationEnabledAndUsingCurrentSessions(countStreamsWithFastVerificationEnabled(s.rtmpConnections))
}
return nil
}
//End RTMP Publish Handlers
//HLS Play Handlers
func getHLSMasterPlaylistHandler(s *LivepeerServer) func(url *url.URL) (*m3u8.MasterPlaylist, error) {
return func(url *url.URL) (*m3u8.MasterPlaylist, error) {
var manifestID core.ManifestID
if s.ExposeCurrentManifest && strings.ToLower(url.Path) == "/stream/current.m3u8" {
manifestID = s.LastManifestID()
} else {
sid := parseStreamID(url.Path)
if sid.Rendition != "" {
// requesting a media PL, not master PL
return nil, vidplayer.ErrNotFound
}
manifestID = sid.ManifestID
}
s.connectionLock.RLock()
defer s.connectionLock.RUnlock()
cxn, ok := s.getActiveRtmpConnectionUnsafe(manifestID)
if !ok || cxn.pl == nil {
return nil, vidplayer.ErrNotFound
}
cpl := cxn.pl
if cpl.ManifestID() != manifestID {
return nil, vidplayer.ErrNotFound
}
return cpl.GetHLSMasterPlaylist(), nil
}
}
func getHLSMediaPlaylistHandler(s *LivepeerServer) func(url *url.URL) (*m3u8.MediaPlaylist, error) {
return func(url *url.URL) (*m3u8.MediaPlaylist, error) {
strmID := parseStreamID(url.Path)
mid := strmID.ManifestID
s.connectionLock.RLock()
defer s.connectionLock.RUnlock()
cxn, ok := s.getActiveRtmpConnectionUnsafe(mid)
if !ok || cxn.pl == nil {
return nil, vidplayer.ErrNotFound
}
//Get the hls playlist
pl := cxn.pl.GetHLSMediaPlaylist(strmID.Rendition)
if pl == nil {
return nil, vidplayer.ErrNotFound
}
return pl, nil
}
}
func getHLSSegmentHandler(s *LivepeerServer) func(url *url.URL) ([]byte, error) {
return func(url *url.URL) ([]byte, error) {
// Strip the /stream/ prefix
segName := cleanStreamPrefix(url.Path)
if segName == "" || drivers.NodeStorage == nil {
glog.Error("SegName not found or storage nil")
return nil, vidplayer.ErrNotFound
}
parts := strings.SplitN(segName, "/", 2)
if len(parts) <= 0 {
glog.Error("Unexpected path structure")
return nil, vidplayer.ErrNotFound
}
memoryOS, ok := drivers.NodeStorage.(*drivers.MemoryOS)
if !ok {
return nil, vidplayer.ErrNotFound
}
// We index the session by the first entry of the path, eg
// <session>/<more-path>/<data>
os := memoryOS.GetSession(parts[0])
if os == nil {
return nil, vidplayer.ErrNotFound
}
data := os.GetData(segName)
if len(data) > 0 {
return data, nil
}
return nil, vidplayer.ErrNotFound
}
}
//End HLS Play Handlers
//Start RTMP Play Handlers
func getRTMPStreamHandler(s *LivepeerServer) func(url *url.URL) (stream.RTMPVideoStream, error) {
return func(url *url.URL) (stream.RTMPVideoStream, error) {
mid := parseManifestID(url.Path)
s.connectionLock.RLock()
cxn, ok := s.getActiveRtmpConnectionUnsafe(mid)
defer s.connectionLock.RUnlock()
if !ok {
glog.Error("Cannot find RTMP stream for ManifestID ", mid)
return nil, vidplayer.ErrNotFound
}
//Could use a subscriber, but not going to here because the RTMP stream doesn't need to be available for consumption by multiple views. It's only for the segmenter.
return cxn.stream, nil
}
}
//End RTMP Handlers
type BreakOperation bool
// HandlePush processes request for HTTP ingest
func (s *LivepeerServer) HandlePush(w http.ResponseWriter, r *http.Request) {
errorOut := func(status int, s string, params ...interface{}) {
httpErr := fmt.Sprintf(s, params...)
glog.Error(httpErr)
http.Error(w, httpErr, status)
}
start := time.Now()
if r.Method != "POST" && r.Method != "PUT" {
errorOut(http.StatusMethodNotAllowed, `http push request wrong method=%s url=%s host=%s`, r.Method, r.URL, r.Host)
return
}
authHeaderConfig, err := getTranscodeConfiguration(r)
if err != nil {
httpErr := fmt.Sprintf(`failed to parse transcode config header: %q`, err)
glog.Error(httpErr)
http.Error(w, httpErr, http.StatusBadRequest)
return
}
body, err := common.ReadAtMost(r.Body, common.MaxSegSize)
if err != nil {
errorOut(http.StatusInternalServerError, `Error reading http request body: %s`, err.Error())
return
}
r.Body.Close()
r.URL = &url.URL{Scheme: "http", Host: r.Host, Path: r.URL.Path}
// Determine the input format the request is claiming to have
ext := path.Ext(r.URL.Path)
format := common.ProfileExtensionFormat(ext)
if ffmpeg.FormatNone == format {
// ffmpeg sends us a m3u8 as well, so ignore
// Alternatively, reject m3u8s explicitly and take any other type
// TODO also look at use content-type
errorOut(http.StatusBadRequest, `ignoring file extension: %s`, ext)
return
}
ctx := r.Context()
mid := parseManifestID(r.URL.Path)
if mid != "" {
ctx = clog.AddManifestID(ctx, string(mid))
}
remoteAddr := getRemoteAddr(r)
ctx = clog.AddVal(ctx, clog.ClientIP, remoteAddr)
sliceFromStr := r.Header.Get("Content-Slice-From")
sliceToStr := r.Header.Get("Content-Slice-To")
clog.Infof(ctx, "Got push request at url=%s ua=%s addr=%s bytes=%d dur=%s resolution=%s slice-from=%s slice-to=%s", r.URL.String(), r.UserAgent(),
remoteAddr, len(body), r.Header.Get("Content-Duration"), r.Header.Get("Content-Resolution"), sliceFromStr, sliceToStr)
var sliceFromDur time.Duration
if valMs, err := strconv.ParseUint(sliceFromStr, 10, 64); err == nil {
sliceFromDur = time.Duration(valMs) * time.Millisecond
}
var sliceToDur time.Duration
if valMs, err := strconv.ParseUint(sliceToStr, 10, 64); err == nil {
sliceToDur = time.Duration(valMs) * time.Millisecond
}
var segPar *core.SegmentParameters
if sliceFromDur > 0 || sliceToDur > 0 {
if sliceFromDur > 0 && sliceToDur > 0 && sliceFromDur > sliceToDur {
httpErr := fmt.Sprintf(`Invalid slice config from=%s to=%s`, sliceFromDur, sliceToDur)
clog.Errorf(ctx, httpErr)
http.Error(w, httpErr, http.StatusBadRequest)
return
}
segPar = &core.SegmentParameters{
From: sliceFromDur,
To: sliceToDur,
}
}
now := time.Now()
if mid == "" {
errorOut(http.StatusBadRequest, "Bad URL url=%s", r.URL)
return
}
s.connectionLock.RLock()
if intmid, exists := s.internalManifests[mid]; exists {
mid = intmid
}
cxn, exists := s.getActiveRtmpConnectionUnsafe(mid)
if monitor.Enabled {
fastVerificationEnabled, fastVerificationUsing := countStreamsWithFastVerificationEnabled(s.rtmpConnections)
monitor.FastVerificationEnabledAndUsingCurrentSessions(fastVerificationEnabled, fastVerificationUsing)
}
s.connectionLock.RUnlock()
ctx = clog.AddManifestID(ctx, string(mid))
if exists && cxn != nil {
s.connectionLock.Lock()
cxn.lastUsed = now
s.connectionLock.Unlock()
ctx = clog.AddNonce(ctx, cxn.nonce)
}
status, mediaFormat, err := ffmpeg.GetCodecInfoBytes(body)
isZeroFrame := status == ffmpeg.CodecStatusNeedsBypass
if err != nil {
errorOut(http.StatusUnprocessableEntity, "Error getting codec info url=%s", r.URL)
return
}
var vcodec *ffmpeg.VideoCodec
if len(mediaFormat.Vcodec) == 0 {
clog.Warningf(ctx, "Couldn't detect input video stream codec")
} else {
vcodecVal, ok := ffmpeg.FfmpegNameToVideoCodec[mediaFormat.Vcodec]
vcodec = &vcodecVal
if !ok {
errorOut(http.StatusUnprocessableEntity, "Unknown input stream codec=%s", mediaFormat.Vcodec)
return
}
}
// Check for presence and register if a fresh cxn
if !exists {
appData := (createRTMPStreamIDHandler(ctx, s, authHeaderConfig))(r.URL)
if appData == nil {
errorOut(http.StatusInternalServerError, "Could not create stream ID: url=%s", r.URL)
return
}
params := streamParams(appData)
params.Resolution = r.Header.Get("Content-Resolution")
params.Format = format
s.connectionLock.RLock()
_, cxnExists := s.getActiveRtmpConnectionUnsafe(params.ManifestID)
if mid != params.ManifestID && cxnExists && s.internalManifests[mid] == "" {
// Pre-existing connection found for this new stream with the same underlying manifestID
var oldStreamID core.ManifestID
for k, v := range s.internalManifests {
if v == params.ManifestID {
oldStreamID = k
break
}
}
s.connectionLock.RUnlock()
if oldStreamID != "" && mid != oldStreamID {
// Close the old connection, and open a new one
// TODO try to re-use old HLS playlist?
clog.Warningf(ctx, "Ending streamID=%v as new streamID=%s with same manifestID=%s has arrived",
oldStreamID, mid, params.ManifestID)
removeRTMPStream(context.TODO(), s, oldStreamID)
}
} else {
s.connectionLock.RUnlock()
}
st := stream.NewBasicRTMPVideoStream(appData)
// Set output formats if not explicitly specified
for i, v := range params.Profiles {
if ffmpeg.FormatNone == v.Format {
params.Profiles[i].Format = format
}
}
cxn, err = s.registerConnection(ctx, st, vcodec, mediaFormat.PixFormat, segPar)
if err != nil {
st.Close()
if err != errAlreadyExists {
errorOut(http.StatusInternalServerError, "http push error url=%s err=%q", r.URL, err)
return
} // else we continue with the old cxn
} else {
// Start a watchdog to remove session after a period of inactivity
ticker := time.NewTicker(httpPushTimeout)
// print stack trace here:
go func(s *LivepeerServer, intmid, extmid core.ManifestID) {
runCheck := func() BreakOperation {
var lastUsed time.Time
s.connectionLock.RLock()
if cxn, exists := s.getActiveRtmpConnectionUnsafe(intmid); exists {
lastUsed = cxn.lastUsed
}
if _, exists := s.internalManifests[extmid]; !exists && intmid != extmid {
s.connectionLock.RUnlock()
clog.Warningf(ctx, "Watchdog tried closing session for streamID=%s, which was already closed", extmid)
return true
}
s.connectionLock.RUnlock()
if time.Since(lastUsed) > httpPushTimeout {
_ = removeRTMPStream(context.TODO(), s, extmid)
return true
}
return false
}
defer ticker.Stop()
if s.context == nil {
for range ticker.C {
if runCheck() {
return
}
}
}
for {
select {
case <-ticker.C:
if runCheck() {
return
}
case <-s.context.Done():
return
}
}
}(s, cxn.mid, mid)
}
// Regardless of old/new cxn returned by registerConnection, we make sure
// our internalManifests mapping is OK before moving on
if cxn.mid != mid {
// AuthWebhook provided different ManifestID
s.connectionLock.Lock()
s.internalManifests[mid] = cxn.mid
s.connectionLock.Unlock()
mid = cxn.mid
}
}
ctx = clog.AddManifestID(ctx, string(mid))
defer func(now time.Time) {
clog.Infof(ctx, "Finished push request at url=%s ua=%s addr=%s bytes=%d dur=%s resolution=%s took=%s", r.URL.String(), r.UserAgent(), r.RemoteAddr, len(body),
r.Header.Get("Content-Duration"), r.Header.Get("Content-Resolution"), time.Since(now))
}(now)
fname := path.Base(r.URL.Path)
seq, err := strconv.ParseUint(strings.TrimSuffix(fname, ext), 10, 64)
if err != nil {
seq = 0
}
ctx = clog.AddSeqNo(ctx, seq)
duration, err := strconv.Atoi(r.Header.Get("Content-Duration"))
if err != nil {
duration = 2000
glog.Info("Missing duration; filling in a default of 2000ms")
}
seg := &stream.HLSSegment{
Data: body,
Name: fname,
SeqNo: seq,
Duration: float64(duration) / 1000.0,
IsZeroFrame: isZeroFrame,
}
// Kick watchdog periodically so session doesn't time out during long transcodes
requestEnded := make(chan struct{}, 1)
defer func() { requestEnded <- struct{}{} }()
go func() {
for {
tick, cancel := httpPushResetTimer()
select {
case <-requestEnded:
cancel()
return
case <-tick.Done():
clog.V(common.VERBOSE).Infof(ctx, "watchdog reset seq=%d dur=%v started=%v", seq, duration, now)
s.connectionLock.RLock()
if cxn, exists := s.getActiveRtmpConnectionUnsafe(mid); exists {
cxn.lastUsed = time.Now()