Commit f71a9bfa by xiongziliang

修复rtsp播放器时间戳紊乱的bug

parent cded823b
......@@ -10,14 +10,11 @@
#include <set>
#include <cmath>
#include <stdarg.h>
#include <algorithm>
#include <iomanip>
#include "Common/config.h"
#include "RtspPlayer.h"
#include "Util/MD5.h"
#include "Util/mini.h"
#include "Util/util.h"
#include "Util/base64.h"
#include "Network/sockutil.h"
......@@ -40,28 +37,28 @@ RtspPlayer::~RtspPlayer(void) {
}
void RtspPlayer::teardown(){
if (alive()) {
sendRtspRequest("TEARDOWN" ,_strContentBase);
sendRtspRequest("TEARDOWN" ,_content_base);
shutdown(SockException(Err_shutdown,"teardown"));
}
_rtspMd5Nonce.clear();
_rtspRealm.clear();
_aTrackInfo.clear();
_strSession.clear();
_strContentBase.clear();
_md5_nonce.clear();
_realm.clear();
_sdp_track.clear();
_session_id.clear();
_content_base.clear();
RtpReceiver::clear();
CLEAR_ARR(_apRtpSock);
CLEAR_ARR(_apRtcpSock);
CLEAR_ARR(_aui16FirstSeq)
CLEAR_ARR(_aui64RtpRecv)
CLEAR_ARR(_aui64RtpRecv)
CLEAR_ARR(_aui16NowSeq)
_pPlayTimer.reset();
_pRtpTimer.reset();
_uiCseq = 1;
_onHandshake = nullptr;
CLEAR_ARR(_rtp_sock);
CLEAR_ARR(_rtcp_sock);
CLEAR_ARR(_rtp_seq_start)
CLEAR_ARR(_rtp_recv_count)
CLEAR_ARR(_rtp_recv_count)
CLEAR_ARR(_rtp_seq_now)
_play_check_timer.reset();
_rtp_check_timer.reset();
_cseq_send = 1;
_on_response = nullptr;
}
void RtspPlayer::play(const string &strUrl){
......@@ -81,20 +78,20 @@ void RtspPlayer::play(const string &strUrl){
(*this)[kRtspPwdIsMD5] = false;
}
_strUrl = url._url;
_eType = (Rtsp::eRtpType)(int)(*this)[kRtpType];
DebugL << url._url << " " << (url._user.size() ? url._user : "null") << " " << (url._passwd.size() ? url._passwd : "null") << " " << _eType;
_play_url = url._url;
_rtp_type = (Rtsp::eRtpType)(int)(*this)[kRtpType];
DebugL << url._url << " " << (url._user.size() ? url._user : "null") << " " << (url._passwd.size() ? url._passwd : "null") << " " << _rtp_type;
weak_ptr<RtspPlayer> weakSelf = dynamic_pointer_cast<RtspPlayer>(shared_from_this());
float playTimeOutSec = (*this)[kTimeoutMS].as<int>() / 1000.0;
_pPlayTimer.reset( new Timer(playTimeOutSec, [weakSelf]() {
_play_check_timer.reset(new Timer(playTimeOutSec, [weakSelf]() {
auto strongSelf=weakSelf.lock();
if(!strongSelf) {
return false;
}
strongSelf->onPlayResult_l(SockException(Err_timeout,"play rtsp timeout"),false);
return false;
},getPoller()));
}, getPoller()));
if(!(*this)[kNetAdapter].empty()){
setNetAdapter((*this)[kNetAdapter]);
......@@ -111,9 +108,9 @@ void RtspPlayer::onConnect(const SockException &err){
}
void RtspPlayer::onRecv(const Buffer::Ptr& pBuf) {
if(_benchmark_mode && !_pPlayTimer){
if(_benchmark_mode && !_play_check_timer){
//在性能测试模式下,如果rtsp握手完毕后,不再解析rtp包
_rtpTicker.resetTime();
_rtp_recv_ticker.resetTime();
return;
}
input(pBuf->data(),pBuf->size());
......@@ -121,12 +118,12 @@ void RtspPlayer::onRecv(const Buffer::Ptr& pBuf) {
void RtspPlayer::onErr(const SockException &ex) {
//定时器_pPlayTimer为空后表明握手结束了
onPlayResult_l(ex,!_pPlayTimer);
onPlayResult_l(ex,!_play_check_timer);
}
// from live555
bool RtspPlayer::handleAuthenticationFailure(const string &paramsStr) {
if(!_rtspRealm.empty()){
if(!_realm.empty()){
//已经认证过了
return false;
}
......@@ -141,17 +138,17 @@ bool RtspPlayer::handleAuthenticationFailure(const string &paramsStr) {
});
if (sscanf(paramsStr.data(), "Digest realm=\"%[^\"]\", nonce=\"%[^\"]\", stale=%[a-zA-Z]", realm, nonce, stale) == 3) {
_rtspRealm = (const char *)realm;
_rtspMd5Nonce = (const char *)nonce;
_realm = (const char *)realm;
_md5_nonce = (const char *)nonce;
return true;
}
if (sscanf(paramsStr.data(), "Digest realm=\"%[^\"]\", nonce=\"%[^\"]\"", realm, nonce) == 2) {
_rtspRealm = (const char *)realm;
_rtspMd5Nonce = (const char *)nonce;
_realm = (const char *)realm;
_md5_nonce = (const char *)nonce;
return true;
}
if (sscanf(paramsStr.data(), "Basic realm=\"%[^\"]\"", realm) == 1) {
_rtspRealm = (const char *)realm;
_realm = (const char *)realm;
return true;
}
return false;
......@@ -176,30 +173,25 @@ void RtspPlayer::handleResDESCRIBE(const Parser& parser) {
throw std::runtime_error(
StrPrinter << "DESCRIBE:" << parser.Url() << " " << parser.Tail() << endl);
}
_strContentBase = parser["Content-Base"];
_content_base = parser["Content-Base"];
if(_strContentBase.empty()){
_strContentBase = _strUrl;
if(_content_base.empty()){
_content_base = _play_url;
}
if (_strContentBase.back() == '/') {
_strContentBase.pop_back();
if (_content_base.back() == '/') {
_content_base.pop_back();
}
SdpParser sdpParser(parser.Content());
//解析sdp
_aTrackInfo = sdpParser.getAvailableTrack();
_sdp_track = sdpParser.getAvailableTrack();
auto title = sdpParser.getTrack(TrackTitle);
_is_play_back = false;
bool is_play_back = false;
if(title && title->_duration ){
_is_play_back = true;
}
for(auto &stamp : _stamp){
stamp.setPlayBack(_is_play_back);
stamp.setRelativeStamp(0);
is_play_back = true;
}
if (_aTrackInfo.empty()) {
if (_sdp_track.empty()) {
throw std::runtime_error("无有效的Sdp Track");
}
if (!onCheckSDP(sdpParser.toString())) {
......@@ -211,8 +203,8 @@ void RtspPlayer::handleResDESCRIBE(const Parser& parser) {
//有必要的情况下创建udp端口
void RtspPlayer::createUdpSockIfNecessary(int track_idx){
auto &rtpSockRef = _apRtpSock[track_idx];
auto &rtcpSockRef = _apRtcpSock[track_idx];
auto &rtpSockRef = _rtp_sock[track_idx];
auto &rtcpSockRef = _rtcp_sock[track_idx];
if (!rtpSockRef || !rtcpSockRef) {
auto pr = makeSockPair(getPoller(), get_local_ip());
rtpSockRef = pr.first;
......@@ -222,10 +214,10 @@ void RtspPlayer::createUdpSockIfNecessary(int track_idx){
//发送SETUP命令
void RtspPlayer::sendSetup(unsigned int trackIndex) {
_onHandshake = std::bind(&RtspPlayer::handleResSETUP,this, placeholders::_1,trackIndex);
auto &track = _aTrackInfo[trackIndex];
auto baseUrl = _strContentBase + "/" + track->_control_surffix;
switch (_eType) {
_on_response = std::bind(&RtspPlayer::handleResSETUP, this, placeholders::_1, trackIndex);
auto &track = _sdp_track[trackIndex];
auto baseUrl = _content_base + "/" + track->_control_surffix;
switch (_rtp_type) {
case Rtsp::RTP_TCP: {
sendRtspRequest("SETUP",baseUrl,{"Transport",StrPrinter << "RTP/AVP/TCP;unicast;interleaved=" << track->_type * 2 << "-" << track->_type * 2 + 1});
}
......@@ -236,10 +228,10 @@ void RtspPlayer::sendSetup(unsigned int trackIndex) {
break;
case Rtsp::RTP_UDP: {
createUdpSockIfNecessary(trackIndex);
sendRtspRequest("SETUP",baseUrl,{"Transport",
sendRtspRequest("SETUP", baseUrl, {"Transport",
StrPrinter << "RTP/AVP;unicast;client_port="
<< _apRtpSock[trackIndex]->get_local_port() << "-"
<< _apRtcpSock[trackIndex]->get_local_port()});
<< _rtp_sock[trackIndex]->get_local_port() << "-"
<< _rtcp_sock[trackIndex]->get_local_port()});
}
break;
default:
......@@ -253,34 +245,34 @@ void RtspPlayer::handleResSETUP(const Parser &parser, unsigned int uiTrackIndex)
StrPrinter << "SETUP:" << parser.Url() << " " << parser.Tail() << endl);
}
if (uiTrackIndex == 0) {
_strSession = parser["Session"];
_strSession.append(";");
_strSession = FindField(_strSession.data(), nullptr, ";");
_session_id = parser["Session"];
_session_id.append(";");
_session_id = FindField(_session_id.data(), nullptr, ";");
}
auto strTransport = parser["Transport"];
if(strTransport.find("TCP") != string::npos || strTransport.find("interleaved") != string::npos){
_eType = Rtsp::RTP_TCP;
_rtp_type = Rtsp::RTP_TCP;
}else if(strTransport.find("multicast") != string::npos){
_eType = Rtsp::RTP_MULTICAST;
_rtp_type = Rtsp::RTP_MULTICAST;
}else{
_eType = Rtsp::RTP_UDP;
_rtp_type = Rtsp::RTP_UDP;
}
RtspSplitter::enableRecvRtp(_eType == Rtsp::RTP_TCP);
RtspSplitter::enableRecvRtp(_rtp_type == Rtsp::RTP_TCP);
if(_eType == Rtsp::RTP_TCP) {
if(_rtp_type == Rtsp::RTP_TCP) {
string interleaved = FindField( FindField((strTransport + ";").data(), "interleaved=", ";").data(), NULL, "-");
_aTrackInfo[uiTrackIndex]->_interleaved = atoi(interleaved.data());
_sdp_track[uiTrackIndex]->_interleaved = atoi(interleaved.data());
}else{
const char *strPos = (_eType == Rtsp::RTP_MULTICAST ? "port=" : "server_port=") ;
const char *strPos = (_rtp_type == Rtsp::RTP_MULTICAST ? "port=" : "server_port=") ;
auto port_str = FindField((strTransport + ";").data(), strPos, ";");
uint16_t rtp_port = atoi(FindField(port_str.data(), NULL, "-").data());
uint16_t rtcp_port = atoi(FindField(port_str.data(), "-",NULL).data());
auto &pRtpSockRef = _apRtpSock[uiTrackIndex];
auto &pRtcpSockRef = _apRtcpSock[uiTrackIndex];
auto &pRtpSockRef = _rtp_sock[uiTrackIndex];
auto &pRtcpSockRef = _rtcp_sock[uiTrackIndex];
if (_eType == Rtsp::RTP_MULTICAST) {
if (_rtp_type == Rtsp::RTP_MULTICAST) {
//udp组播
auto multiAddr = FindField((strTransport + ";").data(), "destination=", ";");
pRtpSockRef.reset(new Socket(getPoller()));
......@@ -322,7 +314,7 @@ void RtspPlayer::handleResSETUP(const Parser &parser, unsigned int uiTrackIndex)
WarnL << "收到其他地址的rtp数据:" << SockUtil::inet_ntoa(((struct sockaddr_in *) addr)->sin_addr);
return;
}
strongSelf->handleOneRtp(uiTrackIndex, strongSelf->_aTrackInfo[uiTrackIndex], (unsigned char *) buf->data(), buf->size());
strongSelf->handleOneRtp(uiTrackIndex, strongSelf->_sdp_track[uiTrackIndex], (unsigned char *) buf->data(), buf->size());
});
if(pRtcpSockRef) {
......@@ -336,12 +328,12 @@ void RtspPlayer::handleResSETUP(const Parser &parser, unsigned int uiTrackIndex)
WarnL << "收到其他地址的rtcp数据:" << SockUtil::inet_ntoa(((struct sockaddr_in *) addr)->sin_addr);
return;
}
strongSelf->onRtcpPacket(uiTrackIndex, strongSelf->_aTrackInfo[uiTrackIndex], (unsigned char *) buf->data(), buf->size());
strongSelf->onRtcpPacket(uiTrackIndex, strongSelf->_sdp_track[uiTrackIndex], (unsigned char *) buf->data(), buf->size());
});
}
}
if (uiTrackIndex < _aTrackInfo.size() - 1) {
if (uiTrackIndex < _sdp_track.size() - 1) {
//需要继续发送SETUP命令
sendSetup(uiTrackIndex + 1);
return;
......@@ -353,12 +345,12 @@ void RtspPlayer::handleResSETUP(const Parser &parser, unsigned int uiTrackIndex)
void RtspPlayer::sendDescribe() {
//发送DESCRIBE命令后处理函数:handleResDESCRIBE
_onHandshake = std::bind(&RtspPlayer::handleResDESCRIBE,this, placeholders::_1);
sendRtspRequest("DESCRIBE",_strUrl,{"Accept","application/sdp"});
_on_response = std::bind(&RtspPlayer::handleResDESCRIBE, this, placeholders::_1);
sendRtspRequest("DESCRIBE", _play_url, {"Accept", "application/sdp"});
}
void RtspPlayer::sendOptions(){
_onHandshake = [this](const Parser& parser){
_on_response = [this](const Parser& parser){
if (parser.Url() != "200") {
throw std::runtime_error(StrPrinter << "OPTIONS:" << parser.Url() << " " << parser.Tail() << endl);
}
......@@ -372,36 +364,36 @@ void RtspPlayer::sendOptions(){
//发送Describe请求,获取sdp
sendDescribe();
};
sendRtspRequest("OPTIONS",_strUrl);
sendRtspRequest("OPTIONS", _play_url);
}
void RtspPlayer::sendKeepAlive(){
_onHandshake = [this](const Parser& parser){};
_on_response = [this](const Parser& parser){};
if(_supported_cmd.find("GET_PARAMETER") != _supported_cmd.end()){
//支持GET_PARAMETER,用此命令保活
sendRtspRequest("GET_PARAMETER",_strUrl);
sendRtspRequest("GET_PARAMETER", _play_url);
}else{
//不支持GET_PARAMETER,用OPTIONS命令保活
sendRtspRequest("OPTIONS",_strUrl);
sendRtspRequest("OPTIONS", _play_url);
}
}
void RtspPlayer::sendPause(int type , uint32_t seekMS){
_onHandshake = std::bind(&RtspPlayer::handleResPAUSE,this, placeholders::_1,type);
_on_response = std::bind(&RtspPlayer::handleResPAUSE, this, placeholders::_1, type);
//开启或暂停rtsp
switch (type){
case type_pause:
sendRtspRequest("PAUSE", _strContentBase);
sendRtspRequest("PAUSE", _content_base);
break;
case type_play:
sendRtspRequest("PLAY", _strContentBase);
sendRtspRequest("PLAY", _content_base);
break;
case type_seek:
sendRtspRequest("PLAY", _strContentBase, {"Range",StrPrinter << "npt=" << setiosflags(ios::fixed) << setprecision(2) << seekMS / 1000.0 << "-"});
sendRtspRequest("PLAY", _content_base, {"Range",StrPrinter << "npt=" << setiosflags(ios::fixed) << setprecision(2) << seekMS / 1000.0 << "-"});
break;
default:
WarnL << "unknown type : " << type;
_onHandshake = nullptr;
_on_response = nullptr;
break;
}
}
......@@ -428,7 +420,7 @@ void RtspPlayer::handleResPAUSE(const Parser& parser,int type) {
if (type == type_pause) {
//暂停成功!
_pRtpTimer.reset();
_rtp_check_timer.reset();
return;
}
......@@ -445,22 +437,20 @@ void RtspPlayer::handleResPAUSE(const Parser& parser,int type) {
DebugL << "seekTo(ms):" << iSeekTo;
}
//设置相对时间戳
_stamp[0].setRelativeStamp(iSeekTo);
_stamp[1].setRelativeStamp(iSeekTo);
onPlayResult_l(SockException(Err_success, type == type_seek ? "resum rtsp success" : "rtsp play success"), type == type_seek);
}
void RtspPlayer::onWholeRtspPacket(Parser &parser) {
try {
decltype(_onHandshake) fun;
_onHandshake.swap(fun);
if(fun){
fun(parser);
decltype(_on_response) func;
_on_response.swap(func);
if(func){
func(parser);
}
parser.Clear();
} catch (std::exception &err) {
//定时器_pPlayTimer为空后表明握手结束了
onPlayResult_l(SockException(Err_other, err.what()),!_pPlayTimer);
onPlayResult_l(SockException(Err_other, err.what()),!_play_check_timer);
}
}
......@@ -470,12 +460,12 @@ void RtspPlayer::onRtpPacket(const char *data, uint64_t len) {
if(interleaved %2 == 0){
trackIdx = getTrackIndexByInterleaved(interleaved);
if (trackIdx != -1) {
handleOneRtp(trackIdx,_aTrackInfo[trackIdx],(unsigned char *)data + 4, len - 4);
handleOneRtp(trackIdx, _sdp_track[trackIdx], (unsigned char *)data + 4, len - 4);
}
}else{
trackIdx = getTrackIndexByInterleaved(interleaved - 1);
if (trackIdx != -1) {
onRtcpPacket(trackIdx, _aTrackInfo[trackIdx], (unsigned char *) data + 4, len - 4);
onRtcpPacket(trackIdx, _sdp_track[trackIdx], (unsigned char *) data + 4, len - 4);
}
}
}
......@@ -545,8 +535,8 @@ void RtspPlayer::sendReceiverReport(bool overTcp,int iTrackIndex){
static const char s_cname[] = "ZLMediaKitRtsp";
uint8_t aui8Rtcp[4 + 32 + 10 + sizeof(s_cname) + 1] = {0};
uint8_t *pui8Rtcp_RR = aui8Rtcp + 4, *pui8Rtcp_SDES = pui8Rtcp_RR + 32;
auto &track = _aTrackInfo[iTrackIndex];
auto &counter = _aRtcpCnt[iTrackIndex];
auto &track = _sdp_track[iTrackIndex];
auto &counter = _rtcp_counter[iTrackIndex];
aui8Rtcp[0] = '$';
aui8Rtcp[1] = track->_interleaved + 1;
......@@ -602,25 +592,22 @@ void RtspPlayer::sendReceiverReport(bool overTcp,int iTrackIndex){
if(overTcp){
send(obtainBuffer((char *) aui8Rtcp, sizeof(aui8Rtcp)));
}else if(_apRtcpSock[iTrackIndex]) {
_apRtcpSock[iTrackIndex]->send((char *) aui8Rtcp + 4, sizeof(aui8Rtcp) - 4);
}else if(_rtcp_sock[iTrackIndex]) {
_rtcp_sock[iTrackIndex]->send((char *) aui8Rtcp + 4, sizeof(aui8Rtcp) - 4);
}
}
void RtspPlayer::onRtpSorted(const RtpPacket::Ptr &rtppt, int trackidx){
//统计丢包率
if (_aui16FirstSeq[trackidx] == 0 || rtppt->sequence < _aui16FirstSeq[trackidx]) {
_aui16FirstSeq[trackidx] = rtppt->sequence;
_aui64RtpRecv[trackidx] = 0;
if (_rtp_seq_start[trackidx] == 0 || rtppt->sequence < _rtp_seq_start[trackidx]) {
_rtp_seq_start[trackidx] = rtppt->sequence;
_rtp_recv_count[trackidx] = 0;
}
_aui64RtpRecv[trackidx] ++;
_aui16NowSeq[trackidx] = rtppt->sequence;
_rtp_recv_count[trackidx] ++;
_rtp_seq_now[trackidx] = rtppt->sequence;
_stamp[trackidx] = rtppt->timeStamp;
//计算相对时间戳
int64_t dts_out;
_stamp[trackidx].revise(rtppt->timeStamp,rtppt->timeStamp,dts_out,dts_out);
rtppt->timeStamp = dts_out;
onRecvRTP_l(rtppt,_aTrackInfo[trackidx]);
onRecvRTP_l(rtppt, _sdp_track[trackidx]);
}
float RtspPlayer::getPacketLossRate(TrackType type) const{
......@@ -628,9 +615,9 @@ float RtspPlayer::getPacketLossRate(TrackType type) const{
if(iTrackIdx == -1){
uint64_t totalRecv = 0;
uint64_t totalSend = 0;
for (unsigned int i = 0; i < _aTrackInfo.size(); i++) {
totalRecv += _aui64RtpRecv[i];
totalSend += (_aui16NowSeq[i] - _aui16FirstSeq[i] + 1);
for (unsigned int i = 0; i < _sdp_track.size(); i++) {
totalRecv += _rtp_recv_count[i];
totalSend += (_rtp_seq_now[i] - _rtp_seq_start[i] + 1);
}
if(totalSend == 0){
return 0;
......@@ -638,14 +625,14 @@ float RtspPlayer::getPacketLossRate(TrackType type) const{
return 1.0 - (double)totalRecv / totalSend;
}
if(_aui16NowSeq[iTrackIdx] - _aui16FirstSeq[iTrackIdx] + 1 == 0){
if(_rtp_seq_now[iTrackIdx] - _rtp_seq_start[iTrackIdx] + 1 == 0){
return 0;
}
return 1.0 - (double)_aui64RtpRecv[iTrackIdx] / (_aui16NowSeq[iTrackIdx] - _aui16FirstSeq[iTrackIdx] + 1);
return 1.0 - (double)_rtp_recv_count[iTrackIdx] / (_rtp_seq_now[iTrackIdx] - _rtp_seq_start[iTrackIdx] + 1);
}
uint32_t RtspPlayer::getProgressMilliSecond() const{
return MAX(_stamp[0].getRelativeStamp(),_stamp[1].getRelativeStamp());
return MAX(_stamp[0],_stamp[1]);
}
void RtspPlayer::seekToMilliSecond(uint32_t ms) {
......@@ -668,15 +655,15 @@ void RtspPlayer::sendRtspRequest(const string &cmd, const string &url, const std
void RtspPlayer::sendRtspRequest(const string &cmd, const string &url,const StrCaseMap &header_const) {
auto header = header_const;
header.emplace("CSeq",StrPrinter << _uiCseq++);
header.emplace("CSeq",StrPrinter << _cseq_send++);
header.emplace("User-Agent",SERVER_NAME);
if(!_strSession.empty()){
header.emplace("Session",_strSession);
if(!_session_id.empty()){
header.emplace("Session", _session_id);
}
if(!_rtspRealm.empty() && !(*this)[kRtspUser].empty()){
if(!_rtspMd5Nonce.empty()){
if(!_realm.empty() && !(*this)[kRtspUser].empty()){
if(!_md5_nonce.empty()){
//MD5认证
/*
response计算方法如下:
......@@ -688,14 +675,14 @@ void RtspPlayer::sendRtspRequest(const string &cmd, const string &url,const StrC
*/
string encrypted_pwd = (*this)[kRtspPwd];
if(!(*this)[kRtspPwdIsMD5].as<bool>()){
encrypted_pwd = MD5((*this)[kRtspUser]+ ":" + _rtspRealm + ":" + encrypted_pwd).hexdigest();
encrypted_pwd = MD5((*this)[kRtspUser] + ":" + _realm + ":" + encrypted_pwd).hexdigest();
}
auto response = MD5( encrypted_pwd + ":" + _rtspMd5Nonce + ":" + MD5(cmd + ":" + url).hexdigest()).hexdigest();
auto response = MD5(encrypted_pwd + ":" + _md5_nonce + ":" + MD5(cmd + ":" + url).hexdigest()).hexdigest();
_StrPrinter printer;
printer << "Digest ";
printer << "username=\"" << (*this)[kRtspUser] << "\", ";
printer << "realm=\"" << _rtspRealm << "\", ";
printer << "nonce=\"" << _rtspMd5Nonce << "\", ";
printer << "realm=\"" << _realm << "\", ";
printer << "nonce=\"" << _md5_nonce << "\", ";
printer << "uri=\"" << url << "\", ";
printer << "response=\"" << response << "\"";
header.emplace("Authorization",printer);
......@@ -717,23 +704,23 @@ void RtspPlayer::sendRtspRequest(const string &cmd, const string &url,const StrC
}
void RtspPlayer::onRecvRTP_l(const RtpPacket::Ptr &pkt, const SdpTrack::Ptr &track) {
_rtpTicker.resetTime();
_rtp_recv_ticker.resetTime();
onRecvRTP(pkt, track);
int iTrackIndex = getTrackIndexByInterleaved(pkt->interleaved);
if (iTrackIndex == -1) {
return;
}
RtcpCounter &counter = _aRtcpCnt[iTrackIndex];
RtcpCounter &counter = _rtcp_counter[iTrackIndex];
counter.pktCnt = pkt->sequence;
auto &ticker = _aRtcpTicker[iTrackIndex];
auto &ticker = _rtcp_send_ticker[iTrackIndex];
if (ticker.elapsedTime() > 5 * 1000) {
//send rtcp every 5 second
counter.lastTimeStamp = counter.timeStamp;
//直接保存网络字节序
memcpy(&counter.timeStamp, pkt->data() + 8, 4);
if (counter.lastTimeStamp != 0) {
sendReceiverReport(_eType == Rtsp::RTP_TCP, iTrackIndex);
sendReceiverReport(_rtp_type == Rtsp::RTP_TCP, iTrackIndex);
ticker.resetTime();
}
......@@ -750,27 +737,27 @@ void RtspPlayer::onPlayResult_l(const SockException &ex , bool handshakeComplete
if(!ex){
//播放成功,恢复rtp接收超时定时器
_rtpTicker.resetTime();
_rtp_recv_ticker.resetTime();
weak_ptr<RtspPlayer> weakSelf = dynamic_pointer_cast<RtspPlayer>(shared_from_this());
int timeoutMS = (*this)[kMediaTimeoutMS].as<int>();
//创建rtp数据接收超时检测定时器
_pRtpTimer.reset( new Timer(timeoutMS / 2000.0, [weakSelf,timeoutMS]() {
_rtp_check_timer.reset(new Timer(timeoutMS / 2000.0, [weakSelf,timeoutMS]() {
auto strongSelf=weakSelf.lock();
if(!strongSelf) {
return false;
}
if(strongSelf->_rtpTicker.elapsedTime()> timeoutMS) {
if(strongSelf->_rtp_recv_ticker.elapsedTime() > timeoutMS) {
//接收rtp媒体数据包超时
strongSelf->onPlayResult_l(SockException(Err_timeout,"receive rtp timeout"), true);
return false;
}
return true;
},getPoller()));
}, getPoller()));
}
if (!handshakeCompleted) {
//开始播放阶段
_pPlayTimer.reset();
_play_check_timer.reset();
onPlayResult(ex);
//是否为性能测试模式
_benchmark_mode = (*this)[Client::kBenchmarkMode].as<int>();
......@@ -787,25 +774,25 @@ void RtspPlayer::onPlayResult_l(const SockException &ex , bool handshakeComplete
}
}
int RtspPlayer::getTrackIndexByInterleaved(int interleaved) const{
for (unsigned int i = 0; i < _aTrackInfo.size(); i++) {
if (_aTrackInfo[i]->_interleaved == interleaved) {
int RtspPlayer::getTrackIndexByInterleaved(int interleaved) const {
for (unsigned int i = 0; i < _sdp_track.size(); i++) {
if (_sdp_track[i]->_interleaved == interleaved) {
return i;
}
}
if(_aTrackInfo.size() == 1){
if (_sdp_track.size() == 1) {
return 0;
}
return -1;
}
int RtspPlayer::getTrackIndexByTrackType(TrackType trackType) const {
for (unsigned int i = 0; i < _aTrackInfo.size(); i++) {
if (_aTrackInfo[i]->_type == trackType) {
for (unsigned int i = 0; i < _sdp_track.size(); i++) {
if (_sdp_track[i]->_type == trackType) {
return i;
}
}
if(_aTrackInfo.size() == 1){
if (_sdp_track.size() == 1) {
return 0;
}
return -1;
......
......@@ -105,40 +105,40 @@ private:
void sendReceiverReport(bool overTcp,int iTrackIndex);
void createUdpSockIfNecessary(int track_idx);
private:
string _strUrl;
vector<SdpTrack::Ptr> _aTrackInfo;
function<void(const Parser&)> _onHandshake;
Socket::Ptr _apRtpSock[2]; //RTP端口,trackid idx 为数组下标
Socket::Ptr _apRtcpSock[2];//RTCP端口,trackid idx 为数组下标
string _play_url;
vector<SdpTrack::Ptr> _sdp_track;
function<void(const Parser&)> _on_response;
//RTP端口,trackid idx 为数组下标
Socket::Ptr _rtp_sock[2];
//RTCP端口,trackid idx 为数组下标
Socket::Ptr _rtcp_sock[2];
//rtsp鉴权相关
string _rtspMd5Nonce;
string _rtspRealm;
string _md5_nonce;
string _realm;
//rtsp info
string _strSession;
unsigned int _uiCseq = 1;
string _strContentBase;
Rtsp::eRtpType _eType = Rtsp::RTP_TCP;
string _session_id;
uint32_t _cseq_send = 1;
string _content_base;
Rtsp::eRtpType _rtp_type = Rtsp::RTP_TCP;
/* 丢包率统计需要用到的参数 */
uint16_t _aui16FirstSeq[2] = { 0 , 0};
uint16_t _aui16NowSeq[2] = { 0 , 0 };
uint64_t _aui64RtpRecv[2] = { 0 , 0};
uint16_t _rtp_seq_start[2] = {0, 0};
uint16_t _rtp_seq_now[2] = {0, 0};
uint64_t _rtp_recv_count[2] = {0, 0};
//当前rtp时间戳
uint32_t _stamp[2] = {0, 0};
//超时功能实现
Ticker _rtpTicker;
std::shared_ptr<Timer> _pPlayTimer;
std::shared_ptr<Timer> _pRtpTimer;
Ticker _rtp_recv_ticker;
std::shared_ptr<Timer> _play_check_timer;
std::shared_ptr<Timer> _rtp_check_timer;
//时间戳
Stamp _stamp[2];
//rtcp统计,trackid idx 为数组下标
RtcpCounter _rtcp_counter[2];
//rtcp发送时间,trackid idx 为数组下标
Ticker _rtcp_send_ticker[2];
//rtcp相关
RtcpCounter _aRtcpCnt[2]; //rtcp统计,trackid idx 为数组下标
Ticker _aRtcpTicker[2]; //rtcp发送时间,trackid idx 为数组下标
//是否为rtsp点播
bool _is_play_back;
//是否为性能测试模式
bool _benchmark_mode = false;
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论