main_dvpp.cpp 15.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 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
#include <iostream>
#include <pthread.h>
#include <thread>
#include <chrono>
#include <unistd.h>

#include "FFSaveImg.h"

#ifdef _WIN32
#include "Winsock2.h"
#pragma comment(lib, "ws2_32.lib")
#endif

#ifdef __linux__
#include "arpa/inet.h"
#endif

#include "../interface/FFNvDecoderManager.h"
#include "../interface/utiltools.hpp"

#include "curl/curl.h"


#define MIN_RTP_PORT		10000
#define MAX_RTP_PORT		60000

// ȡ MIN_RTP_PORT(10000)~MAX_RTP_PORT(60000)֮�������˿�(ż���������������˿ڿ���)
int allocRtpPort() {

	static int s_rtpPort = MIN_RTP_PORT;
	if (MIN_RTP_PORT == s_rtpPort)
	{
		srand((unsigned int)time(NULL));
		s_rtpPort = MIN_RTP_PORT + (rand() % MIN_RTP_PORT);
	}

	if (s_rtpPort % 2)
		++s_rtpPort;

	while (true)
	{
		s_rtpPort += 2;
		s_rtpPort = s_rtpPort >= MAX_RTP_PORT ? MIN_RTP_PORT : s_rtpPort;

		int i = 0;
		for (; i < 2; i++)
		{
			sockaddr_in sRecvAddr;
			int s = socket(AF_INET, SOCK_DGRAM, 0);

			sRecvAddr.sin_family = AF_INET;        
			sRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);    
			sRecvAddr.sin_port = htons(s_rtpPort + i); 

			int nResult = bind(s, (sockaddr *)&sRecvAddr, sizeof(sRecvAddr));
			if (nResult != 0)
			{
				break;
			}

			nResult = close(s);
			if (nResult != 0)
			{
				printf("closesocket failed:%d\n", nResult);
				break;
			}
		}

		if (i == 2)
			break;
	}

	return s_rtpPort;
}





unsigned char *pHwRgb[2] = {nullptr, nullptr};

int sum1 = 0;
int sum2 = 0;


string data_home = "/mnt/data/cmhu/tmp/";




static long get_cur_time_ms() {
    chrono::time_point<chrono::system_clock, chrono::milliseconds> tpMicro
        = chrono::time_point_cast<chrono::milliseconds>(chrono::system_clock::now());
    return tpMicro.time_since_epoch().count();
}

/**
 * 注意: gpuFrame 在解码器设置的显卡上,后续操作要十分注意这一点,尤其是多线程情况
 * */
void postDecoded(const void * userPtr, DeviceRgbMemory* devFrame){
    AbstractDecoder* decoder = (AbstractDecoder*)userPtr;
    if (decoder!= nullptr)
    {
    }

    if(devFrame){
        delete devFrame;
        devFrame = nullptr;
    }
}

long start_time = 0;
long end_time = 0;
bool count_flag = false;
int count = 0;
int count_std = 100;


static int sum = 0;
unsigned char *pHwData = nullptr;

void postDecoded0(const void * userPtr, DeviceRgbMemory* devFrame){
    // std::this_thread::sleep_for(std::chrono::milliseconds(30000));

    AbstractDecoder* decoder = (AbstractDecoder*)userPtr;
    if (decoder!= nullptr)
    {
        // cout << "decode name: " << decoder->getName() << endl;
        if (decoder->getName() == "dec")
        {
            if (! count_flag)
            {
                count_flag = true;
                count = 0;
                end_time = start_time = UtilTools::get_cur_time_ms();
            }
            count++;
            sum ++ ;
            if (count >= count_std)
            {
                // end_time = UtilTools::get_cur_time_ms();
                // long time_using = end_time - start_time;
                // double time_per_frame = double(time_using)/count_std ;
                // cout << count_std << "帧用时:" << time_using << "ms 每帧用时:" << time_per_frame << "ms" << endl;
                cout << decoder->getName() << " keyframe: " << devFrame->isKeyFrame() << " width: " << devFrame->getWidth() << " height: "<< devFrame->getHeight() << endl;
                // cout << gpuFrame->pts << endl;

                count_flag = false;
            }
            // cout << "帧数:" << sum << endl;
        }
    }
}

