Blame view

src/gb28181/FFGB28181Decoder.cpp 13.4 KB
3d2ab595   Hu Chunming   支持gb28181
1
2
3
4
  //#include "LOG_manager.h"

  #include <iostream>

  #include "FFGB28181Decoder.h"

  

5686354a   Hu Chunming   初步编译成功cuvid部分的
5
  

3d2ab595   Hu Chunming   支持gb28181
6
7
8
9
10
11
12
  

  extern "C" {

  #include "libavutil/avstring.h"

  #include "libavformat/avformat.h"

  #include "libswscale/swscale.h"

  }

  

372e629f   ming   gb28181支持TCP数据流
13
14
15
  #include"RTPTcpReceiver.h"

  #include"RTPUdpReceiver.h"

  

92989af0   ming   更新解码器
16
17
18
19
  #include <cuda_runtime.h>

  

  #include "common_header.h"

  

5686354a   Hu Chunming   初步编译成功cuvid部分的
20
21
22
  #include "../nvdec/FFCuContextManager.h"

  #include "../nvdec/GpuRgbMemory.hpp"

  #include "../nvdec/cuda_kernels.h"

63e6f7bc   Hu Chunming   完成dvpp。但是nv和gb281...
23
  

3d2ab595   Hu Chunming   支持gb28181
24
25
26
27
28
29
30
  #define ECLOSED 0

  #define ECLOSING 1

  #define ERUNNING 2

  #define EPAUSE 3

  

  static void RTP_Stream_CallBack(void* userdata, int videoType, char* data, int len, int isKey, uint64_t pts, uint64_t localPts)

  {

372e629f   ming   gb28181支持TCP数据流
31
32
      FFGB28181Decoder* decoder = (FFGB28181Decoder*)userdata;

      decoder->stream_callback(videoType, data, len, isKey, pts, localPts);

3d2ab595   Hu Chunming   支持gb28181
33
34
35
36
  }

  

  static void RTP_Stream_End_CallBack(void* userdata)

  {

372e629f   ming   gb28181支持TCP数据流
37
38
      FFGB28181Decoder* decoder = (FFGB28181Decoder*)userdata;

      decoder->stream_end_callback();

3d2ab595   Hu Chunming   支持gb28181
39
40
41
42
43
44
  }

  

  FFGB28181Decoder::FFGB28181Decoder() {

  	m_frameSkip = 1;

      m_port = -1;

      m_dec_keyframe = false;

92989af0   ming   更新解码器
45
      m_post_decode_thread = 0;

3d2ab595   Hu Chunming   支持gb28181
46
47
48
49
50
51
52
53
54
55
56
  }

  

  FFGB28181Decoder::~FFGB28181Decoder()

  {

      close();

  	

      if (m_pAVCodecCtx) {

          avcodec_close(m_pAVCodecCtx);

          avcodec_free_context(&m_pAVCodecCtx);

      }

  

3d2ab595   Hu Chunming   支持gb28181
57
58
59
60
61
62
63
64
65
66
      m_dec_keyframe = false;

      

      LOG_INFO("destroy OK--{}", m_dec_name);

  }

  

  void FFGB28181Decoder::close(){

      if (m_status == ECLOSED || m_status == ECLOSING) return ;

      

      m_status = ECLOSING;

  

372e629f   ming   gb28181支持TCP数据流
67
68
69
70
71
72
73
      LOG_DEBUG("real decode thread exit success 1--{}", m_dec_name);

  

      if(nullptr != m_rtpPtr){

          if (m_rtpPtr->IsOpened()) {

              m_rtpPtr->Close();

              LOG_DEBUG("real decode thread exit success 2--{}", m_dec_name);

          }

3d2ab595   Hu Chunming   支持gb28181
74
  

372e629f   ming   gb28181支持TCP数据流
75
76
          delete m_rtpPtr;

          m_rtpPtr = nullptr;

3d2ab595   Hu Chunming   支持gb28181
77
78
      }

  

92989af0   ming   更新解码器
79
80
81
82
83
84
85
86
87
88
89
90
      if (gpu_options) av_dict_free(&gpu_options);

  

      if (m_post_decode_thread != 0)

  	{

  		pthread_join(m_post_decode_thread,0);

  	}

  

      while(mFrameQueue.size() > 0){

  		AVFrame * gpuFrame = mFrameQueue.front();

  		av_frame_free(&gpuFrame); 

  		mFrameQueue.pop();

  	}

3d2ab595   Hu Chunming   支持gb28181
91
92
  

      m_status = ECLOSED;

92989af0   ming   更新解码器
93
94
  

      LOG_INFO("解码器关闭成功 --{}", m_dec_name);

3d2ab595   Hu Chunming   支持gb28181
95
96
97
  }

  

  bool FFGB28181Decoder::init(FFDecConfig& cfg){

372e629f   ming   gb28181支持TCP数据流
98
99
100
101
102
103
      if(cfg.force_tcp){

          m_rtpPtr = new RTPTcpReceiver();

      }else{

          m_rtpPtr = new RTPUdpReceiver();

      }

      if(nullptr == m_rtpPtr){

3d2ab595   Hu Chunming   支持gb28181
104
105
106
107
108
109
110
111
112
          return false;

      }

  

      m_dec_name = cfg.uri;

  	m_frameSkip = cfg.skip_frame;

      if (m_frameSkip < 1) m_frameSkip = 1;

  

      m_gpuid = atoi(cfg.gpuid.c_str());

  

372e629f   ming   gb28181支持TCP数据流
113
114
115
116
117
118
119
120
121
122
      m_rtpPtr->SetDeviceID(m_dec_name);

  

      if(cfg.request_stream_cbk == nullptr){

          LOG_INFO("request_stream_cbk 为 nullptr -- {}", m_dec_name);

          return false;

      }

  

      post_decoded_cbk = cfg.post_decoded_cbk;

      decode_finished_cbk = cfg.decode_finished_cbk;

      m_rtpPtr->SetRequestStreamCallback(cfg.request_stream_cbk);

3d2ab595   Hu Chunming   支持gb28181
123
124
125
126
127
  

      m_port = cfg.port;

  

      m_cfg = cfg;

  

372e629f   ming   gb28181支持TCP数据流
128
129
      LOG_INFO("init - {} : ", m_dec_name, m_port);

  

3d2ab595   Hu Chunming   支持gb28181
130
131
132
133
134
135
136
      return true;

  }

  

  bool FFGB28181Decoder::start() {

  

      m_status = ERUNNING;

  

372e629f   ming   gb28181支持TCP数据流
137
138
  	m_rtpPtr->SetOutputCallback(RTP_Stream_CallBack, this);

  	m_rtpPtr->SetVodEndCallback(RTP_Stream_End_CallBack, this);

3d2ab595   Hu Chunming   支持gb28181
139
  

372e629f   ming   gb28181支持TCP数据流
140
141
      LOG_INFO("start - {} {}: ", m_dec_name, m_port);

  

92989af0   ming   更新解码器
142
143
144
145
146
147
148
149
150
151
152
153
      bool bRet = m_rtpPtr->Open((uint16_t)m_port);

      if(bRet){

          pthread_create(&m_post_decode_thread,0,

              [](void* arg)

              {

                  FFGB28181Decoder* a=(FFGB28181Decoder*)arg;

                  a->post_decode_thread();

                  return (void*)0;

              }

          ,this);

      }

      return bRet;

3d2ab595   Hu Chunming   支持gb28181
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
  }

  

  void FFGB28181Decoder::setDecKeyframe(bool bKeyframe){

  	m_dec_keyframe = bKeyframe;

  }

  

  static AVPixelFormat get_hw_format(AVCodecContext *avctx, const AVPixelFormat *pix_fmts){

  	return AV_PIX_FMT_CUDA;

  }

  

  void FFGB28181Decoder::stream_callback(int videoType, char* data, int len, int isKey, uint64_t pts, uint64_t localPts) {

      if (m_status == EPAUSE) return;

  

      // 若设置为关键帧解码,非关键帧数据直接返回

      if(m_dec_keyframe && !isKey) return;

      

      if (len <= 0) {

          if (data == nullptr && pts == -1) {

              LOG_INFO("frame callback EOF!");

  			post_decoded_cbk(m_postDecArg, nullptr);

              return ;

          }

          LOG_INFO("frame data is zero --{}", m_dec_name);

          return;

      }

  

ecb0badb   ming   保存jpg图片
180
181
      AVPacket* pkt = av_packet_alloc();

  	av_init_packet(pkt);

3d2ab595   Hu Chunming   支持gb28181
182
  

ecb0badb   ming   保存jpg图片
183
184
      pkt->size = len;

      pkt->data = (uint8_t*)data;

3d2ab595   Hu Chunming   支持gb28181
185
  

3d2ab595   Hu Chunming   支持gb28181
186
  	if (m_pAVCodecCtx == nullptr) {

372e629f   ming   gb28181支持TCP数据流
187
          LOG_INFO("frame data is zero --{}", m_dec_name);

3d2ab595   Hu Chunming   支持gb28181
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
  		if (VIDEO_TYPE_H264 == videoType) {

              if (m_gpuid >= 0){

                  m_pAVCodec = avcodec_find_decoder_by_name("h264_cuvid");

              }

              else{

  				m_pAVCodec = avcodec_find_decoder(AV_CODEC_ID_H264);

  			}

  			LOG_INFO("m_avCodecName is H264");		

  		}

  		else if (VIDEO_TYPE_H265 == videoType)

  		{

              if (m_gpuid >= 0){

                  m_pAVCodec = avcodec_find_decoder_by_name("hevc_cuvid");

              }

              else{

                  m_pAVCodec = avcodec_find_decoder(AV_CODEC_ID_H265);

              }

  			LOG_INFO("m_avCodecName is H265");

  		}

  		else{

  			LOG_INFO("m_avCodecName is unknown, videoType is {}", videoType);

  		}

  

  		if (!m_pAVCodec)

  		{

  			LOG_ERROR("frameCallback frame decode error, ERROR_DECODER_NOT_FOUND");

  			return;

  		}

  

          m_pAVCodecCtx = avcodec_alloc_context3(m_pAVCodec);

3d2ab595   Hu Chunming   支持gb28181
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
  

          if (m_gpuid >= 0) {

              char gpui[8] = { 0 };

              sprintf(gpui, "%d", m_gpuid);

              av_dict_set(&gpu_options, "gpu", gpui, 0);

  

              m_pAVCodecCtx->get_format = get_hw_format;

  

              FFCuContextManager* pCtxMgr = FFCuContextManager::getInstance();

              m_pAVCodecCtx->hw_device_ctx = av_buffer_ref(pCtxMgr->getCuCtx(gpui));

              if (nullptr == m_pAVCodecCtx->hw_device_ctx){

                  // TODO 这里应该抛出错误

                  return ;

              }

          }

  

          if (avcodec_open2(m_pAVCodecCtx, m_pAVCodec, &gpu_options) < 0)

  			return;

3d2ab595   Hu Chunming   支持gb28181
236
237
238
  	}

  

      //开始解码

ecb0badb   ming   保存jpg图片
239
      int ret = avcodec_send_packet(m_pAVCodecCtx, pkt);

3d2ab595   Hu Chunming   支持gb28181
240
241
242
      if (ret < 0) {

          //send_exception(RunMessageType::E2002, e_msg);

          LOG_ERROR("Real stream视频解码失败,请检查视频设备{}: avcodec_send_packet failed. ret={}", m_dec_name, ret);

ecb0badb   ming   保存jpg图片
243
244
          av_packet_free(&pkt);

          pkt = nullptr;

3d2ab595   Hu Chunming   支持gb28181
245
246
247
248
249
250
251
252
          return;

      }

   

      if (frameW < 1) {

          frameW = m_pAVCodecCtx->width;

          frameH = m_pAVCodecCtx->height;

          if (frameW <= 0 || frameH <= 0) {

              LOG_ERROR("[{}] frame W or H is error! ({},{})", m_dec_name, frameW, frameH);

ecb0badb   ming   保存jpg图片
253
254
              av_packet_free(&pkt);

              pkt = nullptr;

3d2ab595   Hu Chunming   支持gb28181
255
256
257
258
259
              return;

          }	

      }

  	// m_fps = m_pAVCodecCtx->pkt_timebase.den == 0 ? 25.0 : av_q2d(m_pAVCodecCtx->pkt_timebase);

      m_fps = av_q2d(m_pAVCodecCtx->framerate);

92989af0   ming   更新解码器
260
261
262
263
264
265
  	// LOG_DEBUG("frameW {}--frameH {}", frameW, frameH);

  

      AVFrame* gpuFrame = av_frame_alloc();

      ret = avcodec_receive_frame(m_pAVCodecCtx, gpuFrame);

      if ((ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) || ret < 0){

          LOG_ERROR("{} - Failed to receive frame: {}", m_dec_name, ret);

ecb0badb   ming   保存jpg图片
266
267
          av_packet_free(&pkt);

          pkt = nullptr;

92989af0   ming   更新解码器
268
          av_frame_free(&gpuFrame);

ecb0badb   ming   保存jpg图片
269
          gpuFrame = nullptr;

92989af0   ming   更新解码器
270
271
          return;

      }

3d2ab595   Hu Chunming   支持gb28181
272
  

ecb0badb   ming   保存jpg图片
273
274
      av_packet_free(&pkt);

      pkt = nullptr;

92989af0   ming   更新解码器
275
276
277
278
      

      if (gpuFrame->width != frameW || gpuFrame->height != frameH){

          LOG_INFO("AVFrame is inconsistent: width is {}, height is {}; original frameW is {}, frameH is {}--{}", gpuFrame->width, gpuFrame->height, frameW, frameH , m_dec_name);

          av_frame_free(&gpuFrame);

ecb0badb   ming   保存jpg图片
279
          gpuFrame = nullptr;

92989af0   ming   更新解码器
280
281
282
283
284
285
286
287
          return;

      }

  

      m_queue_mutex.lock();

      if(mFrameQueue.size() <= 10){

          mFrameQueue.push(gpuFrame);

      }else{

          av_frame_free(&gpuFrame); 

ecb0badb   ming   保存jpg图片
288
          gpuFrame = nullptr;

3d2ab595   Hu Chunming   支持gb28181
289
      }

92989af0   ming   更新解码器
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
      m_queue_mutex.unlock();

  }

  

  void FFGB28181Decoder::post_decode_thread(){

  	

  	int index = 0;

  	while (isRunning())

  	{

  		if(mFrameQueue.size() > 0){

  			std::lock_guard<std::mutex> l(m_snapshot_mutex);

  			// 取队头数据

  			m_queue_mutex.lock();

  			AVFrame * gpuFrame = mFrameQueue.front();

  			mFrameQueue.pop();

  			m_queue_mutex.unlock();

  			// 跳帧

  			if (m_frameSkip == 1 || index % m_frameSkip == 0){

00b0fbdb   Hu Chunming   编译nvdec
307
  				post_decoded_cbk(m_postDecArg, convert2bgr(gpuFrame));

92989af0   ming   更新解码器
308
309
310
  			}

  

  			av_frame_free(&gpuFrame); 

ecb0badb   ming   保存jpg图片
311
              gpuFrame = nullptr;

92989af0   ming   更新解码器
312
313
314
315
316
317
318
  

  			index++;

              if(index >= 100000){

                  index = 0;

              }

  		}

  	}

3d2ab595   Hu Chunming   支持gb28181
319
  

92989af0   ming   更新解码器
320
  	LOG_INFO("post decode thread exited.");

3d2ab595   Hu Chunming   支持gb28181
321
322
323
324
325
326
327
328
329
330
331
  }

  

  void FFGB28181Decoder::stream_end_callback()

  {

      LOG_INFO("send_video_eof--{}", m_dec_name);

  

  	decode_finished_cbk(m_finishedDecArg);

  

      return;

  }

  

