添加 http-flv/rtmp/rtsp通用鉴权接口

This commit is contained in:
xiongziliang 2018-02-05 15:56:44 +08:00
parent 6da3a577a6
commit ec902f5164
9 changed files with 422 additions and 276 deletions

View File

@ -150,8 +150,8 @@ void MediaInfo::parse(const string &url){
auto pos = steamid.find("?"); auto pos = steamid.find("?");
if(pos != string::npos){ if(pos != string::npos){
m_streamid = steamid.substr(0,pos); m_streamid = steamid.substr(0,pos);
auto params = steamid.substr(pos + 1); m_param_strs = steamid.substr(pos + 1);
m_params = Parser::parseArgs(params); m_params = Parser::parseArgs(m_param_strs);
if(m_params.find(VHOST_KEY) != m_params.end()){ if(m_params.find(VHOST_KEY) != m_params.end()){
m_vhost = m_params[VHOST_KEY]; m_vhost = m_params[VHOST_KEY];
} }

View File

@ -83,6 +83,8 @@ public:
string m_app; string m_app;
string m_streamid; string m_streamid;
StrCaseMap m_params; StrCaseMap m_params;
string m_param_strs;
}; };

View File

@ -47,13 +47,13 @@ void loadIniConfig(){
} }
////////////广播名称/////////// ////////////广播名称///////////
namespace Broadcast { namespace Broadcast {
const char kBroadcastMediaPlayed[] = "kBroadcastMediaPlayed";
const char kBroadcastMediaChanged[] = "kBroadcastMediaChanged"; const char kBroadcastMediaChanged[] = "kBroadcastMediaChanged";
const char kBroadcastRecordMP4[] = "kBroadcastRecordMP4"; const char kBroadcastRecordMP4[] = "kBroadcastRecordMP4";
const char kBroadcastHttpRequest[] = "kBroadcastHttpRequest"; const char kBroadcastHttpRequest[] = "kBroadcastHttpRequest";
const char kBroadcastOnGetRtspRealm[] = "kBroadcastOnGetRtspRealm"; const char kBroadcastOnGetRtspRealm[] = "kBroadcastOnGetRtspRealm";
const char kBroadcastOnRtspAuth[] = "kBroadcastOnRtspAuth"; const char kBroadcastOnRtspAuth[] = "kBroadcastOnRtspAuth";
const char kBroadcastMediaPlayed[] = "kBroadcastMediaPlayed";
const char kBroadcastRtmpPublish[] = "kBroadcastRtmpPublish";
} //namespace Broadcast } //namespace Broadcast
//代理失败最大重试次数 //代理失败最大重试次数

View File

@ -51,6 +51,7 @@ void loadIniConfig();
#define SERVER_NAME "ZLMediaKit" #define SERVER_NAME "ZLMediaKit"
#define VHOST_KEY "vhost" #define VHOST_KEY "vhost"
#define HTTP_SCHEMA "http"
#define RTSP_SCHEMA "rtsp" #define RTSP_SCHEMA "rtsp"
#define RTMP_SCHEMA "rtmp" #define RTMP_SCHEMA "rtmp"
#define DEFAULT_VHOST "__defaultVhost__" #define DEFAULT_VHOST "__defaultVhost__"
@ -59,15 +60,16 @@ void loadIniConfig();
////////////广播名称/////////// ////////////广播名称///////////
namespace Broadcast { namespace Broadcast {
extern const char kBroadcastMediaPlayed[];
#define BroadcastMediaPlayedArgs const char *schema,const char *vhost,const char *app,const char *stream
//注册或反注册MediaSource事件广播
extern const char kBroadcastMediaChanged[]; extern const char kBroadcastMediaChanged[];
#define BroadcastMediaChangedArgs bool bRegist, const char *schema,const char *vhost,const char *app,const char *stream #define BroadcastMediaChangedArgs bool bRegist, const char *schema,const char *vhost,const char *app,const char *stream
//录制mp4文件成功后广播
extern const char kBroadcastRecordMP4[]; extern const char kBroadcastRecordMP4[];
#define BroadcastRecordMP4Args const Mp4Info &info #define BroadcastRecordMP4Args const Mp4Info &info
//收到http api请求广播
extern const char kBroadcastHttpRequest[]; extern const char kBroadcastHttpRequest[];
#define BroadcastHttpRequestArgs const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed #define BroadcastHttpRequestArgs const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed
@ -80,6 +82,18 @@ extern const char kBroadcastOnGetRtspRealm[];
extern const char kBroadcastOnRtspAuth[]; extern const char kBroadcastOnRtspAuth[];
#define BroadcastOnRtspAuthArgs const char *user_name,bool must_no_encrypt,const RtspSession::onAuth &invoker #define BroadcastOnRtspAuthArgs const char *user_name,bool must_no_encrypt,const RtspSession::onAuth &invoker
//鉴权结果回调对象
typedef std::function<void(bool success)> AuthInvoker;
//收到rtmp推流事件广播通过该事件控制推流鉴权
extern const char kBroadcastRtmpPublish[];
#define BroadcastRtmpPublishArgs MediaInfo &args,Broadcast::AuthInvoker &invoker
//播放rtsp或rtmp事件广播通过该事件控制播放鉴权
extern const char kBroadcastMediaPlayed[];
#define BroadcastMediaPlayedArgs MediaInfo &args,Broadcast::AuthInvoker &invoker
} //namespace Broadcast } //namespace Broadcast
//代理失败最大重试次数 //代理失败最大重试次数

View File

@ -171,7 +171,8 @@ void HttpSession::onManager() {
shutdown(); shutdown();
} }
} }
//http-flv 链接格式:http://vhost-url:port/app/streamid.flv?key1=value1&key2=value2
//如果url(除去?以及后面的参数)后缀是.flv,那么表明该url是一个http-flv直播。
inline bool HttpSession::checkLiveFlvStream(){ inline bool HttpSession::checkLiveFlvStream(){
auto pos = strrchr(m_parser.Url().data(),'.'); auto pos = strrchr(m_parser.Url().data(),'.');
if(!pos){ if(!pos){
@ -182,87 +183,118 @@ inline bool HttpSession::checkLiveFlvStream(){
//未找到".flv"后缀 //未找到".flv"后缀
return false; return false;
} }
auto fullUrl = string("http://") + m_parser["Host"] + FindField(m_parser.Url().data(),NULL,pos); //拼接成完整url
auto fullUrl = string(HTTP_SCHEMA) + "://" + m_parser["Host"] + m_parser.FullUrl();
MediaInfo info(fullUrl); MediaInfo info(fullUrl);
if(!m_parser.getUrlArgs()[VHOST_KEY].empty()){ info.m_streamid.erase(info.m_streamid.size() - 4);//去除.flv后缀
info.m_vhost = m_parser.getUrlArgs()[VHOST_KEY];
}
auto mediaSrc = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,info.m_vhost,info.m_app,info.m_streamid)); auto mediaSrc = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,info.m_vhost,info.m_app,info.m_streamid));
if(!mediaSrc){ if(!mediaSrc){
//该rtmp源不存在 //该rtmp源不存在
return false; sendNotFound(true);
shutdown();
return true;
} }
if(!mediaSrc->ready()){ if(!mediaSrc->ready()){
//未准备好 //未准备好
return false; sendNotFound(true);
shutdown();
return true;
} }
//找到rtmp源发送http头负载后续发送
sendResponse("200 OK", makeHttpHeader(false,0,get_mime_type(m_parser.Url().data())), "");
//发送flv文件头
char flv_file_header[] = "FLV\x1\x5\x0\x0\x0\x9"; // have audio and have video
bool is_have_audio = false,is_have_video = false;
mediaSrc->getConfigFrame([&](const RtmpPacket::Ptr &pkt){ auto onRes = [this,mediaSrc](bool authSuccess){
if(pkt->typeId == MSG_VIDEO){ if(!authSuccess){
is_have_video = true; string status = "401 Unauthorized";
} sendResponse(status.data(), makeHttpHeader(true,status.size()),status);
if(pkt->typeId == MSG_AUDIO){ shutdown();
is_have_audio = true; return ;
} }
}); //找到rtmp源发送http头负载后续发送
sendResponse("200 OK", makeHttpHeader(false,0,get_mime_type(".flv")), "");
//发送flv文件头
char flv_file_header[] = "FLV\x1\x5\x0\x0\x0\x9"; // have audio and have video
bool is_have_audio = false,is_have_video = false;
if (is_have_audio && is_have_video) { mediaSrc->getConfigFrame([&](const RtmpPacket::Ptr &pkt){
flv_file_header[4] = 0x05; if(pkt->typeId == MSG_VIDEO){
} else if (is_have_audio && !is_have_video) { is_have_video = true;
flv_file_header[4] = 0x04; }
} else if (!is_have_audio && is_have_video) { if(pkt->typeId == MSG_AUDIO){
flv_file_header[4] = 0x01; is_have_audio = true;
} else { }
flv_file_header[4] = 0x00; });
}
//send flv header
send(flv_file_header, sizeof(flv_file_header) - 1);
//send metadata
AMFEncoder invoke;
invoke << "onMetaData" << mediaSrc->getMetaData();
sendRtmp(MSG_DATA, invoke.data(), 0);
//send config frame
mediaSrc->getConfigFrame([&](const RtmpPacket::Ptr &pkt){
onSendMedia(pkt);
});
//开始发送rtmp负载 if (is_have_audio && is_have_video) {
m_pRingReader = mediaSrc->getRing()->attach(); flv_file_header[4] = 0x05;
weak_ptr<HttpSession> weakSelf = dynamic_pointer_cast<HttpSession>(shared_from_this()); } else if (is_have_audio && !is_have_video) {
m_pRingReader->setReadCB([weakSelf](const RtmpPacket::Ptr &pkt){ flv_file_header[4] = 0x04;
auto strongSelf = weakSelf.lock(); } else if (!is_have_audio && is_have_video) {
if(!strongSelf) { flv_file_header[4] = 0x01;
return; } else {
} flv_file_header[4] = 0x00;
strongSelf->async([pkt,weakSelf](){ }
auto strongSelf = weakSelf.lock(); //send flv header
if(!strongSelf) { send(flv_file_header, sizeof(flv_file_header) - 1);
return; //send metadata
} AMFEncoder invoke;
strongSelf->onSendMedia(pkt); invoke << "onMetaData" << mediaSrc->getMetaData();
}); sendRtmp(MSG_DATA, invoke.data(), 0);
}); //send config frame
m_pRingReader->setDetachCB([weakSelf](){ mediaSrc->getConfigFrame([&](const RtmpPacket::Ptr &pkt){
auto strongSelf = weakSelf.lock(); onSendMedia(pkt);
if(!strongSelf) { });
return;
}
strongSelf->async_first([weakSelf](){
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
return;
}
strongSelf->shutdown();
});
});
return true;
//开始发送rtmp负载
m_pRingReader = mediaSrc->getRing()->attach();
weak_ptr<HttpSession> weakSelf = dynamic_pointer_cast<HttpSession>(shared_from_this());
m_pRingReader->setReadCB([weakSelf](const RtmpPacket::Ptr &pkt){
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
return;
}
strongSelf->async([pkt,weakSelf](){
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
return;
}
strongSelf->onSendMedia(pkt);
});
});
m_pRingReader->setDetachCB([weakSelf](){
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
return;
}
strongSelf->async_first([weakSelf](){
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
return;
}
strongSelf->shutdown();
});
});
};
weak_ptr<HttpSession> weakSelf = dynamic_pointer_cast<HttpSession>(shared_from_this());
Broadcast::AuthInvoker invoker = [weakSelf,onRes](bool authSuccess){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
strongSelf->async([weakSelf,onRes,authSuccess](){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
onRes(authSuccess);
});
};
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed,info,invoker);
if(!flag){
//该事件无人监听,默认不鉴权
onRes(true);
}
return true;
} }
inline HttpSession::HttpCode HttpSession::Handle_Req_GET() { inline HttpSession::HttpCode HttpSession::Handle_Req_GET() {
//先看看该http事件是否被拦截 //先看看该http事件是否被拦截
@ -274,11 +306,9 @@ inline HttpSession::HttpCode HttpSession::Handle_Req_GET() {
} }
//事件未被拦截则认为是http下载请求 //事件未被拦截则认为是http下载请求
auto fullUrl = string("http://") + m_parser["Host"] + m_parser.Url(); auto fullUrl = string(HTTP_SCHEMA) + "://" + m_parser["Host"] + m_parser.FullUrl();
MediaInfo info(fullUrl); MediaInfo info(fullUrl);
if(!m_parser.getUrlArgs()[VHOST_KEY].empty()){
info.m_vhost = m_parser.getUrlArgs()[VHOST_KEY];
}
string strFile = m_strPath + "/" + info.m_vhost + m_parser.Url(); string strFile = m_strPath + "/" + info.m_vhost + m_parser.Url();
/////////////HTTP连接是否需要被关闭//////////////// /////////////HTTP连接是否需要被关闭////////////////
static uint32_t reqCnt = mINI::Instance()[Config::Http::kMaxReqCount].as<uint32_t>(); static uint32_t reqCnt = mINI::Instance()[Config::Http::kMaxReqCount].as<uint32_t>();

View File

@ -101,7 +101,7 @@ void RtmpSession::onCmd_connect(AMFDecoder &dec) {
m_strTcUrl = params["tcUrl"].as_string(); m_strTcUrl = params["tcUrl"].as_string();
if(m_strTcUrl.empty()){ if(m_strTcUrl.empty()){
//defaultVhost:默认vhost //defaultVhost:默认vhost
m_strTcUrl = "rtmp://127.0.0.1/" + m_mediaInfo.m_app; m_strTcUrl = string(RTMP_SCHEMA) + "://" + DEFAULT_VHOST + "/" + m_mediaInfo.m_app;
} }
bool ok = true; //(app == APP_NAME); bool ok = true; //(app == APP_NAME);
AMFValue version(AMF_OBJECT); AMFValue version(AMF_OBJECT);
@ -129,26 +129,54 @@ void RtmpSession::onCmd_createStream(AMFDecoder &dec) {
void RtmpSession::onCmd_publish(AMFDecoder &dec) { void RtmpSession::onCmd_publish(AMFDecoder &dec) {
dec.load<AMFValue>();/* NULL */ dec.load<AMFValue>();/* NULL */
m_mediaInfo.parse(m_strTcUrl + "/" + dec.load<std::string>()); m_mediaInfo.parse(m_strTcUrl + "/" + dec.load<std::string>());
auto src = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,
m_mediaInfo.m_vhost, auto onRes = [this](bool authSuccess){
m_mediaInfo.m_app, auto src = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,
m_mediaInfo.m_streamid, m_mediaInfo.m_vhost,
false)); m_mediaInfo.m_app,
bool ok = (!src && !m_pPublisherSrc); m_mediaInfo.m_streamid,
AMFValue status(AMF_OBJECT); false));
status.set("level", ok ? "status" : "error"); bool ok = (!src && !m_pPublisherSrc && authSuccess);
status.set("code", ok ? "NetStream.Publish.Start" : "NetStream.Publish.BadName"); AMFValue status(AMF_OBJECT);
status.set("description", ok ? "Started publishing stream." : "Already publishing."); status.set("level", ok ? "status" : "error");
status.set("clientid", "0"); status.set("code", ok ? "NetStream.Publish.Start" : (authSuccess ? "NetStream.Publish.BadName" : "NetStream.Publish.BadAuth"));
sendReply("onStatus", nullptr, status); status.set("description", ok ? "Started publishing stream." : (authSuccess ? "Already publishing." : "Auth failed"));
if (!ok) { status.set("clientid", "0");
throw std::runtime_error( StrPrinter << "Already publishing:" sendReply("onStatus", nullptr, status);
<< m_mediaInfo.m_vhost << " " if (!ok) {
<< m_mediaInfo.m_app << " " WarnL << "onPublish:"
<< m_mediaInfo.m_streamid << endl); << (authSuccess ? "Already publishing:" : "Auth failed:")
} << m_mediaInfo.m_vhost << " "
m_bPublisherSrcRegisted = false; << m_mediaInfo.m_app << " "
m_pPublisherSrc.reset(new RtmpToRtspMediaSource(m_mediaInfo.m_vhost,m_mediaInfo.m_app,m_mediaInfo.m_streamid)); << m_mediaInfo.m_streamid << endl;
shutdown();
return;
}
m_bPublisherSrcRegisted = false;
m_pPublisherSrc.reset(new RtmpToRtspMediaSource(m_mediaInfo.m_vhost,m_mediaInfo.m_app,m_mediaInfo.m_streamid));
};
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
Broadcast::AuthInvoker invoker = [weakSelf,onRes](bool success){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
strongSelf->async([weakSelf,onRes,success](){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
onRes(success);
});
};
auto flag = NoticeCenter::Instance().emitEvent(Config::Broadcast::kBroadcastRtmpPublish,
m_mediaInfo,
invoker);
if(!flag){
//该事件无人监听,默认鉴权成功
onRes(true);
}
} }
void RtmpSession::onCmd_deleteStream(AMFDecoder &dec) { void RtmpSession::onCmd_deleteStream(AMFDecoder &dec) {
@ -161,112 +189,134 @@ void RtmpSession::onCmd_deleteStream(AMFDecoder &dec) {
} }
void RtmpSession::doPlay(AMFDecoder &dec){ void RtmpSession::doPlay(AMFDecoder &dec){
m_mediaInfo.parse(m_strTcUrl + "/" + dec.load<std::string>()); auto onRes = [this](bool authSuccess) {
auto src = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA, auto src = dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,
m_mediaInfo.m_vhost, m_mediaInfo.m_vhost,
m_mediaInfo.m_app, m_mediaInfo.m_app,
m_mediaInfo.m_streamid, m_mediaInfo.m_streamid,
true)); true));
bool ok = (src.operator bool()); bool ok = (src.operator bool() && authSuccess);
ok = ok && src->ready(); if(ok){
//stream begin ok = ok && src->ready();
sendUserControl(CONTROL_STREAM_BEGIN, STREAM_MEDIA); }
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." : "Auth failed"));
status.set("details", m_mediaInfo.m_streamid);
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
if (!ok) {
WarnL << "onPlayed:"
<< (authSuccess ? "No such stream:" : "Auth failed:")
<< m_mediaInfo.m_vhost << " "
<< m_mediaInfo.m_app << " "
<< m_mediaInfo.m_streamid
<< endl;
shutdown();
return;
}
// onStatus(NetStream.Play.Reset) // onStatus(NetStream.Play.Start)
AMFValue status(AMF_OBJECT); status.clear();
status.set("level", ok ? "status" : "error"); status.set("level", "status");
status.set("code", ok ? "NetStream.Play.Reset" : "NetStream.Play.StreamNotFound"); status.set("code", "NetStream.Play.Start");
status.set("description", ok ? "Resetting and playing." : "No such stream."); status.set("description", "Started playing.");
status.set("details", m_mediaInfo.m_streamid); status.set("details", m_mediaInfo.m_streamid);
status.set("clientid", "0"); status.set("clientid", "0");
sendReply("onStatus", nullptr, status); sendReply("onStatus", nullptr, status);
if (!ok) {
throw std::runtime_error( StrPrinter << "No such stream:"
<< m_mediaInfo.m_vhost << " "
<< m_mediaInfo.m_app << " "
<< m_mediaInfo.m_streamid
<< endl);
}
// onStatus(NetStream.Play.Start) // |RtmpSampleAccess(true, true)
status.clear(); AMFEncoder invoke;
status.set("level", "status"); invoke << "|RtmpSampleAccess" << true << true;
status.set("code", "NetStream.Play.Start"); sendResponse(MSG_DATA, invoke.data());
status.set("description", "Started playing.");
status.set("details", m_mediaInfo.m_streamid);
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
// |RtmpSampleAccess(true, true) //onStatus(NetStream.Data.Start)
AMFEncoder invoke; invoke.clear();
invoke << "|RtmpSampleAccess" << true << true; AMFValue obj(AMF_OBJECT);
sendResponse(MSG_DATA, invoke.data()); obj.set("code", "NetStream.Data.Start");
invoke << "onStatus" << obj;
sendResponse(MSG_DATA, invoke.data());
//onStatus(NetStream.Data.Start) //onStatus(NetStream.Play.PublishNotify)
invoke.clear(); status.clear();
AMFValue obj(AMF_OBJECT); status.set("level", "status");
obj.set("code","NetStream.Data.Start"); status.set("code", "NetStream.Play.PublishNotify");
invoke << "onStatus" << obj; status.set("description", "Now published.");
sendResponse(MSG_DATA, invoke.data()); status.set("details", m_mediaInfo.m_streamid);
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
//onStatus(NetStream.Play.PublishNotify) // onMetaData
status.clear(); invoke.clear();
status.set("level", "status"); invoke << "onMetaData" << src->getMetaData();
status.set("code", "NetStream.Play.PublishNotify"); sendResponse(MSG_DATA, invoke.data());
status.set("description", "Now published.");
status.set("details", m_mediaInfo.m_streamid);
status.set("clientid", "0");
sendReply("onStatus", nullptr, status);
// onMetaData src->getConfigFrame([&](const RtmpPacket::Ptr &pkt) {
invoke.clear(); //DebugL<<"send initial frame";
invoke << "onMetaData" << src->getMetaData(); onSendMedia(pkt);
sendResponse(MSG_DATA, invoke.data()); });
src->getConfigFrame([&](const RtmpPacket::Ptr &pkt) { m_pRingReader = src->getRing()->attach();
//DebugL<<"send initial frame"; weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
onSendMedia(pkt); SockUtil::setNoDelay(sock->rawFD(), false);
}); m_pRingReader->setReadCB([weakSelf](const RtmpPacket::Ptr &pkt) {
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
return;
}
strongSelf->async([weakSelf, pkt]() {
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
return;
}
strongSelf->onSendMedia(pkt);
});
});
m_pRingReader->setDetachCB([weakSelf]() {
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
return;
}
strongSelf->safeShutdown();
});
m_pPlayerSrc = src;
if (src->getRing()->readerCount() == 1) {
src->seekTo(0);
}
};
m_pRingReader = src->getRing()->attach(); weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this());
weak_ptr<RtmpSession> weakSelf = dynamic_pointer_cast<RtmpSession>(shared_from_this()); Broadcast::AuthInvoker invoker = [weakSelf,onRes](bool authSuccess){
SockUtil::setNoDelay(sock->rawFD(), false); auto strongSelf = weakSelf.lock();
m_pRingReader->setReadCB([weakSelf](const RtmpPacket::Ptr &pkt){ if(!strongSelf){
auto strongSelf = weakSelf.lock(); return;
if(!strongSelf) { }
return; strongSelf->async([weakSelf,onRes,authSuccess](){
} auto strongSelf = weakSelf.lock();
strongSelf->async([weakSelf,pkt]() { if(!strongSelf){
auto strongSelf = weakSelf.lock(); return;
if(!strongSelf) { }
return; onRes(authSuccess);
} });
strongSelf->onSendMedia(pkt); };
}); auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed,m_mediaInfo,invoker);
}); if(!flag){
m_pRingReader->setDetachCB([weakSelf]() { //该事件无人监听,默认不鉴权
auto strongSelf = weakSelf.lock(); onRes(true);
if(!strongSelf) { }
return;
}
strongSelf->safeShutdown();
});
m_pPlayerSrc = src;
if(src->getRing()->readerCount() == 1){
src->seekTo(0);
}
NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed,
RTMP_SCHEMA,
m_mediaInfo.m_vhost.data(),
m_mediaInfo.m_app.data(),
m_mediaInfo.m_streamid.data());
} }
void RtmpSession::onCmd_play2(AMFDecoder &dec) { void RtmpSession::onCmd_play2(AMFDecoder &dec) {
doPlay(dec); doPlay(dec);
} }
void RtmpSession::onCmd_play(AMFDecoder &dec) { void RtmpSession::onCmd_play(AMFDecoder &dec) {
dec.load<AMFValue>();/* NULL */ dec.load<AMFValue>();/* NULL */
m_mediaInfo.parse(m_strTcUrl + "/" + dec.load<std::string>());
doPlay(dec); doPlay(dec);
} }