//get请求和post请求数据响应函数
size_t req_reply(void *ptr, size_t size, size_t nmemb, void *stream)
{ 
	//在注释的里面可以打印请求流,cookie的信息
	//cout << "----->reply" << endl;
	string *str = (string*)stream;
	//cout << *str << endl;
	(*str).append((char*)ptr, size*nmemb);
	return size * nmemb;
}

//http POST请求 
CURLcode curl_post_body_getVideoRealStream(const string &url, const string &postParams, string &response, string devid, string ip, string port)
{ 
	// curl初始化 
	CURL *curl = curl_easy_init();
	// curl返回值 
	CURLcode res;
	if (curl)
	{ 
		// set params
		//设置curl的请求头
		struct curl_slist* header_list = NULL;
		header_list = curl_slist_append(header_list, "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
		// header_list = curl_slist_append(header_list, "Content-Type:application/x-www-form-urlencoded; charset=UTF-8");

        header_list = curl_slist_append(header_list, "Accept: application/json");
        header_list = curl_slist_append(header_list, "Content-Type: application/json");//text/html
        header_list = curl_slist_append(header_list, "charsets: utf-8");

		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);

		//不接收响应头数据0代表不接收 1代表接收
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);

		//设置请求为post请求
		// curl_easy_setopt(curl, CURLOPT_POST, 1);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");

		//设置请求的URL地址
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		//设置post请求的参数
		// curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str());

		//设置ssl验证
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

		//CURLOPT_VERBOSE的值为1时,会显示详细的调试信息
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);

        string strResult = "{ \
                            \"authinfo\": \"hisense|hisense123|201807311630\", \
                            \"method\": \"getVideoRealStream\", \
                            \"deviceId\": \""+devid+"\", \
                            \"streamFormat\": \"0\", \
                            \"recvIp\": \""+ip+"\", \
                            \"recvPort\": \""+port+"\", \
                            \"remark\": \"\", \
                            \"protocol\": \"1\" \
                        }";

        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,strResult.c_str());

		curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);

		//设置数据接收和写入函数
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);

		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

		//设置超时时间
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 6);
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 6);

		// 开启post请求
		res = curl_easy_perform(curl);
	}
	//释放curl 
	curl_easy_cleanup(curl);
	return res;
}

//http POST请求 
CURLcode curl_post_body_stopVideoRealStream(const string &url, const string &postParams, string &response, string handleId)
{ 
   
	// curl初始化 
	CURL *curl = curl_easy_init();
	// curl返回值 
	CURLcode res;
	if (curl)
	{ 
		// set params
		//设置curl的请求头
		struct curl_slist* header_list = NULL;
		header_list = curl_slist_append(header_list, "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
		// header_list = curl_slist_append(header_list, "Content-Type:application/x-www-form-urlencoded; charset=UTF-8");

        header_list = curl_slist_append(header_list, "Accept: application/json");
        header_list = curl_slist_append(header_list, "Content-Type: application/json");//text/html
        header_list = curl_slist_append(header_list, "charsets: utf-8");

		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);

		//不接收响应头数据0代表不接收 1代表接收
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);

		//设置请求为post请求
		// curl_easy_setopt(curl, CURLOPT_POST, 1);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");

		//设置请求的URL地址
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		//设置post请求的参数
		// curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str());

		//设置ssl验证
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

		//CURLOPT_VERBOSE的值为1时,会显示详细的调试信息
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);

        string strResult = "{ \
                                \"authinfo\": \"hisense|hisense123|201807311630\", \
                                \"method\": \"stopVideoRealStream\", \
                                \"handleId\": \""+ handleId + "\" \
                            }";

        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,strResult.c_str());

		curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);

		//设置数据接收和写入函数
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);

		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

		//设置超时时间
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 6);
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 6);

		// 开启post请求
		res = curl_easy_perform(curl);
	}
	//释放curl 
	curl_easy_cleanup(curl);
	return res;
}