00b0fbdb   Hu Chunming   编译nvdec
332
333
334
335
336
337
338
339
  void FFGB28181Decoder::setPostDecArg(const void* postDecArg){

  	m_postDecArg = postDecArg;

  }

  

  void FFGB28181Decoder::setFinishedDecArg(const void* finishedDecArg){

  	m_finishedDecArg = finishedDecArg;

  }

  

3d2ab595   Hu Chunming   支持gb28181
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
  void FFGB28181Decoder::pause() {

      m_status = EPAUSE;

      LOG_INFO("pause --{}", m_dec_name);

  }

  

  void FFGB28181Decoder::resume() {

      m_status = ERUNNING;

      LOG_INFO("resume --{}", m_dec_name);

  }

  

  bool FFGB28181Decoder::isRunning(){

      if (m_status == ECLOSED || m_status == ECLOSING){

          return false;

      }

      return true;

  }

  

  bool FFGB28181Decoder::isFinished(){

      if (m_status == ECLOSED || m_status == ECLOSING){

          return true;

      }

      return false;

  }

  

  bool FFGB28181Decoder::isPausing(){

      if (m_status == EPAUSE){

          return true;

      }

      return false;

  }

  

  bool FFGB28181Decoder::getResolution( int &width, int &height ){

      width = frameW;

      height = frameH;

      return true;

  }

  

  float FFGB28181Decoder::fps() {

      return m_fps;

  }

  

  bool FFGB28181Decoder::isSurport(FFDecConfig& cfg){

      // 由于是否支持需要在拿到数据后才能断定,无法事先判断,所以这个地方默认返回true

      return true;

  }

  

  int FFGB28181Decoder::getCachedQueueLength(){

372e629f   ming   gb28181支持TCP数据流
387
      return m_rtpPtr->GetPsFrameListSize();

63e6f7bc   Hu Chunming   完成dvpp。但是nv和gb281...
388
389
  }

  

