Blame view

src/gb28181/RTPTcpReceiver.cpp 9.02 KB
372e629f   ming   gb28181支持TCP数据流
1
  #include"RTPTcpReceiver.h"
372e629f   ming   gb28181支持TCP数据流
2
  
92989af0   ming   更新解码器
3
  #include "common_header.h"
372e629f   ming   gb28181支持TCP数据流
4
  
372e629f   ming   gb28181支持TCP数据流
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
  
  // class TcpRTPSession : public RTPSession
  // {
  // public:
  //     void setReceiver(RTPTcpReceiver* r){
  //         tcpReceiver = r;
  //     }
  
  // protected:
  // 	void OnValidatedRTPPacket(RTPSourceData *srcdat, RTPPacket *rtppack, bool isonprobation, bool *ispackethandled)
  // 	{
  // 		// printf("SSRC %x Got packet (%d bytes) in OnValidatedRTPPacket from source 0x%04x!\n", GetLocalSSRC(), 
  // 		// 	   (int)rtppack->GetPayloadLength(), srcdat->GetSSRC());
  
  //         LOG_DEBUG("SSRC {} Got packet ({} bytes) in OnValidatedRTPPacket from source {}}!\n", GetLocalSSRC(), 
  // 			   (int)rtppack->GetPayloadLength(), srcdat->GetSSRC());
  
  //         if(nullptr != tcpReceiver){
  //             tcpReceiver->ParsePacket(rtppack);
  //         }
  // 		DeletePacket(rtppack);
  // 		*ispackethandled = true;
  // 	}
  
  // 	void OnRTCPSDESItem(RTPSourceData *srcdat, RTCPSDESPacket::ItemType t, const void *itemdata, size_t itemlength)
  // 	{
  // 		char msg[1024];
  
  // 		memset(msg, 0, sizeof(msg));
  // 		if (itemlength >= sizeof(msg))
  // 			itemlength = sizeof(msg)-1;
  
  // 		memcpy(msg, itemdata, itemlength);
  // 		// printf("SSRC %x Received SDES item (%d): %s from SSRC %x\n", GetLocalSSRC(), (int)t, msg, srcdat->GetSSRC());
  //         LOG_DEBUG("SSRC {} Received SDES item ({}): {} from SSRC {}\n", GetLocalSSRC(), (int)t, msg, srcdat->GetSSRC());
  // 	}
  
  // private:
  //     RTPTcpReceiver* tcpReceiver{nullptr};
  // };
  
  class MyTCPTransmitter : public RTPTCPTransmitter
  {
  public:
      void setReceiver(RTPTcpReceiver* r){
          tcpReceiver = r;
      }
  
  public:
  	MyTCPTransmitter() : RTPTCPTransmitter(0){ }
  
  	void OnSendError(SocketType sock)
  	{
          LOG_ERROR("Error sending over socket {}, removing destination", sock);
  		DeleteDestination(RTPTCPAddress(sock));
          if(nullptr != tcpReceiver && !tcpReceiver->isClosing()){
92989af0   ming   更新解码器
61
              tcpReceiver->ReConnect();
372e629f   ming   gb28181支持TCP数据流
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
          }
  	}
  	
  	void OnReceiveError(SocketType sock)
  	{
          LOG_ERROR("Error receiving over socket {}, removing destination", sock);
  		DeleteDestination(RTPTCPAddress(sock));
  	}
  
  private:
      RTPTcpReceiver* tcpReceiver{nullptr};
  };
  
  static int rtp_revc_thread_(void* param)
  {
  	if (!param)
  	{
  		return -1;
  	}
  
  	RTPTcpReceiver* self = (RTPTcpReceiver*)param;
  	return self->OnRtpRecv();
  }
  
92989af0   ming   更新解码器
86
87
88
89
90
91
92
93
94
95
  static int listen_finish_thread_(void* param)
  {
  	if (!param)
  	{
  		return -1;
  	}
  
  	RTPTcpReceiver* self = (RTPTcpReceiver*)param;
  	return self->ListenFinish();
  }