void decode_finished_cbk(const void* userPtr){
    cout << "当前时间戳: " << UtilTools::get_cur_time_ms() << endl;
}

string recv_port = "13012";

bool decode_request_stream_cbk(const char* deviceId){
    // cout << "需在此请求流" << endl;

    string url_post = "http://172.16.6.129:7000/httpRequest";
    string paramsLogin = "key1=value1&key2=value2";
    string resPost;

    static string last_handleid = "";
    if(!last_handleid.empty()){
        auto res3 = curl_post_body_stopVideoRealStream(url_post, paramsLogin, resPost, last_handleid);
        if (res3 == CURLE_OK)
        {
            cout << resPost << endl;
        }
    }

    auto res = curl_post_body_getVideoRealStream(url_post, paramsLogin, resPost, deviceId, "172.16.6.129", recv_port);
    if (res == CURLE_OK)
    {
        cout << resPost << endl;

        size_t start = resPost.find_last_of(":") + 3;
        size_t end = resPost.find_last_of("\"");
        if (start == end){
            return false;
        }
        last_handleid = resPost.substr(start,end - start);

        cout << last_handleid << endl;
    }

    return true;
}

// string test_uri = "rtmp://192.168.10.56:1935/objecteye/1";
// string test_uri = "/home/cmhu/data/output_800x480.mp4";
// string test_uri = "/home/cmhu/data/output_1920x1080.mp4";
// string test_uri = "rtsp://176.10.0.2:8554/stream";
// string test_uri = "/mnt/f/fiss/test_data/h265.mp4";
// string test_uri = "rtsp://176.10.0.4:8554/stream";
// string test_uri = "rtsp://admin:admin@123456@192.168.60.176:554/cam/realmonitor?channel=1&subtype=0";
string test_uri = "/home/huchunming/data/woyikewangh265.mp4";

void createDecode(int index, const char* gpu_id){
    FFNvDecoderManager* pDecManager = FFNvDecoderManager::getInstance();
    MgrDecConfig config;
    config.name = "dec" + to_string(index);
    config.cfg.uri = test_uri;
    config.cfg.post_decoded_cbk = postDecoded;
    config.cfg.decode_finished_cbk = decode_finished_cbk;
    config.cfg.force_tcp = true;
    config.dec_type = DECODER_TYPE_FFMPEG;
    config.snap_time_interval = 100;

    config.cfg.gpuid = gpu_id;
    // if (index % 2 == 0)
    // {
    //     config.cfg.gpuid = "0";
    // }
    // else
    // {
    //     config.cfg.gpuid = "0";
    // }
    
    AbstractDecoder* decoder = pDecManager->createDecoder(config);
    if (!decoder)
    {
        return ;
    }
    pDecManager->setPostDecArg(config.name, decoder);
    pDecManager->setFinishedDecArg(config.name, decoder);
    pDecManager->startDecodeByName(config.name);
}

void createGB28181Decode(char* devid, char* gpu_id, int port){
    FFNvDecoderManager* pDecManager = FFNvDecoderManager::getInstance();
    MgrDecConfig config;
    config.name = devid;
    config.cfg.uri = config.name;
    config.cfg.post_decoded_cbk = postDecoded;
    config.cfg.decode_finished_cbk = decode_finished_cbk;
    config.cfg.request_stream_cbk = decode_request_stream_cbk;
    config.cfg.force_tcp = true;

    config.dec_type = DECODER_TYPE_GB28181;
    config.cfg.port = port;//allocRtpPort();
    
    config.cfg.gpuid = gpu_id;
    config.snap_time_interval = 100;

    recv_port = to_string(port);
    
    AbstractDecoder* decoder = pDecManager->createDecoder(config);
    if (!decoder)
    {
        return ;
    }
    pDecManager->setPostDecArg(config.name, decoder);
    pDecManager->setFinishedDecArg(config.name, decoder);
    pDecManager->startDecodeByName(config.name);
}

