ZLMediaKit/src/Rtsp/RtspPusher.cpp

488 lines
16 KiB
C++
Raw Normal View History

2020-04-04 20:30:09 +08:00
/*
* Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
*
* This file is part of ZLMediaKit(https://github.com/xia-chu/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.
*/
2019-03-27 18:41:52 +08:00
#include "Util/MD5.h"
#include "Util/base64.h"
#include "RtspPusher.h"
#include "RtspSession.h"
2019-03-27 18:56:49 +08:00
using namespace mediakit::Client;
2019-03-27 18:41:52 +08:00
namespace mediakit {
2020-08-30 11:40:03 +08:00
RtspPusher::RtspPusher(const EventPoller::Ptr &poller, const RtspMediaSource::Ptr &src) : TcpClient(poller) {
_push_src = src;
2019-03-27 18:41:52 +08:00
}
RtspPusher::~RtspPusher() {
teardown();
DebugL << endl;
}
2021-01-17 10:28:06 +08:00
void RtspPusher::sendTeardown(){
2019-03-27 18:41:52 +08:00
if (alive()) {
2021-01-17 10:28:06 +08:00
if (!_content_base.empty()) {
sendRtspRequest("TEARDOWN", _content_base);
}
2020-08-30 11:40:03 +08:00
shutdown(SockException(Err_shutdown, "teardown"));
2019-03-27 18:41:52 +08:00
}
2021-01-17 10:28:06 +08:00
}
2019-03-27 18:41:52 +08:00
2021-01-17 10:28:06 +08:00
void RtspPusher::teardown() {
sendTeardown();
2019-03-27 18:41:52 +08:00
reset();
2020-08-30 11:40:03 +08:00
CLEAR_ARR(_udp_socks);
_nonce.clear();
_realm.clear();
_track_vec.clear();
_session_id.clear();
_content_base.clear();
_session_id.clear();
_cseq = 1;
_publish_timer.reset();
_beat_timer.reset();
_rtsp_reader.reset();
_track_vec.clear();
_on_res_func = nullptr;
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
void RtspPusher::publish(const string &url_str) {
RtspUrl url;
2020-08-30 11:40:03 +08:00
if (!url.parse(url_str)) {
onPublishResult(SockException(Err_other, StrPrinter << "illegal rtsp url:" << url_str), false);
2019-03-27 18:41:52 +08:00
return;
}
2019-03-28 09:43:47 +08:00
2019-03-27 18:41:52 +08:00
teardown();
if (url._user.size()) {
(*this)[kRtspUser] = url._user;
2019-03-27 18:41:52 +08:00
}
if (url._passwd.size()) {
(*this)[kRtspPwd] = url._passwd;
2019-03-27 18:56:49 +08:00
(*this)[kRtspPwdIsMD5] = false;
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
_url = url_str;
_rtp_type = (Rtsp::eRtpType) (int) (*this)[kRtpType];
DebugL << url._url << " " << (url._user.size() ? url._user : "null") << " "
<< (url._passwd.size() ? url._passwd : "null") << " " << _rtp_type;
2019-03-27 18:41:52 +08:00
2020-08-30 11:40:03 +08:00
weak_ptr<RtspPusher> weak_self = dynamic_pointer_cast<RtspPusher>(shared_from_this());
float publish_timeout_sec = (*this)[kTimeoutMS].as<int>() / 1000.0f;
2020-08-30 11:40:03 +08:00
_publish_timer.reset(new Timer(publish_timeout_sec, [weak_self]() {
auto strong_self = weak_self.lock();
if (!strong_self) {
2019-03-27 18:41:52 +08:00
return false;
}
2020-08-30 11:40:03 +08:00
strong_self->onPublishResult(SockException(Err_timeout, "publish rtsp timeout"), false);
2019-03-27 18:41:52 +08:00
return false;
2020-08-30 11:40:03 +08:00
}, getPoller()));
2019-03-27 18:41:52 +08:00
2020-08-30 11:40:03 +08:00
if (!(*this)[kNetAdapter].empty()) {
2019-03-27 18:41:52 +08:00
setNetAdapter((*this)[kNetAdapter]);
}
2020-08-30 11:40:03 +08:00
startConnect(url._host, url._port, publish_timeout_sec);
}
2020-08-30 11:40:03 +08:00
void RtspPusher::onPublishResult(const SockException &ex, bool handshake_done) {
if (ex.getErrCode() == Err_shutdown) {
//主动shutdown的不触发回调
return;
}
if (!handshake_done) {
//播放结果回调
2020-08-30 11:40:03 +08:00
_publish_timer.reset();
if (_on_published) {
_on_published(ex);
}
} else {
//播放成功后异常断开回调
2020-08-30 11:40:03 +08:00
if (_on_shutdown) {
_on_shutdown(ex);
}
}
2020-08-30 11:40:03 +08:00
if (ex) {
2021-01-17 10:28:06 +08:00
sendTeardown();
}
2019-03-27 18:41:52 +08:00
}
void RtspPusher::onErr(const SockException &ex) {
//定时器_pPublishTimer为空后表明握手结束了
2020-08-30 11:40:03 +08:00
onPublishResult(ex, !_publish_timer);
2019-03-27 18:41:52 +08:00
}
void RtspPusher::onConnect(const SockException &err) {
2020-08-30 11:40:03 +08:00
if (err) {
onPublishResult(err, false);
2019-03-27 18:41:52 +08:00
return;
}
sendAnnounce();
}
2020-08-30 11:40:03 +08:00
void RtspPusher::onRecv(const Buffer::Ptr &buf){
2019-03-27 18:41:52 +08:00
try {
2020-08-30 11:40:03 +08:00
input(buf->data(), buf->size());
2019-03-27 18:41:52 +08:00
} catch (exception &e) {
SockException ex(Err_other, e.what());
//定时器_pPublishTimer为空后表明握手结束了
2020-08-30 11:40:03 +08:00
onPublishResult(ex, !_publish_timer);
2019-03-27 18:41:52 +08:00
}
}
void RtspPusher::onWholeRtspPacket(Parser &parser) {
2020-08-30 11:40:03 +08:00
decltype(_on_res_func) func;
_on_res_func.swap(func);
if (func) {
func(parser);
2019-03-27 18:41:52 +08:00
}
parser.Clear();
}
2019-03-28 09:34:22 +08:00
void RtspPusher::sendAnnounce() {
2020-08-30 11:40:03 +08:00
auto src = _push_src.lock();
2019-03-27 18:41:52 +08:00
if (!src) {
throw std::runtime_error("the media source was released");
}
//解析sdp
2020-08-30 11:40:03 +08:00
_sdp_parser.load(src->getSdp());
_track_vec = _sdp_parser.getAvailableTrack();
2019-03-27 18:41:52 +08:00
2020-08-30 11:40:03 +08:00
if (_track_vec.empty()) {
2019-03-27 18:41:52 +08:00
throw std::runtime_error("无有效的Sdp Track");
}
2020-08-30 11:40:03 +08:00
_on_res_func = std::bind(&RtspPusher::handleResAnnounce, this, placeholders::_1);
sendRtspRequest("ANNOUNCE", _url, {}, src->getSdp());
2019-03-27 18:41:52 +08:00
}
void RtspPusher::handleResAnnounce(const Parser &parser) {
string authInfo = parser["WWW-Authenticate"];
//发送DESCRIBE命令后的回复
if ((parser.Url() == "401") && handleAuthenticationFailure(authInfo)) {
sendAnnounce();
return;
}
2020-08-30 11:40:03 +08:00
if (parser.Url() == "302") {
2019-03-27 18:41:52 +08:00
auto newUrl = parser["Location"];
2020-08-30 11:40:03 +08:00
if (newUrl.empty()) {
2019-03-27 18:41:52 +08:00
throw std::runtime_error("未找到Location字段(跳转url)");
}
publish(newUrl);
return;
}
if (parser.Url() != "200") {
throw std::runtime_error(StrPrinter << "ANNOUNCE:" << parser.Url() << " " << parser.Tail());
}
2020-08-30 11:40:03 +08:00
_content_base = parser["Content-Base"];
2019-03-27 18:41:52 +08:00
2020-08-30 11:40:03 +08:00
if (_content_base.empty()) {
_content_base = _url;
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
if (_content_base.back() == '/') {
_content_base.pop_back();
2019-03-27 18:41:52 +08:00
}
sendSetup(0);
}
2020-08-30 11:40:03 +08:00
bool RtspPusher::handleAuthenticationFailure(const string &params_str) {
if (!_realm.empty()) {
2019-03-27 18:41:52 +08:00
//已经认证过了
return false;
}
2020-08-30 11:40:03 +08:00
char *realm = new char[params_str.size()];
char *nonce = new char[params_str.size()];
char *stale = new char[params_str.size()];
onceToken token(nullptr, [&]() {
2019-03-27 18:41:52 +08:00
delete[] realm;
delete[] nonce;
delete[] stale;
});
2020-08-30 11:40:03 +08:00
if (sscanf(params_str.data(), "Digest realm=\"%[^\"]\", nonce=\"%[^\"]\", stale=%[a-zA-Z]", realm, nonce, stale) == 3) {
_realm = (const char *) realm;
_nonce = (const char *) nonce;
2019-03-27 18:41:52 +08:00
return true;
}
2020-08-30 11:40:03 +08:00
if (sscanf(params_str.data(), "Digest realm=\"%[^\"]\", nonce=\"%[^\"]\"", realm, nonce) == 2) {
_realm = (const char *) realm;
_nonce = (const char *) nonce;
2019-03-27 18:41:52 +08:00
return true;
}
2020-08-30 11:40:03 +08:00
if (sscanf(params_str.data(), "Basic realm=\"%[^\"]\"", realm) == 1) {
_realm = (const char *) realm;
2019-03-27 18:41:52 +08:00
return true;
}
return false;
}
2019-07-11 12:15:13 +08:00
//有必要的情况下创建udp端口
void RtspPusher::createUdpSockIfNecessary(int track_idx){
2020-08-30 11:40:03 +08:00
auto &rtp_sock = _udp_socks[track_idx];
if (!rtp_sock) {
rtp_sock = createSocket();
2019-07-11 12:15:13 +08:00
//rtp随机端口
2020-08-30 11:40:03 +08:00
if (!rtp_sock->bindUdpSock(0, get_local_ip().data())) {
rtp_sock.reset();
throw std::runtime_error("open rtp sock failed");
}
}
}
2020-08-30 11:40:03 +08:00
void RtspPusher::sendSetup(unsigned int track_idx) {
_on_res_func = std::bind(&RtspPusher::handleResSetup, this, placeholders::_1, track_idx);
auto &track = _track_vec[track_idx];
auto base_url = _content_base + "/" + track->_control_surffix;
2020-11-07 17:45:58 +08:00
if (track->_control.find("://") != string::npos) {
base_url = track->_control;
}
2020-08-30 11:40:03 +08:00
switch (_rtp_type) {
2019-03-27 18:41:52 +08:00
case Rtsp::RTP_TCP: {
2020-08-30 11:40:03 +08:00
sendRtspRequest("SETUP", base_url, {"Transport",
StrPrinter << "RTP/AVP/TCP;unicast;interleaved=" << track->_type * 2
<< "-" << track->_type * 2 + 1});
2019-03-27 18:41:52 +08:00
}
2019-03-28 09:34:22 +08:00
break;
2019-03-27 18:41:52 +08:00
case Rtsp::RTP_UDP: {
2020-08-30 11:40:03 +08:00
createUdpSockIfNecessary(track_idx);
int port = _udp_socks[track_idx]->get_local_port();
sendRtspRequest("SETUP", base_url,
{"Transport", StrPrinter << "RTP/AVP;unicast;client_port=" << port << "-" << port + 1});
2019-03-27 18:41:52 +08:00
}
2019-03-28 09:34:22 +08:00
break;
2019-03-27 18:41:52 +08:00
default:
2019-03-28 09:34:22 +08:00
break;
2019-03-27 18:41:52 +08:00
}
}
2020-08-30 11:40:03 +08:00
void RtspPusher::handleResSetup(const Parser &parser, unsigned int track_idx) {
2019-03-27 18:41:52 +08:00
if (parser.Url() != "200") {
2020-08-30 11:40:03 +08:00
throw std::runtime_error(StrPrinter << "SETUP:" << parser.Url() << " " << parser.Tail() << endl);
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
if (track_idx == 0) {
_session_id = parser["Session"];
_session_id.append(";");
_session_id = FindField(_session_id.data(), nullptr, ";");
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
auto transport = parser["Transport"];
if (transport.find("TCP") != string::npos || transport.find("interleaved") != string::npos) {
_rtp_type = Rtsp::RTP_TCP;
string interleaved = FindField(FindField((transport + ";").data(), "interleaved=", ";").data(), NULL, "-");
_track_vec[track_idx]->_interleaved = atoi(interleaved.data());
} else if (transport.find("multicast") != string::npos) {
2019-03-27 18:41:52 +08:00
throw std::runtime_error("SETUP rtsp pusher can not support multicast!");
2020-08-30 11:40:03 +08:00
} else {
_rtp_type = Rtsp::RTP_UDP;
createUdpSockIfNecessary(track_idx);
const char *strPos = "server_port=";
auto port_str = FindField((transport + ";").data(), strPos, ";");
2019-03-27 18:41:52 +08:00
uint16_t port = atoi(FindField(port_str.data(), NULL, "-").data());
struct sockaddr_in rtpto;
rtpto.sin_port = ntohs(port);
rtpto.sin_family = AF_INET;
rtpto.sin_addr.s_addr = inet_addr(get_peer_ip().data());
2020-08-30 11:40:03 +08:00
_udp_socks[track_idx]->setSendPeerAddr((struct sockaddr *) &(rtpto));
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
RtspSplitter::enableRecvRtp(_rtp_type == Rtsp::RTP_TCP);
2019-03-27 18:41:52 +08:00
2020-08-30 11:40:03 +08:00
if (track_idx < _track_vec.size() - 1) {
2019-03-27 18:41:52 +08:00
//需要继续发送SETUP命令
2020-08-30 11:40:03 +08:00
sendSetup(track_idx + 1);
2019-03-27 18:41:52 +08:00
return;
}
sendRecord();
}
2019-03-28 09:34:22 +08:00
void RtspPusher::sendOptions() {
2020-08-30 11:40:03 +08:00
_on_res_func = [this](const Parser &parser) {};
sendRtspRequest("OPTIONS", _content_base);
2019-03-27 18:41:52 +08:00
}
2020-04-07 13:03:53 +08:00
inline void RtspPusher::sendRtpPacket(const RtspMediaSource::RingDataType &pkt) {
2020-08-30 11:40:03 +08:00
switch (_rtp_type) {
2019-03-27 18:41:52 +08:00
case Rtsp::RTP_TCP: {
size_t i = 0;
auto size = pkt->size();
2020-04-07 13:03:53 +08:00
setSendFlushFlag(false);
pkt->for_each([&](const RtpPacket::Ptr &rtp) {
if (++i == size) {
setSendFlushFlag(true);
}
BufferRtp::Ptr buffer(new BufferRtp(rtp));
send(std::move(buffer));
2020-04-07 13:03:53 +08:00
});
2019-03-27 18:41:52 +08:00
break;
2020-08-30 11:40:03 +08:00
}
2019-03-27 18:41:52 +08:00
case Rtsp::RTP_UDP: {
size_t i = 0;
auto size = pkt->size();
2020-04-07 13:03:53 +08:00
pkt->for_each([&](const RtpPacket::Ptr &rtp) {
int iTrackIndex = getTrackIndexByTrackType(rtp->type);
2020-08-30 11:40:03 +08:00
auto &pSock = _udp_socks[iTrackIndex];
2020-04-07 13:03:53 +08:00
if (!pSock) {
2020-08-30 11:40:03 +08:00
shutdown(SockException(Err_shutdown, "udp sock not opened yet"));
2020-04-07 13:03:53 +08:00
return;
}
2020-08-30 11:40:03 +08:00
BufferRtp::Ptr buffer(new BufferRtp(rtp, 4));
pSock->send(std::move(buffer), nullptr, 0, ++i == size);
2020-04-07 13:03:53 +08:00
});
2019-03-27 18:41:52 +08:00
break;
2020-08-30 11:40:03 +08:00
}
default : break;
2019-03-27 18:41:52 +08:00
}
}
inline int RtspPusher::getTrackIndexByTrackType(TrackType type) {
2020-08-30 11:40:03 +08:00
for (unsigned int i = 0; i < _track_vec.size(); i++) {
if (type == _track_vec[i]->_type) {
2019-03-27 18:41:52 +08:00
return i;
}
}
2020-08-30 11:40:03 +08:00
if (_track_vec.size() == 1) {
2019-11-25 17:59:04 +08:00
return 0;
}
2020-07-08 22:29:08 +08:00
throw SockException(Err_shutdown, StrPrinter << "no such track with type:" << (int) type);
2019-03-27 18:41:52 +08:00
}
2019-03-28 09:34:22 +08:00
void RtspPusher::sendRecord() {
2020-08-30 11:40:03 +08:00
_on_res_func = [this](const Parser &parser) {
auto src = _push_src.lock();
2019-03-27 18:41:52 +08:00
if (!src) {
throw std::runtime_error("the media source was released");
}
2020-08-30 11:40:03 +08:00
_rtsp_reader = src->getRing()->attach(getPoller());
weak_ptr<RtspPusher> weak_self = dynamic_pointer_cast<RtspPusher>(shared_from_this());
_rtsp_reader->setReadCB([weak_self](const RtspMediaSource::RingDataType &pkt) {
auto strong_self = weak_self.lock();
if (!strong_self) {
2019-03-27 18:41:52 +08:00
return;
}
2020-08-30 11:40:03 +08:00
strong_self->sendRtpPacket(pkt);
2019-03-27 18:41:52 +08:00
});
2020-08-30 11:40:03 +08:00
_rtsp_reader->setDetachCB([weak_self]() {
auto strong_self = weak_self.lock();
if (strong_self) {
strong_self->onPublishResult(SockException(Err_other, "媒体源被释放"), !strong_self->_publish_timer);
2019-03-27 18:41:52 +08:00
}
});
2020-08-30 11:40:03 +08:00
if (_rtp_type != Rtsp::RTP_TCP) {
2019-03-27 18:41:52 +08:00
/////////////////////////心跳/////////////////////////////////
_beat_timer.reset(new Timer((*this)[kBeatIntervalMS].as<int>() / 1000.0f, [weak_self]() {
2020-08-30 11:40:03 +08:00
auto strong_self = weak_self.lock();
if (!strong_self) {
2019-03-27 18:41:52 +08:00
return false;
}
2020-08-30 11:40:03 +08:00
strong_self->sendOptions();
2019-03-28 09:34:22 +08:00
return true;
2020-08-30 11:40:03 +08:00
}, getPoller()));
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
onPublishResult(SockException(Err_success, "success"), false);
//提升发送性能
setSocketFlags();
2019-03-27 18:41:52 +08:00
};
2020-08-30 11:40:03 +08:00
sendRtspRequest("RECORD", _content_base, {"Range", "npt=0.000-"});
2019-03-27 18:41:52 +08:00
}
void RtspPusher::setSocketFlags(){
2020-08-30 11:40:03 +08:00
GET_CONFIG(int, merge_write_ms, General::kMergeWriteMS);
if (merge_write_ms > 0) {
//提高发送性能
2020-04-23 17:50:12 +08:00
setSendFlags(SOCKET_DEFAULE_FLAGS | FLAG_MORE);
SockUtil::setNoDelay(getSock()->rawFD(), false);
}
}
2019-03-28 09:34:22 +08:00
void RtspPusher::sendRtspRequest(const string &cmd, const string &url, const std::initializer_list<string> &header,const string &sdp ) {
2019-03-27 18:41:52 +08:00
string key;
StrCaseMap header_map;
int i = 0;
2020-08-30 11:40:03 +08:00
for (auto &val : header) {
if (++i % 2 == 0) {
header_map.emplace(key, val);
} else {
2019-03-27 18:41:52 +08:00
key = val;
}
}
2020-08-30 11:40:03 +08:00
sendRtspRequest(cmd, url, header_map, sdp);
2019-03-27 18:41:52 +08:00
}
2019-03-28 09:34:22 +08:00
void RtspPusher::sendRtspRequest(const string &cmd, const string &url,const StrCaseMap &header_const,const string &sdp ) {
2019-03-27 18:41:52 +08:00
auto header = header_const;
2020-08-30 11:40:03 +08:00
header.emplace("CSeq", StrPrinter << _cseq++);
header.emplace("User-Agent", SERVER_NAME);
2019-03-27 18:41:52 +08:00
2020-08-30 11:40:03 +08:00
if (!_session_id.empty()) {
header.emplace("Session", _session_id);
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
if (!_realm.empty() && !(*this)[kRtspUser].empty()) {
if (!_nonce.empty()) {
2019-03-27 18:41:52 +08:00
//MD5认证
/*
response计算方法如下
RTSP客户端应该使用username + password并计算response如下:
(1)password为MD5编码,
response = md5( password:nonce:md5(public_method:url) );
(2)password为ANSI字符串,
response= md5( md5(username:realm:password):nonce:md5(public_method:url) );
*/
string encrypted_pwd = (*this)[kRtspPwd];
2020-08-30 11:40:03 +08:00
if (!(*this)[kRtspPwdIsMD5].as<bool>()) {
encrypted_pwd = MD5((*this)[kRtspUser] + ":" + _realm + ":" + encrypted_pwd).hexdigest();
2019-03-27 18:41:52 +08:00
}
2020-08-30 11:40:03 +08:00
auto response = MD5(encrypted_pwd + ":" + _nonce + ":" + MD5(cmd + ":" + url).hexdigest()).hexdigest();
2019-03-27 18:41:52 +08:00
_StrPrinter printer;
printer << "Digest ";
printer << "username=\"" << (*this)[kRtspUser] << "\", ";
2020-08-30 11:40:03 +08:00
printer << "realm=\"" << _realm << "\", ";
printer << "nonce=\"" << _nonce << "\", ";
2019-03-27 18:41:52 +08:00
printer << "uri=\"" << url << "\", ";
printer << "response=\"" << response << "\"";
2020-08-30 11:40:03 +08:00
header.emplace("Authorization", printer);
} else if (!(*this)[kRtspPwdIsMD5].as<bool>()) {
2019-03-27 18:41:52 +08:00
//base64认证
string authStr = StrPrinter << (*this)[kRtspUser] << ":" << (*this)[kRtspPwd];
char authStrBase64[1024] = {0};
av_base64_encode(authStrBase64, sizeof(authStrBase64), (uint8_t *) authStr.data(), (int)authStr.size());
2020-08-30 11:40:03 +08:00
header.emplace("Authorization", StrPrinter << "Basic " << authStrBase64);
2019-03-27 18:41:52 +08:00
}
}
2020-08-30 11:40:03 +08:00
if (!sdp.empty()) {
header.emplace("Content-Length", StrPrinter << sdp.size());
header.emplace("Content-Type", "application/sdp");
2019-03-27 18:41:52 +08:00
}
_StrPrinter printer;
printer << cmd << " " << url << " RTSP/1.0\r\n";
2020-08-30 11:40:03 +08:00
for (auto &pr : header) {
2019-03-27 18:41:52 +08:00
printer << pr.first << ": " << pr.second << "\r\n";
}
printer << "\r\n";
2020-08-30 11:40:03 +08:00
if (!sdp.empty()) {
2019-03-27 18:41:52 +08:00
printer << sdp;
}
SockSender::send(std::move(printer));
2019-03-27 18:41:52 +08:00
}
} /* namespace mediakit */