00b0fbdb   Hu Chunming   编译nvdec
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
  DeviceRgbMemory* FFGB28181Decoder::convert2bgr(AVFrame * gpuFrame){

  	if (gpuFrame != nullptr && gpuFrame->format == AV_PIX_FMT_CUDA ){

  		LOG_DEBUG("decode task: gpuid: {}  width: {} height: {}", m_cfg.gpuid, gpuFrame->width, gpuFrame->height);

  		GpuRgbMemory* gpuMem = new GpuRgbMemory(3, gpuFrame->width, gpuFrame->height, getName(), m_cfg.gpuid, false, true);

  

  		do{

  			if (gpuMem->getMem() == nullptr){

  				LOG_ERROR("new GpuRgbMemory failed !!!");

  				break;

  			}

  			

  			cudaSetDevice(atoi(m_cfg.gpuid.c_str()));

  			cuda_common::setColorSpace( ITU_709, 0 );

  			cudaError_t cudaStatus = cuda_common::CUDAToBGR((CUdeviceptr)gpuFrame->data[0],(CUdeviceptr)gpuFrame->data[1], gpuFrame->linesize[0], gpuFrame->linesize[1], gpuMem->getMem(), gpuFrame->width, gpuFrame->height);

  			cudaDeviceSynchronize();

  			if (cudaStatus != cudaSuccess) {

  				LOG_ERROR("CUDAToBGR failed failed !!!");

  				break;

  			}

  

  			return gpuMem;

  		}while(0);

  

  		delete gpuMem;

  		gpuMem = nullptr;

  	}

  

  	return nullptr;

  }

  

