-
Notifications
You must be signed in to change notification settings - Fork 318
/
serverRTSP.go
473 lines (449 loc) · 13.9 KB
/
serverRTSP.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
package main
import (
"bytes"
"errors"
"fmt"
"net"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
)
var (
Version = "RTSP/1.0"
UserAgent = "Lavf58.29.100"
Session = "000a959d6816"
)
var (
OPTIONS = "OPTIONS"
DESCRIBE = "DESCRIBE"
SETUP = "SETUP"
PLAY = "PLAY"
TEARDOWN = "TEARDOWN"
)
// RTSP response status codes
const (
StatusContinue = 100
StatusOK = 200
StatusCreated = 201
StatusLowOnStorageSpace = 250
StatusMultipleChoices = 300
StatusMovedPermanently = 301
StatusMovedTemporarily = 302
StatusSeeOther = 303
StatusNotModified = 304
StatusUseProxy = 305
StatusBadRequest = 400
StatusUnauthorized = 401
StatusPaymentRequired = 402
StatusForbidden = 403
StatusNotFound = 404
StatusMethodNotAllowed = 405
StatusNotAcceptable = 406
StatusProxyAuthenticationRequired = 407
StatusRequestTimeout = 408
StatusGone = 410
StatusLengthRequired = 411
StatusPreconditionFailed = 412
StatusRequestEntityTooLarge = 413
StatusRequestURITooLong = 414
StatusUnsupportedMediaType = 415
StatusInvalidparameter = 451
StatusIllegalConferenceIdentifier = 452
StatusNotEnoughBandwidth = 453
StatusSessionNotFound = 454
StatusMethodNotValidInThisState = 455
StatusHeaderFieldNotValid = 456
StatusInvalidRange = 457
StatusParameterIsReadOnly = 458
StatusAggregateOperationNotAllowed = 459
StatusOnlyAggregateOperationAllowed = 460
StatusUnsupportedTransport = 461
StatusDestinationUnreachable = 462
StatusInternalServerError = 500
StatusNotImplemented = 501
StatusBadGateway = 502
StatusServiceUnavailable = 503
StatusGatewayTimeout = 504
StatusRTSPVersionNotSupported = 505
StatusOptionNotsupport = 551
)
func StatusText(code int) string {
return statusText[code]
}
var statusText = map[int]string{
StatusContinue: "Continue",
StatusOK: "OK",
StatusCreated: "Created",
StatusLowOnStorageSpace: "Low on Storage Space",
StatusMultipleChoices: "Multiple Choices",
StatusMovedPermanently: "Moved Permanently",
StatusMovedTemporarily: "Moved Temporarily",
StatusSeeOther: "See Other",
StatusNotModified: "Not Modified",
StatusUseProxy: "Use Proxy",
StatusBadRequest: "Bad Request",
StatusUnauthorized: "Unauthorized",
StatusPaymentRequired: "Payment Required",
StatusForbidden: "Forbidden",
StatusNotFound: "Not Found",
StatusMethodNotAllowed: "Method Not Allowed",
StatusNotAcceptable: "Not Acceptable",
StatusProxyAuthenticationRequired: "Proxy Authentication Required",
StatusRequestTimeout: "Request Time-out",
StatusGone: "Gone",
StatusLengthRequired: "Length Required",
StatusPreconditionFailed: "Precondition Failed",
StatusRequestEntityTooLarge: "Request Entity Too Large",
StatusRequestURITooLong: "Request-URI Too Large",
StatusUnsupportedMediaType: "Unsupported Media Type",
StatusInvalidparameter: "Parameter Not Understood",
StatusIllegalConferenceIdentifier: "Conference Not Found",
StatusNotEnoughBandwidth: "Not Enough Bandwidth",
StatusSessionNotFound: "Session Not Found",
StatusMethodNotValidInThisState: "Method Not Valid in This State",
StatusHeaderFieldNotValid: "Header Field Not Valid for Resource",
StatusInvalidRange: "Invalid Range",
StatusParameterIsReadOnly: "Parameter Is Read-Only",
StatusAggregateOperationNotAllowed: "Aggregate operation not allowed",
StatusOnlyAggregateOperationAllowed: "Only aggregate operation allowed",
StatusUnsupportedTransport: "Unsupported transport",
StatusDestinationUnreachable: "Destination unreachable",
StatusInternalServerError: "Internal Server Error",
StatusNotImplemented: "Not Implemented",
StatusBadGateway: "Bad Gateway",
StatusServiceUnavailable: "Service Unavailable",
StatusGatewayTimeout: "Gateway Time-out",
StatusRTSPVersionNotSupported: "RTSP Version not supported",
StatusOptionNotsupport: "Option not supported",
}
//RTSPServer func
func RTSPServer() {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"func": "RTSPServer",
"call": "Start",
}).Infoln("Server RTSP start")
l, err := net.Listen("tcp", Storage.ServerRTSPPort())
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"func": "RTSPServer",
"call": "Listen",
}).Errorln(err)
os.Exit(1)
}
defer func() {
err := l.Close()
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"func": "RTSPServer",
"call": "Close",
}).Errorln(err)
}
}()
for {
conn, err := l.Accept()
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"func": "RTSPServer",
"call": "Accept",
}).Errorln(err)
os.Exit(1)
}
go RTSPServerClientHandle(conn)
}
}
//RTSPServerClientHandle func
func RTSPServerClientHandle(conn net.Conn) {
buf := make([]byte, 4096)
token, uuid, channel, in, cSEQ := "", "", "0", 0, 0
var playStarted bool
defer func() {
err := conn.Close()
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "Close",
}).Errorln(err.Error())
}
}()
err := conn.SetDeadline(time.Now().Add(10 * time.Second))
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "SetDeadline",
}).Errorln(err.Error())
return
}
for {
n, err := conn.Read(buf)
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "Read",
}).Errorln(err.Error())
return
}
cSEQ = parsecSEQ(buf[:n])
stage, err := parseStage(buf[:n])
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "parseStage",
}).Errorln(err.Error())
}
err = conn.SetDeadline(time.Now().Add(60 * time.Second))
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "Request",
}).Debugln(string(buf[:n]))
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "SetDeadline",
}).Errorln(err.Error())
return
}
switch stage {
case OPTIONS:
if playStarted {
err = RTSPServerClientResponse(uuid, channel, conn, 200, map[string]string{"CSeq": strconv.Itoa(cSEQ), "Public": "DESCRIBE, SETUP, TEARDOWN, PLAY"})
if err != nil {
return
}
continue
}
uuid, channel, token, err = parseStreamChannel(buf[:n])
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "parseStreamChannel",
}).Errorln(err.Error())
return
}
if !Storage.StreamChannelExist(uuid, channel) {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "StreamChannelExist",
}).Errorln(ErrorStreamNotFound.Error())
err = RTSPServerClientResponse(uuid, channel, conn, 404, map[string]string{"CSeq": strconv.Itoa(cSEQ)})
if err != nil {
return
}
return
}
if !RemoteAuthorization("RTSP", uuid, channel, token, conn.RemoteAddr().String()) {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "StreamChannelExist",
}).Errorln(ErrorStreamUnauthorized.Error())
err = RTSPServerClientResponse(uuid, channel, conn, 401, map[string]string{"CSeq": strconv.Itoa(cSEQ)})
if err != nil {
return
}
return
}
Storage.StreamChannelRun(uuid, channel)
err = RTSPServerClientResponse(uuid, channel, conn, 200, map[string]string{"CSeq": strconv.Itoa(cSEQ), "Public": "DESCRIBE, SETUP, TEARDOWN, PLAY"})
if err != nil {
return
}
case SETUP:
if !strings.Contains(string(buf[:n]), "interleaved") {
err = RTSPServerClientResponse(uuid, channel, conn, 461, map[string]string{"CSeq": strconv.Itoa(cSEQ)})
if err != nil {
return
}
continue
}
err = RTSPServerClientResponse(uuid, channel, conn, 200, map[string]string{"CSeq": strconv.Itoa(cSEQ), "User-Agent:": UserAgent, "Session": Session, "Transport": "RTP/AVP/TCP;unicast;interleaved=" + strconv.Itoa(in) + "-" + strconv.Itoa(in+1)})
if err != nil {
return
}
in = in + 2
case DESCRIBE:
sdp, err := Storage.StreamChannelSDP(uuid, channel)
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "StreamSDP",
}).Errorln(err.Error())
return
}
err = RTSPServerClientResponse(uuid, channel, conn, 200, map[string]string{"CSeq": strconv.Itoa(cSEQ), "User-Agent:": UserAgent, "Session": Session, "Content-Type": "application/sdp\r\nContent-Length: " + strconv.Itoa(len(sdp)), "sdp": string(sdp)})
if err != nil {
return
}
case PLAY:
err = RTSPServerClientResponse(uuid, channel, conn, 200, map[string]string{"CSeq": strconv.Itoa(cSEQ), "User-Agent:": UserAgent, "Session": Session})
if err != nil {
return
}
playStarted = true
go RTSPServerClientPlay(uuid, channel, conn)
case TEARDOWN:
err = RTSPServerClientResponse(uuid, channel, conn, 200, map[string]string{"CSeq": strconv.Itoa(cSEQ), "User-Agent:": UserAgent, "Session": Session})
if err != nil {
return
}
return
default:
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "Stage",
}).Debugln("stage bad", stage)
}
}
}
//handleRTSPServerPlay func
func RTSPServerClientPlay(uuid string, channel string, conn net.Conn) {
cid, _, ch, err := Storage.ClientAdd(uuid, channel, RTSP)
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "ClientAdd",
}).Errorln(err.Error())
return
}
defer func() {
Storage.ClientDelete(uuid, cid, channel)
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "ClientDelete",
}).Infoln("Client offline")
err := conn.Close()
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "Close",
}).Errorln(err.Error())
}
}()
noVideo := time.NewTimer(10 * time.Second)
for {
select {
case <-noVideo.C:
return
case pck := <-ch:
noVideo.Reset(10 * time.Second)
_, err := conn.Write(*pck)
if err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "handleRTSPServerRequest",
"call": "Write",
}).Errorln(err.Error())
return
}
}
}
}
//handleRTSPServerPlay func
func RTSPServerClientResponse(uuid string, channel string, conn net.Conn, status int, headers map[string]string) error {
var sdp string
builder := bytes.Buffer{}
builder.WriteString(fmt.Sprintf(Version+" %d %s\r\n", status, StatusText(status)))
for k, v := range headers {
if k == "sdp" {
sdp = v
continue
}
builder.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
}
builder.WriteString(fmt.Sprintf("\r\n"))
builder.WriteString(sdp)
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "RTSPServerClientResponse",
"call": "Response",
}).Debugln(builder.String())
if _, err := conn.Write(builder.Bytes()); err != nil {
log.WithFields(logrus.Fields{
"module": "rtsp_server",
"stream": uuid,
"channel": channel,
"func": "RTSPServerClientResponse",
"call": "Write",
}).Errorln(err.Error())
return err
}
return nil
}
//parsecSEQ func
func parsecSEQ(buf []byte) int {
return stringToInt(stringInBetween(string(buf), "CSeq: ", "\r\n"))
}
//parseStage func
func parseStage(buf []byte) (string, error) {
st := strings.Split(string(buf), " ")
if len(st) > 0 {
return st[0], nil
}
return "", errors.New("parse stage error " + string(buf))
}
//parseStreamChannel func
func parseStreamChannel(buf []byte) (string, string, string, error) {
var token string
uri := stringInBetween(string(buf), " ", " ")
u, err := url.Parse(uri)
if err == nil {
token = u.Query().Get("token")
uri = u.Path
}
st := strings.Split(uri, "/")
if len(st) >= 3 {
return st[1], st[2], token, nil
}
return "", "0", token, errors.New("parse stream error " + string(buf))
}