ZLMediaKit/src/Rtmp/RtmpSession.cpp

565 lines
21 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 "RtmpSession.h"
#include "Common/config.h"
2017-04-01 16:35:56 +08:00
#include "Util/onceToken.h"
2018-10-24 17:17:55 +08:00
namespace mediakit {
2017-04-01 16:35:56 +08:00
2018-12-20 10:42:51 +08:00
RtmpSession::RtmpSession(const Socket::Ptr &pSock) : TcpSession(pSock) {
2020-03-20 11:51:24 +08:00
DebugP(this);
2019-05-30 10:41:25 +08:00
GET_CONFIG(uint32_t,keep_alive_sec,Rtmp::kKeepAliveSecond);
pSock->setSendTimeOutSecond(keep_alive_sec);
//起始接收buffer缓存设置为4K节省内存
pSock->setReadBuffer(std::make_shared<BufferRaw>(4 * 1024));
2017-04-01 16:35:56 +08:00
}
RtmpSession::~RtmpSession() {
2019-05-28 18:46:52 +08:00
DebugP(this);
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onError(const SockException& err) {
2019-10-23 12:00:53 +08:00
bool isPlayer = !_pPublisherSrc;
2020-02-13 12:10:08 +08:00
uint64_t duration = _ticker.createdTime()/1000;
2019-12-29 15:38:29 +08:00
WarnP(this) << (isPlayer ? "RTMP播放器(" : "RTMP推流器(")
2019-10-23 12:00:53 +08:00
<< _mediaInfo._vhost << "/"
<< _mediaInfo._app << "/"
<< _mediaInfo._streamid
2020-02-13 12:10:08 +08:00
<< ")断开:" << err.what()
<< ",耗时(s):" << duration;
//流量统计事件广播
2019-05-28 17:14:36 +08:00
GET_CONFIG(uint32_t,iFlowThreshold,General::kFlowThreshold);
2018-02-09 11:42:55 +08:00
2018-10-24 15:43:52 +08:00
if(_ui64TotalBytes > iFlowThreshold * 1024){
2020-04-23 22:04:59 +08:00
NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastFlowReport, _mediaInfo, _ui64TotalBytes, duration, isPlayer, static_cast<SockInfo &>(*this));
}
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onManager() {
2019-08-28 18:20:40 +08:00
GET_CONFIG(uint32_t,handshake_sec,Rtmp::kHandshakeSecond);
2019-05-29 18:24:35 +08:00
GET_CONFIG(uint32_t,keep_alive_sec,Rtmp::kKeepAliveSecond);
2020-03-20 11:51:24 +08:00
if (_ticker.createdTime() > handshake_sec * 1000) {
if (!_pRingReader && !_pPublisherSrc) {
shutdown(SockException(Err_timeout,"illegal connection"));
}
}
if (_pPublisherSrc) {
//publisher
if (_ticker.elapsedTime() > keep_alive_sec * 1000) {
shutdown(SockException(Err_timeout,"recv data from rtmp pusher timeout"));
}
}
2017-04-01 16:35:56 +08:00
}
2018-02-23 15:36:51 +08:00
void RtmpSession::onRecv(const Buffer::Ptr &pBuf) {
2020-03-20 11:51:24 +08:00
_ticker.resetTime();
try {
2018-10-24 15:43:52 +08:00
_ui64TotalBytes += pBuf->size();
2020-03-20 11:51:24 +08:00
onParseRtmp(pBuf->data(), pBuf->size());
} catch (exception &e) {
shutdown(SockException(Err_shutdown, e.what()));
}
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onCmd_connect(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
auto params = dec.load<AMFValue>();
double amfVer = 0;
AMFValue objectEncoding = params["objectEncoding"];
if(objectEncoding){
amfVer = objectEncoding.as_number();
}
///////////set chunk size////////////////
sendChunkSize(60000);
////////////window Acknowledgement size/////
sendAcknowledgementSize(5000000);
///////////set peerBandwidth////////////////
sendPeerBandwidth(5000000);
2017-05-13 17:25:31 +08:00
2018-10-24 15:43:52 +08:00
_mediaInfo._app = params["app"].as_string();
_strTcUrl = params["tcUrl"].as_string();
if(_strTcUrl.empty()){
//defaultVhost:默认vhost
2018-10-24 15:43:52 +08:00
_strTcUrl = string(RTMP_SCHEMA) + "://" + DEFAULT_VHOST + "/" + _mediaInfo._app;
}
2020-03-20 11:51:24 +08:00
bool ok = true; //(app == APP_NAME);
AMFValue version(AMF_OBJECT);
version.set("fmsVer", "FMS/3,0,1,123");
version.set("capabilities", 31.0);
AMFValue status(AMF_OBJECT);
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);
sendReply(ok ? "_result" : "_error", version, status);
if (!ok) {
throw std::runtime_error("Unsupported application: " + _mediaInfo._app);
}
AMFEncoder invoke;
invoke << "onBWDone" << 0.0 << nullptr;
sendResponse(MSG_CMD, invoke.data());
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onCmd_createStream(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
sendReply("_result", nullptr, double(STREAM_MEDIA));
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onCmd_publish(AMFDecoder &dec) {
std::shared_ptr<Ticker> pTicker(new Ticker);
2019-05-28 18:46:52 +08:00
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";
}
}));
2020-03-20 11:51:24 +08:00
dec.load<AMFValue>();/* NULL */
2019-09-06 18:30:42 +08:00
_mediaInfo.parse(_strTcUrl + "/" + getStreamId(dec.load<std::string>()));
_mediaInfo._schema = RTMP_SCHEMA;
auto onRes = [this,pToken](const string &err,bool enableRtxp,bool enableHls,bool enableMP4){
auto src = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,
2018-10-24 15:43:52 +08:00
_mediaInfo._vhost,
_mediaInfo._app,
2020-05-26 10:11:58 +08:00
_mediaInfo._streamid));
2018-02-06 16:17:37 +08:00
bool authSuccess = err.empty();
2018-10-24 15:43:52 +08:00
bool ok = (!src && !_pPublisherSrc && authSuccess);
AMFValue status(AMF_OBJECT);
status.set("level", ok ? "status" : "error");
status.set("code", ok ? "NetStream.Publish.Start" : (authSuccess ? "NetStream.Publish.BadName" : "NetStream.Publish.BadAuth"));
2018-02-05 17:25:22 +08:00
status.set("description", ok ? "Started publishing stream." : (authSuccess ? "Already publishing." : err.data()));
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
if (!ok) {
2019-05-29 18:08:50 +08:00
string errMsg = StrPrinter << (authSuccess ? "already publishing:" : err.data()) << " "
<< _mediaInfo._vhost << " "
<< _mediaInfo._app << " "
<< _mediaInfo._streamid;
shutdown(SockException(Err_shutdown,errMsg));
return;
}
_pPublisherSrc.reset(new RtmpMediaSourceImp(_mediaInfo._vhost,_mediaInfo._app,_mediaInfo._streamid));
2018-10-24 15:43:52 +08:00
_pPublisherSrc->setListener(dynamic_pointer_cast<MediaSourceEvent>(shared_from_this()));
//设置转协议
_pPublisherSrc->setProtocolTranslation(enableRtxp,enableHls,enableMP4);
//如果是rtmp推流客户端那么加大TCP接收缓存这样能提升接收性能
_sock->setReadBuffer(std::make_shared<BufferRaw>(256 * 1024));
setSocketFlags();
};
2020-05-25 16:40:41 +08:00
if(_mediaInfo._app.empty() || _mediaInfo._streamid.empty()){
//不允许莫名其妙的推流url
onRes("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();
if(!strongSelf){
return;
}
strongSelf->async([weakSelf,onRes,err,pToken,enableRtxp,enableHls,enableMP4](){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
onRes(err,enableRtxp,enableHls,enableMP4);
});
};
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPublish,_mediaInfo,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);
}
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onCmd_deleteStream(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
AMFValue status(AMF_OBJECT);
status.set("level", "status");
status.set("code", "NetStream.Unpublish.Success");
status.set("description", "Stop publishing.");
sendReply("onStatus", nullptr, status);
throw std::runtime_error(StrPrinter << "Stop publishing" << endl);
2017-04-01 16:35:56 +08:00
}
2018-10-31 12:11:14 +08:00
void RtmpSession::sendPlayResponse(const string &err,const RtmpMediaSource::Ptr &src){
bool authSuccess = err.empty();
2018-03-14 22:35:54 +08:00
bool ok = (src.operator bool() && authSuccess);
if (ok) {
//stream begin
sendUserControl(CONTROL_STREAM_BEGIN, STREAM_MEDIA);
}
// 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()));
2018-10-24 15:43:52 +08:00
status.set("details", _mediaInfo._streamid);
2018-03-14 22:35:54 +08:00
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
if (!ok) {
2019-05-29 18:08:50 +08:00
string errMsg = StrPrinter << (authSuccess ? "no such stream:" : err.data()) << " "
<< _mediaInfo._vhost << " "
<< _mediaInfo._app << " "
<< _mediaInfo._streamid;
shutdown(SockException(Err_shutdown,errMsg));
2018-03-14 22:35:54 +08:00
return;
}
2017-04-01 16:35:56 +08:00
2018-03-14 22:35:54 +08:00
// onStatus(NetStream.Play.Start)
status.clear();
status.set("level", "status");
status.set("code", "NetStream.Play.Start");
status.set("description", "Started playing.");
2018-10-24 15:43:52 +08:00
status.set("details", _mediaInfo._streamid);
2018-03-14 22:35:54 +08:00
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
// |RtmpSampleAccess(true, true)
AMFEncoder invoke;
invoke << "|RtmpSampleAccess" << true << true;
sendResponse(MSG_DATA, invoke.data());
//onStatus(NetStream.Data.Start)
invoke.clear();
AMFValue obj(AMF_OBJECT);
obj.set("code", "NetStream.Data.Start");
invoke << "onStatus" << obj;
sendResponse(MSG_DATA, invoke.data());
//onStatus(NetStream.Play.PublishNotify)
status.clear();
status.set("level", "status");
status.set("code", "NetStream.Play.PublishNotify");
status.set("description", "Now published.");
2018-10-24 15:43:52 +08:00
status.set("details", _mediaInfo._streamid);
2018-03-14 22:35:54 +08:00
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
2019-09-21 19:27:34 +08:00
auto &metadata = src->getMetaData();
if(metadata){
//在有metadata的情况下才发送metadata
//其实metadata没什么用有些推流器不产生metadata
// onMetaData
invoke.clear();
invoke << "onMetaData" << metadata;
sendResponse(MSG_DATA, invoke.data());
auto duration = metadata["duration"];
if(duration && duration.as_number() > 0){
2020-04-04 15:37:37 +08:00
//这是点播,使用绝对时间戳
_stamp[0].setPlayBack();
_stamp[1].setPlayBack();
}
2019-09-21 19:27:34 +08:00
}
2018-03-14 22:35:54 +08:00
src->getConfigFrame([&](const RtmpPacket::Ptr &pkt) {
2019-05-28 18:46:52 +08:00
//DebugP(this)<<"send initial frame";
2018-03-14 22:35:54 +08:00
onSendMedia(pkt);
});
//音频同步于视频
2020-05-15 18:08:54 +08:00
_stamp[0].syncTo(_stamp[1]);
_pRingReader = src->getRing()->attach(getPoller());
2018-03-14 22:35:54 +08:00
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
2020-04-09 16:19:03 +08:00
_pRingReader->setReadCB([weakSelf](const RtmpMediaSource::RingDataType &pkt) {
2018-03-14 22:35:54 +08:00
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
return;
}
2020-04-09 16:19:03 +08:00
if(strongSelf->_paused){
return;
}
int i = 0;
int size = pkt->size();
strongSelf->setSendFlushFlag(false);
pkt->for_each([&](const RtmpPacket::Ptr &rtmp){
if(++i == size){
strongSelf->setSendFlushFlag(true);
}
strongSelf->onSendMedia(rtmp);
});
2018-03-14 22:35:54 +08:00
});
2018-10-24 15:43:52 +08:00
_pRingReader->setDetachCB([weakSelf]() {
2018-03-14 22:35:54 +08:00
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
return;
}
2019-05-29 18:08:50 +08:00
strongSelf->shutdown(SockException(Err_shutdown,"rtmp ring buffer detached"));
2018-03-14 22:35:54 +08:00
});
2018-10-24 15:43:52 +08:00
_pPlayerSrc = src;
2019-12-28 16:57:35 +08:00
if (src->totalReaderCount() == 1) {
2018-03-14 22:35:54 +08:00
src->seekTo(0);
}
//提高服务器发送性能
setSocketFlags();
2018-03-14 22:35:54 +08:00
}
2018-10-31 12:11:14 +08:00
void RtmpSession::doPlayResponse(const string &err,const std::function<void(bool)> &cb){
if(!err.empty()){
//鉴权失败,直接返回播放失败
sendPlayResponse(err, nullptr);
cb(false);
return;
}
//鉴权成功,查找媒体源并回复
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
2019-12-03 16:10:02 +08:00
MediaSource::findAsync(_mediaInfo,weakSelf.lock(),[weakSelf,cb](const MediaSource::Ptr &src){
auto rtmp_src = dynamic_pointer_cast<RtmpMediaSource>(src);
2018-10-31 12:11:14 +08:00
auto strongSelf = weakSelf.lock();
if(strongSelf){
strongSelf->sendPlayResponse("", rtmp_src);
2018-10-31 12:11:14 +08:00
}
cb(rtmp_src.operator bool());
2018-10-31 12:11:14 +08:00
});
}
2018-03-14 22:35:54 +08:00
void RtmpSession::doPlay(AMFDecoder &dec){
std::shared_ptr<Ticker> pTicker(new Ticker);
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
2019-05-28 18:46:52 +08:00
std::shared_ptr<onceToken> pToken(new onceToken(nullptr,[pTicker,weakSelf](){
auto strongSelf = weakSelf.lock();
if(strongSelf) {
DebugP(strongSelf.get()) << "play 回复时间:" << pTicker->elapsedTime() << "ms";
}
}));
Broadcast::AuthInvoker invoker = [weakSelf,pToken](const string &err){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
strongSelf->async([weakSelf,err,pToken](){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
2018-10-31 12:11:14 +08:00
strongSelf->doPlayResponse(err,[pToken](bool){});
});
};
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed,_mediaInfo,invoker,static_cast<SockInfo &>(*this));
if(!flag){
//该事件无人监听,默认不鉴权
2018-10-31 12:11:14 +08:00
doPlayResponse("",[pToken](bool){});
}
2017-05-18 16:24:36 +08:00
}
void RtmpSession::onCmd_play2(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
doPlay(dec);
2017-05-18 16:24:36 +08:00
}
2019-09-06 18:30:42 +08:00
string RtmpSession::getStreamId(const string &str){
string stream_id;
string params;
auto pos = str.find('?');
if(pos != string::npos){
//有url参数
stream_id = str.substr(0,pos);
//获取url参数
params = str.substr(pos + 1);
}else{
//没有url参数
stream_id = str;
}
pos = stream_id.find(":");
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
//实际使用时发现vlcmpv等会传过来rtmp://127.0.0.1/record/mp4:0.mp4,这里做个判断
auto ext = stream_id.substr(0,pos);
stream_id = stream_id.substr(pos + 1);
if(stream_id.find(ext) == string::npos){
stream_id = stream_id + "." + ext;
}
2019-09-06 18:30:42 +08:00
}
if(params.empty()){
//没有url参数
return stream_id;
}
//有url参数
return stream_id + '?' + params;
}
2017-05-18 16:24:36 +08:00
void RtmpSession::onCmd_play(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
dec.load<AMFValue>();/* NULL */
2019-09-06 18:30:42 +08:00
_mediaInfo.parse(_strTcUrl + "/" + getStreamId(dec.load<std::string>()));
_mediaInfo._schema = RTMP_SCHEMA;
2020-03-20 11:51:24 +08:00
doPlay(dec);
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onCmd_pause(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
dec.load<AMFValue>();/* NULL */
bool paused = dec.load<bool>();
TraceP(this) << paused;
AMFValue status(AMF_OBJECT);
status.set("level", "status");
status.set("code", paused ? "NetStream.Pause.Notify" : "NetStream.Unpause.Notify");
status.set("description", paused ? "Paused stream." : "Unpaused stream.");
sendReply("onStatus", nullptr, status);
2020-04-09 16:19:03 +08:00
//streamBegin
sendUserControl(paused ? CONTROL_STREAM_EOF : CONTROL_STREAM_BEGIN, STREAM_MEDIA);
_paused = paused;
2017-04-01 16:35:56 +08:00
}
void RtmpSession::setMetaData(AMFDecoder &dec) {
2020-03-20 11:51:24 +08:00
if (!_pPublisherSrc) {
throw std::runtime_error("not a publisher");
}
std::string type = dec.load<std::string>();
if (type != "onMetaData") {
throw std::runtime_error("can only set metadata");
}
2019-09-21 19:27:34 +08:00
auto metadata = dec.load<AMFValue>();
// dumpMetadata(metadata);
2019-12-25 11:04:12 +08:00
_pPublisherSrc->setMetaData(metadata);
2020-01-13 15:48:55 +08:00
_set_meta_data = true;
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onProcessCmd(AMFDecoder &dec) {
typedef void (RtmpSession::*rtmpCMDHandle)(AMFDecoder &dec);
2019-08-22 14:56:58 +08:00
static unordered_map<string, rtmpCMDHandle> s_cmd_functions;
static onceToken token([]() {
2019-08-22 14:56:58 +08:00
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>();
2020-03-20 11:51:24 +08:00
auto it = s_cmd_functions.find(method);
if (it == s_cmd_functions.end()) {
2020-01-08 14:00:53 +08:00
// TraceP(this) << "can not support cmd:" << method;
2020-03-20 11:51:24 +08:00
return;
}
_dNowReqID = dec.load<double>();
auto fun = it->second;
(this->*fun)(dec);
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onRtmpChunk(RtmpPacket &chunkData) {
2020-03-20 11:51:24 +08:00
switch (chunkData.typeId) {
case MSG_CMD:
case MSG_CMD3: {
AMFDecoder dec(chunkData.strBuf, chunkData.typeId == MSG_CMD3 ? 1 : 0);
onProcessCmd(dec);
}
break;
case MSG_DATA:
case MSG_DATA3: {
AMFDecoder dec(chunkData.strBuf, chunkData.typeId == MSG_CMD3 ? 1 : 0);
std::string type = dec.load<std::string>();
if (type == "@setDataFrame") {
setMetaData(dec);
}else{
2020-01-08 14:03:56 +08:00
TraceP(this) << "unknown notify:" << type;
}
2020-03-20 11:51:24 +08:00
}
break;
case MSG_AUDIO:
case MSG_VIDEO: {
if (!_pPublisherSrc) {
throw std::runtime_error("Not a rtmp publisher!");
}
GET_CONFIG(bool,rtmp_modify_stamp,Rtmp::kModifyStamp);
2019-08-22 14:56:58 +08:00
if(rtmp_modify_stamp){
int64_t dts_out;
2019-11-29 09:54:48 +08:00
_stamp[chunkData.typeId % 2].revise(chunkData.timeStamp, chunkData.timeStamp, dts_out, dts_out, true);
2019-08-22 14:56:58 +08:00
chunkData.timeStamp = dts_out;
}
2020-01-13 15:48:55 +08:00
if(!_set_meta_data && !chunkData.isCfgFrame()){
_set_meta_data = true;
_pPublisherSrc->setMetaData(TitleMeta().getMetadata());
}
2019-08-22 14:56:58 +08:00
_pPublisherSrc->onWrite(std::make_shared<RtmpPacket>(std::move(chunkData)));
2020-03-20 11:51:24 +08:00
}
break;
default:
WarnP(this) << "unhandled message:" << (int) chunkData.typeId << hexdump(chunkData.strBuf.data(), chunkData.strBuf.size());
break;
}
2017-04-01 16:35:56 +08:00
}
void RtmpSession::onCmd_seek(AMFDecoder &dec) {
dec.load<AMFValue>();/* NULL */
2020-03-20 11:51:24 +08:00
AMFValue status(AMF_OBJECT);
AMFEncoder invoke;
status.set("level", "status");
status.set("code", "NetStream.Seek.Notify");
status.set("description", "Seeking.");
sendReply("onStatus", nullptr, status);
2020-04-04 15:37:37 +08:00
auto milliSeconds = dec.load<AMFValue>().as_number();
InfoP(this) << "rtmp seekTo(ms):" << milliSeconds;
auto stongSrc = _pPlayerSrc.lock();
if (stongSrc) {
stongSrc->seekTo(milliSeconds);
}
2017-04-01 16:35:56 +08:00
}
2017-12-04 23:55:09 +08:00
void RtmpSession::onSendMedia(const RtmpPacket::Ptr &pkt) {
2019-08-22 14:56:58 +08:00
//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);
2017-04-01 16:35:56 +08:00
}
2018-03-14 22:35:54 +08:00
2019-05-31 15:40:55 +08:00
bool RtmpSession::close(MediaSource &sender,bool force) {
//此回调在其他线程触发
2019-12-28 16:48:11 +08:00
if(!_pPublisherSrc || (!force && _pPublisherSrc->totalReaderCount())){
2019-05-31 15:40:55 +08:00
return false;
}
string err = StrPrinter << "close media:" << sender.getSchema() << "/" << sender.getVhost() << "/" << sender.getApp() << "/" << sender.getId() << " " << force;
safeShutdown(SockException(Err_shutdown,err));
return true;
}
2019-12-28 16:48:11 +08:00
int RtmpSession::totalReaderCount(MediaSource &sender) {
return _pPublisherSrc ? _pPublisherSrc->totalReaderCount() : sender.readerCount();
}
void RtmpSession::setSocketFlags(){
2020-04-29 11:08:43 +08:00
GET_CONFIG(int, mergeWriteMS, General::kMergeWriteMS);
if(mergeWriteMS > 0) {
//推流模式下关闭TCP_NODELAY会增加推流端的延时但是服务器性能将提高
SockUtil::setNoDelay(_sock->rawFD(), false);
//播放模式下开启MSG_MORE会增加延时但是能提高发送性能
2020-04-23 17:50:12 +08:00
setSendFlags(SOCKET_DEFAULE_FLAGS | FLAG_MORE);
}
}
2019-09-21 19:27:34 +08:00
void RtmpSession::dumpMetadata(const AMFValue &metadata) {
if(metadata.type() != AMF_OBJECT && metadata.type() != AMF_ECMA_ARRAY){
WarnL << "invalid metadata type:" << metadata.type();
2019-09-21 19:27:34 +08:00
return ;
}
_StrPrinter printer;
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;
}
2018-10-24 17:17:55 +08:00
} /* namespace mediakit */