forked from bluenviron/gortsplib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1930 lines (1631 loc) · 43.5 KB
/
client.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 gortsplib is a RTSP 1.0 library for the Go programming language,
written for rtsp-simple-server.
Examples are available at https://github.com/cobalt-robotics/gortsplib/tree/master/examples
*/
package gortsplib
import (
"context"
"crypto/tls"
"fmt"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pion/rtcp"
"github.com/pion/rtp"
"github.com/cobalt-robotics/gortsplib/pkg/auth"
"github.com/cobalt-robotics/gortsplib/pkg/base"
"github.com/cobalt-robotics/gortsplib/pkg/conn"
"github.com/cobalt-robotics/gortsplib/pkg/headers"
"github.com/cobalt-robotics/gortsplib/pkg/liberrors"
"github.com/cobalt-robotics/gortsplib/pkg/ringbuffer"
"github.com/cobalt-robotics/gortsplib/pkg/rtcpreceiver"
"github.com/cobalt-robotics/gortsplib/pkg/rtcpsender"
"github.com/cobalt-robotics/gortsplib/pkg/rtpcleaner"
"github.com/cobalt-robotics/gortsplib/pkg/rtpreorderer"
"github.com/cobalt-robotics/gortsplib/pkg/sdp"
"github.com/cobalt-robotics/gortsplib/pkg/url"
)
func isAnyPort(p int) bool {
return p == 0 || p == 1
}
func findBaseURL(sd *sdp.SessionDescription, res *base.Response, u *url.URL) (*url.URL, error) {
// use global control attribute
if control, ok := sd.Attribute("control"); ok && control != "*" {
ret, err := url.Parse(control)
if err != nil {
return nil, fmt.Errorf("invalid control attribute: '%v'", control)
}
// add credentials
ret.User = u.User
return ret, nil
}
// use Content-Base
if cb, ok := res.Header["Content-Base"]; ok {
if len(cb) != 1 {
return nil, fmt.Errorf("invalid Content-Base: '%v'", cb)
}
ret, err := url.Parse(cb[0])
if err != nil {
return nil, fmt.Errorf("invalid Content-Base: '%v'", cb)
}
// add credentials
ret.User = u.User
return ret, nil
}
// use URL of request
return u, nil
}
type clientState int
const (
clientStateInitial clientState = iota
clientStatePrePlay
clientStatePlay
clientStatePreRecord
clientStateRecord
)
type clientTrack struct {
id int
track Track
tcpChannel int
udpRTPListener *clientUDPListener
udpRTCPListener *clientUDPListener
// play
udpRTPPacketBuffer *rtpPacketMultiBuffer
udpRTCPReceiver *rtcpreceiver.RTCPReceiver
reorderer *rtpreorderer.Reorderer
cleaner *rtpcleaner.Cleaner
// record
udpRTCPSender *rtcpsender.RTCPSender
}
func (s clientState) String() string {
switch s {
case clientStateInitial:
return "initial"
case clientStatePrePlay:
return "prePlay"
case clientStatePlay:
return "play"
case clientStatePreRecord:
return "preRecord"
case clientStateRecord:
return "record"
}
return "unknown"
}
type optionsReq struct {
url *url.URL
res chan clientRes
}
type describeReq struct {
url *url.URL
res chan clientRes
}
type announceReq struct {
url *url.URL
tracks Tracks
res chan clientRes
}
type setupReq struct {
forPlay bool
track Track
baseURL *url.URL
rtpPort int
rtcpPort int
res chan clientRes
}
type playReq struct {
ra *headers.Range
res chan clientRes
}
type recordReq struct {
res chan clientRes
}
type pauseReq struct {
res chan clientRes
}
type clientRes struct {
tracks Tracks
baseURL *url.URL
res *base.Response
err error
}
// ClientOnPacketRTPCtx is the context of a RTP packet.
type ClientOnPacketRTPCtx struct {
TrackID int
Packet *rtp.Packet
PTSEqualsDTS bool
H264NALUs [][]byte
H264PTS time.Duration
}
// ClientOnPacketRTCPCtx is the context of a RTCP packet.
type ClientOnPacketRTCPCtx struct {
TrackID int
Packet rtcp.Packet
}
// Client is a RTSP client.
type Client struct {
//
// RTSP parameters (all optional)
//
// timeout of read operations.
// It defaults to 10 seconds.
ReadTimeout time.Duration
// timeout of write operations.
// It defaults to 10 seconds.
WriteTimeout time.Duration
// a TLS configuration to connect to TLS (RTSPS) servers.
// It defaults to nil.
TLSConfig *tls.Config
// disable being redirected to other servers, that can happen during Describe().
// It defaults to false.
RedirectDisable bool
// enable communication with servers which don't provide server ports or use
// different server ports than the ones announced.
// This can be a security issue.
// It defaults to false.
AnyPortEnable bool
// the stream transport (UDP, Multicast or TCP).
// If nil, it is chosen automatically (first UDP, then, if it fails, TCP).
// It defaults to nil.
Transport *Transport
// If the client is reading with UDP, it must receive
// at least a packet within this timeout.
// It defaults to 3 seconds.
InitialUDPReadTimeout time.Duration
// read buffer count.
// If greater than 1, allows to pass buffers to routines different than the one
// that is reading frames.
// It defaults to 256.
ReadBufferCount int
// write buffer count.
// It allows to queue packets before sending them.
// It defaults to 256.
WriteBufferCount int
// user agent header
// It defaults to "gortsplib"
UserAgent string
//
// system functions (all optional)
//
// function used to initialize the TCP client.
// It defaults to (&net.Dialer{}).DialContext.
DialContext func(ctx context.Context, network, address string) (net.Conn, error)
// function used to initialize UDP listeners.
// It defaults to net.ListenPacket.
ListenPacket func(network, address string) (net.PacketConn, error)
//
// callbacks (all optional)
//
// called before every request.
OnRequest func(*base.Request)
// called after every response.
OnResponse func(*base.Response)
// called when a RTP packet arrives.
OnPacketRTP func(*ClientOnPacketRTPCtx)
// called when a RTCP packet arrives.
OnPacketRTCP func(*ClientOnPacketRTCPCtx)
//
// private
//
udpSenderReportPeriod time.Duration
udpReceiverReportPeriod time.Duration
checkStreamPeriod time.Duration
keepalivePeriod time.Duration
scheme string
host string
ctx context.Context
ctxCancel func()
state clientState
nconn net.Conn
conn *conn.Conn
session string
sender *auth.Sender
cseq int
optionsSent bool
useGetParameter bool
lastDescribeURL *url.URL
baseURL *url.URL
effectiveTransport *Transport
tracks []*clientTrack
tcpTracksByChannel map[int]*clientTrack
lastRange *headers.Range
writeMutex sync.RWMutex // publish
writeFrameAllowed bool // publish
checkStreamTimer *time.Timer
checkStreamInitial bool
tcpLastFrameTime *int64
keepaliveTimer *time.Timer
closeError error
writerRunning bool
writeBuffer *ringbuffer.RingBuffer
// connCloser channels
connCloserTerminate chan struct{}
connCloserDone chan struct{}
// reader channels
readerErr chan error
// writer channels
writerDone chan struct{}
// in
options chan optionsReq
describe chan describeReq
announce chan announceReq
setup chan setupReq
play chan playReq
record chan recordReq
pause chan pauseReq
// out
done chan struct{}
}
// Start initializes the connection to a server.
func (c *Client) Start(scheme string, host string) error {
// RTSP parameters
if c.ReadTimeout == 0 {
c.ReadTimeout = 10 * time.Second
}
if c.WriteTimeout == 0 {
c.WriteTimeout = 10 * time.Second
}
if c.InitialUDPReadTimeout == 0 {
c.InitialUDPReadTimeout = 3 * time.Second
}
if c.ReadBufferCount == 0 {
c.ReadBufferCount = 256
}
if c.WriteBufferCount == 0 {
c.WriteBufferCount = 256
}
if (c.WriteBufferCount & (c.WriteBufferCount - 1)) != 0 {
return fmt.Errorf("WriteBufferCount must be a power of two")
}
if c.UserAgent == "" {
c.UserAgent = "gortsplib"
}
// system functions
if c.DialContext == nil {
c.DialContext = (&net.Dialer{}).DialContext
}
if c.ListenPacket == nil {
c.ListenPacket = net.ListenPacket
}
// callbacks
if c.OnPacketRTP == nil {
c.OnPacketRTP = func(ctx *ClientOnPacketRTPCtx) {
}
}
if c.OnPacketRTCP == nil {
c.OnPacketRTCP = func(ctx *ClientOnPacketRTCPCtx) {
}
}
// private
if c.udpSenderReportPeriod == 0 {
c.udpSenderReportPeriod = 10 * time.Second
}
if c.udpReceiverReportPeriod == 0 {
c.udpReceiverReportPeriod = 10 * time.Second
}
if c.checkStreamPeriod == 0 {
c.checkStreamPeriod = 1 * time.Second
}
if c.keepalivePeriod == 0 {
c.keepalivePeriod = 30 * time.Second
}
ctx, ctxCancel := context.WithCancel(context.Background())
c.scheme = scheme
c.host = host
c.ctx = ctx
c.ctxCancel = ctxCancel
c.checkStreamTimer = emptyTimer()
c.keepaliveTimer = emptyTimer()
c.options = make(chan optionsReq)
c.describe = make(chan describeReq)
c.announce = make(chan announceReq)
c.setup = make(chan setupReq)
c.play = make(chan playReq)
c.record = make(chan recordReq)
c.pause = make(chan pauseReq)
c.done = make(chan struct{})
go c.run()
return nil
}
// StartPublishing connects to the address and starts publishing the tracks.
func (c *Client) StartPublishing(address string, tracks Tracks) error {
u, err := url.Parse(address)
if err != nil {
return err
}
err = c.Start(u.Scheme, u.Host)
if err != nil {
return err
}
// control attribute of tracks is overridden by Announce().
// use a copy in order not to mess the client-read-republish example.
tracks = tracks.clone()
_, err = c.Announce(u, tracks)
if err != nil {
c.Close()
return err
}
for _, track := range tracks {
_, err := c.Setup(false, track, u, 0, 0)
if err != nil {
c.Close()
return err
}
}
_, err = c.Record()
if err != nil {
c.Close()
return err
}
return nil
}
// Close closes all client resources and waits for them to close.
func (c *Client) Close() error {
c.ctxCancel()
<-c.done
return c.closeError
}
// Wait waits until all client resources are closed.
// This can happen when a fatal error occurs or when Close() is called.
func (c *Client) Wait() error {
<-c.done
return c.closeError
}
// Tracks returns all the tracks that the client is reading or publishing.
func (c *Client) Tracks() Tracks {
ret := make(Tracks, len(c.tracks))
for i, track := range c.tracks {
ret[i] = track.track
}
return ret
}
func (c *Client) run() {
defer close(c.done)
c.closeError = c.runInner()
c.ctxCancel()
c.doClose()
}
func (c *Client) runInner() error {
for {
select {
case req := <-c.options:
res, err := c.doOptions(req.url)
req.res <- clientRes{res: res, err: err}
case req := <-c.describe:
tracks, baseURL, res, err := c.doDescribe(req.url)
req.res <- clientRes{tracks: tracks, baseURL: baseURL, res: res, err: err}
case req := <-c.announce:
res, err := c.doAnnounce(req.url, req.tracks)
req.res <- clientRes{res: res, err: err}
case req := <-c.setup:
res, err := c.doSetup(req.forPlay, req.track, req.baseURL, req.rtpPort, req.rtcpPort)
req.res <- clientRes{res: res, err: err}
case req := <-c.play:
res, err := c.doPlay(req.ra, false)
req.res <- clientRes{res: res, err: err}
case req := <-c.record:
res, err := c.doRecord()
req.res <- clientRes{res: res, err: err}
case req := <-c.pause:
res, err := c.doPause()
req.res <- clientRes{res: res, err: err}
case <-c.checkStreamTimer.C:
if *c.effectiveTransport == TransportUDP ||
*c.effectiveTransport == TransportUDPMulticast {
if c.checkStreamInitial {
c.checkStreamInitial = false
// check that at least one packet has been received
inTimeout := func() bool {
for _, ct := range c.tracks {
lft := atomic.LoadInt64(ct.udpRTPListener.lastPacketTime)
if lft != 0 {
return false
}
lft = atomic.LoadInt64(ct.udpRTCPListener.lastPacketTime)
if lft != 0 {
return false
}
}
return true
}()
if inTimeout {
err := c.trySwitchingProtocol()
if err != nil {
return err
}
}
} else {
inTimeout := func() bool {
now := time.Now()
for _, ct := range c.tracks {
lft := time.Unix(atomic.LoadInt64(ct.udpRTPListener.lastPacketTime), 0)
if now.Sub(lft) < c.ReadTimeout {
return false
}
lft = time.Unix(atomic.LoadInt64(ct.udpRTCPListener.lastPacketTime), 0)
if now.Sub(lft) < c.ReadTimeout {
return false
}
}
return true
}()
if inTimeout {
return liberrors.ErrClientUDPTimeout{}
}
}
} else { // TCP
inTimeout := func() bool {
now := time.Now()
lft := time.Unix(atomic.LoadInt64(c.tcpLastFrameTime), 0)
return now.Sub(lft) >= c.ReadTimeout
}()
if inTimeout {
return liberrors.ErrClientTCPTimeout{}
}
}
c.checkStreamTimer = time.NewTimer(c.checkStreamPeriod)
case <-c.keepaliveTimer.C:
_, err := c.do(&base.Request{
Method: func() base.Method {
// the VLC integrated rtsp server requires GET_PARAMETER
if c.useGetParameter {
return base.GetParameter
}
return base.Options
}(),
// use the stream base URL, otherwise some cameras do not reply
URL: c.baseURL,
}, true, false)
if err != nil {
return err
}
c.keepaliveTimer = time.NewTimer(c.keepalivePeriod)
case err := <-c.readerErr:
c.readerErr = nil
return err
case <-c.ctx.Done():
return liberrors.ErrClientTerminated{}
}
}
}
func (c *Client) doClose() {
if c.state == clientStatePlay || c.state == clientStateRecord {
c.playRecordStop(true)
c.do(&base.Request{
Method: base.Teardown,
URL: c.baseURL,
}, true, false)
c.nconn.Close()
c.nconn = nil
c.conn = nil
} else if c.nconn != nil {
c.connCloserStop()
c.nconn.Close()
c.nconn = nil
c.conn = nil
}
for _, track := range c.tracks {
if track.udpRTPListener != nil {
track.udpRTPListener.close()
track.udpRTCPListener.close()
}
}
}
func (c *Client) reset() {
c.doClose()
c.state = clientStateInitial
c.session = ""
c.sender = nil
c.cseq = 0
c.optionsSent = false
c.useGetParameter = false
c.baseURL = nil
c.effectiveTransport = nil
c.tracks = nil
c.tcpTracksByChannel = nil
}
func (c *Client) checkState(allowed map[clientState]struct{}) error {
if _, ok := allowed[c.state]; ok {
return nil
}
allowedList := make([]fmt.Stringer, len(allowed))
i := 0
for a := range allowed {
allowedList[i] = a
i++
}
return liberrors.ErrClientInvalidState{AllowedList: allowedList, State: c.state}
}
func (c *Client) trySwitchingProtocol() error {
prevScheme := c.scheme
prevHost := c.host
prevBaseURL := c.baseURL
oldUseGetParameter := c.useGetParameter
prevTracks := c.tracks
c.reset()
v := TransportTCP
c.effectiveTransport = &v
c.useGetParameter = oldUseGetParameter
c.scheme = prevScheme
c.host = prevHost
// some Hikvision cameras require a describe before a setup
_, _, _, err := c.doDescribe(c.lastDescribeURL)
if err != nil {
return err
}
for _, track := range prevTracks {
_, err := c.doSetup(true, track.track, prevBaseURL, 0, 0)
if err != nil {
return err
}
}
_, err = c.doPlay(c.lastRange, true)
if err != nil {
return err
}
return nil
}
func (c *Client) playRecordStart() {
// stop connCloser
c.connCloserStop()
// start writer
if c.state == clientStatePlay {
// when reading, writeBuffer is only used to send RTCP receiver reports,
// that are much smaller than RTP packets and are sent at a fixed interval.
// decrease RAM consumption by allocating less buffers.
c.writeBuffer, _ = ringbuffer.New(8)
} else {
c.writeBuffer, _ = ringbuffer.New(uint64(c.WriteBufferCount))
}
c.writerRunning = true
c.writerDone = make(chan struct{})
go c.runWriter()
// allow writing
c.writeMutex.Lock()
c.writeFrameAllowed = true
c.writeMutex.Unlock()
if c.state == clientStatePlay {
for _, ct := range c.tracks {
if *c.effectiveTransport == TransportUDP || *c.effectiveTransport == TransportUDPMulticast {
ct.reorderer = rtpreorderer.New()
}
_, isH264 := ct.track.(*TrackH264)
ct.cleaner = rtpcleaner.New(isH264, *c.effectiveTransport == TransportTCP)
}
c.keepaliveTimer = time.NewTimer(c.keepalivePeriod)
switch *c.effectiveTransport {
case TransportUDP:
for trackID, ct := range c.tracks {
ctrackID := trackID
ct.udpRTPPacketBuffer = newRTPPacketMultiBuffer(uint64(c.ReadBufferCount))
ct.udpRTCPReceiver = rtcpreceiver.New(c.udpReceiverReportPeriod, nil,
ct.track.ClockRate(), func(pkt rtcp.Packet) {
c.WritePacketRTCP(ctrackID, pkt)
})
}
c.checkStreamTimer = time.NewTimer(c.InitialUDPReadTimeout)
c.checkStreamInitial = true
for _, ct := range c.tracks {
ct.udpRTPListener.start(true)
ct.udpRTCPListener.start(true)
}
case TransportUDPMulticast:
for trackID, ct := range c.tracks {
ctrackID := trackID
ct.udpRTPPacketBuffer = newRTPPacketMultiBuffer(uint64(c.ReadBufferCount))
ct.udpRTCPReceiver = rtcpreceiver.New(c.udpReceiverReportPeriod, nil,
ct.track.ClockRate(), func(pkt rtcp.Packet) {
c.WritePacketRTCP(ctrackID, pkt)
})
}
c.checkStreamTimer = time.NewTimer(c.checkStreamPeriod)
for _, ct := range c.tracks {
ct.udpRTPListener.start(true)
ct.udpRTCPListener.start(true)
}
default: // TCP
c.checkStreamTimer = time.NewTimer(c.checkStreamPeriod)
v := time.Now().Unix()
c.tcpLastFrameTime = &v
}
} else if *c.effectiveTransport == TransportUDP {
for trackID, ct := range c.tracks {
ctrackID := trackID
ct.udpRTCPSender = rtcpsender.New(c.udpSenderReportPeriod,
ct.track.ClockRate(), func(pkt rtcp.Packet) {
c.WritePacketRTCP(ctrackID, pkt)
})
}
for _, ct := range c.tracks {
ct.udpRTPListener.start(false)
ct.udpRTCPListener.start(false)
}
}
// for some reason, SetReadDeadline() must always be called in the same
// goroutine, otherwise Read() freezes.
// therefore, we disable the deadline and perform a check with a ticker.
c.nconn.SetReadDeadline(time.Time{})
// start reader
c.readerErr = make(chan error)
go c.runReader()
}
func (c *Client) runReader() {
c.readerErr <- func() error {
if *c.effectiveTransport == TransportUDP || *c.effectiveTransport == TransportUDPMulticast {
for {
_, err := c.conn.ReadResponse()
if err != nil {
return err
}
}
} else {
var processFunc func(*clientTrack, bool, []byte) error
if c.state == clientStatePlay {
tcpRTPPacketBuffer := newRTPPacketMultiBuffer(uint64(c.ReadBufferCount))
processFunc = func(track *clientTrack, isRTP bool, payload []byte) error {
now := time.Now()
atomic.StoreInt64(c.tcpLastFrameTime, now.Unix())
if isRTP {
pkt := tcpRTPPacketBuffer.next()
err := pkt.Unmarshal(payload)
if err != nil {
return err
}
out, err := track.cleaner.Process(pkt)
if err != nil {
return err
}
for _, entry := range out {
c.OnPacketRTP(&ClientOnPacketRTPCtx{
TrackID: track.id,
Packet: entry.Packet,
PTSEqualsDTS: entry.PTSEqualsDTS,
H264NALUs: entry.H264NALUs,
H264PTS: entry.H264PTS,
})
}
} else {
if len(payload) > maxPacketSize {
return fmt.Errorf("payload size (%d) greater than maximum allowed (%d)",
len(payload), maxPacketSize)
}
packets, err := rtcp.Unmarshal(payload)
if err != nil {
// some cameras send invalid RTCP packets.
// skip them.
return nil
}
for _, pkt := range packets {
c.OnPacketRTCP(&ClientOnPacketRTCPCtx{
TrackID: track.id,
Packet: pkt,
})
}
}
return nil
}
} else {
processFunc = func(track *clientTrack, isRTP bool, payload []byte) error {
if !isRTP {
if len(payload) > maxPacketSize {
return fmt.Errorf("payload size (%d) greater than maximum allowed (%d)",
len(payload), maxPacketSize)
}
packets, err := rtcp.Unmarshal(payload)
if err != nil {
return err
}
for _, pkt := range packets {
c.OnPacketRTCP(&ClientOnPacketRTCPCtx{
TrackID: track.id,
Packet: pkt,
})
}
}
return nil
}
}
for {
what, err := c.conn.ReadInterleavedFrameOrResponse()
if err != nil {
return err
}
if fr, ok := what.(*base.InterleavedFrame); ok {
channel := fr.Channel
isRTP := true
if (channel % 2) != 0 {
channel--
isRTP = false
}
track, ok := c.tcpTracksByChannel[channel]
if !ok {
continue
}
err := processFunc(track, isRTP, fr.Payload)
if err != nil {
return err
}
}
}
}
}()
}
func (c *Client) playRecordStop(isClosing bool) {
// stop reader
if c.readerErr != nil {
c.nconn.SetReadDeadline(time.Now())
<-c.readerErr
}
// forbid writing
c.writeMutex.Lock()
c.writeFrameAllowed = false
c.writeMutex.Unlock()
if *c.effectiveTransport == TransportUDP ||
*c.effectiveTransport == TransportUDPMulticast {
for _, ct := range c.tracks {
ct.udpRTPListener.stop()
ct.udpRTCPListener.stop()
}
if c.state == clientStatePlay {
for _, ct := range c.tracks {
ct.udpRTPPacketBuffer = nil
ct.udpRTCPReceiver.Close()
ct.udpRTCPReceiver = nil
}
} else {
for _, ct := range c.tracks {
ct.udpRTCPSender.Close()
ct.udpRTCPSender = nil
}
}
}
for _, ct := range c.tracks {
ct.cleaner = nil
ct.reorderer = nil
}
// stop timers
c.checkStreamTimer = emptyTimer()
c.keepaliveTimer = emptyTimer()
// stop writer
c.writeBuffer.Close()
<-c.writerDone
c.writerRunning = false
c.writeBuffer = nil
// start connCloser
if !isClosing {
c.connCloserStart()
}
}
func (c *Client) connOpen() error {
if c.scheme != "rtsp" && c.scheme != "rtsps" {
return fmt.Errorf("unsupported scheme '%s'", c.scheme)
}
if c.scheme == "rtsps" && c.Transport != nil && *c.Transport != TransportTCP {
return fmt.Errorf("RTSPS can be used only with TCP")
}
// add default port
_, _, err := net.SplitHostPort(c.host)
if err != nil {
if c.scheme == "rtsp" {
c.host = net.JoinHostPort(c.host, "554")
} else { // rtsps
c.host = net.JoinHostPort(c.host, "322")
}
}
ctx, cancel := context.WithTimeout(c.ctx, c.ReadTimeout)
defer cancel()
nconn, err := c.DialContext(ctx, "tcp", c.host)
if err != nil {
return err
}
c.nconn = func() net.Conn {
if c.scheme == "rtsps" {
tlsConfig := c.TLSConfig
if tlsConfig == nil {
tlsConfig = &tls.Config{}
}
host, _, _ := net.SplitHostPort(c.host)
tlsConfig.ServerName = host
return tls.Client(nconn, tlsConfig)
}
return nconn
}()
c.conn = conn.NewConn(c.nconn)
c.connCloserStart()
return nil
}
func (c *Client) connCloserStart() {
c.connCloserTerminate = make(chan struct{})
c.connCloserDone = make(chan struct{})
go func() {
defer close(c.connCloserDone)
select {
case <-c.ctx.Done():
c.nconn.Close()
case <-c.connCloserTerminate:
}
}()