ZLMediaKit/src/Rtmp/RtmpPlayer.cpp

406 lines
13 KiB
C++
Raw Normal View History

2017-10-09 22:11:01 +08:00
/*
2020-04-04 20:30:09 +08:00
* Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
2017-09-27 16:20:30 +08:00
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
2020-04-04 20:30:09 +08:00
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
2017-04-01 16:35:56 +08:00
*/
#include "RtmpPlayer.h"
2017-04-25 11:35:41 +08:00
#include "Rtmp/utils.h"
2017-04-01 16:35:56 +08:00
#include "Util/util.h"
#include "Util/onceToken.h"
2017-04-25 11:35:41 +08:00
#include "Thread/ThreadPool.h"
2018-10-24 17:17:55 +08:00
using namespace toolkit;
2019-03-27 18:56:49 +08:00
using namespace mediakit::Client;
2017-04-25 11:35:41 +08:00
2018-10-24 17:17:55 +08:00
namespace mediakit {
2017-04-01 16:35:56 +08:00
RtmpPlayer::RtmpPlayer(const EventPoller::Ptr &poller) : TcpClient(poller) {
2017-04-01 16:35:56 +08:00
}
RtmpPlayer::~RtmpPlayer() {
2020-03-20 11:51:24 +08:00
DebugL << endl;
2017-04-01 16:35:56 +08:00
}
2017-04-01 16:35:56 +08:00
void RtmpPlayer::teardown() {
2020-03-20 11:51:24 +08:00
if (alive()) {
shutdown(SockException(Err_shutdown,"teardown"));
}
_strApp.clear();
_strStream.clear();
_strTcUrl.clear();
_pBeatTimer.reset();
_pPlayTimer.reset();
_pMediaTimer.reset();
_iSeekTo = 0;
RtmpProtocol::reset();
CLEAR_ARR(_aiFistStamp);
CLEAR_ARR(_aiNowStamp);
lock_guard<recursive_mutex> lck(_mtxOnResultCB);
_mapOnResultCB.clear();
lock_guard<recursive_mutex> lck2(_mtxOnStatusCB);
_dqOnStatusCB.clear();
2017-04-01 16:35:56 +08:00
}
2019-03-27 18:41:52 +08:00
void RtmpPlayer::play(const string &strUrl) {
2020-03-20 11:51:24 +08:00
teardown();
string strHost = FindField(strUrl.data(), "://", "/");
_strApp = FindField(strUrl.data(), (strHost + "/").data(), "/");
2019-03-27 18:41:52 +08:00
_strStream = FindField(strUrl.data(), (strHost + "/" + _strApp + "/").data(), NULL);
2018-10-24 15:43:52 +08:00
_strTcUrl = string("rtmp://") + strHost + "/" + _strApp;
2017-04-01 16:35:56 +08:00
2018-10-24 15:43:52 +08:00
if (!_strApp.size() || !_strStream.size()) {
onPlayResult_l(SockException(Err_other,"rtmp url非法"),false);
2017-04-01 16:35:56 +08:00
return;
}
2020-03-20 11:51:24 +08:00
DebugL << strHost << " " << _strApp << " " << _strStream;
2017-04-01 16:35:56 +08:00
2020-03-20 11:51:24 +08:00
auto iPort = atoi(FindField(strHost.data(), ":", NULL).data());
if (iPort <= 0) {
2017-04-01 16:35:56 +08:00
//rtmp 默认端口1935
2020-03-20 11:51:24 +08:00
iPort = 1935;
} else {
2017-04-01 16:35:56 +08:00
//服务器域名
2020-03-20 11:51:24 +08:00
strHost = FindField(strHost.data(), NULL, ":");
}
if(!(*this)[kNetAdapter].empty()){
setNetAdapter((*this)[kNetAdapter]);
}
weak_ptr<RtmpPlayer> weakSelf= dynamic_pointer_cast<RtmpPlayer>(shared_from_this());
float playTimeOutSec = (*this)[kTimeoutMS].as<int>() / 1000.0;
_pPlayTimer.reset( new Timer(playTimeOutSec, [weakSelf]() {
auto strongSelf=weakSelf.lock();
if(!strongSelf) {
return false;
}
strongSelf->onPlayResult_l(SockException(Err_timeout,"play rtmp timeout"),false);
return false;
},getPoller()));
_metadata_got = false;
startConnect(strHost, iPort , playTimeOutSec);
}
void RtmpPlayer::onErr(const SockException &ex){
//定时器_pPlayTimer为空后表明握手结束了
2020-03-20 11:51:24 +08:00
onPlayResult_l(ex, !_pPlayTimer);
2019-03-28 12:02:59 +08:00
}
void RtmpPlayer::onPlayResult_l(const SockException &ex , bool handshakeCompleted) {
2020-03-20 11:51:24 +08:00
WarnL << ex.getErrCode() << " " << ex.what();
2019-05-08 15:27:37 +08:00
if(!ex){
//播放成功恢复rtmp接收超时定时器
2019-05-08 15:27:37 +08:00
_mediaTicker.resetTime();
weak_ptr<RtmpPlayer> weakSelf = dynamic_pointer_cast<RtmpPlayer>(shared_from_this());
int timeoutMS = (*this)[kMediaTimeoutMS].as<int>();
2020-03-20 11:51:24 +08:00
//创建rtmp数据接收超时检测定时器
2019-05-08 15:27:37 +08:00
_pMediaTimer.reset( new Timer(timeoutMS / 2000.0, [weakSelf,timeoutMS]() {
auto strongSelf=weakSelf.lock();
if(!strongSelf) {
return false;
}
if(strongSelf->_mediaTicker.elapsedTime()> timeoutMS) {
//接收rtmp媒体数据超时
strongSelf->onPlayResult_l(SockException(Err_timeout,"receive rtmp timeout"),true);
2019-05-08 15:27:37 +08:00
return false;
}
return true;
},getPoller()));
}
2020-03-20 11:51:24 +08:00
if (!handshakeCompleted) {
//开始播放阶段
_pPlayTimer.reset();
onPlayResult(ex);
} else if (ex) {
//播放成功后异常断开回调
onShutdown(ex);
} else {
//恢复播放
onResume();
}
if(ex){
teardown();
}
}
void RtmpPlayer::onConnect(const SockException &err){
2020-03-20 11:51:24 +08:00
if(err.getErrCode() != Err_success) {
onPlayResult_l(err, false);
return;
}
weak_ptr<RtmpPlayer> weakSelf= dynamic_pointer_cast<RtmpPlayer>(shared_from_this());
startClientSession([weakSelf](){
2017-04-01 16:35:56 +08:00
auto strongSelf=weakSelf.lock();
2020-03-20 11:51:24 +08:00
if(!strongSelf) {
2017-04-01 16:35:56 +08:00
return;
}
2020-03-20 11:51:24 +08:00
strongSelf->send_connect();
});
2017-04-01 16:35:56 +08:00
}
2018-02-23 15:36:51 +08:00
void RtmpPlayer::onRecv(const Buffer::Ptr &pBuf){
2020-03-20 11:51:24 +08:00
try {
onParseRtmp(pBuf->data(), pBuf->size());
} catch (exception &e) {
SockException ex(Err_other, e.what());
//定时器_pPlayTimer为空后表明握手结束了
2020-03-20 11:51:24 +08:00
onPlayResult_l(ex, !_pPlayTimer);
}
2017-04-01 16:35:56 +08:00
}
void RtmpPlayer::pause(bool bPause) {
2020-03-20 11:51:24 +08:00
send_pause(bPause);
2017-04-01 16:35:56 +08:00
}
inline void RtmpPlayer::send_connect() {
2020-03-20 11:51:24 +08:00
AMFValue obj(AMF_OBJECT);
obj.set("app", _strApp);
obj.set("tcUrl", _strTcUrl);
//未使用代理
obj.set("fpad", false);
//参考librtmp,什么作用?
obj.set("capabilities", 15);
//SUPPORT_VID_CLIENT_SEEK 支持seek
obj.set("videoFunction", 1);
2017-04-01 16:35:56 +08:00
//只支持aac
obj.set("audioCodecs", (double)(0x0400));
2017-04-01 16:35:56 +08:00
//只支持H264
obj.set("videoCodecs", (double)(0x0080));
2020-03-20 11:51:24 +08:00
sendInvoke("connect", obj);
addOnResultCB([this](AMFDecoder &dec){
//TraceL << "connect result";
dec.load<AMFValue>();
auto val = dec.load<AMFValue>();
auto level = val["level"].as_string();
auto code = val["code"].as_string();
if(level != "status"){
throw std::runtime_error(StrPrinter <<"connect 失败:" << level << " " << code << endl);
}
send_createStream();
});
2017-04-01 16:35:56 +08:00
}
inline void RtmpPlayer::send_createStream() {
2020-03-20 11:51:24 +08:00
AMFValue obj(AMF_NULL);
sendInvoke("createStream", obj);
addOnResultCB([this](AMFDecoder &dec){
//TraceL << "createStream result";
dec.load<AMFValue>();
_ui32StreamId = dec.load<int>();
send_play();
});
2017-04-01 16:35:56 +08:00
}
inline void RtmpPlayer::send_play() {
2020-03-20 11:51:24 +08:00
AMFEncoder enc;
enc << "play" << ++_iReqID << nullptr << _strStream << (double)_ui32StreamId;
sendRequest(MSG_CMD, enc.data());
auto fun = [this](AMFValue &val){
//TraceL << "play onStatus";
auto level = val["level"].as_string();
auto code = val["code"].as_string();
if(level != "status"){
throw std::runtime_error(StrPrinter <<"play 失败:" << level << " " << code << endl);
}
};
addOnStatusCB(fun);
addOnStatusCB(fun);
2017-04-01 16:35:56 +08:00
}
inline void RtmpPlayer::send_pause(bool bPause) {
2020-03-20 11:51:24 +08:00
AMFEncoder enc;
enc << "pause" << ++_iReqID << nullptr << bPause;
sendRequest(MSG_CMD, enc.data());
auto fun = [this,bPause](AMFValue &val){
2017-04-01 16:35:56 +08:00
//TraceL << "pause onStatus";
auto level = val["level"].as_string();
auto code = val["code"].as_string();
if(level != "status") {
if(!bPause){
2017-08-09 18:39:30 +08:00
throw std::runtime_error(StrPrinter <<"pause 恢复播放失败:" << level << " " << code << endl);
2017-04-01 16:35:56 +08:00
}
}else{
2018-10-24 15:43:52 +08:00
_bPaused = bPause;
2017-04-01 16:35:56 +08:00
if(!bPause){
onPlayResult_l(SockException(Err_success, "resum rtmp success"), true);
2017-04-01 16:35:56 +08:00
}else{
//暂停播放
2018-10-24 15:43:52 +08:00
_pMediaTimer.reset();
2017-04-01 16:35:56 +08:00
}
}
2020-03-20 11:51:24 +08:00
};
addOnStatusCB(fun);
_pBeatTimer.reset();
if(bPause){
weak_ptr<RtmpPlayer> weakSelf = dynamic_pointer_cast<RtmpPlayer>(shared_from_this());
_pBeatTimer.reset(new Timer((*this)[kBeatIntervalMS].as<int>() / 1000.0,[weakSelf](){
auto strongSelf = weakSelf.lock();
if (!strongSelf){
return false;
}
uint32_t timeStamp = ::time(NULL);
strongSelf->sendUserControl(CONTROL_PING_REQUEST, timeStamp);
return true;
},getPoller()));
}
2017-04-01 16:35:56 +08:00
}
void RtmpPlayer::onCmd_result(AMFDecoder &dec){
2020-03-20 11:51:24 +08:00
auto iReqId = dec.load<int>();
lock_guard<recursive_mutex> lck(_mtxOnResultCB);
auto it = _mapOnResultCB.find(iReqId);
if(it != _mapOnResultCB.end()){
it->second(dec);
_mapOnResultCB.erase(it);
}else{
WarnL << "unhandled _result";
}
2017-04-01 16:35:56 +08:00
}
void RtmpPlayer::onCmd_onStatus(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
AMFValue val;
while(true){
val = dec.load<AMFValue>();
if(val.type() == AMF_OBJECT){
break;
}
}
if(val.type() != AMF_OBJECT){
throw std::runtime_error("onStatus:the result object was not found");
}
2017-04-01 16:35:56 +08:00
2018-10-24 15:43:52 +08:00
lock_guard<recursive_mutex> lck(_mtxOnStatusCB);
2020-03-20 11:51:24 +08:00
if(_dqOnStatusCB.size()){
_dqOnStatusCB.front()(val);
_dqOnStatusCB.pop_front();
}else{
auto level = val["level"];
auto code = val["code"].as_string();
if(level.type() == AMF_STRING){
if(level.as_string() != "status"){
throw std::runtime_error(StrPrinter <<"onStatus 失败:" << level.as_string() << " " << code << endl);
}
}
//WarnL << "unhandled onStatus:" << code;
2017-04-01 16:35:56 +08:00
}
}
void RtmpPlayer::onCmd_onMetaData(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
//TraceL;
auto val = dec.load<AMFValue>();
if(!onCheckMeta(val)){
throw std::runtime_error("onCheckMeta failed");
}
_metadata_got = true;
2017-04-01 16:35:56 +08:00
}
void RtmpPlayer::onStreamDry(uint32_t ui32StreamId) {
2020-03-20 11:51:24 +08:00
//TraceL << ui32StreamId;
onPlayResult_l(SockException(Err_other,"rtmp stream dry"), true);
2017-04-01 16:35:56 +08:00
}
void RtmpPlayer::onMediaData_l(const RtmpPacket::Ptr &packet) {
2020-03-20 11:51:24 +08:00
_mediaTicker.resetTime();
if(!_pPlayTimer){
//已经触发了onPlayResult事件直接触发onMediaData事件
onMediaData(packet);
return;
}
if(packet->isCfgFrame()){
//输入配置帧以便初始化完成各个track
onMediaData(packet);
}else{
//先触发onPlayResult事件这个时候解码器才能初始化完毕
onPlayResult_l(SockException(Err_success,"play rtmp success"), false);
//触发onPlayResult事件后再把帧数据输入到解码器
onMediaData(packet);
}
}
2017-04-01 16:35:56 +08:00
void RtmpPlayer::onRtmpChunk(RtmpPacket &chunkData) {
2020-03-20 11:51:24 +08:00
typedef void (RtmpPlayer::*rtmp_func_ptr)(AMFDecoder &dec);
static unordered_map<string, rtmp_func_ptr> s_func_map;
static onceToken token([]() {
s_func_map.emplace("_error",&RtmpPlayer::onCmd_result);
s_func_map.emplace("_result",&RtmpPlayer::onCmd_result);
s_func_map.emplace("onStatus",&RtmpPlayer::onCmd_onStatus);
s_func_map.emplace("onMetaData",&RtmpPlayer::onCmd_onMetaData);
}, []() {});
switch (chunkData.typeId) {
case MSG_CMD:
case MSG_CMD3:
case MSG_DATA:
case MSG_DATA3: {
AMFDecoder dec(chunkData.strBuf, 0);
std::string type = dec.load<std::string>();
auto it = s_func_map.find(type);
if(it != s_func_map.end()){
auto fun = it->second;
(this->*fun)(dec);
}else{
WarnL << "can not support cmd:" << type;
}
}
break;
case MSG_AUDIO:
case MSG_VIDEO: {
2017-04-01 16:35:56 +08:00
auto idx = chunkData.typeId%2;
2018-10-24 15:43:52 +08:00
if (_aNowStampTicker[idx].elapsedTime() > 500) {
2020-03-20 11:51:24 +08:00
//计算播放进度时间轴用
2018-10-26 14:12:16 +08:00
_aiNowStamp[idx] = chunkData.timeStamp;
2017-04-01 16:35:56 +08:00
}
2020-03-20 11:51:24 +08:00
if(!_metadata_got){
if(!onCheckMeta(TitleMeta().getMetadata())){
throw std::runtime_error("onCheckMeta failed");
}
_metadata_got = true;
}
onMediaData_l(std::make_shared<RtmpPacket>(std::move(chunkData)));
}
break;
default:
//WarnL << "unhandled message:" << (int) chunkData.typeId << hexdump(chunkData.strBuf.data(), chunkData.strBuf.size());
break;
}
2017-04-01 16:35:56 +08:00
}
2018-10-26 14:12:16 +08:00
uint32_t RtmpPlayer::getProgressMilliSecond() const{
2020-03-20 11:51:24 +08:00
uint32_t iTime[2] = {0,0};
2017-04-01 16:35:56 +08:00
for(auto i = 0 ;i < 2 ;i++){
2018-10-26 14:12:16 +08:00
iTime[i] = _aiNowStamp[i] - _aiFistStamp[i];
2017-04-01 16:35:56 +08:00
}
2018-10-26 14:12:16 +08:00
return _iSeekTo + MAX(iTime[0],iTime[1]);
2017-04-01 16:35:56 +08:00
}
2018-10-26 14:12:16 +08:00
void RtmpPlayer::seekToMilliSecond(uint32_t seekMS){
2018-10-24 15:43:52 +08:00
if (_bPaused) {
2017-04-01 16:35:56 +08:00
pause(false);
}
AMFEncoder enc;
2018-10-26 14:12:16 +08:00
enc << "seek" << ++_iReqID << nullptr << seekMS * 1.0;
2017-04-01 16:35:56 +08:00
sendRequest(MSG_CMD, enc.data());
2018-10-26 14:12:16 +08:00
addOnStatusCB([this,seekMS](AMFValue &val) {
2017-04-01 16:35:56 +08:00
//TraceL << "seek result";
2018-10-24 15:43:52 +08:00
_aNowStampTicker[0].resetTime();
_aNowStampTicker[1].resetTime();
2020-03-20 11:51:24 +08:00
int iTimeInc = seekMS - getProgressMilliSecond();
2017-04-01 16:35:56 +08:00
for(auto i = 0 ;i < 2 ;i++){
2018-10-26 14:12:16 +08:00
_aiFistStamp[i] = _aiNowStamp[i] + iTimeInc;
_aiNowStamp[i] = _aiFistStamp[i];
2017-04-01 16:35:56 +08:00
}
2018-10-26 14:12:16 +08:00
_iSeekTo = seekMS;
2017-04-01 16:35:56 +08:00
});
}
2018-10-24 17:17:55 +08:00
} /* namespace mediakit */
2017-04-01 16:35:56 +08:00