void createDvppDecoder(int index, char* devId, int channelId){
    FFNvDecoderManager* pDecManager = FFNvDecoderManager::getInstance();
    MgrDecConfig config;
    config.name = "dec" + to_string(index);
    config.cfg.uri = test_uri;
    config.cfg.post_decoded_cbk = postDecoded;
    config.cfg.decode_finished_cbk = decode_finished_cbk;
    config.cfg.force_tcp = true;
    config.dec_type = DECODER_TYPE_DVPP;

    config.cfg.gpuid = devId;
    
    AbstractDecoder* decoder = pDecManager->createDecoder(config);
    if (!decoder)
    {
        cout << "创建解码器失败" << endl;
        return ;
    }
    pDecManager->setPostDecArg(config.name, decoder);
    pDecManager->setFinishedDecArg(config.name, decoder);
    pDecManager->startDecodeByName(config.name);
}

void logFF(void *, int level, const char *fmt, va_list ap)
{
    vfprintf(stdout, fmt, ap);
}


int main(int argc, char* argv[]){

    // test_uri = argv[1];
    char* gpuid = argv[2];
    int port = atoi(argv[3]);
    char* devId = argv[4];
    cout << test_uri << "   gpu_id:" << gpuid << "   port:" << port << "   devId:" << devId << endl;

    // av_log_set_callback(&logFF);

    // CheckCUDAProperty(atoi(gpuid));

    pthread_t m_decode_thread;
    pthread_create(&m_decode_thread,0,
        [](void* arg)
        {
            // cudaSetDevice(atoi(gpuid));
            while (true)
            {
                std::this_thread::sleep_for(std::chrono::seconds(10));
                FFNvDecoderManager* pDecManager = FFNvDecoderManager::getInstance();
                int count = pDecManager->count();
                cout << "当前时间:" << UtilTools::get_cur_time_ms() << "  当前运行路数: " << pDecManager->count() << endl;
                vector<FFImgInfo*> vec_img = pDecManager->timing_snapshot_all();
                for (auto imgInfo : vec_img){
                    auto task_id = imgInfo->dec_name;

                    std::string fpath_ori = "./time_snapshot/" + task_id + "_" + std::to_string(imgInfo->timestamp) + ".jpg";

                    saveJpg(imgInfo->width, imgInfo->height, imgInfo->pData, fpath_ori.c_str());
                    
                    pDecManager->releaseFFImgInfo(imgInfo);
                }
            }  

            return (void*)0;
        }
    ,nullptr);


    FFNvDecoderManager* pDecManager = FFNvDecoderManager::getInstance();
    int i = 0;

    while (true)
    {
        int ch = getchar();
        if (ch == 'q')
        {
            break;
        }

        switch (ch)
        {
        case 'f':
        case 'F':
            createDecode(i, gpuid);
            i++;
            break;
        case 'g':
        case 'G':
            createGB28181Decode(devId, gpuid, port);
            i++;
            break;
        case 'd':
        case 'D':
            createDvppDecoder(i, gpuid, 0);
            i++;
            break;
        case 'r':
        case 'R':
            pDecManager->resumeDecoder("dec0");
            break;
        case 'p':
        case 'P':
            pDecManager->pauseDecoder("dec0");
            break;

        case 'c':
        case 'C':
            i--;
            pDecManager->closeDecoderByName("dec" + to_string(i));
            break;

        case 'i':
        case 'I':
        {
            int w,h;
            pDecManager->getResolution("dec0", w,h);
            printf( "%s : %dx%d\n", "dec0" , w,h );
        }
            break;

        default:
            break;
        }

        /* code */
    }

    cout << "总共帧数:" << sum << endl;
    pDecManager->closeAllDecoder();
}