372e629f   ming   gb28181支持TCP数据流
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
  
  RTPTcpReceiver::RTPTcpReceiver()
  : m_bRtpExit(false)
  , m_bOpened(false)
  , m_idleCount(-1)
  , m_noDataCount(-1)
  , m_nListener(-1)
  , m_bAccepted(false)
  , m_bClosing(false)
  {
      m_rtpSessionPtr = new RTPSession();
      m_pSessparams = new RTPSessionParams();
      m_pTrans = new MyTCPTransmitter();
  }
  
  RTPTcpReceiver::~RTPTcpReceiver(){
      if (IsOpened())
  		Close();
  
      if(m_rtpSessionPtr != nullptr){
          delete m_rtpSessionPtr;
          m_rtpSessionPtr = nullptr;
      }
  
      if(m_pSessparams != nullptr){
          delete m_pSessparams;
          m_pSessparams = nullptr;
      }
  
      if(m_pTrans != nullptr){
          delete m_pTrans;
          m_pTrans = nullptr;
      }
  }
  
  bool RTPTcpReceiver::Open(uint16_t localPort){
      if(0 != initSession(localPort)){
          return false;
      }
      
      m_bOpened = true;
  
      LOG_INFO("[{}] started.", m_deviceID);
  
      return true;
  }
  
  bool RTPTcpReceiver::IsOpened(){
      LOG_INFO("[{}] isopng:{} ", m_deviceID, m_bOpened);
      return m_bOpened;
  }
  
  void RTPTcpReceiver::Close(){
92989af0   ming   更新解码器
149
150
151
152
153
154
155
156
157
      m_bRtpExit = true;
  
      if(m_listenFinishThread.joinable()){
          m_listenFinishThread.join();
      }
  }
  
  void RTPTcpReceiver::close_task(){
      m_bRtpExit = true;
372e629f   ming   gb28181支持TCP数据流
158
159
160
161
  
      m_bClosing = true;
  
      m_bAccepted = true;
372e629f   ming   gb28181支持TCP数据流
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
  
      LOG_DEBUG("[{}] 1.", m_deviceID);
      
      // rtp接收线程退出
      if (m_rtpThread.joinable())
      {
          m_rtpThread.join();
      }
  
      LOG_DEBUG("[{}] 2.", m_deviceID);
  
  	ClosePsThread();
  
      m_bOpened = false;
      
      LOG_INFO("[{}] closed.", m_deviceID);
  }
  
  bool RTPTcpReceiver::isClosing(){
      return m_bClosing;
  }
  
  int RTPTcpReceiver::initSession(int localPort){
      m_nListener = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
  	if (m_nListener < 0)
  	{
  		return  -1;
  	}
   
  	sockaddr_in   serverAddr;
  	memset(&serverAddr, 0, sizeof(sockaddr_in));
  	serverAddr.sin_family = AF_INET;
  	serverAddr.sin_port = htons(localPort);
  	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  	int  nRet = bind(m_nListener, (sockaddr*)&serverAddr, sizeof(serverAddr));
  	if (nRet == -1)
  	{
          LOG_ERROR("[{}] 绑定端口失败: {}", m_deviceID, localPort);
  		return  -1;
  	}
  
  	if (listen(m_nListener, 1) == -1)
  	{
          LOG_ERROR("[{}] listen 失败", m_deviceID);
  		return  -1;
  	}
  
  	int  nPackSize = 45678;
  	m_pSessparams->SetProbationType(RTPSources::NoProbation);
  	m_pSessparams->SetOwnTimestampUnit(90000.0 / 25.0);
  	m_pSessparams->SetMaximumPacketSize(nPackSize + 64);
  
  	int status = m_pTrans->Init(false);
  	status = m_pTrans->Create(65535, NULL);
      m_pTrans->setReceiver(this);
  
  	status = m_rtpSessionPtr->Create(*m_pSessparams, m_pTrans);
  	if (status < 0)
  	{
92989af0   ming   更新解码器
221
222
          // status = -59 ,需运行 export LOGNAME=root ,见 https://blog.csdn.net/m0_37876242/article/details/128588162
          LOG_ERROR("[{}] create session error: {}", m_deviceID, status);
372e629f   ming   gb28181支持TCP数据流
223
224
225
226
  		return -1;
  	}
  
      m_rtpThread = std::thread(rtp_revc_thread_, this);
92989af0   ming   更新解码器
227
      m_listenFinishThread = std::thread(listen_finish_thread_, this);
372e629f   ming   gb28181支持TCP数据流
228
229
230
  
      InitPS();
  
92989af0   ming   更新解码器
231
232
233
234
235
236
      // bool bRet = RequestStream();
      // if (!bRet)
      // {
      //     LOG_INFO("[{}] 请求流失败!", m_deviceID);
      //     return -1;
      // }
372e629f   ming   gb28181支持TCP数据流
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
  
      LOG_INFO("[{}] 初始化成功, congratulations !!!", m_deviceID);
  
      return 0;
  }
  
  int RTPTcpReceiver::OnRtpRecv()
  {
      if(nullptr == m_rtpSessionPtr){
          return -1;
      }
  
      LOG_INFO("[{}] OnRtpRecv started, m_nListener : {}", m_deviceID, m_nListener);
  
      sockaddr_in   clientAddr;
  	int  nLen = sizeof(sockaddr_in);
  	SocketType nServer = -1;
      
      LOG_INFO("[{}] Poll started.", m_deviceID);
92989af0   ming   更新解码器
256
257
258
      int reconn_times = 0;
      int reaccept_times = 0;
      bool bReconn = false;
372e629f   ming   gb28181支持TCP数据流
259
260
      while(!m_bRtpExit){
          while(!m_bAccepted){
92989af0   ming   更新解码器
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
              if(m_bRtpExit){
                  goto end_flag;
              }
              
              while (!bReconn){
                  if(m_bRtpExit){
                      goto end_flag;
                  }
  
                  reconn_times++;
                  if(reconn_times > 10){
                      // 10次请求都失败,结束任务
                      m_bRtpExit = true;
                      goto end_flag;
                  }
                  LOG_DEBUG("[{}] RequestStream...", m_deviceID);
                  bReconn = RequestStream();
                  if (bReconn){
                      LOG_DEBUG("[{}] RequestStream, True", m_deviceID);
                     continue;
                  }
                  LOG_DEBUG("[{}] RequestStream, False", m_deviceID);
                  
                  std::this_thread::sleep_for(std::chrono::seconds(3));
              }
              
372e629f   ming   gb28181支持TCP数据流
287
288
289
              LOG_DEBUG("[{}] accepting...", m_deviceID);
              nServer = accept(m_nListener, (sockaddr*)&clientAddr, (socklen_t * ) &nLen);
              if (-1 == nServer){
92989af0   ming   更新解码器
290
291
292
293
294
295
296
297
                  reaccept_times++;
                  LOG_DEBUG("[{}] reaccept_times =  {}", m_deviceID, reaccept_times);
                  if(reaccept_times > 600){
                      LOG_DEBUG("[{}] reaccept_times > 600", m_deviceID);
                      bReconn = false;
                      reaccept_times = 0;
                  }
                  std::this_thread::sleep_for(std::chrono::milliseconds(50));
372e629f   ming   gb28181支持TCP数据流
298
299
                  continue;
              }
92989af0   ming   更新解码器
300
              LOG_DEBUG("[{}] accept success", m_deviceID);
372e629f   ming   gb28181支持TCP数据流
301
302
              m_rtpSessionPtr->AddDestination(RTPTCPAddress(nServer));
              m_bAccepted = true;
92989af0   ming   更新解码器
303
304
305
              bReconn = false;
              reconn_times = 0;
              reaccept_times = 0;
372e629f   ming   gb28181支持TCP数据流
306
307
308
309
310
311
312
313
314
315
316
317
318
319
  
              LOG_INFO("[{}] nServer={}", m_deviceID, nServer);
              break;
          }
  
          m_rtpSessionPtr->BeginDataAccess();
          if (m_rtpSessionPtr->GotoFirstSourceWithData())
          {
              do
              {
                  RTPPacket *pack;
                  
                  while ((pack = m_rtpSessionPtr->GetNextPacket()) != NULL)
                  {
92989af0   ming   更新解码器
320
                      // LOG_DEBUG("[{}] time: {} ", m_deviceID, UtilTools::get_cur_time_ms());
372e629f   ming   gb28181支持TCP数据流
321
322
323
324
325
326
327
328
329
330
331
332
333
                      ParsePacket(pack);
                      
                      m_rtpSessionPtr->DeletePacket(pack);
                  }
              } while (m_rtpSessionPtr->GotoNextSourceWithData());
          }
          
          m_rtpSessionPtr->EndDataAccess();
  
          m_rtpSessionPtr->Poll();
  		std::this_thread::sleep_for(std::chrono::milliseconds(10));
      }
  
92989af0   ming   更新解码器
334
335
  end_flag:
  
372e629f   ming   gb28181支持TCP数据流
336
337
338
339
340
341
342
343
344
345
346
347
348
349
      m_rtpSessionPtr->Destroy();
  
      if(nServer > 0){
          close(nServer);
      }
      if(m_nListener > 0){
          close(m_nListener);
      }
  
      LOG_INFO("[{}] OnRtpRecv exited.", m_deviceID);
  
      return 0;
  }
  
92989af0   ming   更新解码器
350
351
352
  int RTPTcpReceiver::ListenFinish(){
      while(!m_bRtpExit){
          std::this_thread::sleep_for(std::chrono::seconds(3));
372e629f   ming   gb28181支持TCP数据流
353
      }
92989af0   ming   更新解码器
354
355
356
357
358
  
      close_task();
  }
  
  bool RTPTcpReceiver::ReConnect(){
372e629f   ming   gb28181支持TCP数据流
359
      m_bAccepted = false;
92989af0   ming   更新解码器
360
  }
372e629f   ming   gb28181支持TCP数据流
361
  
92989af0   ming   更新解码器
362
363
  bool RTPTcpReceiver::RequestStream(){
      return m_callback_request_stream(m_deviceID.c_str());
372e629f   ming   gb28181支持TCP数据流
364
  }