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
| #include "rtp.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string>
#include <stdint.h>
#define H264_FILE_NAME "./data/test.h264" // 修改文件位置
#define SERVER_PORT 8554
#define SERVER_RTP_PORT 55532
#define SERVER_RTCP_PORT 55533
#define BUF_MAX_SIZE (1024*1024)
static int createTcpSocket()
{
int sockfd;
int on = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
return -1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
return sockfd;
}
static int createUdpSocket()
{
int sockfd;
int on = 1;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
return -1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
return sockfd;
}
static int bindSocketAddr(int sockfd, const char* ip, int port)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip);
if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr)) < 0)
return -1;
return 0;
}
static int acceptClient(int sockfd, char* ip, int* port)
{
int clientfd;
socklen_t len = 0;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
len = sizeof(addr);
clientfd = accept(sockfd, (struct sockaddr*)&addr, &len);
if (clientfd < 0)
return -1;
strcpy(ip, inet_ntoa(addr.sin_addr));
*port = ntohs(addr.sin_port);
return clientfd;
}
static int closesocket(int fd){
close(fd);
return 1;
}
static inline int startCode3(char* buf) // h264文件必定已001 || 0001开头
{
if (buf[0] == 0 && buf[1] == 0 && buf[2] == 1)
return 1;
else
return 0;
}
static inline int startCode4(char* buf)
{
if (buf[0] == 0 && buf[1] == 0 && buf[2] == 0 && buf[3] == 1)
return 1;
else
return 0;
}
static char* findNextStartCode(char* buf, int len) // 找到下一个nalu包开始
{
int i;
if (len < 3)
return NULL;
for (i = 0; i < len - 3; ++i)
{
if (startCode3(buf) || startCode4(buf))
return buf;
++buf; // http://c.biancheng.net/view/1769.html
}
if (startCode3(buf))
return buf;
return NULL;
}
static int getFrameFromH264File(FILE* fp, char* frame, int size) {
int rSize, frameSize;
char* nextStartCode;
if (fp < 0)
return -1;
rSize = fread(frame, 1, size, fp); // 读取1*size个数据
if (!startCode3(frame) && !startCode4(frame)) // 判断frame是否合法
return -1;
nextStartCode = findNextStartCode(frame + 3, rSize - 3); // 排除startCode前三位?
if (!nextStartCode)
{
//lseek(fd, 0, SEEK_SET);
//frameSize = rSize;
return -1;
}
else
{
frameSize = (nextStartCode - frame); // 高地址-低地址
// 从当前位置前移rSize-frameSize个(第一次是文件头到第一个nalu包尾的数据)
//并且下次读取从该位置读取,所以不会一直是相同值
fseek(fp, frameSize - rSize, SEEK_CUR);
}
return frameSize;
}
static int rtpSendH264Frame(int serverRtpSockfd, const char* ip, int16_t port,
struct RtpPacket* rtpPacket, char* frame, uint32_t frameSize)
{
uint8_t naluType;
int sendBytes = 0;
int ret;
naluType = frame[0]; // nalu头第一个字节
printf("frameSize=%d \n", frameSize);
if (frameSize <= RTP_MAX_PKT_SIZE) // nalu长度小于最大包长:单一NALU单元模式
{
//* 0 1 2 3 4 5 6 7 8 9
//* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//* |F|NRI| Type | a single NAL unit ... |
//* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
memcpy(rtpPacket->payload, frame, frameSize);
ret = rtpSendPacketOverUdp(serverRtpSockfd, ip, port, rtpPacket, frameSize);
if(ret < 0)
return -1;
rtpPacket->rtpHeader.seq++;
sendBytes += ret;
if ((naluType & 0x1F) == 6 || (naluType & 0x1F) == 7 || (naluType & 0x1F) == 8) // 如果是SEI、SPS、PPS就不需要加时间戳
goto out;
}
else // nalu长度小于最大包场:分片模式
{
//* 0 1 2
//* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
//* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//* | FU indicator | FU header | FU payload ... |
//* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//* FU Indicator
//* 0 1 2 3 4 5 6 7
//* +-+-+-+-+-+-+-+-+
//* |F|NRI| Type |
//* +---------------+
//* FU Header
//* 0 1 2 3 4 5 6 7
//* +-+-+-+-+-+-+-+-+
//* |S|E|R| Type |
//* +---------------+
int pktNum = frameSize / RTP_MAX_PKT_SIZE; // 有几个完整的包
int remainPktSize = frameSize % RTP_MAX_PKT_SIZE; // 剩余不完整包的大小
int i, pos = 1;
// 发送完整的包
for (i = 0; i < pktNum; i++)
{
// 0x60:0110 0000、 28:0001 1100
rtpPacket->payload[0] = (naluType & 0x60) | 28; // & 获取NRI、| 获取TYPE = 28
rtpPacket->payload[1] = naluType & 0x1F; // 1F:0001 1111 获取NALU的type
if (i == 0) //第一包数据
rtpPacket->payload[1] |= 0x80; // 判断start 1000 0000
else if (remainPktSize == 0 && i == pktNum - 1) //最后一包数据
rtpPacket->payload[1] |= 0x40; // 判断end 0100 0000
memcpy(rtpPacket->payload+2, frame+pos, RTP_MAX_PKT_SIZE); // 除FU两个字节,将剩余数据放入load
ret = rtpSendPacketOverUdp(serverRtpSockfd, ip, port, rtpPacket, RTP_MAX_PKT_SIZE+2); // +2包含FU
if(ret < 0)
return -1;
rtpPacket->rtpHeader.seq++;
sendBytes += ret;
pos += RTP_MAX_PKT_SIZE;
}
// 发送剩余的数据
if (remainPktSize > 0)
{
rtpPacket->payload[0] = (naluType & 0x60) | 28;
rtpPacket->payload[1] = naluType & 0x1F;
rtpPacket->payload[1] |= 0x40; //end
memcpy(rtpPacket->payload+2, frame+pos, remainPktSize+2);
ret = rtpSendPacketOverUdp(serverRtpSockfd, ip, port, rtpPacket, remainPktSize+2);
if(ret < 0)
return -1;
rtpPacket->rtpHeader.seq++;
sendBytes += ret;
}
}
rtpPacket->rtpHeader.timestamp += 90000 / 25; // https://blog.csdn.net/jwybobo2007/article/details/7235942
out:
return sendBytes;
}
static int handleCmd_OPTIONS(char* result, int cseq)
{
sprintf(result, "RTSP/1.0 200 OK\r\n"
"CSeq: %d\r\n"
"Public: OPTIONS, DESCRIBE, SETUP, PLAY\r\n"
"\r\n",
cseq);
return 0;
}
static int handleCmd_DESCRIBE(char* result, int cseq, char* url)
{
char sdp[500];
char localIp[100];
sscanf(url, "rtsp://%[^:]:", localIp);
sprintf(sdp, "v=0\r\n"
"o=- 9%ld 1 IN IP4 %s\r\n"
"t=0 0\r\n"
"a=control:*\r\n"
"m=video 0 RTP/AVP 96\r\n"
"a=rtpmap:96 H264/90000\r\n"
"a=control:track0\r\n",
time(NULL), localIp);
sprintf(result, "RTSP/1.0 200 OK\r\nCSeq: %d\r\n"
"Content-Base: %s\r\n"
"Content-type: application/sdp\r\n"
"Content-length: %zu\r\n\r\n"
"%s",
cseq,
url,
strlen(sdp),
sdp);
return 0;
}
static int handleCmd_SETUP(char* result, int cseq, int client_Rtp_Port)
{
sprintf(result, "RTSP/1.0 200 OK\r\n"
"CSeq: %d\r\n"
"Transport: RTP/AVP;unicast;client_port=%d-%d;server_port=%d-%d\r\n"
"Session: 66334873\r\n"
"\r\n",
cseq,
client_Rtp_Port,
client_Rtp_Port + 1,
SERVER_RTP_PORT,
SERVER_RTCP_PORT);
return 0;
}
static int handleCmd_PLAY(char* result, int cseq)
{
sprintf(result, "RTSP/1.0 200 OK\r\n"
"CSeq: %d\r\n"
"Range: npt=0.000-\r\n"
"Session: 66334873; timeout=10\r\n\r\n",
cseq);
return 0;
}
static void doClient(int clientSockfd, const char* clientIP, int clientPort) {
char method[40];
char url[100];
char version[40];
int CSeq;
int serverRtpSockfd = -1, serverRtcpSockfd = -1;
int client_Rtp_Port, client_Rtcp_Port;
char* rBuf = (char*)malloc(BUF_MAX_SIZE);
char* sBuf = (char*)malloc(BUF_MAX_SIZE);
while (true) { // 循环接收客户端发送的每个请求并做处理
int recvLen;
recvLen = recv(clientSockfd, rBuf, BUF_MAX_SIZE, 0);
if (recvLen <= 0) {
break;
}
rBuf[recvLen] = '\0';
printf("%s rBuf = %s \n",__FUNCTION__,rBuf);
const char* sep = "\n";
char* line = strtok(rBuf, sep);
while (line) { // 解析客户端发送的请求
if (strstr(line, "OPTIONS") ||
strstr(line, "DESCRIBE") ||
strstr(line, "SETUP") ||
strstr(line, "PLAY")) {
if (sscanf(line, "%s %s %s\r\n", method, url, version) != 3) {
// error
}
}
else if (strstr(line, "CSeq")) {
if (sscanf(line, "CSeq: %d\r\n", &CSeq) != 1) {
// error
}
}
else if (!strncmp(line, "Transport:", strlen("Transport:"))) {
// Transport: RTP/AVP/UDP;unicast;client_port=13358-13359
// Transport: RTP/AVP;unicast;client_port=13358-13359
if (sscanf(line, "Transport: RTP/AVP/UDP;unicast;client_port=%d-%d\r\n",
&client_Rtp_Port, &client_Rtcp_Port) != 2) {
// error
printf("parse Transport error \n");
}
}
line = strtok(NULL, sep);
}
// 服务端回应客户端请求,目前只是填充了sBuf
if (!strcmp(method, "OPTIONS")) {
if (handleCmd_OPTIONS(sBuf, CSeq))
{
printf("failed to handle options\n");
break;
}
}
else if (!strcmp(method, "DESCRIBE")) {
if (handleCmd_DESCRIBE(sBuf, CSeq, url))
{
printf("failed to handle describe\n");
break;
}
}
else if (!strcmp(method, "SETUP")) { //SETUP返回服务端 端口号
if (handleCmd_SETUP(sBuf, CSeq, client_Rtp_Port))
{
printf("failed to handle setup\n");
break;
}
// 创建服务端 端口号 用于通信
serverRtpSockfd = createUdpSocket();
serverRtcpSockfd = createUdpSocket();
if (serverRtpSockfd < 0 || serverRtcpSockfd < 0)
{
printf("failed to create udp socket\n");
break;
}
if (bindSocketAddr(serverRtpSockfd, "0.0.0.0", SERVER_RTP_PORT) < 0 ||
bindSocketAddr(serverRtcpSockfd, "0.0.0.0", SERVER_RTCP_PORT) < 0)
{
printf("failed to bind addr\n");
break;
}
}
else if (!strcmp(method, "PLAY")) {
if (handleCmd_PLAY(sBuf, CSeq))
{
printf("failed to handle play\n");
break;
}
}
else {
printf("未定义的method = %s \n", method);
break;
}
/*
sBuf = RTSP/1.0 200 OK
CSeq: 2
Content-Base: rtsp://127.0.0.1:8554
Content-type: application/sdp
Content-length: 125
...
*/
printf("sBuf = %s \n", sBuf);
/*
doClient rBuf = SETUP rtsp://127.0.0.1:8554/track0 RTSP/1.0
Transport: RTP/AVP/UDP;unicast;client_port=16010-16011
CSeq: 3
User-Agent: Lavf58.45.100
*/
printf("%s sBuf = %s \n", __FUNCTION__, sBuf);
send(clientSockfd, sBuf, strlen(sBuf), 0); // 回应客户端请求 用填充后的sBuf
//开始播放,发送RTP包to Client
if (!strcmp(method, "PLAY")) {
int frameSize, startCode;
char* frame = (char*)malloc(500000);
struct RtpPacket* rtpPacket = (struct RtpPacket*)malloc(500000);
FILE* fp = fopen(H264_FILE_NAME, "rb"); // read binary
if (!fp) {
printf("读取 %s 失败\n", H264_FILE_NAME);
break;
}
// 正常顺序 1: version padding extension csrcLen; 2: payloadType; 3: seq; 4: timestamp; 5:ssrc; 6:csrc
rtpHeaderInit(rtpPacket, 0, 0, 0, RTP_VERSION, RTP_PAYLOAD_TYPE_H264, 0,
0, 0, 0x88923423);
printf("start play\n");
printf("client ip:%s\n", clientIP);
printf("client port:%d\n", client_Rtp_Port);
while (true) {
frameSize = getFrameFromH264File(fp, frame, 500000);
if (frameSize < 0)
{
printf("读取%s结束,frameSize=%d \n", H264_FILE_NAME, frameSize);
break;
}
if (startCode3(frame))
startCode = 3;
else
startCode = 4;
frameSize -= startCode;
rtpSendH264Frame(serverRtpSockfd, clientIP, client_Rtp_Port,
rtpPacket, frame + startCode, frameSize);
usleep(40000);
//usleep(40000);//1000/25 * 1000
}
free(frame);
free(rtpPacket);
break;
}
memset(method,0,sizeof(method)/sizeof(char));
memset(url,0,sizeof(url)/sizeof(char));
CSeq = 0;
}
closesocket(clientSockfd);
if (serverRtpSockfd) {
closesocket(serverRtpSockfd);
}
if (serverRtcpSockfd > 0) {
closesocket(serverRtcpSockfd);
}
free(rBuf);
free(sBuf);
}
int main(int argc, char* argv[])
{
int rtspServerSockfd;
rtspServerSockfd = createTcpSocket();
if (rtspServerSockfd < 0)
{
printf("failed to create tcp socket\n");
return -1;
}
if (bindSocketAddr(rtspServerSockfd, "0.0.0.0", SERVER_PORT) < 0)
{
printf("failed to bind addr\n");
return -1;
}
if (listen(rtspServerSockfd, 10) < 0)
{
printf("failed to listen\n");
return -1;
}
printf("%s rtsp://127.0.0.1:%d\n", __FILE__, SERVER_PORT);
while (true) {
int clientSockfd;
char clientIp[40];
int clientPort;
clientSockfd = acceptClient(rtspServerSockfd, clientIp, &clientPort);
if (clientSockfd < 0)
{
printf("failed to accept client\n");
return -1;
}
printf("accept client;client ip:%s,client port:%d\n", clientIp, clientPort);
doClient(clientSockfd, clientIp, clientPort);
}
closesocket(rtspServerSockfd);
return 0;
}
|