-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathrtsp.go
More file actions
1605 lines (1424 loc) · 50.6 KB
/
Copy pathrtsp.go
File metadata and controls
1605 lines (1424 loc) · 50.6 KB
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 viamrtsp implements RTSP camera support in a Viam module
package viamrtsp
import (
"context"
"encoding/hex"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtph264"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtph265"
"github.com/bluenviron/gortsplib/v4/pkg/liberrors"
"github.com/bluenviron/mediacommon/pkg/codecs/h264"
"github.com/bluenviron/mediacommon/pkg/codecs/h265"
"github.com/erh/viamupnp"
"github.com/pion/rtcp"
"github.com/pion/rtp"
"github.com/viam-modules/viamrtsp/formatprocessor"
"github.com/viam-modules/viamrtsp/registry"
"github.com/viam-modules/video-store/videostore"
"go.viam.com/rdk/components/camera"
"go.viam.com/rdk/components/camera/rtppassthrough"
"go.viam.com/rdk/data"
"go.viam.com/rdk/gostream"
"go.viam.com/rdk/logging"
"go.viam.com/rdk/pointcloud"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/services/discovery"
"go.viam.com/rdk/spatialmath"
rutils "go.viam.com/rdk/utils"
"go.viam.com/utils"
)
const (
// reconnectIntervalSeconds is the interval in secs to wait before reconnecting the background worker.
reconnectIntervalSeconds = 5
// noFrameTimeoutSeconds is how long we let a stream go without a frame before reconnecting.
// While frames keep arriving we leave the connection alone, even if OPTIONS fails: some cameras
// (e.g. FLIR) never answer OPTIONS while streaming fine.
noFrameTimeoutSeconds = 10
// webRTCPayloadMaxSize is the maximum size of a WebRTC RTP payload, calculated as 1200 - 12 (RTP header).
webRTCPayloadMaxSize = 1188
// defaultPayloadType is the default payload type for RTP packets.
defaultPayloadType = 96
// h264NALUTypeMask is the mask to extract the NALU type from the first byte of an H264 NALU.
h264NALUTypeMask = 0x1F
// initialFramePoolSize is the initial size of the frame pool.
initialFramePoolSize = 5
// defaultMPEG4ProfileLevelID is the default profile-level-id value for MPEG4 video
// as specified in RFC 6416 Section 7.1 https://datatracker.ietf.org/doc/html/rfc6416#section-7.1
defaultMPEG4ProfileLevelID = 1
// allowed transport protocol strings.
transportTCP = "tcp"
transportUDP = "udp"
transportUDPMulticast = "udp-multicast"
)
var (
reconnectIntervalDuration = reconnectIntervalSeconds * time.Second
noFrameTimeout = noFrameTimeoutSeconds * time.Second
)
var (
// Family is the namespace family for the viamrtsp module.
Family = resource.ModelNamespace("viam").WithFamily("viamrtsp")
// ModelAgnostic selects the best available codec.
ModelAgnostic = Family.WithModel("rtsp")
// ModelH264 uses the h264 codec.
ModelH264 = Family.WithModel("rtsp-h264")
// ModelH265 uses the h265 codec.
ModelH265 = Family.WithModel("rtsp-h265")
// ModelMJPEG uses the mjpeg codec.
ModelMJPEG = Family.WithModel("rtsp-mjpeg")
// ModelMPEG4 uses the mpeg4 codec.
ModelMPEG4 = Family.WithModel("rtsp-mpeg4")
// Models is a slice containing the above available models.
Models = []resource.Model{ModelAgnostic, ModelH264, ModelH265, ModelMJPEG, ModelMPEG4}
// ErrH264PassthroughNotEnabled is an error indicating H264 passthrough is not enabled.
ErrH264PassthroughNotEnabled = errors.New("H264 passthrough is not enabled")
// allowedTransports is a list of valid transport protocols for the RTSP camera.
allowedTransports = []string{
transportTCP,
transportUDP,
transportUDPMulticast,
}
)
func init() {
for _, model := range Models {
resource.RegisterComponent(camera.API, model, resource.Registration[camera.Camera, *Config]{
Constructor: NewRTSPCamera,
})
}
}
type videoStoreStorageConfig struct {
SizeGB int `json:"size_gb"`
UploadPath string `json:"upload_path,omitempty"`
StoragePath string `json:"storage_path,omitempty"`
}
type videoStoreConfig struct {
Storage videoStoreStorageConfig `json:"storage"`
}
// Resolution is the frame size of the video stream.
type Resolution struct {
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
}
// Config are the config attributes for an RTSP camera model.
type Config struct {
Address string `json:"rtsp_address"`
RTPPassthrough *bool `json:"rtp_passthrough"`
LazyDecode bool `json:"lazy_decode,omitempty"`
IframeOnlyDecode bool `json:"i_frame_only_decode,omitempty"`
FrameRate int `json:"frame_rate,omitempty"`
Resolution *Resolution `json:"resolution,omitempty"` // Use a pointer here
Codec string `json:"codec,omitempty"`
Query viamupnp.DeviceQuery `json:"query,omitempty"`
DiscoveryDep string `json:"discovery_dep,omitempty"`
VideoStore *videoStoreConfig `json:"video_store,omitempty"`
// New attribute to specify allowed transports: "tcp", "udp", "udp-multicast"
Transports []string `json:"transports,omitempty"`
}
// CodecFormat contains a pointer to a format and the corresponding FFmpeg codec.
type codecFormat struct {
formatPointer interface{}
codec videoCodec
}
func isValidTransport(transport string) bool {
return slices.Contains(allowedTransports, strings.ToLower(transport))
}
// Validate checks to see if the attributes of the model are valid.
func (conf *Config) Validate(path string) ([]string, []string, error) {
_, err := base.ParseURL(conf.Address)
if err != nil {
return nil, nil, fmt.Errorf("invalid address '%s' for component at path '%s': %w", conf.Address, path, err)
}
for _, t := range conf.Transports {
if !isValidTransport(t) {
return nil, nil, fmt.Errorf("invalid transport '%s' for component at path '%s', allowed values are: tcp, udp, udp-multicast", t, path)
}
}
var deps []string
if conf.DiscoveryDep != "" {
deps = []string{conf.DiscoveryDep}
}
return deps, nil, nil
}
func (conf *Config) parseAndFixAddress(ctx context.Context, logger logging.Logger) (*base.URL, error) {
u, err := base.ParseURL(conf.Address)
if err != nil {
return nil, err
}
// TODO: remove this & query logic
if u.Hostname() == "UPNP_DISCOVER" {
hosts, _, err := viamupnp.FindHost(ctx, logger, []viamupnp.DeviceQuery{conf.Query}, false)
if err != nil {
return nil, err
}
p := u.Port()
if p == "" {
u.Host = hosts[0]
} else {
u.Host = fmt.Sprintf("%s:%s", hosts[0], u.Port())
}
}
return u, nil
}
type (
unitSubscriberFunc func(formatprocessor.Unit)
bufAndCB struct {
cb unitSubscriberFunc
buf *rtppassthrough.Buffer
}
)
type cache struct {
mimeType string
bytes []byte
responseMimeType string
}
// rtspCamera contains the rtsp client, and the reader function that fulfills the camera interface.
type rtspCamera struct {
resource.Named
resource.AlwaysRebuild
model resource.Model
gostream.VideoReader
u *base.URL
lazyDecode bool
iframeOnlyDecode bool
closeMu sync.RWMutex
videoRequest *videoRequest
auMu sync.Mutex
au [][]byte
client *gortsplib.Client
rawDecoder *decoder
// h264Media is the RTSP media track for H264.
h264Media *description.Media
// firSeqNum holds the last FIR sequence number (0–255), wraps per RFC 5104.
firSeqNum atomic.Uint32
cancelCtx context.Context
cancelFunc context.CancelFunc
activeBackgroundWorkers sync.WaitGroup
// latestFrameMu protects critical sections where frame state changes (e.g. ref counting) need to be atomic
// with swapping out the latest frame.
latestFrameMu sync.Mutex
latestMJPEGBytes atomic.Pointer[[]byte]
latestFrame *avFrameWrapper
latestFrameCache cache
// We use a pool data structure to amortize the malloc cost of AVFrames and reduce pressure on memory
// management. We create one pool for the entire lifetime of the RTSP camera. Additionally, frames
// from the pool may be for a resolution that does not match the current image. The user of the pool
// is responsible for the underlying frame contents and further initializing it and/or throwing it away.
avFramePool *framePool
mimeHandler *mimeHandler
logger logging.Logger
// lastFrameTime is the UnixNano time of the last received frame, and the single source of truth
// for liveness. The reconnect worker only reconnects once frames stop; Image() uses it to avoid
// returning stale frames. A stream that keeps delivering frames is never reconnected.
lastFrameTime atomic.Int64
rtpPassthrough bool
currentCodec atomic.Int64
rtpPassthroughCtx context.Context
rtpPassthroughCancelCauseFn context.CancelCauseFunc
subsMu sync.RWMutex
bufAndCBByID map[rtppassthrough.SubscriptionID]bufAndCB
preferredTransports []*gortsplib.Transport
// lossMonitor aggregates RTP packet-loss stats into periodic, actionable log messages.
lossMonitor *lossMonitor
}
// Close closes the camera. It always returns nil, but because of Close() interface, it needs to return an error.
func (rc *rtspCamera) Close(_ context.Context) error {
if err := registry.Global.Remove(rc.Name().String()); err != nil {
rc.logger.Errorf("error removing camera from global registry: %s", err.Error())
}
rc.cancelFunc()
// Wait for the reconnect worker to exit before taking closeMu. The worker grabs closeMu while
// reconnecting, so holding it here would deadlock.
rc.activeBackgroundWorkers.Wait()
rc.closeMu.Lock()
rc.unsubscribeAll()
rc.closeConnection()
rc.mimeHandler.close()
// Clean up latestFrame cache if it exists. This is necessary to ensure that the frame is properly
// freed when the avFramePool is closed.
rc.latestFrameMu.Lock()
if rc.latestFrame != nil {
if refCount := rc.latestFrame.decrementRefs(); refCount == 0 {
rc.avFramePool.put(rc.latestFrame)
}
rc.latestFrame = nil
}
rc.latestFrameMu.Unlock()
rc.avFramePool.close()
rc.closeMu.Unlock()
rc.videoRequest.clear()
return nil
}
// clientReconnectBackgroundWorker reconnects the client when the stream stops delivering frames.
// A stream that produced a frame within noFrameTimeout is healthy and left alone, regardless of the
// OPTIONS probe. Only once frames stop do we probe OPTIONS (for the log) and reconnect.
func (rc *rtspCamera) clientReconnectBackgroundWorker(codecInfo videoCodec) {
rc.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
for utils.SelectContextOrWait(rc.cancelCtx, reconnectIntervalDuration) {
// Frames still arriving means the stream is healthy, so leave it alone even if OPTIONS
// would fail. Reconnecting a working stream just churns it.
if since := rc.timeSinceLastFrame(); since < noFrameTimeout {
continue
}
// Frames stopped. Probe OPTIONS for a better log message, then reconnect either way.
reason := fmt.Sprintf("no frames received in %s", noFrameTimeout)
if rc.client == nil {
reason = "RTSP client is not connected"
} else {
res, err := rc.client.Options(rc.u)
// Nick S:
// This error happens all the time on hardware we need to support & does not affect
// the performance of camera streaming. As a result, we ignore this error specifically
var errClientInvalidState liberrors.ErrClientInvalidState
if err != nil && !errors.As(err, &errClientInvalidState) {
reason = fmt.Sprintf("%s: %s", reason, err.Error())
} else if res != nil && res.StatusCode != base.StatusOK {
reason = fmt.Sprintf("%s: RTSP server responded with status code: %d", reason, res.StatusCode)
}
}
rc.logger.Warnf("stream unhealthy, trying to reconnect to %s, reason: %s", rc.u, reason)
if err := rc.reconnectClientWithFallbackTransports(codecInfo); err != nil {
rc.logger.Warnf("cannot reconnect to rtsp server err: %s", err.Error())
} else {
rc.logger.Infof("reconnected to rtsp server url: %s", rc.u)
// Give the new connection a full grace period to start delivering frames.
rc.markFrameReceived()
}
}
}, rc.activeBackgroundWorkers.Done)
}
// lossMonitorBackgroundWorker periodically samples the RTSP client's cumulative RTP stats and
// feeds them to the loss monitor, which logs windowed packet-loss summaries and warnings.
func (rc *rtspCamera) lossMonitorBackgroundWorker() {
rc.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
for utils.SelectContextOrWait(rc.cancelCtx, lossReportIntervalDuration) {
// closeMu excludes reconnectClient, which replaces the client and mutates its
// media/format maps while holding the write lock; Stats() itself only reads atomics.
rc.closeMu.RLock()
var stats *gortsplib.ClientStats
if rc.client != nil {
stats = rc.client.Stats()
}
rc.closeMu.RUnlock()
if stats == nil {
continue
}
rc.lossMonitor.observe(rtpStatsSnapshot{
packetsReceived: stats.Session.RTPPacketsReceived,
packetsLost: stats.Session.RTPPacketsLost,
packetsInError: stats.Session.RTPPacketsInError,
bytesReceived: stats.Session.BytesReceived,
jitter: stats.Session.RTPPacketsJitter,
})
}
}, rc.activeBackgroundWorkers.Done)
}
func (rc *rtspCamera) closeConnection() {
if rc.client != nil {
rc.client.Close()
rc.client = nil
}
rc.h264Media = nil
rc.resetLazyAU([][]byte{})
rc.currentCodec.Store(0)
if rc.rawDecoder != nil {
rc.rawDecoder.close()
rc.rawDecoder = nil
}
rc.videoRequest.stop()
}
// reconnectClientWithFallbackTransports attempts to setup the RTSP client with the given codec
// using the transports specified in the module config. This overrides gortsplib's
// default behavior of trying UDP first.
func (rc *rtspCamera) reconnectClientWithFallbackTransports(codecInfo videoCodec) error {
// Try to reconnect with each transport in the order defined above.
// If all attempts fail, return the last error.
var lastErr error
for _, transport := range rc.preferredTransports {
if err := rc.reconnectClient(codecInfo, transport); err != nil {
rc.logger.Warnf("cannot reconnect to rtsp server using transport %s, err: %s", transport.String(), err.Error())
lastErr = err
continue
}
rc.logger.Debugf("successfully reconnected to rtsp server url: %s using transport: %s", rc.u, transport.String())
return nil
}
return fmt.Errorf("all attempts to reconnect to rtsp server failed: %w", lastErr)
}
// reconnectClient reconnects the RTSP client to the streaming server by closing the old one and starting a new one.
func (rc *rtspCamera) reconnectClient(codecInfo videoCodec, transport *gortsplib.Transport) error {
rc.logger.Warnf("reconnectClient called with codec: %s and transport: %s", codecInfo, transport.String())
rc.closeMu.Lock()
defer rc.closeMu.Unlock()
rc.closeConnection()
// replace the client with a new one, but close it if setup is not successful
rc.client = &gortsplib.Client{
Transport: transport,
}
// Per-event logs stay at debug; the loss monitor aggregates the same counters (via
// client.Stats()) into windowed, actionable messages at higher levels.
rc.client.OnPacketLost = func(err error) {
rc.logger.Debugf("OnPacketLost: err: %s", err)
}
rc.client.OnTransportSwitch = func(err error) {
// A transport switch changes the meaning of subsequent loss logs, so it is worth an info.
rc.logger.Infof("OnTransportSwitch: err: %s", err)
}
rc.client.OnDecodeError = func(err error) {
rc.logger.Debugf("OnDecodeError: err: %s", err)
}
if err := rc.client.Start(rc.u.Scheme, rc.u.Host); err != nil {
return fmt.Errorf("when calling RTSP START on Scheme: %s, Host: %s, Error: %w", rc.u.Scheme, rc.u.Host, err)
}
var clientSuccessful bool
defer func() {
if !clientSuccessful {
rc.closeConnection()
}
}()
session, _, err := rc.client.Describe(rc.u)
if err != nil {
return fmt.Errorf("when calling RTSP DESCRIBE on %s: %w", rc.u, err)
}
rc.logger.Debugf("Session media info: %+v", session)
for _, media := range session.Medias {
for i, format := range media.Formats {
rc.logger.Debugf("Media %d format: %s", i+1, format.Codec())
rc.logger.Debugf("Format clock rate: %d", format.ClockRate())
rc.logger.Debugf("Format payload type: %d", format.PayloadType())
rc.logger.Debugf("Format RTPMap: %s", format.RTPMap())
rc.logger.Debugf("Format FMTP: %+v", format.FMTP())
}
}
if codecInfo == Agnostic {
codecInfo = rc.getAvailableCodec(session)
}
switch codecInfo {
case H264:
rc.logger.Info("setting up H264 decoder")
if err := rc.initH264(session); err != nil {
return err
}
case H265:
rc.logger.Info("setting up H265 decoder")
if err := rc.initH265(session); err != nil {
return err
}
case MJPEG:
rc.logger.Info("setting up MJPEG decoder")
if err := rc.initMJPEG(session); err != nil {
return err
}
case MPEG4:
rc.logger.Info("setting up MPEG4 decoder")
if err := rc.initMPEG4(session); err != nil {
return err
}
case Unknown, Agnostic:
return fmt.Errorf("codecInfo was '%s' after getting session info. Codec could not be determined", codecInfo.String())
default:
return fmt.Errorf("codec not supported: '%s'", codecInfo.String())
}
if _, err := rc.client.Play(nil); err != nil {
return err
}
clientSuccessful = true
rc.currentCodec.Store(int64(codecInfo))
// The new client's stats counters start at zero, so reset the loss monitor's baseline.
rc.lossMonitor.setConnection(transport.String())
// if after reconnecting we no longer support rtp_passthrough
// terminate all subscription
// otherwise, let any remaining subscriptions continue
// NOTE: We should test if subscriptions ALWAY recover after
// reconnecting. If not, we might want to terminate all subscriptions
// regardless of whether or not passthrough is supported so that
// subscribers can request new subscriptions.
if err := rc.validateSupportsPassthrough(); err != nil {
rc.unsubscribeAll()
}
return nil
}
func (rc *rtspCamera) consumeLazyAU() {
rc.auMu.Lock()
defer rc.auMu.Unlock()
if len(rc.au) > 0 {
codec := videoCodec(rc.currentCodec.Load())
switch codec {
case H264:
rc.storeH264Frame(rc.au)
case H265:
for _, au := range rc.au {
// h265 AUs are already packed into a single frame
// before they were added to rc.au
rc.storeH265Frame(au)
}
case Unknown:
case Agnostic:
case MJPEG:
case MPEG4:
fallthrough
default:
rc.logger.Infof("consumeLazyAU: called with unexpected codec: %s, int: %d", codec, codec)
}
rc.au = nil
}
}
func (rc *rtspCamera) resetLazyAU(au [][]byte) {
rc.auMu.Lock()
defer rc.auMu.Unlock()
rc.au = au
}
func (rc *rtspCamera) appendLazyAU(au [][]byte) {
rc.auMu.Lock()
defer rc.auMu.Unlock()
rc.au = append(rc.au, au...)
}
// initH264 initializes the H264 decoder and sets up the client to receive H264 packets.
func (rc *rtspCamera) initH264(session *description.Session) (err error) {
// setup RTP/H264 -> H264 decoder
var f *format.H264
media := session.FindFormat(&f)
if media == nil {
rc.logger.Warn("tracks available")
for _, x := range session.Medias {
rc.logger.Warnf("\t %v", x)
}
return errors.New("h264 track not found")
}
rc.h264Media = media
// setup RTP/H264 -> H264 decoder
rtpDec, err := f.CreateDecoder()
if err != nil {
return fmt.Errorf("creating H264 RTP decoder: %w", err)
}
// setup H264 -> raw frames decoder
rc.rawDecoder, err = newH264Decoder(rc.avFramePool, rc.logger)
if err != nil {
return fmt.Errorf("creating H264 raw decoder: %w", err)
}
// if SPS and PPS are present into the SDP, send them to the decoder
initialSPSAndPPS := [][]byte{}
if f.SPS != nil {
initialSPSAndPPS = append(initialSPSAndPPS, f.SPS)
var sps h264.SPS
if err := sps.Unmarshal(f.SPS); err == nil {
rc.lossMonitor.setVideoInfo(sps.Width(), sps.Height(), sps.FPS())
}
} else {
rc.logger.Warn("no initial SPS found in H264 format")
}
if f.PPS != nil {
initialSPSAndPPS = append(initialSPSAndPPS, f.PPS)
} else {
rc.logger.Warn("no initial PPS found in H264 format")
}
var receivedFirstIDR bool
storeImage := func(au [][]byte) {
// A full access unit arrived, so the stream is alive. Stamp liveness here on the receive
// path, before the iframe-only/lazy gates below, so it doesn't depend on decode mode or how
// often Image() is polled.
rc.markFrameReceived()
// NOTE(Nick S): This is duplicating work that the videoStoreMuxer is doing
// we could probably save a few iterations through au by
// consolidating that logic
// it is also potentially not resillient if we never get sps & pps from the SDP
if !receivedFirstIDR && h264.IDRPresent(au) {
rc.logger.Debug("adding initial SPS & PPS")
receivedFirstIDR = true
au = append(initialSPSAndPPS, au...)
rc.storeH264Frame(au)
return
}
if rc.iframeOnlyDecode && !h264.IDRPresent(au) {
return
}
if rc.lazyDecode {
if h264.IDRPresent(au) {
rc.resetLazyAU(au)
} else {
rc.appendLazyAU(au)
}
} else {
rc.storeH264Frame(au)
}
}
var publishToWebRTC func(pkt *rtp.Packet, pts int64)
if rc.rtpPassthrough {
fp, err := formatprocessor.New(webRTCPayloadMaxSize, f, true)
if err != nil {
return fmt.Errorf("unable to create new h264 rtp formatprocessor: %w", err)
}
publishToWebRTC = func(pkt *rtp.Packet, pts int64) {
ntp := time.Now()
u, err := fp.ProcessRTPPacket(pkt, ntp, time.Duration(pts), true)
if err != nil {
rc.logger.Debug(err.Error())
return
}
rc.subsMu.RLock()
defer rc.subsMu.RUnlock()
if len(rc.bufAndCBByID) == 0 {
return
}
// Publish the newly received packet Unit to all subscribers
for _, bufAndCB := range rc.bufAndCBByID {
if err := bufAndCB.buf.Publish(func() { bufAndCB.cb(u) }); err != nil {
rc.logger.Debug("RTP packet dropped due to %s", err.Error())
}
}
}
}
params := [][]byte{f.SPS, f.PPS}
onPacketRTP := wrapWithMarkerFromTimestamp(func(pkt *rtp.Packet) {
pts, ok := rc.client.PacketPTS2(media, pkt)
if !ok {
rc.logger.Debug("no pts found for packet")
return
}
if publishToWebRTC != nil {
publishToWebRTC(pkt, pts)
}
au, err := rtpDec.Decode(pkt)
if err != nil {
if !errors.Is(err, rtph264.ErrNonStartingPacketAndNoPrevious) && !errors.Is(err, rtph264.ErrMorePacketsNeeded) {
rc.logger.Debugf("error decoding(1) h264 rtsp stream %w", err)
}
return
}
storeImage(au)
rc.videoRequest.write(videostore.CodecTypeH264, params, au, pts)
})
_, err = rc.client.Setup(session.BaseURL, media, 0, 0)
if err != nil {
return fmt.Errorf("when calling RTSP Setup on %s for H264: %w", session.BaseURL, err)
}
rc.client.OnPacketRTP(media, f, onPacketRTP)
return nil
}
var codecToCodecType = map[videoCodec]videostore.CodecType{
H264: videostore.CodecTypeH264,
H265: videostore.CodecTypeH264,
}
func (rc *rtspCamera) RequestVideo(mux registry.Mux, codecCandiates []videostore.CodecType) (context.Context, error) {
currentCodec := codecToCodecType[videoCodec(rc.currentCodec.Load())]
if !slices.Contains(codecCandiates, currentCodec) {
return nil, registry.ErrUnsupported
}
return rc.videoRequest.newRequest(mux)
}
func (rc *rtspCamera) CancelRequest(mux registry.Mux) error {
return rc.videoRequest.cancelRequest(mux)
}
// initH265 initializes the H265 decoder and sets up the client to receive H265 packets.
func (rc *rtspCamera) initH265(session *description.Session) (err error) {
if rc.rtpPassthrough {
rc.logger.Warn("rtp_passthrough is only supported for H264 codec. rtp_passthrough features disabled due to H265 RTSP track")
}
var f *format.H265
media := session.FindFormat(&f)
if media == nil {
rc.logger.Warn("tracks available")
for _, x := range session.Medias {
rc.logger.Warnf("\t %v", x)
}
return errors.New("h265 track not found")
}
rtpDec, err := f.CreateDecoder()
if err != nil {
return fmt.Errorf("creating H265 RTP decoder: %w", err)
}
rc.rawDecoder, err = newH265Decoder(rc.avFramePool, rc.logger)
if err != nil {
return fmt.Errorf("creating H265 raw decoder: %w", err)
}
// For H.265, handle VPS, SPS, and PPS
if f.VPS != nil {
if _, err := rc.rawDecoder.decode(f.VPS); err != nil {
rc.logger.Debugf("failed to decode vps from SDP: %#v", f.VPS)
}
} else {
rc.logger.Warn("no VPS found in H265 format")
}
if f.SPS != nil {
if _, err := rc.rawDecoder.decode(f.SPS); err != nil {
rc.logger.Debugf("failed to decode sps from SDP: %#v", f.SPS)
}
var sps h265.SPS
if err := sps.Unmarshal(f.SPS); err == nil {
rc.lossMonitor.setVideoInfo(sps.Width(), sps.Height(), sps.FPS())
}
} else {
rc.logger.Warn("no SPS found in H265 format")
}
if f.PPS != nil {
if _, err := rc.rawDecoder.decode(f.PPS); err != nil {
rc.logger.Debugf("failed to decode pps from SDP: %#v", f.PPS)
}
} else {
rc.logger.Warn("no PPS found in H265 format")
}
storeImage := func(au [][]byte) {
// Stamp liveness on the receive path, before any gating (see H264 storeImage).
rc.markFrameReceived()
if rc.iframeOnlyDecode && !h265.IsRandomAccess(au) {
return
}
packedAU := packH265AUIntoNALU(au, rc.logger)
if rc.lazyDecode {
if h265.IsRandomAccess(au) {
rc.resetLazyAU([][]byte{packedAU})
} else {
rc.appendLazyAU([][]byte{packedAU})
}
} else {
rc.storeH265Frame(packedAU)
}
}
params := [][]byte{f.VPS, f.SPS, f.PPS}
onPacketRTP := wrapWithMarkerFromTimestamp(func(pkt *rtp.Packet) {
pts, ok := rc.client.PacketPTS2(media, pkt)
if !ok {
rc.logger.Debug("no pts found for packet")
return
}
au, err := rtpDec.Decode(pkt)
if err != nil {
if !errors.Is(err, rtph265.ErrNonStartingPacketAndNoPrevious) && !errors.Is(err, rtph265.ErrMorePacketsNeeded) {
rc.logger.Debugw("error decoding(1) h265 rtsp stream", "err", err.Error())
}
return
}
storeImage(au)
rc.videoRequest.write(videostore.CodecTypeH265, params, au, pts)
})
_, err = rc.client.Setup(session.BaseURL, media, 0, 0)
if err != nil {
return fmt.Errorf("when calling RTSP Setup on %s for H265: %w", session.BaseURL, err)
}
// On packet retreival, turn it into an image, and store it in shared memory
rc.client.OnPacketRTP(media, f, onPacketRTP)
return nil
}
func packH265AUIntoNALU(au [][]byte, logger logging.Logger) []byte {
// If the AU has more than one NALU, compact them into a single payload with NALUs separated
// in AnnexB format. This is necessary because the H.265 decoder expects all NALUs for a frame
// to be in a single payload rather than chunked across multiple decode calls.
packedNALU := []byte{}
firstNALU := true
for _, nalu := range au {
if len(nalu) == 0 {
logger.Warn("empty NALU found in H265 AU, skipping NALU")
continue
}
// Add start code prefix to all NALUs except the first non-empty one.
if !firstNALU {
packedNALU = append(packedNALU, H2645StartCode()...)
}
packedNALU = append(packedNALU, nalu...)
firstNALU = false
}
return packedNALU
}
func (rc *rtspCamera) storeH265Frame(nalu []byte) {
if len(nalu) == 0 {
rc.logger.Warn("no NALUs found in H265 AU, skipping packet")
return
}
frame, err := rc.rawDecoder.decode(nalu)
if err != nil {
rc.logger.Debugw("error decoding(2) h265 rtsp stream", "err", err.Error())
return
}
if frame != nil {
rc.handleLatestFrame(frame)
}
}
// initMJPEG initializes the MJPEG decoder and sets up the client to receive JPEG frames.
func (rc *rtspCamera) initMJPEG(session *description.Session) error {
if rc.rtpPassthrough {
rc.logger.Warn("rtp_passthrough is only supported for H264 codec. rtp_passthrough features disabled due to MJPEG RTSP track")
}
if rc.lazyDecode {
rc.logger.Warn("lazy_decode is currently only supported for H264 and H265 codecs. lazy_decode features disabled due to MJPEG RTSP track")
}
if rc.iframeOnlyDecode {
rc.logger.Warn("i_frame_only_decode is currently only supported for H264 and H265 codecs. " +
"lazy_decode features disabled due to MJPEG RTSP track")
}
if rc.videoRequest.active() {
rc.logger.Warn("video-store is currently only supported for H264 and H265 codecs. " +
"unable to store video due to MJPEG RTSP track")
}
var f *format.MJPEG
media := session.FindFormat(&f)
if media == nil {
rc.logger.Warn("tracks available")
for _, x := range session.Medias {
rc.logger.Warnf("\t %v", x)
}
return errors.New("MJPEG track not found")
}
mjpegDecoder, err := f.CreateDecoder()
if err != nil {
return fmt.Errorf("creating MJPEG RTP decoder: %w", err)
}
_, err = rc.client.Setup(session.BaseURL, media, 0, 0)
if err != nil {
return fmt.Errorf("when calling RTSP Setup on %s for MJPEG: %w", session.BaseURL, err)
}
rc.client.OnPacketRTP(media, f, func(pkt *rtp.Packet) {
frame, err := mjpegDecoder.Decode(pkt)
if err != nil {
return
}
rc.latestMJPEGBytes.Store(&frame)
rc.markFrameReceived()
})
return nil
}
// getMPEG4FromGeneric attempts to find an MPEG4 format from generic format(s) in the session that can be converted to MPEG4.
// Returns the format and media if found.
func getMPEG4FromGeneric(session *description.Session) (*format.MPEG4Video, *description.Media, error) {
for _, media := range session.Medias {
for _, f := range media.Formats {
generic, ok := f.(*format.Generic)
if !ok {
continue
}
if !strings.HasPrefix(strings.ToUpper(generic.RTPMap()), "MP4V-ES/") {
continue
}
mpeg4 := &format.MPEG4Video{
PayloadTyp: generic.PayloadType(),
ProfileLevelID: defaultMPEG4ProfileLevelID,
}
fmtp := generic.FMTP()
if fmtp == nil {
return mpeg4, media, nil
}
if config, ok := fmtp["config"]; ok {
configBytes, err := hex.DecodeString(config)
if err != nil {
return nil, nil, fmt.Errorf("failed to decode MPEG4 config: %w", err)
}
mpeg4.Config = configBytes
}
if profileID, ok := fmtp["profile-level-id"]; ok {
id, err := strconv.Atoi(profileID)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse profile-level-id: %w", err)
}
mpeg4.ProfileLevelID = id
}
return mpeg4, media, nil
}
}
return nil, nil, nil
}
// initMPEG4 initializes the MPEG4 decoder and sets up the client to receive MPEG4 packets.
func (rc *rtspCamera) initMPEG4(session *description.Session) error {
if rc.rtpPassthrough {
rc.logger.Warn("rtp_passthrough is only supported for H264 codec. rtp_passthrough features disabled due to MPEG4 RTSP track")
}
if rc.lazyDecode {
rc.logger.Warn("lazy_decode is currently only supported for H264 and H265 codecs. lazy_decode features disabled due to MPEG4 RTSP track")
}
if rc.iframeOnlyDecode {
rc.logger.Warn("i_frame_only_decode is currently only supported for H264 and H265 codecs. " +
"lazy_decode features disabled due to MPEG4 RTSP track")
}
if rc.videoRequest.active() {
rc.logger.Warn("video-store is currently only supported for H264 and H265 codecs. " +
"unable to store video due to MPEG4 RTSP track")
}
var f *format.MPEG4Video
media := session.FindFormat(&f)
var err error
if media == nil {
// If direct MPEG4 format not found, try to find it in generic formats
f, media, err = getMPEG4FromGeneric(session)
if err != nil {
return fmt.Errorf("error finding MPEG4 track: %w", err)
}
if media == nil {
for _, x := range session.Medias {
rc.logger.Debugf("\t %v", x)
}
return errors.New("MPEG4 track not found")
}
}
mpeg4Decoder, err := f.CreateDecoder()
if err != nil {
return fmt.Errorf("creating MPEG4 RTP decoder: %w", err)
}
// Initialize the rawDecoder with MPEG4 config data
if f.Config != nil {
// Prepend MPEG4 Visual Object Sequence (VOS) and Video Object (VO) start codes
vosStart := []byte{0x00, 0x00, 0x01, 0xB0}
voStart := []byte{0x00, 0x00, 0x01, 0xB5}
extraData := append(vosStart, voStart...)
extraData = append(extraData, f.Config...)
rc.rawDecoder, err = newMPEG4Decoder(rc.avFramePool, rc.logger, extraData)
if err != nil {
return fmt.Errorf("creating MPEG4 raw decoder: %w", err)
}
} else {
rc.rawDecoder, err = newMPEG4Decoder(rc.avFramePool, rc.logger, nil)
if err != nil {
return fmt.Errorf("creating MPEG4 raw decoder: %w", err)
}
}
_, err = rc.client.Setup(session.BaseURL, media, 0, 0)
if err != nil {