123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- #include "rtspclientdown.h"
- #include <iostream>
- rtspclientdown::rtspclientdown(std::string strrtspserver)
- {
- mpthread = new std::thread(&rtspclientdown::threadrtspdown,this,strrtspserver);
- }
- rtspclientdown::~rtspclientdown()
- {
- mbthreadrun = false;
- mpthread->join();
- }
- void rtspclientdown::threadrtspdown(std::string strrtspserver)
- {
- AVFormatContext *i_fmt_ctx;
- /* should set to NULL so that avformat_open_input() allocate a new one */
- i_fmt_ctx = NULL;
- AVDictionary *avdic=NULL;
- char option_key[]="rtsp_transport";
- char option_value[]="tcp";
- av_dict_set(&avdic,option_key,option_value,0);
- bool bConnected = false;
- while(mbthreadrun)
- {
- if(bConnected == false)
- {
- i_fmt_ctx = NULL;
- if (avformat_open_input(&i_fmt_ctx, strrtspserver.data(), NULL, &avdic)!=0)
- {
- fprintf(stderr, " = could not open input file\n");
- std::this_thread::sleep_for(std::chrono::milliseconds(1000));
- continue ;
- }
- if (avformat_find_stream_info(i_fmt_ctx,NULL)<0)
- {
- fprintf(stderr, " = could not find stream info\n");
- std::this_thread::sleep_for(std::chrono::milliseconds(1000));
- continue ;
- }
- bConnected = true;
- }
- AVPacket i_pkt;
- av_init_packet(&i_pkt);
- i_pkt.size = 0;
- i_pkt.data = NULL;
- if (av_read_frame(i_fmt_ctx, &i_pkt) <0 )
- {
- bConnected = false;
- std::cout<<"connect fail. retry."<<std::endl;
- continue;
- }
- iv::h264rawframedata xframe;
- xframe.mdatasize = i_pkt.size;
- xframe.mpstr_ptr = std::shared_ptr<char>(new char[xframe.mdatasize]);
- memcpy(xframe.mpstr_ptr.get(),i_pkt.data,xframe.mdatasize);
- mmutexframe.lock();
- while(mvectorframe.size()>900)
- {
- std::cout<<" rtspclientdown::threadrtspdown. erase frame."<<std::endl;
- mvectorframe.erase(mvectorframe.begin());
- }
- mvectorframe.push_back(xframe);
- mmutexframe.unlock();
- mcv.notify_all();
- av_packet_unref(&i_pkt);
- }
- }
- int rtspclientdown::Getrtspframe(iv::h264rawframedata &xframe, int nwaitms)
- {
- int nrtn = 0;
- if(mvectorframe.size()>0)
- {
- mmutexframe.lock();
- if(mvectorframe.size()>0)
- {
- xframe = mvectorframe[0];
- mvectorframe.erase(mvectorframe.begin());
- nrtn = 1;
- }
- else
- {
- nrtn = 0;
- }
- mmutexframe.unlock();
- return nrtn;
- }
- if(nwaitms == 0)return nrtn;
- std::unique_lock<std::mutex> lk(mmutexcv);
- if(mcv.wait_for(lk, std::chrono::milliseconds(nwaitms)) == std::cv_status::timeout)
- {
- lk.unlock();
- }
- else
- {
- lk.unlock();
- }
- mmutexframe.lock();
- if(mvectorframe.size()>0)
- {
- xframe = mvectorframe[0];
- mvectorframe.erase(mvectorframe.begin());
- nrtn = 1;
- }
- else
- {
- nrtn = 0;
- }
- mmutexframe.unlock();
- return nrtn;
- }
|