-
Notifications
You must be signed in to change notification settings - Fork 176
/
broadcast.go
1419 lines (1260 loc) · 44.9 KB
/
broadcast.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
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"math/big"
"math/rand"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/golang/glog"
"github.com/livepeer/go-livepeer/common"
"github.com/livepeer/go-livepeer/core"
"github.com/livepeer/go-livepeer/drivers"
"github.com/livepeer/go-livepeer/monitor"
"github.com/livepeer/go-livepeer/net"
"github.com/livepeer/go-livepeer/pm"
"github.com/livepeer/go-livepeer/verification"
"github.com/livepeer/livepeer-data/pkg/data"
"github.com/livepeer/livepeer-data/pkg/event"
"github.com/livepeer/lpms/ffmpeg"
"github.com/livepeer/lpms/stream"
)
var refreshTimeout = 2500 * time.Millisecond
var maxDurationSec = common.MaxDuration.Seconds()
// Max threshold for # of broadcast sessions under which we will refresh the session list
var maxRefreshSessionsThreshold = 8.0
var Policy *verification.Policy
var BroadcastCfg = &BroadcastConfig{}
var MaxAttempts = 3
var MetadataQueue event.Producer
var MetadataPublishTimeout = 1 * time.Second
var getOrchestratorInfoRPC = GetOrchestratorInfo
var downloadSeg = drivers.GetSegmentData
type BroadcastConfig struct {
maxPrice *big.Rat
mu sync.RWMutex
}
type SegFlightMetadata struct {
startTime time.Time
segDur time.Duration
}
func (cfg *BroadcastConfig) MaxPrice() *big.Rat {
cfg.mu.RLock()
defer cfg.mu.RUnlock()
return cfg.maxPrice
}
func (cfg *BroadcastConfig) SetMaxPrice(price *big.Rat) {
cfg.mu.Lock()
defer cfg.mu.Unlock()
cfg.maxPrice = price
if monitor.Enabled {
monitor.MaxTranscodingPrice(price)
}
}
type sessionsCreator func() ([]*BroadcastSession, error)
type SessionPool struct {
mid core.ManifestID
// Accessing or changing any of the below requires ownership of this mutex
lock sync.Mutex
sel BroadcastSessionsSelector
lastSess []*BroadcastSession
sessMap map[string]*BroadcastSession
numOrchs int // how many orchs to request at once
poolSize int
refreshing bool // only allow one refresh in-flight
finished bool // set at stream end
createSessions sessionsCreator
sus *suspender
}
func NewSessionPool(mid core.ManifestID, poolSize, numOrchs int, sus *suspender, createSession sessionsCreator,
sel BroadcastSessionsSelector) *SessionPool {
return &SessionPool{
mid: mid,
numOrchs: numOrchs,
poolSize: poolSize,
sessMap: make(map[string]*BroadcastSession),
sel: sel,
createSessions: createSession,
sus: sus,
}
}
func (sp *SessionPool) suspend(orch string) {
poolSize := math.Max(1, float64(sp.poolSize))
numOrchs := math.Max(1, float64(sp.numOrchs))
penalty := int(math.Ceil(poolSize / numOrchs))
sp.sus.suspend(orch, penalty)
}
func (sp *SessionPool) refreshSessions() {
started := time.Now()
glog.V(common.DEBUG).Infof("Starting session refresh manifestID=%s", sp.mid)
defer func() {
sp.lock.Lock()
glog.V(common.DEBUG).Infof("Ending session refresh manifestID=%s dur=%s orchs=%d", sp.mid, time.Since(started),
sp.sel.Size())
sp.lock.Unlock()
}()
sp.lock.Lock()
if sp.finished || sp.refreshing {
sp.lock.Unlock()
return
}
sp.refreshing = true
sp.lock.Unlock()
sp.sus.signalRefresh()
newBroadcastSessions, err := sp.createSessions()
if err != nil {
sp.lock.Lock()
sp.refreshing = false
sp.lock.Unlock()
return
}
// if newBroadcastSessions is empty, exit without refreshing list
if len(newBroadcastSessions) <= 0 {
sp.lock.Lock()
sp.refreshing = false
sp.lock.Unlock()
return
}
uniqueSessions := make([]*BroadcastSession, 0, len(newBroadcastSessions))
sp.lock.Lock()
defer sp.lock.Unlock()
sp.refreshing = false
if sp.finished {
return
}
for _, sess := range newBroadcastSessions {
if _, ok := sp.sessMap[sess.OrchestratorInfo.Transcoder]; ok {
continue
}
uniqueSessions = append(uniqueSessions, sess)
sp.sessMap[sess.OrchestratorInfo.Transcoder] = sess
}
sp.sel.Add(uniqueSessions)
}
func includesSession(sessions []*BroadcastSession, session *BroadcastSession) bool {
for _, sess := range sessions {
if sess == session {
return true
}
}
return false
}
func getOrchs(sessions []*BroadcastSession) []string {
res := make([]string, len(sessions))
for i, sess := range sessions {
res[i] = sess.Transcoder()
}
return res
}
func removeSessionFromList(sessions []*BroadcastSession, sess *BroadcastSession) []*BroadcastSession {
var res []*BroadcastSession
for _, ls := range sessions {
if ls != sess {
res = append(res, ls)
}
}
return res
}
func selectSession(sessions []*BroadcastSession, exclude []*BroadcastSession, durMult int) *BroadcastSession {
for _, session := range sessions {
if len(session.SegsInFlight) > 0 &&
time.Since(session.SegsInFlight[0].startTime) < time.Duration(durMult)*session.SegsInFlight[0].segDur &&
!includesSession(exclude, session) {
// Re-use last session if oldest segment is in-flight for < durMult * segDur
return session
}
}
return nil
}
func (sp *SessionPool) selectSessions(sessionsNum int) []*BroadcastSession {
sp.lock.Lock()
defer sp.lock.Unlock()
if sp.poolSize == 0 {
return nil
}
checkSessions := func(m *SessionPool) bool {
numSess := m.sel.Size()
if numSess < int(math.Min(maxRefreshSessionsThreshold, math.Ceil(float64(m.numOrchs)/2.0))) {
go m.refreshSessions()
}
return (numSess > 0 || len(sp.lastSess) > 0)
}
var selectedSessions []*BroadcastSession
for checkSessions(sp) {
var sess *BroadcastSession
// Re-use last session if oldest segment is in-flight for < segDur
gotFromLast := false
sess = selectSession(sp.lastSess, selectedSessions, 1)
if sess == nil {
// Or try a new session from the available ones
sess = sp.sel.Select()
} else {
gotFromLast = true
}
if sess == nil {
// If no new sessions are available, re-use last session when oldest segment is in-flight for < 2 * segDur
sess = selectSession(sp.lastSess, selectedSessions, 2)
if sess != nil {
gotFromLast = true
glog.V(common.DEBUG).Infof("No sessions in the selector for manifestID=%v re-using orch=%v with acceptable in-flight time",
sp.mid, sess.Transcoder())
}
}
// No session found, return nil
if sess == nil {
break
}
/*
Don't select sessions no longer in the map.
Retry if the first selected session has been removed from the map.
This may occur if the session is removed while still in the list.
To avoid a runtime search of the session list under lock, simply
fixup the session list at selection time by retrying the selection.
*/
if _, ok := sp.sessMap[sess.Transcoder()]; ok {
selectedSessions = append(selectedSessions, sess)
if len(selectedSessions) == sessionsNum {
break
}
} else {
if gotFromLast {
// Last session got removed from map (possibly due to a failure) so stop tracking its in-flight segments
sess.SegsInFlight = nil
sp.lastSess = removeSessionFromList(sp.lastSess, sess)
glog.V(common.DEBUG).Infof("Removing orch=%v from manifestID=%s session list", sess.Transcoder(), sp.mid)
if monitor.Enabled {
monitor.OrchestratorSwapped()
}
}
}
}
if len(selectedSessions) == 0 {
// No session found, return nil
sp.lastSess = nil
} else {
for _, ls := range sp.lastSess {
if !includesSession(selectedSessions, ls) {
glog.V(common.DEBUG).Infof("Swapping from orch=%v to orch=%+v for manifestID=%s", ls.Transcoder(),
getOrchs(selectedSessions), sp.mid)
if monitor.Enabled {
monitor.OrchestratorSwapped()
}
}
}
sp.lastSess = append([]*BroadcastSession{}, selectedSessions...)
}
return selectedSessions
}
func (sp *SessionPool) removeSession(session *BroadcastSession) {
sp.lock.Lock()
defer sp.lock.Unlock()
delete(sp.sessMap, session.Transcoder())
}
func (sp *SessionPool) cleanup() {
sp.lock.Lock()
defer sp.lock.Unlock()
sp.finished = true
sp.lastSess = nil
sp.sel.Clear()
sp.sessMap = make(map[string]*BroadcastSession) // prevent segfaults
}
func (sp *SessionPool) completeSession(sess *BroadcastSession) {
sp.lock.Lock()
defer sp.lock.Unlock()
if existingSess, ok := sp.sessMap[sess.Transcoder()]; ok {
if existingSess != sess {
// that means that sess object was removed from pool and then same
// Orchestrator was added to the pool again
return
}
sess.lock.Lock()
defer sess.lock.Unlock()
if len(sess.SegsInFlight) == 1 {
sess.SegsInFlight = nil
} else if len(sess.SegsInFlight) > 1 {
sess.SegsInFlight = sess.SegsInFlight[1:]
// skip returning this session back to the selector
// we will return it later in transcodeSegment() once all in-flight segs downloaded
return
}
sp.sel.Complete(sess)
}
}
type BroadcastSessionsManager struct {
mid core.ManifestID
VerificationFreq uint
// Accessing or changing any of the below requires ownership of this mutex
sessLock sync.Mutex
finished bool // set at stream end
trustedPool *SessionPool
untrustedPool *SessionPool
verifiedSession *BroadcastSession
}
func NewSessionManager(node *core.LivepeerNode, params *core.StreamParameters, sel BroadcastSessionsSelectorFactory) *BroadcastSessionsManager {
var trustedPoolSize, untrustedPoolSize float64
if node.OrchestratorPool != nil {
trustedPoolSize = float64(node.OrchestratorPool.SizeWith(common.ScoreAtLeast(common.Score_Trusted)))
untrustedPoolSize = float64(node.OrchestratorPool.SizeWith(common.ScoreEqualTo(common.Score_Untrusted)))
}
maxInflight := common.HTTPTimeout.Seconds() / SegLen.Seconds()
trustedNumOrchs := int(math.Min(trustedPoolSize, maxInflight*2))
untrustedNumOrchs := int(untrustedPoolSize)
susTrusted := newSuspender()
susUntrusted := newSuspender()
createSessionsTrusted := func() ([]*BroadcastSession, error) {
return selectOrchestrator(node, params, trustedNumOrchs, susTrusted, common.ScoreAtLeast(common.Score_Trusted))
}
createSessionsUntrusted := func() ([]*BroadcastSession, error) {
return selectOrchestrator(node, params, untrustedNumOrchs, susUntrusted, common.ScoreEqualTo(common.Score_Untrusted))
}
var stakeRdr stakeReader
if node.Eth != nil {
stakeRdr = &storeStakeReader{store: node.Database}
}
bsm := &BroadcastSessionsManager{
mid: params.ManifestID,
VerificationFreq: params.VerificationFreq,
trustedPool: NewSessionPool(params.ManifestID, int(trustedPoolSize), trustedNumOrchs, susTrusted, createSessionsTrusted, NewMinLSSelector(stakeRdr, 1.0)),
untrustedPool: NewSessionPool(params.ManifestID, int(untrustedPoolSize), untrustedNumOrchs, susUntrusted, createSessionsUntrusted, NewMinLSSelectorWithRandFreq(stakeRdr, 1.0, SelectRandFreq)),
}
bsm.trustedPool.refreshSessions()
bsm.untrustedPool.refreshSessions()
return bsm
}
func (bsm *BroadcastSessionsManager) suspendAndRemoveOrch(sess *BroadcastSession) {
if sess.OrchestratorScore == common.Score_Untrusted {
bsm.untrustedPool.suspend(sess.OrchestratorInfo.GetTranscoder())
bsm.untrustedPool.removeSession(sess)
} else {
bsm.trustedPool.suspend(sess.OrchestratorInfo.GetTranscoder())
bsm.trustedPool.removeSession(sess)
}
}
func (bsm *BroadcastSessionsManager) removeSession(session *BroadcastSession) {
bsm.sessLock.Lock()
defer bsm.sessLock.Unlock()
if session.OrchestratorScore == common.Score_Untrusted {
bsm.untrustedPool.removeSession(session)
} else {
bsm.trustedPool.removeSession(session)
}
}
func (bs *BroadcastSession) pushSegInFlight(seg *stream.HLSSegment) {
bs.lock.Lock()
bs.SegsInFlight = append(bs.SegsInFlight,
SegFlightMetadata{
startTime: time.Now(),
segDur: time.Duration(seg.Duration * float64(time.Second)),
})
bs.lock.Unlock()
}
// selects number of sessions to use according to current algorithm
func (bsm *BroadcastSessionsManager) selectSessions() ([]*BroadcastSession, bool, bool) {
bsm.sessLock.Lock()
defer bsm.sessLock.Unlock()
var verified bool
if bsm.VerificationFreq > 0 {
// Select 1 trusted O and 2 untrusted Os
sessions := bsm.trustedPool.selectSessions(1)
untrustedSessions := bsm.untrustedPool.selectSessions(2)
sessions = append(sessions, untrustedSessions...)
// Only return the last verified session if:
// - It is present in the 3 sessions returned by the selector
// - With probability 1 - 1/VerificationFrequency
if bsm.verifiedSession != nil && includesSession(sessions, bsm.verifiedSession) &&
common.RandomUintUnder(bsm.VerificationFreq) > 0 {
glog.V(common.DEBUG).Infof("Reusing verified orch=%v", bsm.verifiedSession.OrchestratorInfo.Transcoder)
verified = true
// Mark remaining unused sessions returned by selector as complete
remaining := removeSessionFromList(sessions, bsm.verifiedSession)
for _, sess := range remaining {
bsm.completeSessionUnsafe(sess)
}
sessions = []*BroadcastSession{bsm.verifiedSession}
} else if bsm.verifiedSession != nil && !includesSession(sessions, bsm.verifiedSession) {
bsm.verifiedSession = nil
}
// Return selected sessions
return sessions, true, verified
}
// Default to selecting from untrusted pool
sessions := bsm.untrustedPool.selectSessions(1)
if len(sessions) == 0 {
sessions = bsm.trustedPool.selectSessions(1)
}
return sessions, false, verified
}
func (bsm *BroadcastSessionsManager) cleanup() {
bsm.sessLock.Lock()
defer bsm.sessLock.Unlock()
bsm.finished = true
bsm.trustedPool.cleanup()
bsm.untrustedPool.cleanup()
}
func (bsm *BroadcastSessionsManager) chooseResults(submitResultsCh chan *SubmitResult,
submittedCount int) (*BroadcastSession, *ReceivedTranscodeResult, error) {
submitResults := make([]*SubmitResult, submittedCount)
// can have different strategies - for example, just use first one
// and ignore everything else
// for now wait for all the results
for i := 0; i < submittedCount; i++ {
submitResults[i] = <-submitResultsCh
}
// we're here because we're doing verification
var trustedResults *SubmitResult
var untrustedResults []*SubmitResult
var err error
for _, res := range submitResults {
if res.Err == nil && res.TranscodeResult != nil {
if res.Session.OrchestratorScore == common.Score_Trusted {
trustedResults = res
} else {
untrustedResults = append(untrustedResults, res)
}
}
if res.Err != nil {
err = res.Err
if isNonRetryableError(err) {
bsm.completeSession(res.Session)
} else {
bsm.suspendAndRemoveOrch(res.Session)
}
}
}
if trustedResults == nil {
// no results from trusted orch, using anything
if len(untrustedResults) == 0 {
// no results at all
return nil, nil, fmt.Errorf("error transcoding: no results at all err=%w", err)
}
return untrustedResults[0].Session, untrustedResults[0].TranscodeResult, untrustedResults[0].Err
}
if len(untrustedResults) == 0 {
// no results from untrusted orch, just using trusted ones
return trustedResults.Session, trustedResults.TranscodeResult, trustedResults.Err
}
segmToCheckIndex := rand.Intn(len(trustedResults.TranscodeResult.Segments))
// downloading hashes
trustedHash, err := drivers.GetSegmentData(trustedResults.TranscodeResult.Segments[segmToCheckIndex].PerceptualHashUrl)
if err != nil {
err = fmt.Errorf("error downloading perceptual hash from url=%s err=%w",
trustedResults.TranscodeResult.Segments[segmToCheckIndex].PerceptualHashUrl, err)
return nil, nil, err
}
var sessionsToSuspend []*BroadcastSession
for _, untrustedResult := range untrustedResults {
untrustedHash, err := drivers.GetSegmentData(untrustedResult.TranscodeResult.Segments[segmToCheckIndex].PerceptualHashUrl)
if err != nil {
err = fmt.Errorf("error downloading perceptual hash from url=%s err=%w",
untrustedResult.TranscodeResult.Segments[segmToCheckIndex].PerceptualHashUrl, err)
return nil, nil, err
}
equal, err := ffmpeg.CompareSignatureByBuffer(trustedHash, untrustedHash)
if monitor.Enabled {
monitor.FastVerificationDone()
}
if err != nil {
glog.Errorf("error comparing perceptual hashes from url=%s err=%v",
untrustedResult.TranscodeResult.Segments[segmToCheckIndex].PerceptualHashUrl, err)
}
glog.Infof("Hashes from url=%s and url=%s are equal=%v",
trustedResults.TranscodeResult.Segments[segmToCheckIndex].PerceptualHashUrl,
untrustedResult.TranscodeResult.Segments[segmToCheckIndex].PerceptualHashUrl, equal)
if equal {
// stick to this verified orchestrator for further segments.
if untrustedResult.Err == nil {
bsm.sessionVerified(untrustedResult.Session)
}
// suspend sessions which returned incorrect results
for _, s := range sessionsToSuspend {
bsm.suspendAndRemoveOrch(s)
}
return untrustedResult.Session, untrustedResult.TranscodeResult, untrustedResult.Err
} else {
sessionsToSuspend = append(sessionsToSuspend, untrustedResult.Session)
if monitor.Enabled {
monitor.FastVerificationFailed()
}
}
}
return trustedResults.Session, trustedResults.TranscodeResult, trustedResults.Err
}
// the caller needs to ensure bsm.sessLock is acquired before calling this.
func (bsm *BroadcastSessionsManager) completeSessionUnsafe(sess *BroadcastSession) {
if sess.OrchestratorScore == common.Score_Untrusted {
bsm.untrustedPool.completeSession(sess)
} else if sess.OrchestratorScore == common.Score_Trusted {
bsm.trustedPool.completeSession(sess)
} else {
panic("shouldn't happen")
}
}
func (bsm *BroadcastSessionsManager) completeSession(sess *BroadcastSession) {
bsm.sessLock.Lock()
defer bsm.sessLock.Unlock()
bsm.completeSessionUnsafe(sess)
}
func (bsm *BroadcastSessionsManager) sessionVerified(sess *BroadcastSession) {
bsm.sessLock.Lock()
defer bsm.sessLock.Unlock()
bsm.verifiedSession = sess
}
func (bsm *BroadcastSessionsManager) usingVerified() bool {
bsm.sessLock.Lock()
defer bsm.sessLock.Unlock()
return bsm.verifiedSession != nil
}
func selectOrchestrator(n *core.LivepeerNode, params *core.StreamParameters, count int, sus *suspender,
scorePred common.ScorePred) ([]*BroadcastSession, error) {
if n.OrchestratorPool == nil {
glog.Info("No orchestrators specified; not transcoding")
return nil, errDiscovery
}
tinfos, err := n.OrchestratorPool.GetOrchestrators(count, sus, params.Capabilities, scorePred)
if len(tinfos) <= 0 {
glog.Info("No orchestrators found; not transcoding. Error: ", err)
return nil, errNoOrchs
}
if err != nil {
return nil, err
}
var sessions []*BroadcastSession
for _, tinfo := range tinfos {
var (
sessionID string
balance Balance
ticketParams *pm.TicketParams
)
if tinfo.AuthToken == nil {
glog.Errorf("Missing auth token orch=%v", tinfo.Transcoder)
continue
}
if n.Sender != nil {
if tinfo.TicketParams == nil {
glog.Errorf("Missing ticket params orch=%v", tinfo.Transcoder)
continue
}
ticketParams = pmTicketParams(tinfo.TicketParams)
sessionID = n.Sender.StartSession(*ticketParams)
if n.Balances != nil {
balance = core.NewBalance(ticketParams.Recipient, core.ManifestID(tinfo.AuthToken.SessionId), n.Balances)
}
}
var orchOS drivers.OSSession
if len(tinfo.Storage) > 0 {
orchOS = drivers.NewSession(tinfo.Storage[0])
}
bcastOS := params.OS
if bcastOS.IsExternal() {
// Give each O its own OS session to prevent front running uploads
pfx := fmt.Sprintf("%v/%v", params.ManifestID, tinfo.AuthToken.SessionId)
bcastOS = bcastOS.OS().NewSession(pfx)
}
session := &BroadcastSession{
Broadcaster: core.NewBroadcaster(n),
Params: params,
OrchestratorInfo: tinfo,
OrchestratorOS: orchOS,
BroadcasterOS: bcastOS,
Sender: n.Sender,
PMSessionID: sessionID,
Balances: n.Balances,
Balance: balance,
lock: &sync.RWMutex{},
OrchestratorScore: n.OrchestratorPool.GetInfo(tinfo.Transcoder).Score, // todo: use score from OrchestratorLocalInfo
}
sessions = append(sessions, session)
}
return sessions, nil
}
func processSegment(cxn *rtmpConnection, seg *stream.HLSSegment) ([]string, error) {
rtmpStrm := cxn.stream
nonce := cxn.nonce
cpl := cxn.pl
mid := cxn.mid
vProfile := cxn.profile
if seg.Duration > maxDurationSec || seg.Duration < 0 {
glog.Errorf("Invalid duration nonce=%d manifestID=%s seqNo=%d dur=%v", nonce, mid, seg.SeqNo, seg.Duration)
return nil, fmt.Errorf("Invalid duration %v", seg.Duration)
}
glog.V(common.DEBUG).Infof("Processing segment nonce=%d manifestID=%s seqNo=%d dur=%v bytes=%v", nonce, mid, seg.SeqNo, seg.Duration, len(seg.Data))
if monitor.Enabled {
monitor.SegmentEmerged(nonce, seg.SeqNo, len(BroadcastJobVideoProfiles), seg.Duration)
}
atomic.AddUint64(&cxn.sourceBytes, uint64(len(seg.Data)))
seg.Name = "" // hijack seg.Name to convey the uploaded URI
ext, err := common.ProfileFormatExtension(vProfile.Format)
if err != nil {
glog.Errorf("Unknown format extension manifestID=%s seqNo=%d err=%s", mid, seg.SeqNo, err)
return nil, err
}
name := fmt.Sprintf("%s/%d%s", vProfile.Name, seg.SeqNo, ext)
ros := cpl.GetRecordOSSession()
segDurMs := getSegDurMsString(seg)
now := time.Now()
hasZeroVideoFrame, err := ffmpeg.HasZeroVideoFrameBytes(seg.Data)
if err != nil {
glog.Warningf("Error checking for zero video frame manifestID=%s name=%s bytes=%d took=%s err=%v",
mid, seg.Name, len(seg.Data), time.Since(now), err)
}
if ros != nil && !hasZeroVideoFrame {
go func() {
now := time.Now()
uri, err := drivers.SaveRetried(ros, name, seg.Data, map[string]string{"duration": segDurMs}, 2)
took := time.Since(now)
if err != nil {
glog.Errorf("Error saving nonce=%d manifestID=%s name=%s bytes=%d to record store err=%v",
nonce, mid, name, len(seg.Data), err)
} else {
cpl.InsertHLSSegmentJSON(vProfile, seg.SeqNo, uri, seg.Duration)
glog.Infof("Successfully saved nonce=%d manifestID=%s name=%s bytes=%d to record store took=%s",
nonce, mid, name, len(seg.Data), took)
cpl.FlushRecord()
}
if monitor.Enabled {
monitor.RecordingSegmentSaved(took, err)
}
}()
}
uri, err := cpl.GetOSSession().SaveData(name, seg.Data, nil, 0)
if err != nil {
glog.Errorf("Error saving segment nonce=%d seqNo=%d: %v", nonce, seg.SeqNo, err)
if monitor.Enabled {
monitor.SegmentUploadFailed(nonce, seg.SeqNo, monitor.SegmentUploadErrorUnknown, err, true)
}
return nil, err
}
if cpl.GetOSSession().IsExternal() {
seg.Name = uri // hijack seg.Name to convey the uploaded URI
}
err = cpl.InsertHLSSegment(vProfile, seg.SeqNo, uri, seg.Duration)
if monitor.Enabled {
monitor.SourceSegmentAppeared(nonce, seg.SeqNo, string(mid), vProfile.Name, ros != nil)
}
if err != nil {
glog.Errorf("Error inserting segment manifestID=%s nonce=%d seqNo=%d err=%v", cxn.mid, nonce, seg.SeqNo, err)
if monitor.Enabled {
monitor.SegmentUploadFailed(nonce, seg.SeqNo, monitor.SegmentUploadErrorDuplicateSegment, err, false)
}
}
if hasZeroVideoFrame {
var urls []string
for _, profile := range cxn.params.Profiles {
ext, err := common.ProfileFormatExtension(profile.Format)
if err != nil {
glog.Errorf("Error getting extension for profile=%v with segment manifestID=%s nonce=%d seqNo=%d err=%v",
profile.Format, cxn.mid, nonce, seg.SeqNo, err)
return nil, err
}
name := fmt.Sprintf("%s/%d%s", profile.Name, seg.SeqNo, ext)
uri, err := cpl.GetOSSession().SaveData(name, seg.Data, nil, 0)
if err != nil {
glog.Errorf("Error saving segment manifestID=%s nonce=%d seqNo=%d err=%v", cxn.mid, nonce, seg.SeqNo, err)
if monitor.Enabled {
monitor.SegmentUploadFailed(nonce, seg.SeqNo, monitor.SegmentUploadErrorUnknown, err, true)
}
return nil, err
}
urls = append(urls, uri)
err = cpl.InsertHLSSegment(&profile, seg.SeqNo, uri, seg.Duration)
if err != nil {
glog.Errorf("Error inserting segment manifestID=%s nonce=%d seqNo=%d err=%v", cxn.mid, nonce, seg.SeqNo, err)
if monitor.Enabled {
monitor.SegmentUploadFailed(nonce, seg.SeqNo, monitor.SegmentUploadErrorDuplicateSegment, err, false)
}
}
}
return urls, nil
}
var sv *verification.SegmentVerifier
if Policy != nil {
sv = verification.NewSegmentVerifier(Policy)
}
var (
startTime = time.Now()
attempts []data.TranscodeAttemptInfo
urls []string
)
for len(attempts) < MaxAttempts {
// if transcodeSegment fails, retry; rudimentary
var info *data.TranscodeAttemptInfo
urls, info, err = transcodeSegment(cxn, seg, name, sv)
attempts = append(attempts, *info)
if err == nil {
break
}
if shouldStopStream(err) {
glog.Warningf("Stopping current stream due to err=%v", err)
rtmpStrm.Close()
break
}
if isNonRetryableError(err) {
glog.Warningf("Not retrying current segment nonce=%d seqNo=%d due to non-retryable error err=%v", nonce, seg.SeqNo, err)
break
}
// recoverable error, retry
}
if MetadataQueue != nil {
success := err == nil && len(urls) > 0
streamID := string(mid)
if cxn.params != nil && cxn.params.ExternalStreamID != "" {
streamID = cxn.params.ExternalStreamID
}
key := newTranscodeEventKey(mid, streamID)
evt := newTranscodeEvent(streamID, seg, startTime, success, attempts)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), MetadataPublishTimeout)
defer cancel()
if err := MetadataQueue.Publish(ctx, key, evt, false); err != nil {
glog.Errorf("Error publishing stream transcode event: err=%q manifestID=%q seqNo=%d key=%q event=%+v", err, mid, seg.SeqNo, key, evt)
}
}()
}
if len(attempts) == MaxAttempts && err != nil {
err = fmt.Errorf("Hit max transcode attempts: %w", err)
}
return urls, err
}
func transcodeSegment(cxn *rtmpConnection, seg *stream.HLSSegment, name string,
verifier *verification.SegmentVerifier) ([]string, *data.TranscodeAttemptInfo, error) {
var urls []string
info := &data.TranscodeAttemptInfo{}
var err error
defer func(startTime time.Time) {
info.LatencyMs = time.Since(startTime).Milliseconds()
if err != nil {
errStr := err.Error()
info.Error = &errStr
}
}(time.Now())
nonce := cxn.nonce
sessions, calcPerceptualHash, verified := cxn.sessManager.selectSessions()
// Return early under a few circumstances:
// View-only (non-transcoded) streams or no sessions available
if len(sessions) == 0 {
if monitor.Enabled {
monitor.SegmentTranscodeFailed(monitor.SegmentTranscodeErrorNoOrchestrators, nonce, seg.SeqNo, errNoOrchs, true)
}
glog.Infof("No sessions available for segment nonce=%d manifestID=%s seqNo=%d", nonce, cxn.mid, seg.SeqNo)
// We may want to introduce a "non-retryable" error type here
// would help error propagation for live ingest.
// similar to the orchestrator's RemoteTranscoderFatalError
return nil, info, nil
}
info.Orchestrator = data.OrchestratorMetadata{
TranscoderUri: sessions[0].Transcoder(),
Address: sessions[0].Address(),
}
glog.Infof("Trying to transcode segment manifestID=%v nonce=%d seqNo=%d using sessions=%d", cxn.mid, nonce, seg.SeqNo, len(sessions))
if monitor.Enabled {
monitor.TranscodeTry(nonce, seg.SeqNo)
}
if len(sessions) == 1 {
// shortcut for most common path
sess := sessions[0]
if seg, err = prepareForTranscoding(cxn, sess, seg, name); err != nil {
return nil, info, err
}
// cxn.sessManager.pushSegInFlight(sess, seg)
sess.pushSegInFlight(seg)
var res *ReceivedTranscodeResult
res, err = SubmitSegment(sess.Clone(), seg, nonce, calcPerceptualHash, verified)
if err != nil || res == nil {
if isNonRetryableError(err) {
cxn.sessManager.completeSession(sess)
return nil, info, err
}
cxn.sessManager.suspendAndRemoveOrch(sess)
if res == nil && err == nil {
err = errors.New("empty response")
}
return nil, info, err
}
// [EXPERIMENTAL] send content detection results to callback webhook
// for now use detection only in common path
if DetectionWebhookURL != nil && len(res.Detections) > 0 {
glog.V(common.DEBUG).Infof("Got detection result %v", res.Detections)
go func(mid core.ManifestID, config core.DetectionConfig, seqNo uint64, detections []*net.DetectData) {
req := common.DetectionWebhookRequest{ManifestID: string(mid), SeqNo: seqNo}
for _, detection := range detections {
switch x := detection.Value.(type) {
case *net.DetectData_SceneClassification:
probs := x.SceneClassification.ClassProbs
// match returned probs (key: class id) with one of the user-selected class names
for _, name := range config.SelectedClassNames {
if id, ok := ffmpeg.DetectorClassIDLookup[name]; ok {
if prob, ok := probs[uint32(id)]; ok {
req.SceneClassification = append(req.SceneClassification,
common.SceneClassificationResult{
Name: name,
Probability: prob,
})
}
}
}
}
}
jsonValue, err := json.Marshal(req)
if err != nil {
glog.Errorf("Unable to marshal detection result into JSON manifestID=%v seqNo=%v", mid, seqNo)
return
}
resp, err := DetectionWhClient.Post(DetectionWebhookURL.String(), "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
glog.Errorf("Unable to POST detection result on webhook url=%v manifestID=%v seqNo=%v err=%v",
DetectionWebhookURL.Redacted(), mid, seqNo, err)
} else if resp.StatusCode < 200 || resp.StatusCode >= 300 {
rbody, rerr := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if rerr != nil {
glog.Errorf("Detection webhook returned error status=%v manifestID=%v seqNo=%v with unreadable body err=%v",
resp.StatusCode, mid, seqNo, rerr)
} else {
glog.Errorf("Detection webhook returned error status=%v err=%v manifestID=%v seqNo=%v",
resp.StatusCode, string(rbody), mid, seqNo)
}
}
}(cxn.mid, cxn.params.Detection, seg.SeqNo, res.Detections)
}
// Ensure perceptual hash is generated if we ask for it
if calcPerceptualHash {
segmToCheckIndex := rand.Intn(len(res.Segments))
segHash, err := drivers.GetSegmentData(res.Segments[segmToCheckIndex].PerceptualHashUrl)
if err != nil || len(segHash) <= 0 {
err = fmt.Errorf("error downloading perceptual hash from url=%s err=%w",
res.Segments[segmToCheckIndex].PerceptualHashUrl, err)
return nil, info, err
}
}
urls, err = downloadResults(cxn, seg, sess, res, verifier)
return urls, info, err
} else {
resc := make(chan *SubmitResult, len(sessions))
submittedCount := 0
for _, sess := range sessions {
// todo: run it in own goroutine (move to submitSegment?)
seg2, err := prepareForTranscoding(cxn, sess, seg, name)
if err != nil || seg2 == nil {
continue
}
// cxn.sessManager.pushSegInFlight(sess, seg)
sess.pushSegInFlight(seg2)
go submitSegment(sess, seg2, nonce, calcPerceptualHash, resc)
submittedCount++
}
if submittedCount == 0 {
return nil, info, fmt.Errorf("error: not submitted anything")
}
sess, results, err := cxn.sessManager.chooseResults(resc, submittedCount)
if err != nil {
glog.Errorf("Error choosing results: err=%v", err)
return nil, info, err
}
for _, usedSession := range sessions {
if usedSession != sess {
// return session that we're not using
cxn.sessManager.completeSession(usedSession)
}
}
urls, err = downloadResults(cxn, seg, sess, results, verifier)
return urls, info, err
}
}
type SubmitResult struct {
Session *BroadcastSession
TranscodeResult *ReceivedTranscodeResult
Err error
}
func submitSegment(sess *BroadcastSession, seg *stream.HLSSegment, nonce uint64, calcPerceptualHash bool, resc chan *SubmitResult) {
res, err := SubmitSegment(sess.Clone(), seg, nonce, calcPerceptualHash, false)
resc <- &SubmitResult{
Session: sess,
TranscodeResult: res,
Err: err,
}
}
func prepareForTranscoding(cxn *rtmpConnection, sess *BroadcastSession, seg *stream.HLSSegment,
name string) (*stream.HLSSegment, error) {
// storage the orchestrator prefers
res := seg
sess.lock.RLock()
ios := sess.OrchestratorOS
sess.lock.RUnlock()