View File

@ -101,15 +101,15 @@ public:
} }
if (start == buf) { if (start == buf) {
m_strMethod = FindField(line.c_str(), NULL, " "); m_strMethod = FindField(line.c_str(), NULL, " ");
auto full_url = FindField(line.c_str(), " ", " "); m_strFullUrl = FindField(line.c_str(), " ", " ");
auto args_pos = full_url.find('?'); auto args_pos = m_strFullUrl.find('?');
if(args_pos != string::npos){ if(args_pos != string::npos){
m_strUrl = full_url.substr(0,args_pos); m_strUrl = m_strFullUrl.substr(0,args_pos);
m_mapUrlArgs = parseArgs(full_url.substr(args_pos + 1 )); m_mapUrlArgs = parseArgs(m_strFullUrl.substr(args_pos + 1 ));
}else{ }else{
m_strUrl = full_url; m_strUrl = m_strFullUrl;
} }
m_strTail = FindField(line.c_str(), (full_url + " ").c_str(), NULL); m_strTail = FindField(line.c_str(), (m_strFullUrl + " ").c_str(), NULL);
} else { } else {
auto field = FindField(line.c_str(), NULL, ": "); auto field = FindField(line.c_str(), NULL, ": ");
auto value = FindField(line.c_str(), ": ", NULL); auto value = FindField(line.c_str(), ": ", NULL);
@ -132,6 +132,10 @@ public:
//rtsp url //rtsp url
return m_strUrl; return m_strUrl;
} }
const string& FullUrl() const {
//rtsp url with args
return m_strFullUrl;
}
const string& Tail() const { const string& Tail() const {
//RTSP/1.0 //RTSP/1.0
return m_strTail; return m_strTail;
@ -150,6 +154,7 @@ public:
void Clear() { void Clear() {
m_strMethod.clear(); m_strMethod.clear();
m_strUrl.clear(); m_strUrl.clear();
m_strFullUrl.clear();
m_strTail.clear(); m_strTail.clear();
m_strContent.clear(); m_strContent.clear();
m_mapValues.clear(); m_mapValues.clear();
@ -189,6 +194,7 @@ private:
string m_strTail; string m_strTail;
string m_strContent; string m_strContent;
string m_strNull; string m_strNull;
string m_strFullUrl;
mutable StrCaseMap m_mapValues; mutable StrCaseMap m_mapValues;
mutable StrCaseMap m_mapUrlArgs; mutable StrCaseMap m_mapUrlArgs;
}; };

View File

@ -193,10 +193,7 @@ bool RtspSession::handleReq_Describe() {
{ {
//解析url获取媒体名称 //解析url获取媒体名称
m_strUrl = m_parser.Url(); m_strUrl = m_parser.Url();
m_mediaInfo.parse(m_strUrl); m_mediaInfo.parse(m_parser.FullUrl());
if(!m_parser.getUrlArgs()[VHOST_KEY].empty()){
m_mediaInfo.m_vhost = m_parser.getUrlArgs()[VHOST_KEY];
}
} }
if (!findStream()) { if (!findStream()) {
@ -644,82 +641,113 @@ bool RtspSession::handleReq_Play() {
send_SessionNotFound(); send_SessionNotFound();
return false; return false;
} }
auto onRes = [this](bool authSuccess){
if(m_pRtpReader){ char response[2 * 1024];
weak_ptr<RtspSession> weakSelf = dynamic_pointer_cast<RtspSession>(shared_from_this()); m_pcBuf = response;
SockUtil::setNoDelay(m_pSender->rawFD(), false); if(!authSuccess && m_bFirstPlay){
m_pRtpReader->setReadCB([weakSelf](const RtpPacket::Ptr &pack) { //第一次play是播放否则是恢复播放。只对播放鉴权
auto strongSelf = weakSelf.lock(); int n = sprintf(m_pcBuf,
if(!strongSelf) { "RTSP/1.0 401 Unauthorized\r\n"
return; "CSeq: %d\r\n"
} "Server: %s-%0.2f(build in %s)\r\n"
strongSelf->async([weakSelf,pack](){ "%s\r\n",
auto strongSelf = weakSelf.lock(); m_iCseq, SERVER_NAME, RTSP_VERSION, RTSP_BUILDTIME, dateHeader().data());
if(!strongSelf) { send(m_pcBuf,n);
return; shutdown();
} return;
strongSelf->sendRtpPacket(pack);
});
});
}
auto pMediaSrc = m_pMediaSrc.lock();
uint32_t iStamp = 0;
if(pMediaSrc){
auto strRange = m_parser["Range"];
if (strRange.size() && !m_bFirstPlay) {
auto strStart = FindField(strRange.data(), "npt=", "-");
if (strStart == "now") {
strStart = "0";
}
auto iStartTime = atof(strStart.data());
InfoL << "rtsp seekTo:" << iStartTime;
pMediaSrc->seekTo(iStartTime * 1000);
iStamp = pMediaSrc->getStamp();
}else if(pMediaSrc->getRing()->readerCount() == 1){
//第一个消费者
pMediaSrc->seekTo(0);
iStamp = 0;
}else{
iStamp = pMediaSrc->getStamp();
} }
for (unsigned int i = 0; i < m_uiTrackCnt; i++) { if(m_pRtpReader){
auto &track = m_aTrackInfo[i]; weak_ptr<RtspSession> weakSelf = dynamic_pointer_cast<RtspSession>(shared_from_this());
track.ssrc = pMediaSrc->getSsrc(track.trackId); SockUtil::setNoDelay(m_pSender->rawFD(), false);
track.seq = pMediaSrc->getSeqence(track.trackId); m_pRtpReader->setReadCB([weakSelf](const RtpPacket::Ptr &pack) {
track.timeStamp = pMediaSrc->getTimestamp(track.trackId); auto strongSelf = weakSelf.lock();
} if(!strongSelf) {
} return;
m_bFirstPlay = false; }
int iLen = sprintf(m_pcBuf, "RTSP/1.0 200 OK\r\n" strongSelf->async([weakSelf,pack](){
"CSeq: %d\r\n" auto strongSelf = weakSelf.lock();
"Server: %s-%0.2f(build in %s)\r\n" if(!strongSelf) {
"%s" return;
"Session: %s\r\n" }
"Range: npt=%.2f-\r\n" strongSelf->sendRtpPacket(pack);
"RTP-Info: ", m_iCseq, SERVER_NAME, RTSP_VERSION, RTSP_BUILDTIME, });
dateHeader().data(), m_strSession.data(),iStamp/1000.0);
for (unsigned int i = 0; i < m_uiTrackCnt; i++) { });
auto &track = m_aTrackInfo[i]; }
if (track.inited == false) {
//还有track没有setup auto pMediaSrc = m_pMediaSrc.lock();
return false; uint32_t iStamp = 0;
} if(pMediaSrc){
iLen += sprintf(m_pcBuf + iLen, "url=%s/%s%d;seq=%d;rtptime=%u,", auto strRange = m_parser["Range"];
m_strUrl.data(), track.trackStyle.data(), if (strRange.size() && !m_bFirstPlay) {
track.trackId, track.seq,track.timeStamp); auto strStart = FindField(strRange.data(), "npt=", "-");
} if (strStart == "now") {
iLen -= 1; strStart = "0";
(m_pcBuf)[iLen] = '\0'; }
iLen += sprintf(m_pcBuf + iLen, "\r\n\r\n"); auto iStartTime = atof(strStart.data());
send(m_pcBuf, iLen); InfoL << "rtsp seekTo:" << iStartTime;
NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed, pMediaSrc->seekTo(iStartTime * 1000);
RTSP_SCHEMA, iStamp = pMediaSrc->getStamp();
m_mediaInfo.m_vhost.data(), }else if(pMediaSrc->getRing()->readerCount() == 1){
m_mediaInfo.m_app.data(), //第一个消费者
m_mediaInfo.m_streamid.data()); pMediaSrc->seekTo(0);
iStamp = 0;
}else{
iStamp = pMediaSrc->getStamp();
}
for (unsigned int i = 0; i < m_uiTrackCnt; i++) {
auto &track = m_aTrackInfo[i];
track.ssrc = pMediaSrc->getSsrc(track.trackId);
track.seq = pMediaSrc->getSeqence(track.trackId);
track.timeStamp = pMediaSrc->getTimestamp(track.trackId);
}
}
m_bFirstPlay = false;
int iLen = sprintf(m_pcBuf, "RTSP/1.0 200 OK\r\n"
"CSeq: %d\r\n"
"Server: %s-%0.2f(build in %s)\r\n"
"%s"
"Session: %s\r\n"
"Range: npt=%.2f-\r\n"
"RTP-Info: ", m_iCseq, SERVER_NAME, RTSP_VERSION, RTSP_BUILDTIME,
dateHeader().data(), m_strSession.data(),iStamp/1000.0);
for (unsigned int i = 0; i < m_uiTrackCnt; i++) {
auto &track = m_aTrackInfo[i];
if (track.inited == false) {
//还有track没有setup
shutdown();
return;
}
iLen += sprintf(m_pcBuf + iLen, "url=%s/%s%d;seq=%d;rtptime=%u,",
m_strUrl.data(), track.trackStyle.data(),
track.trackId, track.seq,track.timeStamp);
}
iLen -= 1;
(m_pcBuf)[iLen] = '\0';
iLen += sprintf(m_pcBuf + iLen, "\r\n\r\n");
send(m_pcBuf, iLen);
};
weak_ptr<RtspSession> weakSelf = dynamic_pointer_cast<RtspSession>(shared_from_this());
Broadcast::AuthInvoker invoker = [weakSelf,onRes](bool authSuccess){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
strongSelf->async([weakSelf,onRes,authSuccess](){
auto strongSelf = weakSelf.lock();
if(!strongSelf){
return;
}
onRes(authSuccess);
});
};
auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaPlayed,m_mediaInfo,invoker);
if(!flag){
//该事件无人监听,默认不鉴权
onRes(true);
}
return true; return true;
} }

View File

@ -107,6 +107,22 @@ static onceToken s_token([](){
invoker(false,user); invoker(false,user);
}); });
}); });
NoticeCenter::Instance().addListener(nullptr,Config::Broadcast::kBroadcastRtmpPublish,[](BroadcastRtmpPublishArgs){
InfoL << args.m_vhost << " " << args.m_app << " " << args.m_streamid << " " << args.m_param_strs ;
EventPoller::Instance().async([invoker](){
invoker(true);
});
});
NoticeCenter::Instance().addListener(nullptr,Config::Broadcast::kBroadcastMediaPlayed,[](BroadcastMediaPlayedArgs){
InfoL << args.m_schema << " " << args.m_vhost << " " << args.m_app << " " << args.m_streamid << " " << args.m_param_strs ;
EventPoller::Instance().async([invoker](){
invoker(true);
});
});
}, nullptr); }, nullptr);
int main(int argc,char *argv[]){ int main(int argc,char *argv[]){