mirror of
https://github.com/ZLMediaKit/ZLMediaKit.git
synced 2026-06-14 03:55:58 +08:00
整理代码
This commit is contained in:
@@ -13,12 +13,12 @@
|
||||
#include "Util/onceToken.h"
|
||||
namespace mediakit {
|
||||
|
||||
RtmpSession::RtmpSession(const Socket::Ptr &pSock) : TcpSession(pSock) {
|
||||
RtmpSession::RtmpSession(const Socket::Ptr &sock) : TcpSession(sock) {
|
||||
DebugP(this);
|
||||
GET_CONFIG(uint32_t,keep_alive_sec,Rtmp::kKeepAliveSecond);
|
||||
pSock->setSendTimeOutSecond(keep_alive_sec);
|
||||
sock->setSendTimeOutSecond(keep_alive_sec);
|
||||
//起始接收buffer缓存设置为4K,节省内存
|
||||
pSock->setReadBuffer(std::make_shared<BufferRaw>(4 * 1024));
|
||||
sock->setReadBuffer(std::make_shared<BufferRaw>(4 * 1024));
|
||||
}
|
||||
|
||||
RtmpSession::~RtmpSession() {
|
||||
@@ -26,20 +26,20 @@ RtmpSession::~RtmpSession() {
|
||||
}
|
||||
|
||||
void RtmpSession::onError(const SockException& err) {
|
||||
bool isPlayer = !_pPublisherSrc;
|
||||
bool isPlayer = !_publisher_src;
|
||||
uint64_t duration = _ticker.createdTime()/1000;
|
||||
WarnP(this) << (isPlayer ? "RTMP播放器(" : "RTMP推流器(")
|
||||
<< _mediaInfo._vhost << "/"
|
||||
<< _mediaInfo._app << "/"
|
||||
<< _mediaInfo._streamid
|
||||
<< _media_info._vhost << "/"
|
||||
<< _media_info._app << "/"
|
||||
<< _media_info._streamid
|
||||
<< ")断开:" << err.what()
|
||||
<< ",耗时(s):" << duration;
|
||||
|
||||
//流量统计事件广播
|
||||
GET_CONFIG(uint32_t,iFlowThreshold,General::kFlowThreshold);
|
||||
|
||||
if(_ui64TotalBytes > iFlowThreshold * 1024){
|
||||
NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastFlowReport, _mediaInfo, _ui64TotalBytes, duration, isPlayer, static_cast<SockInfo &>(*this));
|
||||
if(_total_bytes > iFlowThreshold * 1024){
|
||||
NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastFlowReport, _media_info, _total_bytes, duration, isPlayer, static_cast<SockInfo &>(*this));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,11 +48,11 @@ void RtmpSession::onManager() {
|
||||
GET_CONFIG(uint32_t,keep_alive_sec,Rtmp::kKeepAliveSecond);
|
||||
|
||||
if (_ticker.createdTime() > handshake_sec * 1000) {
|
||||
if (!_pRingReader && !_pPublisherSrc) {
|
||||
if (!_ring_reader && !_publisher_src) {
|
||||
shutdown(SockException(Err_timeout,"illegal connection"));
|
||||
}
|
||||
}
|
||||
if (_pPublisherSrc) {
|
||||
if (_publisher_src) {
|
||||
//publisher
|
||||
if (_ticker.elapsedTime() > keep_alive_sec * 1000) {
|
||||
shutdown(SockException(Err_timeout,"recv data from rtmp pusher timeout"));
|
||||
@@ -60,22 +60,22 @@ void RtmpSession::onManager() {
|
||||
}
|
||||
}
|
||||
|
||||
void RtmpSession::onRecv(const Buffer::Ptr &pBuf) {
|
||||
void RtmpSession::onRecv(const Buffer::Ptr &buf) {
|
||||
_ticker.resetTime();
|
||||
try {
|
||||
_ui64TotalBytes += pBuf->size();
|
||||
onParseRtmp(pBuf->data(), pBuf->size());
|
||||
} catch (exception &e) {
|
||||
shutdown(SockException(Err_shutdown, e.what()));
|
||||
_total_bytes += buf->size();
|
||||
onParseRtmp(buf->data(), buf->size());
|
||||
} catch (exception &ex) {
|
||||
shutdown(SockException(Err_shutdown, ex.what()));
|
||||
}
|
||||
}
|
||||
|
||||
void RtmpSession::onCmd_connect(AMFDecoder &dec) {
|
||||
auto params = dec.load<AMFValue>();
|
||||
double amfVer = 0;
|
||||
double amf_ver = 0;
|
||||
AMFValue objectEncoding = params["objectEncoding"];
|
||||
if(objectEncoding){
|
||||
amfVer = objectEncoding.as_number();
|
||||
amf_ver = objectEncoding.as_number();
|
||||
}
|
||||
///////////set chunk size////////////////
|
||||
sendChunkSize(60000);
|
||||
@@ -84,11 +84,11 @@ void RtmpSession::onCmd_connect(AMFDecoder &dec) {
|
||||
///////////set peerBandwidth////////////////
|
||||
sendPeerBandwidth(5000000);
|
||||
|
||||
_mediaInfo._app = params["app"].as_string();
|
||||
_strTcUrl = params["tcUrl"].as_string();
|
||||
if(_strTcUrl.empty()){
|
||||
_media_info._app = params["app"].as_string();
|
||||
_tc_url = params["tcUrl"].as_string();
|
||||
if(_tc_url.empty()){
|
||||
//defaultVhost:默认vhost
|
||||
_strTcUrl = string(RTMP_SCHEMA) + "://" + DEFAULT_VHOST + "/" + _mediaInfo._app;
|
||||
_tc_url = string(RTMP_SCHEMA) + "://" + DEFAULT_VHOST + "/" + _media_info._app;
|
||||
}
|
||||
bool ok = true; //(app == APP_NAME);
|
||||
AMFValue version(AMF_OBJECT);
|
||||
@@ -98,10 +98,10 @@ void RtmpSession::onCmd_connect(AMFDecoder &dec) {
|
||||
status.set("level", ok ? "status" : "error");
|
||||
status.set("code", ok ? "NetConnection.Connect.Success" : "NetConnection.Connect.InvalidApp");
|
||||
status.set("description", ok ? "Connection succeeded." : "InvalidApp.");
|
||||
status.set("objectEncoding", amfVer);
|
||||
status.set("objectEncoding", amf_ver);
|
||||
sendReply(ok ? "_result" : "_error", version, status);
|
||||
if (!ok) {
|
||||
throw std::runtime_error("Unsupported application: " + _mediaInfo._app);
|
||||
throw std::runtime_error("Unsupported application: " + _media_info._app);
|
||||
}
|
||||
|
||||
AMFEncoder invoke;
|
||||
@@ -114,75 +114,75 @@ void RtmpSession::onCmd_createStream(AMFDecoder &dec) {
|
||||
}
|
||||
|
||||
void RtmpSession::onCmd_publish(AMFDecoder &dec) {
|
||||
std::shared_ptr<Ticker> pTicker(new Ticker);
|
||||
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
|
||||
std::shared_ptr<onceToken> pToken(new onceToken(nullptr,[pTicker,weakSelf](){
|
||||
auto strongSelf = weakSelf.lock();
|
||||
if(strongSelf){
|
||||
DebugP(strongSelf.get()) << "publish 回复时间:" << pTicker->elapsedTime() << "ms";
|
||||
std::shared_ptr<Ticker> ticker(new Ticker);
|
||||
weak_ptr<RtmpSession> weak_self = dynamic_pointer_cast<RtmpSession>(shared_from_this());
|
||||
std::shared_ptr<onceToken> pToken(new onceToken(nullptr,[ticker,weak_self](){
|
||||
auto strong_self = weak_self.lock();
|
||||
if(strong_self){
|
||||
DebugP(strong_self.get()) << "publish 回复时间:" << ticker->elapsedTime() << "ms";
|
||||
}
|
||||
}));
|
||||
dec.load<AMFValue>();/* NULL */
|
||||
_mediaInfo.parse(_strTcUrl + "/" + getStreamId(dec.load<std::string>()));
|
||||
_mediaInfo._schema = RTMP_SCHEMA;
|
||||
_media_info.parse(_tc_url + "/" + getStreamId(dec.load<std::string>()));
|
||||
_media_info._schema = RTMP_SCHEMA;
|
||||
|
||||
auto onRes = [this,pToken](const string &err,bool enableRtxp,bool enableHls,bool enableMP4){
|
||||
auto on_res = [this,pToken](const string &err, bool enableRtxp, bool enableHls, bool enableMP4){
|
||||
auto src = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,
|
||||
_mediaInfo._vhost,
|
||||
_mediaInfo._app,
|
||||
_mediaInfo._streamid));
|
||||
bool authSuccess = err.empty();
|
||||
bool ok = (!src && !_pPublisherSrc && authSuccess);
|
||||
_media_info._vhost,
|
||||
_media_info._app,
|
||||
_media_info._streamid));
|
||||
bool auth_success = err.empty();
|
||||
bool ok = (!src && !_publisher_src && auth_success);
|
||||
AMFValue status(AMF_OBJECT);
|
||||
status.set("level", ok ? "status" : "error");
|
||||
status.set("code", ok ? "NetStream.Publish.Start" : (authSuccess ? "NetStream.Publish.BadName" : "NetStream.Publish.BadAuth"));
|
||||
status.set("description", ok ? "Started publishing stream." : (authSuccess ? "Already publishing." : err.data()));
|
||||
status.set("code", ok ? "NetStream.Publish.Start" : (auth_success ? "NetStream.Publish.BadName" : "NetStream.Publish.BadAuth"));
|
||||
status.set("description", ok ? "Started publishing stream." : (auth_success ? "Already publishing." : err.data()));
|
||||
status.set("clientid", "0");
|
||||
sendReply("onStatus", nullptr, status);
|
||||
if (!ok) {
|
||||
string errMsg = StrPrinter << (authSuccess ? "already publishing:" : err.data()) << " "
|
||||
<< _mediaInfo._vhost << " "
|
||||
<< _mediaInfo._app << " "
|
||||
<< _mediaInfo._streamid;
|
||||
string errMsg = StrPrinter << (auth_success ? "already publishing:" : err.data()) << " "
|
||||
<< _media_info._vhost << " "
|
||||
<< _media_info._app << " "
|
||||
<< _media_info._streamid;
|
||||
shutdown(SockException(Err_shutdown,errMsg));
|
||||
return;
|
||||
}
|
||||
_pPublisherSrc.reset(new RtmpMediaSourceImp(_mediaInfo._vhost,_mediaInfo._app,_mediaInfo._streamid));
|
||||
_pPublisherSrc->setListener(dynamic_pointer_cast<MediaSourceEvent>(shared_from_this()));
|
||||
_publisher_src.reset(new RtmpMediaSourceImp(_media_info._vhost, _media_info._app, _media_info._streamid));
|
||||
_publisher_src->setListener(dynamic_pointer_cast<MediaSourceEvent>(shared_from_this()));
|
||||
//设置转协议
|
||||
_pPublisherSrc->setProtocolTranslation(enableRtxp,enableHls,enableMP4);
|
||||
_publisher_src->setProtocolTranslation(enableRtxp, enableHls, enableMP4);
|
||||
|
||||
//如果是rtmp推流客户端,那么加大TCP接收缓存,这样能提升接收性能
|
||||
_sock->setReadBuffer(std::make_shared<BufferRaw>(256 * 1024));
|
||||
setSocketFlags();
|
||||
};
|
||||
|
||||
if(_mediaInfo._app.empty() || _mediaInfo._streamid.empty()){
|
||||
if(_media_info._app.empty() || _media_info._streamid.empty()){
|
||||
//不允许莫名其妙的推流url
|
||||
onRes("rtmp推流url非法", false, false, false);
|
||||
on_res("rtmp推流url非法", false, false, false);
|
||||
return;
|
||||
}
|
||||
|
||||
Broadcast::PublishAuthInvoker invoker = [weakSelf,onRes,pToken](const string &err,bool enableRtxp,bool enableHls,bool enableMP4){
|
||||
auto strongSelf = weakSelf.lock();
|
||||
Broadcast::PublishAuthInvoker invoker = [weak_self,on_res,pToken](const string &err, bool enableRtxp, bool enableHls, bool enableMP4){
|
||||
auto strongSelf = weak_self.lock();
|
||||
if(!strongSelf){
|
||||
return;
|
||||
}
|
||||
strongSelf->async([weakSelf,onRes,err,pToken,enableRtxp,enableHls,enableMP4](){
|
||||
auto strongSelf = weakSelf.lock();
|
||||
strongSelf->async([weak_self,on_res,err,pToken,enableRtxp,enableHls,enableMP4](){
|
||||
auto strongSelf = weak_self.lock();
|
||||
if(!strongSelf){
|
||||
return;
|
||||
}
|
||||
onRes(err,enableRtxp,enableHls,enableMP4);
|
||||
on_res(err, enableRtxp, enableHls, enableMP4);
|
||||
});
|
||||
};
|
||||
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPublish,_mediaInfo,invoker,static_cast<SockInfo &>(*this));
|
||||
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPublish, _media_info, invoker, static_cast<SockInfo &>(*this));
|
||||
if(!flag){
|
||||
//该事件无人监听,默认鉴权成功
|
||||
GET_CONFIG(bool,toRtxp,General::kPublishToRtxp);
|
||||
GET_CONFIG(bool,toHls,General::kPublishToHls);
|
||||
GET_CONFIG(bool,toMP4,General::kPublishToMP4);
|
||||
onRes("",toRtxp,toHls,toMP4);
|
||||
GET_CONFIG(bool,to_rtxp,General::kPublishToRtxp);
|
||||
GET_CONFIG(bool,to_hls,General::kPublishToHls);
|
||||
GET_CONFIG(bool,to_mp4,General::kPublishToMP4);
|
||||
on_res("", to_rtxp, to_hls, to_mp4);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,8 +196,8 @@ void RtmpSession::onCmd_deleteStream(AMFDecoder &dec) {
|
||||
}
|
||||
|
||||
void RtmpSession::sendPlayResponse(const string &err,const RtmpMediaSource::Ptr &src){
|
||||
bool authSuccess = err.empty();
|
||||
bool ok = (src.operator bool() && authSuccess);
|
||||
bool auth_success = err.empty();
|
||||
bool ok = (src.operator bool() && auth_success);
|
||||
if (ok) {
|
||||
//stream begin
|
||||
sendUserControl(CONTROL_STREAM_BEGIN, STREAM_MEDIA);
|
||||
@@ -205,17 +205,17 @@ void RtmpSession::sendPlayResponse(const string &err,const RtmpMediaSource::Ptr
|
||||
// onStatus(NetStream.Play.Reset)
|
||||
AMFValue status(AMF_OBJECT);
|
||||
status.set("level", ok ? "status" : "error");
|
||||
status.set("code", ok ? "NetStream.Play.Reset" : (authSuccess ? "NetStream.Play.StreamNotFound" : "NetStream.Play.BadAuth"));
|
||||
status.set("description", ok ? "Resetting and playing." : (authSuccess ? "No such stream." : err.data()));
|
||||
status.set("details", _mediaInfo._streamid);
|
||||
status.set("code", ok ? "NetStream.Play.Reset" : (auth_success ? "NetStream.Play.StreamNotFound" : "NetStream.Play.BadAuth"));
|
||||
status.set("description", ok ? "Resetting and playing." : (auth_success ? "No such stream." : err.data()));
|
||||
status.set("details", _media_info._streamid);
|
||||
status.set("clientid", "0");
|
||||
sendReply("onStatus", nullptr, status);
|
||||
if (!ok) {
|
||||
string errMsg = StrPrinter << (authSuccess ? "no such stream:" : err.data()) << " "
|
||||
<< _mediaInfo._vhost << " "
|
||||
<< _mediaInfo._app << " "
|
||||
<< _mediaInfo._streamid;
|
||||
shutdown(SockException(Err_shutdown,errMsg));
|
||||
string err_msg = StrPrinter << (auth_success ? "no such stream:" : err.data()) << " "
|
||||
<< _media_info._vhost << " "
|
||||
<< _media_info._app << " "
|
||||
<< _media_info._streamid;
|
||||
shutdown(SockException(Err_shutdown, err_msg));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ void RtmpSession::sendPlayResponse(const string &err,const RtmpMediaSource::Ptr
|
||||
status.set("level", "status");
|
||||
status.set("code", "NetStream.Play.Start");
|
||||
status.set("description", "Started playing.");
|
||||
status.set("details", _mediaInfo._streamid);
|
||||
status.set("details", _media_info._streamid);
|
||||
status.set("clientid", "0");
|
||||
sendReply("onStatus", nullptr, status);
|
||||
|
||||
@@ -245,7 +245,7 @@ void RtmpSession::sendPlayResponse(const string &err,const RtmpMediaSource::Ptr
|
||||
status.set("level", "status");
|
||||
status.set("code", "NetStream.Play.PublishNotify");
|
||||
status.set("description", "Now published.");
|
||||
status.set("details", _mediaInfo._streamid);
|
||||
status.set("details", _media_info._streamid);
|
||||
status.set("clientid", "0");
|
||||
sendReply("onStatus", nullptr, status);
|
||||
|
||||
@@ -273,9 +273,9 @@ void RtmpSession::sendPlayResponse(const string &err,const RtmpMediaSource::Ptr
|
||||
|
||||
//音频同步于视频
|
||||
_stamp[0].syncTo(_stamp[1]);
|
||||
_pRingReader = src->getRing()->attach(getPoller());
|
||||
_ring_reader = src->getRing()->attach(getPoller());
|
||||
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
|
||||
_pRingReader->setReadCB([weakSelf](const RtmpMediaSource::RingDataType &pkt) {
|
||||
_ring_reader->setReadCB([weakSelf](const RtmpMediaSource::RingDataType &pkt) {
|
||||
auto strongSelf = weakSelf.lock();
|
||||
if (!strongSelf) {
|
||||
return;
|
||||
@@ -293,14 +293,14 @@ void RtmpSession::sendPlayResponse(const string &err,const RtmpMediaSource::Ptr
|
||||
strongSelf->onSendMedia(rtmp);
|
||||
});
|
||||
});
|
||||
_pRingReader->setDetachCB([weakSelf]() {
|
||||
_ring_reader->setDetachCB([weakSelf]() {
|
||||
auto strongSelf = weakSelf.lock();
|
||||
if (!strongSelf) {
|
||||
return;
|
||||
}
|
||||
strongSelf->shutdown(SockException(Err_shutdown,"rtmp ring buffer detached"));
|
||||
});
|
||||
_pPlayerSrc = src;
|
||||
_player_src = src;
|
||||
if (src->totalReaderCount() == 1) {
|
||||
src->seekTo(0);
|
||||
}
|
||||
@@ -317,46 +317,47 @@ void RtmpSession::doPlayResponse(const string &err,const std::function<void(bool
|
||||
}
|
||||
|
||||
//鉴权成功,查找媒体源并回复
|
||||
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
|
||||
MediaSource::findAsync(_mediaInfo,weakSelf.lock(),[weakSelf,cb](const MediaSource::Ptr &src){
|
||||
weak_ptr<RtmpSession> weak_self = dynamic_pointer_cast<RtmpSession>(shared_from_this());
|
||||
MediaSource::findAsync(_media_info, weak_self.lock(), [weak_self,cb](const MediaSource::Ptr &src){
|
||||
auto rtmp_src = dynamic_pointer_cast<RtmpMediaSource>(src);
|
||||
auto strongSelf = weakSelf.lock();
|
||||
if(strongSelf){
|
||||
strongSelf->sendPlayResponse("", rtmp_src);
|
||||
auto strong_self = weak_self.lock();
|
||||
if(strong_self){
|
||||
strong_self->sendPlayResponse("", rtmp_src);
|
||||
}
|
||||
cb(rtmp_src.operator bool());
|
||||
});
|
||||
}
|
||||
|
||||
void RtmpSession::doPlay(AMFDecoder &dec){
|
||||
std::shared_ptr<Ticker> pTicker(new Ticker);
|
||||
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
|
||||
std::shared_ptr<onceToken> pToken(new onceToken(nullptr,[pTicker,weakSelf](){
|
||||
auto strongSelf = weakSelf.lock();
|
||||
if(strongSelf) {
|
||||
DebugP(strongSelf.get()) << "play 回复时间:" << pTicker->elapsedTime() << "ms";
|
||||
std::shared_ptr<Ticker> ticker(new Ticker);
|
||||
weak_ptr<RtmpSession> weak_self = dynamic_pointer_cast<RtmpSession>(shared_from_this());
|
||||
std::shared_ptr<onceToken> token(new onceToken(nullptr, [ticker,weak_self](){
|
||||
auto strongSelf = weak_self.lock();
|
||||
if (strongSelf) {
|
||||
DebugP(strongSelf.get()) << "play 回复时间:" << ticker->elapsedTime() << "ms";
|
||||
}
|
||||
}));
|
||||
Broadcast::AuthInvoker invoker = [weakSelf,pToken](const string &err){
|
||||
auto strongSelf = weakSelf.lock();
|
||||
if(!strongSelf){
|
||||
Broadcast::AuthInvoker invoker = [weak_self,token](const string &err){
|
||||
auto strong_self = weak_self.lock();
|
||||
if (!strong_self) {
|
||||
return;
|
||||
}
|
||||
strongSelf->async([weakSelf,err,pToken](){
|
||||
auto strongSelf = weakSelf.lock();
|
||||
if(!strongSelf){
|
||||
strong_self->async([weak_self, err, token]() {
|
||||
auto strong_self = weak_self.lock();
|
||||
if (!strong_self) {
|
||||
return;
|
||||
}
|
||||
strongSelf->doPlayResponse(err,[pToken](bool){});
|
||||
strong_self->doPlayResponse(err, [token](bool) {});
|
||||
});
|
||||
};
|
||||
|
||||
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed,_mediaInfo,invoker,static_cast<SockInfo &>(*this));
|
||||
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed, _media_info, invoker, static_cast<SockInfo &>(*this));
|
||||
if(!flag){
|
||||
//该事件无人监听,默认不鉴权
|
||||
doPlayResponse("",[pToken](bool){});
|
||||
doPlayResponse("",[token](bool){});
|
||||
}
|
||||
}
|
||||
|
||||
void RtmpSession::onCmd_play2(AMFDecoder &dec) {
|
||||
doPlay(dec);
|
||||
}
|
||||
@@ -365,30 +366,30 @@ string RtmpSession::getStreamId(const string &str){
|
||||
string stream_id;
|
||||
string params;
|
||||
auto pos = str.find('?');
|
||||
if(pos != string::npos){
|
||||
if (pos != string::npos) {
|
||||
//有url参数
|
||||
stream_id = str.substr(0,pos);
|
||||
stream_id = str.substr(0, pos);
|
||||
//获取url参数
|
||||
params = str.substr(pos + 1);
|
||||
}else{
|
||||
} else {
|
||||
//没有url参数
|
||||
stream_id = str;
|
||||
}
|
||||
|
||||
pos = stream_id.find(":");
|
||||
if(pos != string::npos){
|
||||
if (pos != string::npos) {
|
||||
//vlc和ffplay在播放 rtmp://127.0.0.1/record/0.mp4时,
|
||||
//传过来的url会是rtmp://127.0.0.1/record/mp4:0,
|
||||
//我们在这里还原成0.mp4
|
||||
//实际使用时发现vlc,mpv等会传过来rtmp://127.0.0.1/record/mp4:0.mp4,这里做个判断
|
||||
auto ext = stream_id.substr(0,pos);
|
||||
auto ext = stream_id.substr(0, pos);
|
||||
stream_id = stream_id.substr(pos + 1);
|
||||
if(stream_id.find(ext) == string::npos){
|
||||
if (stream_id.find(ext) == string::npos) {
|
||||
stream_id = stream_id + "." + ext;
|
||||
}
|
||||
}
|
||||
|
||||
if(params.empty()){
|
||||
if (params.empty()) {
|
||||
//没有url参数
|
||||
return stream_id;
|
||||
}
|
||||
@@ -399,8 +400,8 @@ string RtmpSession::getStreamId(const string &str){
|
||||
|
||||
void RtmpSession::onCmd_play(AMFDecoder &dec) {
|
||||
dec.load<AMFValue>();/* NULL */
|
||||
_mediaInfo.parse(_strTcUrl + "/" + getStreamId(dec.load<std::string>()));
|
||||
_mediaInfo._schema = RTMP_SCHEMA;
|
||||
_media_info.parse(_tc_url + "/" + getStreamId(dec.load<std::string>()));
|
||||
_media_info._schema = RTMP_SCHEMA;
|
||||
doPlay(dec);
|
||||
}
|
||||
|
||||
@@ -419,7 +420,7 @@ void RtmpSession::onCmd_pause(AMFDecoder &dec) {
|
||||
}
|
||||
|
||||
void RtmpSession::setMetaData(AMFDecoder &dec) {
|
||||
if (!_pPublisherSrc) {
|
||||
if (!_publisher_src) {
|
||||
throw std::runtime_error("not a publisher");
|
||||
}
|
||||
std::string type = dec.load<std::string>();
|
||||
@@ -428,22 +429,23 @@ void RtmpSession::setMetaData(AMFDecoder &dec) {
|
||||
}
|
||||
auto metadata = dec.load<AMFValue>();
|
||||
// dumpMetadata(metadata);
|
||||
_pPublisherSrc->setMetaData(metadata);
|
||||
_publisher_src->setMetaData(metadata);
|
||||
_set_meta_data = true;
|
||||
}
|
||||
|
||||
void RtmpSession::onProcessCmd(AMFDecoder &dec) {
|
||||
typedef void (RtmpSession::*rtmpCMDHandle)(AMFDecoder &dec);
|
||||
static unordered_map<string, rtmpCMDHandle> s_cmd_functions;
|
||||
typedef void (RtmpSession::*cmd_function)(AMFDecoder &dec);
|
||||
static unordered_map<string, cmd_function> s_cmd_functions;
|
||||
static onceToken token([]() {
|
||||
s_cmd_functions.emplace("connect",&RtmpSession::onCmd_connect);
|
||||
s_cmd_functions.emplace("createStream",&RtmpSession::onCmd_createStream);
|
||||
s_cmd_functions.emplace("publish",&RtmpSession::onCmd_publish);
|
||||
s_cmd_functions.emplace("deleteStream",&RtmpSession::onCmd_deleteStream);
|
||||
s_cmd_functions.emplace("play",&RtmpSession::onCmd_play);
|
||||
s_cmd_functions.emplace("play2",&RtmpSession::onCmd_play2);
|
||||
s_cmd_functions.emplace("seek",&RtmpSession::onCmd_seek);
|
||||
s_cmd_functions.emplace("pause",&RtmpSession::onCmd_pause);}, []() {});
|
||||
s_cmd_functions.emplace("connect", &RtmpSession::onCmd_connect);
|
||||
s_cmd_functions.emplace("createStream", &RtmpSession::onCmd_createStream);
|
||||
s_cmd_functions.emplace("publish", &RtmpSession::onCmd_publish);
|
||||
s_cmd_functions.emplace("deleteStream", &RtmpSession::onCmd_deleteStream);
|
||||
s_cmd_functions.emplace("play", &RtmpSession::onCmd_play);
|
||||
s_cmd_functions.emplace("play2", &RtmpSession::onCmd_play2);
|
||||
s_cmd_functions.emplace("seek", &RtmpSession::onCmd_seek);
|
||||
s_cmd_functions.emplace("pause", &RtmpSession::onCmd_pause);
|
||||
});
|
||||
|
||||
std::string method = dec.load<std::string>();
|
||||
auto it = s_cmd_functions.find(method);
|
||||
@@ -451,52 +453,54 @@ void RtmpSession::onProcessCmd(AMFDecoder &dec) {
|
||||
// TraceP(this) << "can not support cmd:" << method;
|
||||
return;
|
||||
}
|
||||
_dNowReqID = dec.load<double>();
|
||||
_recv_req_id = dec.load<double>();
|
||||
auto fun = it->second;
|
||||
(this->*fun)(dec);
|
||||
}
|
||||
|
||||
void RtmpSession::onRtmpChunk(RtmpPacket &chunkData) {
|
||||
switch (chunkData.typeId) {
|
||||
void RtmpSession::onRtmpChunk(RtmpPacket &chunk_data) {
|
||||
switch (chunk_data.type_id) {
|
||||
case MSG_CMD:
|
||||
case MSG_CMD3: {
|
||||
AMFDecoder dec(chunkData.strBuf, chunkData.typeId == MSG_CMD3 ? 1 : 0);
|
||||
AMFDecoder dec(chunk_data.buffer, chunk_data.type_id == MSG_CMD3 ? 1 : 0);
|
||||
onProcessCmd(dec);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case MSG_DATA:
|
||||
case MSG_DATA3: {
|
||||
AMFDecoder dec(chunkData.strBuf, chunkData.typeId == MSG_CMD3 ? 1 : 0);
|
||||
AMFDecoder dec(chunk_data.buffer, chunk_data.type_id == MSG_CMD3 ? 1 : 0);
|
||||
std::string type = dec.load<std::string>();
|
||||
if (type == "@setDataFrame") {
|
||||
setMetaData(dec);
|
||||
}else{
|
||||
} else {
|
||||
TraceP(this) << "unknown notify:" << type;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case MSG_AUDIO:
|
||||
case MSG_VIDEO: {
|
||||
if (!_pPublisherSrc) {
|
||||
if (!_publisher_src) {
|
||||
throw std::runtime_error("Not a rtmp publisher!");
|
||||
}
|
||||
GET_CONFIG(bool,rtmp_modify_stamp,Rtmp::kModifyStamp);
|
||||
if(rtmp_modify_stamp){
|
||||
GET_CONFIG(bool, rtmp_modify_stamp, Rtmp::kModifyStamp);
|
||||
if (rtmp_modify_stamp) {
|
||||
int64_t dts_out;
|
||||
_stamp[chunkData.typeId % 2].revise(chunkData.timeStamp, chunkData.timeStamp, dts_out, dts_out, true);
|
||||
chunkData.timeStamp = dts_out;
|
||||
_stamp[chunk_data.type_id % 2].revise(chunk_data.time_stamp, chunk_data.time_stamp, dts_out, dts_out, true);
|
||||
chunk_data.time_stamp = dts_out;
|
||||
}
|
||||
|
||||
if(!_set_meta_data && !chunkData.isCfgFrame()){
|
||||
if (!_set_meta_data && !chunk_data.isCfgFrame()) {
|
||||
_set_meta_data = true;
|
||||
_pPublisherSrc->setMetaData(TitleMeta().getMetadata());
|
||||
_publisher_src->setMetaData(TitleMeta().getMetadata());
|
||||
}
|
||||
_pPublisherSrc->onWrite(std::make_shared<RtmpPacket>(std::move(chunkData)));
|
||||
}
|
||||
_publisher_src->onWrite(std::make_shared<RtmpPacket>(std::move(chunk_data)));
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
WarnP(this) << "unhandled message:" << (int) chunkData.typeId << hexdump(chunkData.strBuf.data(), chunkData.strBuf.size());
|
||||
WarnP(this) << "unhandled message:" << (int) chunk_data.type_id << hexdump(chunk_data.buffer.data(), chunk_data.buffer.size());
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -512,23 +516,23 @@ void RtmpSession::onCmd_seek(AMFDecoder &dec) {
|
||||
|
||||
auto milliSeconds = dec.load<AMFValue>().as_number();
|
||||
InfoP(this) << "rtmp seekTo(ms):" << milliSeconds;
|
||||
auto stongSrc = _pPlayerSrc.lock();
|
||||
if (stongSrc) {
|
||||
stongSrc->seekTo(milliSeconds);
|
||||
auto strong_src = _player_src.lock();
|
||||
if (strong_src) {
|
||||
strong_src->seekTo(milliSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
void RtmpSession::onSendMedia(const RtmpPacket::Ptr &pkt) {
|
||||
//rtmp播放器时间戳从零开始
|
||||
int64_t dts_out;
|
||||
_stamp[pkt->typeId % 2].revise(pkt->timeStamp, 0, dts_out, dts_out);
|
||||
sendRtmp(pkt->typeId, pkt->streamId, pkt, dts_out, pkt->chunkId);
|
||||
_stamp[pkt->type_id % 2].revise(pkt->time_stamp, 0, dts_out, dts_out);
|
||||
sendRtmp(pkt->type_id, pkt->stream_index, pkt, dts_out, pkt->chunk_id);
|
||||
}
|
||||
|
||||
|
||||
bool RtmpSession::close(MediaSource &sender,bool force) {
|
||||
//此回调在其他线程触发
|
||||
if(!_pPublisherSrc || (!force && _pPublisherSrc->totalReaderCount())){
|
||||
if(!_publisher_src || (!force && _publisher_src->totalReaderCount())){
|
||||
return false;
|
||||
}
|
||||
string err = StrPrinter << "close media:" << sender.getSchema() << "/" << sender.getVhost() << "/" << sender.getApp() << "/" << sender.getId() << " " << force;
|
||||
@@ -537,12 +541,12 @@ bool RtmpSession::close(MediaSource &sender,bool force) {
|
||||
}
|
||||
|
||||
int RtmpSession::totalReaderCount(MediaSource &sender) {
|
||||
return _pPublisherSrc ? _pPublisherSrc->totalReaderCount() : sender.readerCount();
|
||||
return _publisher_src ? _publisher_src->totalReaderCount() : sender.readerCount();
|
||||
}
|
||||
|
||||
void RtmpSession::setSocketFlags(){
|
||||
GET_CONFIG(int, mergeWriteMS, General::kMergeWriteMS);
|
||||
if(mergeWriteMS > 0) {
|
||||
GET_CONFIG(int, merge_write_ms, General::kMergeWriteMS);
|
||||
if (merge_write_ms > 0) {
|
||||
//推流模式下,关闭TCP_NODELAY会增加推流端的延时,但是服务器性能将提高
|
||||
SockUtil::setNoDelay(_sock->rawFD(), false);
|
||||
//播放模式下,开启MSG_MORE会增加延时,但是能提高发送性能
|
||||
@@ -551,14 +555,14 @@ void RtmpSession::setSocketFlags(){
|
||||
}
|
||||
|
||||
void RtmpSession::dumpMetadata(const AMFValue &metadata) {
|
||||
if(metadata.type() != AMF_OBJECT && metadata.type() != AMF_ECMA_ARRAY){
|
||||
if (metadata.type() != AMF_OBJECT && metadata.type() != AMF_ECMA_ARRAY) {
|
||||
WarnL << "invalid metadata type:" << metadata.type();
|
||||
return ;
|
||||
return;
|
||||
}
|
||||
_StrPrinter printer;
|
||||
metadata.object_for_each([&](const string &key, const AMFValue &val){
|
||||
printer << "\r\n" << key << "\t:" << val.to_string() ;
|
||||
metadata.object_for_each([&](const string &key, const AMFValue &val) {
|
||||
printer << "\r\n" << key << "\t:" << val.to_string();
|
||||
});
|
||||
InfoL << _mediaInfo._vhost << " " << _mediaInfo._app << " " << _mediaInfo._streamid << (string)printer;
|
||||
InfoL << _media_info._vhost << " " << _media_info._app << " " << _media_info._streamid << (string) printer;
|
||||
}
|
||||
} /* namespace mediakit */
|
||||
|
||||
Reference in New Issue
Block a user