-
Notifications
You must be signed in to change notification settings - Fork 19
/
connection.go
1552 lines (1220 loc) · 44.5 KB
/
connection.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 srt
import (
"bytes"
"context"
"fmt"
"io"
"math"
"net"
"strings"
"sync"
"time"
"github.com/datarhei/gosrt/circular"
"github.com/datarhei/gosrt/congestion"
"github.com/datarhei/gosrt/congestion/live"
"github.com/datarhei/gosrt/crypto"
"github.com/datarhei/gosrt/packet"
)
// Conn is a SRT network connection.
type Conn interface {
// Read reads data from the connection.
// Read can be made to time out and return an error after a fixed
// time limit; see SetDeadline and SetReadDeadline.
Read(p []byte) (int, error)
// ReadPacket reads a packet from the queue of received packets. It blocks
// if the queue is empty. Only data packets are returned. Using ReadPacket
// and Read at the same time may lead to data loss.
ReadPacket() (packet.Packet, error)
// Write writes data to the connection.
// Write can be made to time out and return an error after a fixed
// time limit; see SetDeadline and SetWriteDeadline.
Write(p []byte) (int, error)
// WritePacket writes a packet to the write queue. Packets on the write queue
// will be sent to the peer of the connection. Only data packets will be sent.
WritePacket(p packet.Packet) error
// Close closes the connection.
// Any blocked Read or Write operations will be unblocked and return errors.
Close() error
// LocalAddr returns the local network address. The returned net.Addr is not shared by other invocations of LocalAddr.
LocalAddr() net.Addr
// RemoteAddr returns the remote network address. The returned net.Addr is not shared by other invocations of RemoteAddr.
RemoteAddr() net.Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
// SocketId return the socketid of the connection.
SocketId() uint32
// PeerSocketId returns the socketid of the peer of the connection.
PeerSocketId() uint32
// StreamId returns the streamid use for the connection.
StreamId() string
// Stats returns accumulated and instantaneous statistics of the connection.
Stats(s *Statistics)
// Version returns the connection version, either 4 or 5. With version 4, the streamid is not available
Version() uint32
}
type rtt struct {
rtt float64 // microseconds
rttVar float64 // microseconds
lock sync.RWMutex
}
func (r *rtt) Recalculate(rtt time.Duration) {
// 4.10. Round-Trip Time Estimation
lastRTT := float64(rtt.Microseconds())
r.lock.Lock()
defer r.lock.Unlock()
r.rtt = r.rtt*0.875 + lastRTT*0.125
r.rttVar = r.rttVar*0.75 + math.Abs(r.rtt-lastRTT)*0.25
}
func (r *rtt) RTT() float64 {
r.lock.RLock()
defer r.lock.RUnlock()
return r.rtt
}
func (r *rtt) RTTVar() float64 {
r.lock.RLock()
defer r.lock.RUnlock()
return r.rttVar
}
func (r *rtt) NAKInterval() float64 {
r.lock.RLock()
defer r.lock.RUnlock()
// 4.8.2. Packet Retransmission (NAKs)
nakInterval := (r.rtt + 4*r.rttVar) / 2
if nakInterval < 20000 {
nakInterval = 20000 // 20ms
}
return nakInterval
}
type connStats struct {
headerSize uint64
pktSentACK uint64
pktRecvACK uint64
pktSentACKACK uint64
pktRecvACKACK uint64
pktSentNAK uint64
pktRecvNAK uint64
pktSentKM uint64
pktRecvKM uint64
pktRecvUndecrypt uint64
byteRecvUndecrypt uint64
pktRecvInvalid uint64
pktSentKeepalive uint64
pktRecvKeepalive uint64
pktSentShutdown uint64
pktRecvShutdown uint64
mbpsLinkCapacity float64
}
// Check if we implement the net.Conn interface
var _ net.Conn = &srtConn{}
type srtConn struct {
version uint32
isCaller bool // Only relevant if version == 4
localAddr net.Addr
remoteAddr net.Addr
start time.Time
shutdownOnce sync.Once
socketId uint32
peerSocketId uint32
config Config
crypto crypto.Crypto
keyBaseEncryption packet.PacketEncryption
kmPreAnnounceCountdown uint64
kmRefreshCountdown uint64
kmConfirmed bool
cryptoLock sync.Mutex
peerIdleTimeout *time.Timer
rtt rtt // microseconds
ackLock sync.RWMutex
ackNumbers map[uint32]time.Time
nextACKNumber circular.Number
initialPacketSequenceNumber circular.Number
tsbpdTimeBase uint64 // microseconds
tsbpdWrapPeriod bool
tsbpdTimeBaseOffset uint64 // microseconds
tsbpdDelay uint64 // microseconds
tsbpdDrift uint64 // microseconds
peerTsbpdDelay uint64 // microseconds
dropThreshold uint64 // microseconds
// Queue for packets that are coming from the network
networkQueue chan packet.Packet
// Queue for packets that are written with writePacket() and will be send to the network
writeQueue chan packet.Packet
writeBuffer bytes.Buffer
writeData []byte
// Queue for packets that will be read locally with ReadPacket()
readQueue chan packet.Packet
readBuffer bytes.Buffer
onSend func(p packet.Packet)
onShutdown func(socketId uint32)
tick time.Duration
// Congestion control
recv congestion.Receiver
snd congestion.Sender
// context of all channels and routines
ctx context.Context
cancelCtx context.CancelFunc
statistics connStats
statisticsLock sync.RWMutex
logger Logger
debug struct {
expectedRcvPacketSequenceNumber circular.Number
expectedReadPacketSequenceNumber circular.Number
}
// HSv4
stopHSRequests context.CancelFunc
stopKMRequests context.CancelFunc
}
type srtConnConfig struct {
version uint32
isCaller bool
localAddr net.Addr
remoteAddr net.Addr
config Config
start time.Time
socketId uint32
peerSocketId uint32
tsbpdTimeBase uint64 // microseconds
tsbpdDelay uint64 // microseconds
peerTsbpdDelay uint64 // microseconds
initialPacketSequenceNumber circular.Number
crypto crypto.Crypto
keyBaseEncryption packet.PacketEncryption
onSend func(p packet.Packet)
onShutdown func(socketId uint32)
logger Logger
}
func newSRTConn(config srtConnConfig) *srtConn {
c := &srtConn{
version: config.version,
isCaller: config.isCaller,
localAddr: config.localAddr,
remoteAddr: config.remoteAddr,
config: config.config,
start: config.start,
socketId: config.socketId,
peerSocketId: config.peerSocketId,
tsbpdTimeBase: config.tsbpdTimeBase,
tsbpdDelay: config.tsbpdDelay,
peerTsbpdDelay: config.peerTsbpdDelay,
initialPacketSequenceNumber: config.initialPacketSequenceNumber,
crypto: config.crypto,
keyBaseEncryption: config.keyBaseEncryption,
onSend: config.onSend,
onShutdown: config.onShutdown,
logger: config.logger,
}
if c.onSend == nil {
c.onSend = func(p packet.Packet) {}
}
if c.onShutdown == nil {
c.onShutdown = func(socketId uint32) {}
}
c.nextACKNumber = circular.New(1, packet.MAX_TIMESTAMP)
c.ackNumbers = make(map[uint32]time.Time)
c.kmPreAnnounceCountdown = c.config.KMRefreshRate - c.config.KMPreAnnounce
c.kmRefreshCountdown = c.config.KMRefreshRate
// 4.10. Round-Trip Time Estimation
c.rtt = rtt{
rtt: float64((100 * time.Millisecond).Microseconds()),
rttVar: float64((50 * time.Millisecond).Microseconds()),
}
c.networkQueue = make(chan packet.Packet, 1024)
c.writeQueue = make(chan packet.Packet, 1024)
if c.version == 4 {
// libsrt-1.2.3 receiver doesn't like it when the payload is larger than 7*188 bytes.
// Here we just take a multiple of a mpegts chunk size.
c.writeData = make([]byte, int(c.config.PayloadSize/188*188))
} else {
// For v5 we use the max. payload size: https://github.com/Haivision/srt/issues/876
c.writeData = make([]byte, int(c.config.PayloadSize))
}
c.readQueue = make(chan packet.Packet, 1024)
c.peerIdleTimeout = time.AfterFunc(c.config.PeerIdleTimeout, func() {
c.log("connection:close", func() string {
return fmt.Sprintf("no more data received from peer for %s. shutting down", c.config.PeerIdleTimeout)
})
go c.close()
})
c.tick = 10 * time.Millisecond
// 4.8.1. Packet Acknowledgement (ACKs, ACKACKs) -> periodicACK = 10 milliseconds
// 4.8.2. Packet Retransmission (NAKs) -> periodicNAK at least 20 milliseconds
c.recv = live.NewReceiver(live.ReceiveConfig{
InitialSequenceNumber: c.initialPacketSequenceNumber,
PeriodicACKInterval: 10_000,
PeriodicNAKInterval: 20_000,
OnSendACK: c.sendACK,
OnSendNAK: c.sendNAK,
OnDeliver: c.deliver,
})
// 4.6. Too-Late Packet Drop -> 125% of SRT latency, at least 1 second
// https://github.com/Haivision/srt/blob/master/docs/API/API-socket-options.md#SRTO_SNDDROPDELAY
c.dropThreshold = uint64(float64(c.peerTsbpdDelay)*1.25) + uint64(c.config.SendDropDelay.Microseconds())
if c.dropThreshold < uint64(time.Second.Microseconds()) {
c.dropThreshold = uint64(time.Second.Microseconds())
}
c.dropThreshold += 20_000
c.snd = live.NewSender(live.SendConfig{
InitialSequenceNumber: c.initialPacketSequenceNumber,
DropThreshold: c.dropThreshold,
MaxBW: c.config.MaxBW,
InputBW: c.config.InputBW,
MinInputBW: c.config.MinInputBW,
OverheadBW: c.config.OverheadBW,
OnDeliver: c.pop,
})
c.ctx, c.cancelCtx = context.WithCancel(context.Background())
go c.networkQueueReader(c.ctx)
go c.writeQueueReader(c.ctx)
go c.ticker(c.ctx)
c.debug.expectedRcvPacketSequenceNumber = c.initialPacketSequenceNumber
c.debug.expectedReadPacketSequenceNumber = c.initialPacketSequenceNumber
c.statistics.headerSize = 8 + 16 // 8 bytes UDP + 16 bytes SRT
if strings.Count(c.localAddr.String(), ":") < 2 {
c.statistics.headerSize += 20 // 20 bytes IPv4 header
} else {
c.statistics.headerSize += 40 // 40 bytes IPv6 header
}
if c.version == 4 && c.isCaller {
var hsrequestsCtx context.Context
hsrequestsCtx, c.stopHSRequests = context.WithCancel(context.Background())
go c.sendHSRequests(hsrequestsCtx)
if c.crypto != nil {
var kmrequestsCtx context.Context
kmrequestsCtx, c.stopKMRequests = context.WithCancel(context.Background())
go c.sendKMRequests(kmrequestsCtx)
}
}
return c
}
func (c *srtConn) LocalAddr() net.Addr {
if c.localAddr == nil {
return nil
}
addr, _ := net.ResolveUDPAddr("udp", c.localAddr.String())
return addr
}
func (c *srtConn) RemoteAddr() net.Addr {
if c.remoteAddr == nil {
return nil
}
addr, _ := net.ResolveUDPAddr("udp", c.remoteAddr.String())
return addr
}
func (c *srtConn) SocketId() uint32 {
return c.socketId
}
func (c *srtConn) PeerSocketId() uint32 {
return c.peerSocketId
}
func (c *srtConn) StreamId() string {
return c.config.StreamId
}
func (c *srtConn) Version() uint32 {
return c.version
}
// ticker invokes the congestion control in regular intervals with
// the current connection time.
func (c *srtConn) ticker(ctx context.Context) {
ticker := time.NewTicker(c.tick)
defer ticker.Stop()
defer func() {
c.log("connection:close", func() string { return "left ticker loop" })
}()
for {
select {
case <-ctx.Done():
return
case t := <-ticker.C:
tickTime := uint64(t.Sub(c.start).Microseconds())
c.recv.Tick(c.tsbpdTimeBase + tickTime)
c.snd.Tick(tickTime)
}
}
}
func (c *srtConn) ReadPacket() (packet.Packet, error) {
var p packet.Packet
select {
case <-c.ctx.Done():
return nil, io.EOF
case p = <-c.readQueue:
}
if p.Header().PacketSequenceNumber.Gt(c.debug.expectedReadPacketSequenceNumber) {
c.log("connection:error", func() string {
return fmt.Sprintf("lost packets. got: %d, expected: %d (%d)", p.Header().PacketSequenceNumber.Val(), c.debug.expectedReadPacketSequenceNumber.Val(), c.debug.expectedReadPacketSequenceNumber.Distance(p.Header().PacketSequenceNumber))
})
} else if p.Header().PacketSequenceNumber.Lt(c.debug.expectedReadPacketSequenceNumber) {
c.log("connection:error", func() string {
return fmt.Sprintf("packet out of order. got: %d, expected: %d (%d)", p.Header().PacketSequenceNumber.Val(), c.debug.expectedReadPacketSequenceNumber.Val(), c.debug.expectedReadPacketSequenceNumber.Distance(p.Header().PacketSequenceNumber))
})
return nil, io.EOF
}
c.debug.expectedReadPacketSequenceNumber = p.Header().PacketSequenceNumber.Inc()
return p, nil
}
func (c *srtConn) Read(b []byte) (int, error) {
if c.readBuffer.Len() != 0 {
return c.readBuffer.Read(b)
}
c.readBuffer.Reset()
p, err := c.ReadPacket()
if err != nil {
return 0, err
}
c.readBuffer.Write(p.Data())
// The packet is out of congestion control and written to the read buffer
p.Decommission()
return c.readBuffer.Read(b)
}
// WritePacket writes a packet to the write queue. Packets on the write queue
// will be sent to the peer of the connection. Only data packets will be sent.
func (c *srtConn) WritePacket(p packet.Packet) error {
if p.Header().IsControlPacket {
// Ignore control packets
return nil
}
_, err := c.Write(p.Data())
if err != nil {
return err
}
return nil
}
func (c *srtConn) Write(b []byte) (int, error) {
c.writeBuffer.Write(b)
for {
n, err := c.writeBuffer.Read(c.writeData)
if err != nil {
return 0, err
}
p := packet.NewPacket(nil)
p.SetData(c.writeData[:n])
p.Header().IsControlPacket = false
// Give the packet a deliver timestamp
p.Header().PktTsbpdTime = c.getTimestamp()
// Non-blocking write to the write queue
select {
case <-c.ctx.Done():
return 0, io.EOF
case c.writeQueue <- p:
default:
return 0, io.EOF
}
if c.writeBuffer.Len() == 0 {
break
}
}
c.writeBuffer.Reset()
return len(b), nil
}
// push puts a packet on the network queue. This is where packets go that came in from the network.
func (c *srtConn) push(p packet.Packet) {
// Non-blocking write to the network queue
select {
case <-c.ctx.Done():
case c.networkQueue <- p:
default:
c.log("connection:error", func() string { return "network queue is full" })
}
}
// getTimestamp returns the elapsed time since the start of the connection in microseconds.
func (c *srtConn) getTimestamp() uint64 {
return uint64(time.Since(c.start).Microseconds())
}
// getTimestampForPacket returns the elapsed time since the start of the connection in
// microseconds clamped a 32bit value.
func (c *srtConn) getTimestampForPacket() uint32 {
return uint32(c.getTimestamp() & uint64(packet.MAX_TIMESTAMP))
}
// pop adds the destination address and socketid to the packet and sends it out to the network.
// The packet will be encrypted if required.
func (c *srtConn) pop(p packet.Packet) {
p.Header().Addr = c.remoteAddr
p.Header().DestinationSocketId = c.peerSocketId
if !p.Header().IsControlPacket {
c.cryptoLock.Lock()
if c.crypto != nil {
p.Header().KeyBaseEncryptionFlag = c.keyBaseEncryption
c.crypto.EncryptOrDecryptPayload(p.Data(), p.Header().KeyBaseEncryptionFlag, p.Header().PacketSequenceNumber.Val())
c.kmPreAnnounceCountdown--
c.kmRefreshCountdown--
if c.kmPreAnnounceCountdown == 0 && !c.kmConfirmed {
c.sendKMRequest(c.keyBaseEncryption.Opposite())
// Resend the request until we get a response
c.kmPreAnnounceCountdown = c.config.KMPreAnnounce/10 + 1
}
if c.kmRefreshCountdown == 0 {
c.kmPreAnnounceCountdown = c.config.KMRefreshRate - c.config.KMPreAnnounce
c.kmRefreshCountdown = c.config.KMRefreshRate
// Switch the keys
c.keyBaseEncryption = c.keyBaseEncryption.Opposite()
c.kmConfirmed = false
}
if c.kmRefreshCountdown == c.config.KMRefreshRate-c.config.KMPreAnnounce {
// Decommission the previous key, resp. create a new SEK that will
// be used in the next switch.
c.crypto.GenerateSEK(c.keyBaseEncryption.Opposite())
}
}
c.cryptoLock.Unlock()
c.log("data:send:dump", func() string { return p.Dump() })
}
// Send the packet on the wire
c.onSend(p)
}
// networkQueueReader reads the packets from the network queue in order to process them.
func (c *srtConn) networkQueueReader(ctx context.Context) {
defer func() {
c.log("connection:close", func() string { return "left network queue reader loop" })
}()
for {
select {
case <-ctx.Done():
return
case p := <-c.networkQueue:
c.handlePacket(p)
}
}
}
// writeQueueReader reads the packets from the write queue and puts them into congestion
// control for sending.
func (c *srtConn) writeQueueReader(ctx context.Context) {
defer func() {
c.log("connection:close", func() string { return "left write queue reader loop" })
}()
for {
select {
case <-ctx.Done():
return
case p := <-c.writeQueue:
// Put the packet into the send congestion control
c.snd.Push(p)
}
}
}
// deliver writes the packets to the read queue in order to be consumed by the Read function.
func (c *srtConn) deliver(p packet.Packet) {
// Non-blocking write to the read queue
select {
case <-c.ctx.Done():
case c.readQueue <- p:
default:
c.log("connection:error", func() string { return "readQueue was blocking, dropping packet" })
}
}
// handlePacket checks the packet header. If it is a control packet it will forwarded to the
// respective handler. If it is a data packet it will be put into congestion control for
// receiving. The packet will be decrypted if required.
func (c *srtConn) handlePacket(p packet.Packet) {
if p == nil {
return
}
c.peerIdleTimeout.Reset(c.config.PeerIdleTimeout)
header := p.Header()
if header.IsControlPacket {
if header.ControlType == packet.CTRLTYPE_KEEPALIVE {
c.handleKeepAlive(p)
} else if header.ControlType == packet.CTRLTYPE_SHUTDOWN {
c.handleShutdown(p)
} else if header.ControlType == packet.CTRLTYPE_NAK {
c.handleNAK(p)
} else if header.ControlType == packet.CTRLTYPE_ACK {
c.handleACK(p)
} else if header.ControlType == packet.CTRLTYPE_ACKACK {
c.handleACKACK(p)
} else if header.ControlType == packet.CTRLTYPE_USER {
c.log("connection:recv:ctrl:user", func() string {
return fmt.Sprintf("got CTRLTYPE_USER packet, subType: %s", header.SubType)
})
// HSv4 Extension
if header.SubType == packet.EXTTYPE_HSREQ {
c.handleHSRequest(p)
} else if header.SubType == packet.EXTTYPE_HSRSP {
c.handleHSResponse(p)
}
// 3.2.2. Key Material
if header.SubType == packet.EXTTYPE_KMREQ {
c.handleKMRequest(p)
} else if header.SubType == packet.EXTTYPE_KMRSP {
c.handleKMResponse(p)
}
}
return
}
if header.PacketSequenceNumber.Gt(c.debug.expectedRcvPacketSequenceNumber) {
c.log("connection:error", func() string {
return fmt.Sprintf("recv lost packets. got: %d, expected: %d (%d)\n", header.PacketSequenceNumber.Val(), c.debug.expectedRcvPacketSequenceNumber.Val(), c.debug.expectedRcvPacketSequenceNumber.Distance(header.PacketSequenceNumber))
})
}
c.debug.expectedRcvPacketSequenceNumber = header.PacketSequenceNumber.Inc()
//fmt.Printf("%s\n", p.String())
// Ignore FEC filter control packets
// https://github.com/Haivision/srt/blob/master/docs/features/packet-filtering-and-fec.md
// "An FEC control packet is distinguished from a regular data packet by having
// its message number equal to 0. This value isn't normally used in SRT (message
// numbers start from 1, increment to a maximum, and then roll back to 1)."
if header.MessageNumber == 0 {
c.log("connection:filter", func() string { return "dropped FEC filter control packet" })
return
}
// 4.5.1.1. TSBPD Time Base Calculation
if !c.tsbpdWrapPeriod {
if header.Timestamp > packet.MAX_TIMESTAMP-(30*1000000) {
c.tsbpdWrapPeriod = true
c.log("connection:tsbpd", func() string { return "TSBPD wrapping period started" })
}
} else {
if header.Timestamp >= (30*1000000) && header.Timestamp <= (60*1000000) {
c.tsbpdWrapPeriod = false
c.tsbpdTimeBaseOffset += uint64(packet.MAX_TIMESTAMP) + 1
c.log("connection:tsbpd", func() string { return "TSBPD wrapping period finished" })
}
}
tsbpdTimeBaseOffset := c.tsbpdTimeBaseOffset
if c.tsbpdWrapPeriod {
if header.Timestamp < (30 * 1000000) {
tsbpdTimeBaseOffset += uint64(packet.MAX_TIMESTAMP) + 1
}
}
header.PktTsbpdTime = c.tsbpdTimeBase + tsbpdTimeBaseOffset + uint64(header.Timestamp) + c.tsbpdDelay + c.tsbpdDrift
c.log("data:recv:dump", func() string { return p.Dump() })
c.cryptoLock.Lock()
if c.crypto != nil {
if header.KeyBaseEncryptionFlag != 0 {
if err := c.crypto.EncryptOrDecryptPayload(p.Data(), header.KeyBaseEncryptionFlag, header.PacketSequenceNumber.Val()); err != nil {
c.statisticsLock.Lock()
c.statistics.pktRecvUndecrypt++
c.statistics.byteRecvUndecrypt += p.Len()
c.statisticsLock.Unlock()
}
} else {
c.statisticsLock.Lock()
c.statistics.pktRecvUndecrypt++
c.statistics.byteRecvUndecrypt += p.Len()
c.statisticsLock.Unlock()
}
}
c.cryptoLock.Unlock()
// Put the packet into receive congestion control
c.recv.Push(p)
}
// handleKeepAlive resets the idle timeout and sends a keepalive to the peer.
func (c *srtConn) handleKeepAlive(p packet.Packet) {
c.log("control:recv:keepalive:dump", func() string { return p.Dump() })
c.statisticsLock.Lock()
c.statistics.pktRecvKeepalive++
c.statistics.pktSentKeepalive++
c.statisticsLock.Unlock()
c.peerIdleTimeout.Reset(c.config.PeerIdleTimeout)
c.log("control:send:keepalive:dump", func() string { return p.Dump() })
c.pop(p)
}
// handleShutdown closes the connection
func (c *srtConn) handleShutdown(p packet.Packet) {
c.log("control:recv:shutdown:dump", func() string { return p.Dump() })
c.statisticsLock.Lock()
c.statistics.pktRecvShutdown++
c.statisticsLock.Unlock()
go c.close()
}
// handleACK forwards the acknowledge sequence number to the congestion control and
// returns a ACKACK (on a full ACK). The RTT is also updated in case of a full ACK.
func (c *srtConn) handleACK(p packet.Packet) {
c.log("control:recv:ACK:dump", func() string { return p.Dump() })
c.statisticsLock.Lock()
c.statistics.pktRecvACK++
c.statisticsLock.Unlock()
cif := &packet.CIFACK{}
if err := p.UnmarshalCIF(cif); err != nil {
c.statisticsLock.Lock()
c.statistics.pktRecvInvalid++
c.statisticsLock.Unlock()
c.log("control:recv:ACK:error", func() string { return fmt.Sprintf("invalid ACK: %s", err) })
return
}
c.log("control:recv:ACK:cif", func() string { return cif.String() })
c.snd.ACK(cif.LastACKPacketSequenceNumber)
if !cif.IsLite && !cif.IsSmall {
// 4.10. Round-Trip Time Estimation
c.recalculateRTT(time.Duration(int64(cif.RTT)) * time.Microsecond)
// Estimated Link Capacity (from packets/s to Mbps)
c.statisticsLock.Lock()
c.statistics.mbpsLinkCapacity = float64(cif.EstimatedLinkCapacity) * MAX_PAYLOAD_SIZE * 8 / 1024 / 1024
c.statisticsLock.Unlock()
c.sendACKACK(p.Header().TypeSpecific)
}
}
// handleNAK forwards the lost sequence number to the congestion control.
func (c *srtConn) handleNAK(p packet.Packet) {
c.log("control:recv:NAK:dump", func() string { return p.Dump() })
c.statisticsLock.Lock()
c.statistics.pktRecvNAK++
c.statisticsLock.Unlock()
cif := &packet.CIFNAK{}
if err := p.UnmarshalCIF(cif); err != nil {
c.statisticsLock.Lock()
c.statistics.pktRecvInvalid++
c.statisticsLock.Unlock()
c.log("control:recv:NAK:error", func() string { return fmt.Sprintf("invalid NAK: %s", err) })
return
}
c.log("control:recv:NAK:cif", func() string { return cif.String() })
// Inform congestion control about lost packets
c.snd.NAK(cif.LostPacketSequenceNumber)
}
// handleACKACK updates the RTT and NAK interval for the congestion control.
func (c *srtConn) handleACKACK(p packet.Packet) {
c.ackLock.Lock()
c.statisticsLock.Lock()
c.statistics.pktRecvACKACK++
c.statisticsLock.Unlock()
c.log("control:recv:ACKACK:dump", func() string { return p.Dump() })
// p.typeSpecific is the ACKNumber
if ts, ok := c.ackNumbers[p.Header().TypeSpecific]; ok {
// 4.10. Round-Trip Time Estimation
c.recalculateRTT(time.Since(ts))
delete(c.ackNumbers, p.Header().TypeSpecific)
} else {
c.log("control:recv:ACKACK:error", func() string { return fmt.Sprintf("got unknown ACKACK (%d)", p.Header().TypeSpecific) })
c.statisticsLock.Lock()
c.statistics.pktRecvInvalid++
c.statisticsLock.Unlock()
}
for i := range c.ackNumbers {
if i < p.Header().TypeSpecific {
delete(c.ackNumbers, i)
}
}
c.ackLock.Unlock()
c.recv.SetNAKInterval(uint64(c.rtt.NAKInterval()))
}
// recalculateRTT recalculates the RTT based on a full ACK exchange
func (c *srtConn) recalculateRTT(rtt time.Duration) {
c.rtt.Recalculate(rtt)
c.log("connection:rtt", func() string {
return fmt.Sprintf("RTT=%.0fus RTTVar=%.0fus NAKInterval=%.0fms", c.rtt.RTT(), c.rtt.RTTVar(), c.rtt.NAKInterval()/1000)
})
}
// handleHSRequest handles the HSv4 handshake extension request and sends the response
func (c *srtConn) handleHSRequest(p packet.Packet) {
c.log("control:recv:HSReq:dump", func() string { return p.Dump() })
cif := &packet.CIFHandshakeExtension{}
if err := p.UnmarshalCIF(cif); err != nil {
c.statisticsLock.Lock()
c.statistics.pktRecvInvalid++
c.statisticsLock.Unlock()
c.log("control:recv:HSReq:error", func() string { return fmt.Sprintf("invalid HSReq: %s", err) })
return
}
c.log("control:recv:HSReq:cif", func() string { return cif.String() })
// Check for version
if cif.SRTVersion < 0x010200 || cif.SRTVersion >= 0x010300 {
c.log("control:recv:HSReq:error", func() string { return fmt.Sprintf("unsupported version: %#08x", cif.SRTVersion) })
c.close()
return
}
// Check the required SRT flags
if !cif.SRTFlags.TSBPDSND {
c.log("control:recv:HSRes:error", func() string { return "TSBPDSND flag must be set" })
c.close()
return
}
if !cif.SRTFlags.TLPKTDROP {
c.log("control:recv:HSRes:error", func() string { return "TLPKTDROP flag must be set" })
c.close()
return
}
if !cif.SRTFlags.CRYPT {
c.log("control:recv:HSRes:error", func() string { return "CRYPT flag must be set" })
c.close()
return
}
if !cif.SRTFlags.REXMITFLG {
c.log("control:recv:HSRes:error", func() string { return "REXMITFLG flag must be set" })
c.close()
return
}
// we as receiver don't need this
cif.SRTFlags.TSBPDSND = false
// we as receiver are supporting these
cif.SRTFlags.TSBPDRCV = true
cif.SRTFlags.PERIODICNAK = true
// These flag was introduced in HSv5 and should not be set in HSv4
if cif.SRTFlags.STREAM {
c.log("control:recv:HSReq:error", func() string { return "STREAM flag is set" })
c.close()
return
}
if cif.SRTFlags.PACKET_FILTER {
c.log("control:recv:HSReq:error", func() string { return "PACKET_FILTER flag is set" })
c.close()
return
}
recvTsbpdDelay := uint16(c.config.ReceiverLatency.Milliseconds())
if cif.SendTSBPDDelay > recvTsbpdDelay {
recvTsbpdDelay = cif.SendTSBPDDelay
}
c.tsbpdDelay = uint64(recvTsbpdDelay) * 1000
cif.RecvTSBPDDelay = 0
cif.SendTSBPDDelay = recvTsbpdDelay
p.MarshalCIF(cif)
// Send HS Response
p.Header().SubType = packet.EXTTYPE_HSRSP
c.pop(p)
}
// handleHSResponse handles the HSv4 handshake extension response
func (c *srtConn) handleHSResponse(p packet.Packet) {
c.log("control:recv:HSRes:dump", func() string { return p.Dump() })
cif := &packet.CIFHandshakeExtension{}
if err := p.UnmarshalCIF(cif); err != nil {
c.statisticsLock.Lock()
c.statistics.pktRecvInvalid++
c.statisticsLock.Unlock()
c.log("control:recv:HSRes:error", func() string { return fmt.Sprintf("invalid HSRes: %s", err) })
return
}
c.log("control:recv:HSRes:cif", func() string { return cif.String() })
if c.version == 4 {
// Check for version
if cif.SRTVersion < 0x010200 || cif.SRTVersion >= 0x010300 {
c.log("control:recv:HSRes:error", func() string { return fmt.Sprintf("unsupported version: %#08x", cif.SRTVersion) })
c.close()
return
}
// TSBPDSND is not relevant from the receiver
// PERIODICNAK is the sender's decision, we don't care, but will handle them
// Check the required SRT flags
if !cif.SRTFlags.TSBPDRCV {
c.log("control:recv:HSRes:error", func() string { return "TSBPDRCV flag must be set" })
c.close()
return
}
if !cif.SRTFlags.TLPKTDROP {
c.log("control:recv:HSRes:error", func() string { return "TLPKTDROP flag must be set" })