-
Notifications
You must be signed in to change notification settings - Fork 290
/
helpers.go
110 lines (90 loc) · 2.58 KB
/
helpers.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
package rtsp
import (
"bytes"
"io"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/AlexxIT/go2rtc/pkg/core"
"github.com/pion/rtcp"
"github.com/pion/sdp/v3"
)
type RTCP struct {
Channel byte
Header rtcp.Header
Packets []rtcp.Packet
}
const sdpHeader = `v=0
o=- 0 0 IN IP4 0.0.0.0
s=-
t=0 0`
func UnmarshalSDP(rawSDP []byte) ([]*core.Media, error) {
sd := &sdp.SessionDescription{}
if err := sd.Unmarshal(rawSDP); err != nil {
// fix multiple `s=` https://github.com/AlexxIT/WebRTC/issues/417
re, _ := regexp.Compile("\ns=[^\n]+")
rawSDP = re.ReplaceAll(rawSDP, nil)
// fix SDP header for some cameras
if i := bytes.Index(rawSDP, []byte("\nm=")); i > 0 {
rawSDP = append([]byte(sdpHeader), rawSDP[i:]...)
}
// Fix invalid media type (errSDPInvalidValue) caused by
// some TP-LINK IP camera, e.g. TL-IPC44GW
m := regexp.MustCompile("m=application/[^ ]+")
rawSDP = m.ReplaceAll(rawSDP, []byte("m=application"))
if err == io.EOF {
rawSDP = append(rawSDP, '\n')
}
sd = &sdp.SessionDescription{}
err = sd.Unmarshal(rawSDP)
if err != nil {
return nil, err
}
}
// fix buggy camera https://github.com/AlexxIT/go2rtc/issues/771
forceDirection := sd.Origin.Username == "CV-RTSPHandler"
var medias []*core.Media
for _, md := range sd.MediaDescriptions {
media := core.UnmarshalMedia(md)
// Check buggy SDP with fmtp for H264 on another track
// https://github.com/AlexxIT/WebRTC/issues/419
for _, codec := range media.Codecs {
if codec.Name == core.CodecH264 && codec.FmtpLine == "" {
codec.FmtpLine = findFmtpLine(codec.PayloadType, sd.MediaDescriptions)
}
}
if media.Direction == "" || forceDirection {
media.Direction = core.DirectionRecvonly
}
medias = append(medias, media)
}
return medias, nil
}
func findFmtpLine(payloadType uint8, descriptions []*sdp.MediaDescription) string {
s := strconv.Itoa(int(payloadType))
for _, md := range descriptions {
codec := core.UnmarshalCodec(md, s)
if codec.FmtpLine != "" {
return codec.FmtpLine
}
}
return ""
}
// urlParse fix bugs:
// 1. Content-Base: rtsp://::ffff:192.168.1.123/onvif/profile.1/
// 2. Content-Base: rtsp://rtsp://turret2-cam.lan:554/stream1/
func urlParse(rawURL string) (*url.URL, error) {
if strings.HasPrefix(rawURL, "rtsp://rtsp://") {
rawURL = rawURL[7:]
}
u, err := url.Parse(rawURL)
if err != nil && strings.HasSuffix(err.Error(), "after host") {
if i1 := strings.Index(rawURL, "://"); i1 > 0 {
if i2 := strings.IndexByte(rawURL[i1+3:], '/'); i2 > 0 {
return urlParse(rawURL[:i1+3+i2] + ":" + rawURL[i1+3+i2:])
}
}
}
return u, err
}