forked from Monibuca/plugin-gb28181
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
400 lines (385 loc) · 10.7 KB
/
main.go
File metadata and controls
400 lines (385 loc) · 10.7 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
package gb28181
import (
"bufio"
"bytes"
"encoding/xml"
"io"
"log"
"net"
"net/http"
"strconv"
"sync"
"time"
"github.com/Monibuca/engine/v3"
"github.com/Monibuca/plugin-gb28181/v3/sip"
"github.com/Monibuca/plugin-gb28181/v3/transaction"
"github.com/Monibuca/plugin-gb28181/v3/utils"
. "github.com/Monibuca/utils/v3"
. "github.com/logrusorgru/aurora"
"github.com/pion/rtp"
"golang.org/x/net/html/charset"
)
var (
Devices sync.Map
DeviceNonce = make(map[string]string) //保存nonce防止设备伪造
DeviceRegisterCount = make(map[string]int) //设备注册次数
Ignores = make(map[string]struct{})
publishers Publishers
)
const MaxRegisterCount = 3
func FindChannel(deviceId string, channelId string) (c *Channel) {
if v, ok := Devices.Load(deviceId); ok {
d := v.(*Device)
d.channelMutex.RLock()
c = d.channelMap[channelId]
d.channelMutex.RUnlock()
}
return
}
type Publishers struct {
data map[uint32]*Publisher
sync.RWMutex
}
func (p *Publishers) Add(key uint32, pp *Publisher) {
p.Lock()
p.data[key] = pp
p.Unlock()
}
func (p *Publishers) Remove(key uint32) {
p.Lock()
delete(p.data, key)
p.Unlock()
}
func (p *Publishers) Get(key uint32) *Publisher {
p.RLock()
defer p.RUnlock()
return p.data[key]
}
var config = struct {
Serial string
Realm string
ListenAddr string
Expires int
MediaPort uint16
AutoInvite bool
AutoCloseAfter int
Ignore []string
TCP bool
TCPMediaPortNum uint16
RemoveBanInterval int
PreFetchRecord bool
Username string
Password string
}{"34020000002000000001", "3402000000", "127.0.0.1:5060", 3600, 58200, false, -1, nil, false, 1, 600, false, "", ""}
func init() {
engine.InstallPlugin(&engine.PluginConfig{
Name: "GB28181",
Config: &config,
Run: run,
})
publishers.data = make(map[uint32]*Publisher)
}
func run() {
ipAddr, err := net.ResolveUDPAddr("", config.ListenAddr)
if err != nil {
log.Fatal(err)
}
Print(Green("server gb28181 start at"), BrightBlue(config.ListenAddr))
for _, id := range config.Ignore {
Ignores[id] = struct{}{}
}
useTCP := config.TCP
config := &transaction.Config{
SipIP: ipAddr.IP.String(),
SipPort: uint16(ipAddr.Port),
SipNetwork: "UDP",
Serial: config.Serial,
Realm: config.Realm,
Username: config.Username,
Password: config.Password,
AckTimeout: 10,
MediaIP: ipAddr.IP.String(),
RegisterValidity: config.Expires,
RegisterInterval: 60,
HeartbeatInterval: 60,
HeartbeatRetry: 3,
AudioEnable: true,
WaitKeyFrame: true,
MediaIdleTimeout: 30,
RemoveBanInterval: config.RemoveBanInterval,
}
http.HandleFunc("/api/gb28181/query/records", func(w http.ResponseWriter, r *http.Request) {
CORS(w, r)
id := r.URL.Query().Get("id")
channel := r.URL.Query().Get("channel")
startTime := r.URL.Query().Get("startTime")
endTime := r.URL.Query().Get("endTime")
if c := FindChannel(id, channel); c != nil {
w.WriteHeader(c.QueryRecord(startTime, endTime))
} else {
w.WriteHeader(404)
}
})
http.HandleFunc("/api/gb28181/list", func(w http.ResponseWriter, r *http.Request) {
CORS(w, r)
sse := NewSSE(w, r.Context())
for {
var list []*Device
Devices.Range(func(key, value interface{}) bool {
device := value.(*Device)
if time.Since(device.UpdateTime) > time.Duration(config.RegisterValidity)*time.Second {
Devices.Delete(key)
} else {
list = append(list, device)
}
return true
})
sse.WriteJSON(list)
select {
case <-time.After(time.Second * 5):
case <-sse.Done():
return
}
}
})
http.HandleFunc("/api/gb28181/control", func(w http.ResponseWriter, r *http.Request) {
CORS(w, r)
id := r.URL.Query().Get("id")
channel := r.URL.Query().Get("channel")
ptzcmd := r.URL.Query().Get("ptzcmd")
if c := FindChannel(id, channel); c != nil {
w.WriteHeader(c.Control(ptzcmd))
} else {
w.WriteHeader(404)
}
})
http.HandleFunc("/api/gb28181/invite", func(w http.ResponseWriter, r *http.Request) {
CORS(w, r)
query := r.URL.Query()
id := query.Get("id")
channel := r.URL.Query().Get("channel")
startTime := query.Get("startTime")
endTime := query.Get("endTime")
if c := FindChannel(id, channel); c != nil {
if startTime == "" && c.LivePublisher != nil {
w.WriteHeader(304) //直播流已存在
} else {
w.WriteHeader(c.Invite(startTime, endTime))
}
} else {
w.WriteHeader(404)
}
})
http.HandleFunc("/api/gb28181/bye", func(w http.ResponseWriter, r *http.Request) {
CORS(w, r)
id := r.URL.Query().Get("id")
channel := r.URL.Query().Get("channel")
live := r.URL.Query().Get("live")
if c := FindChannel(id, channel); c != nil {
w.WriteHeader(c.Bye(live != "false"))
} else {
w.WriteHeader(404)
}
})
s := transaction.NewCore(config)
s.OnRegister = func(msg *sip.Message) {
id := msg.From.Uri.UserInfo()
storeDevice := func() {
var d *Device
if _d, loaded := Devices.LoadOrStore(id, &Device{
ID: id,
RegisterTime: time.Now(),
UpdateTime: time.Now(),
Status: string(sip.REGISTER),
Core: s,
from: &sip.Contact{Uri: msg.StartLine.Uri, Params: make(map[string]string)},
to: msg.To,
Addr: msg.Via.GetSendBy(),
SipIP: config.MediaIP,
channelMap: make(map[string]*Channel),
}); loaded {
d = _d.(*Device)
d.UpdateTime = time.Now()
d.from = &sip.Contact{Uri: msg.StartLine.Uri, Params: make(map[string]string)}
d.to = msg.To
d.Addr = msg.Via.GetSendBy()
}
}
// 不需要密码情况
if config.Username == "" && config.Password == "" {
storeDevice()
return
}
sendUnauthorized := func() {
response := msg.BuildResponseWithPhrase(401, "Unauthorized")
if DeviceNonce[id] == "" {
nonce := utils.RandNumString(32)
DeviceNonce[id] = nonce
}
response.WwwAuthenticate = sip.NewWwwAuthenticate(s.Realm, DeviceNonce[id], sip.DIGEST_ALGO_MD5)
s.Send(response)
}
// 需要密码情况 设备第一次上报,返回401和加密算法
if msg.Authorization == nil || msg.Authorization.GetUsername() == "" {
sendUnauthorized()
return
}
// 有些摄像头没有配置用户名的地方,用户名就是摄像头自己的国标id
username := config.Username
if msg.Authorization.GetUsername() == id {
username = id
}
if DeviceRegisterCount[id] >= MaxRegisterCount {
s.Send(msg.BuildResponse(403))
return
}
// 设备第二次上报,校验
if !msg.Authorization.Verify(username, config.Password, config.Realm, DeviceNonce[id]) {
sendUnauthorized()
DeviceRegisterCount[id] += 1
return
}
storeDevice()
delete(DeviceNonce, id)
delete(DeviceRegisterCount, id)
}
s.OnMessage = func(msg *sip.Message) bool {
if v, ok := Devices.Load(msg.From.Uri.UserInfo()); ok {
d := v.(*Device)
if d.Status == string(sip.REGISTER) {
d.Status = "ONLINE"
go d.Query()
}
d.UpdateTime = time.Now()
temp := &struct {
XMLName xml.Name
CmdType string
DeviceID string
DeviceList []*Channel `xml:"DeviceList>Item"`
RecordList []*Record `xml:"RecordList>Item"`
}{}
decoder := xml.NewDecoder(bytes.NewReader([]byte(msg.Body)))
decoder.CharsetReader = charset.NewReaderLabel
err := decoder.Decode(temp)
if err != nil {
err = utils.DecodeGbk(temp, []byte(msg.Body))
if err != nil {
log.Printf("decode catelog err: %s", err)
}
}
switch temp.XMLName.Local {
case "Notify":
switch temp.CmdType {
case "Keeyalive":
if d.subscriber.CallID != "" && time.Now().After(d.subscriber.Timeout) {
go d.Subscribe()
}
d.CheckSubStream()
case "Catalog":
d.UpdateChannels(temp.DeviceList)
}
case "Response":
switch temp.CmdType {
case "Catalog":
d.UpdateChannels(temp.DeviceList)
case "RecordInfo":
d.UpdateRecord(temp.DeviceID, temp.RecordList)
}
}
return true
}
return false
}
//OnStreamClosedHooks.AddHook(func(stream *Stream) {
// Devices.Range(func(key, value interface{}) bool {
// device:=value.(*Device)
// for _,channel := range device.Channels {
// if stream.StreamPath == channel.RecordSP {
//
// }
// }
// })
//})
if useTCP {
listenMediaTCP()
} else {
go listenMediaUDP()
}
// go queryCatalog(config)
if config.Username != "" || config.Password != "" {
go removeBanDevice(config)
}
s.Start()
}
func listenMediaTCP() {
for i := uint16(0); i < config.TCPMediaPortNum; i++ {
addr := ":" + strconv.Itoa(int(config.MediaPort+i))
go ListenTCP(addr, func(conn net.Conn) {
var rtpPacket rtp.Packet
reader := bufio.NewReader(conn)
lenBuf := make([]byte, 2)
defer conn.Close()
var err error
for err == nil {
if _, err = io.ReadFull(reader, lenBuf); err != nil {
return
}
ps := make([]byte, BigEndian.Uint16(lenBuf))
if _, err = io.ReadFull(reader, ps); err != nil {
return
}
if err := rtpPacket.Unmarshal(ps); err != nil {
Println("gb28181 decode rtp error:", err)
} else if publisher := publishers.Get(rtpPacket.SSRC); publisher != nil && publisher.Err() == nil {
publisher.PushPS(&rtpPacket)
}
}
})
}
}
func listenMediaUDP() {
var rtpPacket rtp.Packet
networkBuffer := 1048576
addr := ":" + strconv.Itoa(int(config.MediaPort))
conn, err := ListenUDP(addr, networkBuffer)
if err != nil {
Printf("listen udp %s err: %v", addr, err)
return
}
bufUDP := make([]byte, networkBuffer)
Printf("udp server start listen video port[%d]", config.MediaPort)
defer Printf("udp server stop listen video port[%d]", config.MediaPort)
for n, _, err := conn.ReadFromUDP(bufUDP); err == nil; n, _, err = conn.ReadFromUDP(bufUDP) {
ps := bufUDP[:n]
if err := rtpPacket.Unmarshal(ps); err != nil {
Println("gb28181 decode rtp error:", err)
}
if publisher := publishers.Get(rtpPacket.SSRC); publisher != nil && publisher.Err() == nil {
publisher.PushPS(&rtpPacket)
}
}
}
// func queryCatalog(config *transaction.Config) {
// t := time.NewTicker(time.Duration(config.CatalogInterval) * time.Second)
// for range t.C {
// Devices.Range(func(key, value interface{}) bool {
// device := value.(*Device)
// if time.Since(device.UpdateTime) > time.Duration(config.RegisterValidity)*time.Second {
// Devices.Delete(key)
// } else if device.Channels != nil {
// go device.Subscribe()
// }
// return true
// })
// }
// }
func removeBanDevice(config *transaction.Config) {
t := time.NewTicker(time.Duration(config.RemoveBanInterval) * time.Second)
for range t.C {
for id, cnt := range DeviceRegisterCount {
if cnt >= MaxRegisterCount {
delete(DeviceRegisterCount, id)
}
}
}
}