63e6f7bc   Hu Chunming   完成dvpp。但是nv和gb281...
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
  FFImgInfo* FFGB28181Decoder::snapshot(){

  

  	// 锁住停止队列消耗

  	std::lock_guard<std::mutex> l(m_snapshot_mutex);

  

  	AVFrame * gpuFrame = nullptr;

  

  	bool bFirst = true;

  	while(true){

  		m_queue_mutex.lock();

  		if(mFrameQueue.size() <= 0){

  			m_queue_mutex.unlock();

  			if(bFirst){

  				std::this_thread::sleep_for(std::chrono::milliseconds(100));

  				bFirst = false;

  				continue;

  			}else{

  				// 再进来说明前面已经等了 100 ms

  				// 100 ms都没有等到解码数据,则退出

  				return nullptr;

  			}

  		}

  

  		// 队列中数据大于1 

  		gpuFrame = mFrameQueue.front();

  		m_queue_mutex.unlock();

  		break;

  	}

  

  	if (gpuFrame != nullptr && gpuFrame->format == AV_PIX_FMT_CUDA ){

  		LOG_DEBUG("decode task: gpuid: {}  width: {} height: {}", m_cfg.gpuid, gpuFrame->width, gpuFrame->height);

00b0fbdb   Hu Chunming   编译nvdec
451
  		GpuRgbMemory* gpuMem = new GpuRgbMemory(3, gpuFrame->width, gpuFrame->height, getName(), m_cfg.gpuid , false, true);

63e6f7bc   Hu Chunming   完成dvpp。但是nv和gb281...
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
  

  		if (gpuMem->getMem() == nullptr){

  			LOG_ERROR("new GpuRgbMemory failed !!!");

  			return nullptr;

  		}

  		

  		cudaSetDevice(atoi(m_cfg.gpuid.c_str()));

  		cuda_common::setColorSpace( ITU_709, 0 );

  		cudaError_t cudaStatus = cuda_common::CUDAToBGR((CUdeviceptr)gpuFrame->data[0],(CUdeviceptr)gpuFrame->data[1], gpuFrame->linesize[0], gpuFrame->linesize[1], gpuMem->getMem(), gpuFrame->width, gpuFrame->height);

  		cudaDeviceSynchronize();

  		if (cudaStatus != cudaSuccess) {

  			LOG_ERROR("CUDAToBGR failed failed !!!");

  			return nullptr;

  		}

  

  		unsigned char * pHwRgb = gpuMem->getMem();

  		int channel = gpuMem->getChannel();

  		int width = gpuMem->getWidth();

  		int height = gpuMem->getHeight();

  

  		if (pHwRgb != nullptr && channel > 0 && width > 0 && height > 0){

  			int nSize = channel * height * width;

  

  			LOG_INFO("channel:{} height:{} width:{}", channel, height, width);

  			// unsigned char* cpu_data = new unsigned char[nSize];

  

              unsigned char* cpu_data = (unsigned char *)av_malloc(nSize * sizeof(unsigned char));

  

  			cudaMemcpy(cpu_data, pHwRgb, nSize * sizeof(unsigned char), cudaMemcpyDeviceToHost);

  			cudaDeviceSynchronize();

  

  			delete gpuMem;

  			gpuMem = nullptr;

  

  			FFImgInfo* imgInfo = new FFImgInfo();

  			imgInfo->dec_name = m_dec_name;

  			imgInfo->pData = cpu_data;

  			imgInfo->height = height;

  			imgInfo->width = width;

  			imgInfo->timestamp = UtilTools::get_cur_time_ms();

  			imgInfo->index = m_index;

  

  			m_index++;

  

  			return imgInfo;

  		}

  

  		delete gpuMem;

  		gpuMem = nullptr;

  	}

  

  	return nullptr;

3d2ab595   Hu Chunming   支持gb28181
504
  }