RtspPusher.cpp 15.4 KB
Newer Older
xiongziliang committed
1 2 3 4 5 6 7 8 9
/*
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * 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.
 */
xiongziliang committed
10 11 12 13 14 15

#include "Util/MD5.h"
#include "Util/base64.h"
#include "RtspPusher.h"
#include "RtspSession.h"

xiongziliang committed
16 17
using namespace mediakit::Client;

xiongziliang committed
18 19
namespace mediakit {

20
RtspPusher::RtspPusher(const EventPoller::Ptr &poller,const RtspMediaSource::Ptr &src) : TcpClient(poller){
xiongziliang committed
21 22 23 24 25 26 27 28 29 30 31
    _pMediaSrc = src;
}

RtspPusher::~RtspPusher() {
    teardown();
    DebugL << endl;
}

void RtspPusher::teardown() {
    if (alive()) {
        sendRtspRequest("TEARDOWN" ,_strContentBase);
xiongziliang committed
32
        shutdown(SockException(Err_shutdown,"teardown"));
xiongziliang committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    }

    reset();
    CLEAR_ARR(_apUdpSock);
    _rtspMd5Nonce.clear();
    _rtspRealm.clear();
    _aTrackInfo.clear();
    _strSession.clear();
    _strContentBase.clear();
    _strSession.clear();
    _uiCseq = 1;
    _pPublishTimer.reset();
    _pBeatTimer.reset();
    _pRtspReader.reset();
    _aTrackInfo.clear();
    _onHandshake = nullptr;
}

void RtspPusher::publish(const string &strUrl) {
52 53 54
    RtspUrl url;
    if(!url.parse(strUrl)){
        onPublishResult(SockException(Err_other,StrPrinter << "illegal rtsp url:" << strUrl),false);
xiongziliang committed
55 56
        return;
    }
xiongziliang committed
57

xiongziliang committed
58 59
    teardown();

60 61
    if (url._user.size()) {
        (*this)[kRtspUser] = url._user;
xiongziliang committed
62
    }
63 64
    if (url._passwd.size()) {
        (*this)[kRtspPwd] = url._passwd;
xiongziliang committed
65
        (*this)[kRtspPwdIsMD5] = false;
xiongziliang committed
66 67 68
    }

    _strUrl = strUrl;
69 70
    _eType = (Rtsp::eRtpType)(int)(*this)[kRtpType];
    DebugL << url._url << " " << (url._user.size() ? url._user : "null") << " " << (url._passwd.size() ? url._passwd : "null") << " " << _eType;
xiongziliang committed
71 72

    weak_ptr<RtspPusher> weakSelf = dynamic_pointer_cast<RtspPusher>(shared_from_this());
73 74
    float publishTimeOutSec = (*this)[kTimeoutMS].as<int>() / 1000.0;
    _pPublishTimer.reset( new Timer(publishTimeOutSec,  [weakSelf]() {
xiongziliang committed
75 76 77 78
        auto strongSelf=weakSelf.lock();
        if(!strongSelf) {
            return false;
        }
79
        strongSelf->onPublishResult(SockException(Err_timeout,"publish rtsp timeout"),false);
xiongziliang committed
80 81 82 83 84 85
        return false;
    },getPoller()));

    if(!(*this)[kNetAdapter].empty()){
        setNetAdapter((*this)[kNetAdapter]);
    }
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

    startConnect(url._host, url._port, publishTimeOutSec);
}

void RtspPusher::onPublishResult(const SockException &ex, bool handshakeCompleted) {
    if(!handshakeCompleted){
        //播放结果回调
        _pPublishTimer.reset();
        if(_onPublished){
            _onPublished(ex);
        }
    } else {
        //播放成功后异常断开回调
        if(_onShutdown){
            _onShutdown(ex);
        }
    }

    if(ex){
        teardown();
    }
xiongziliang committed
107 108 109
}

void RtspPusher::onErr(const SockException &ex) {
110 111
    //定时器_pPublishTimer为空后表明握手结束了
    onPublishResult(ex,!_pPublishTimer);
xiongziliang committed
112 113 114 115
}

void RtspPusher::onConnect(const SockException &err) {
    if(err) {
116
        onPublishResult(err,false);
xiongziliang committed
117 118
        return;
    }
119 120
    //推流器不需要多大的接收缓存,节省内存占用
    _sock->setReadBuffer(std::make_shared<BufferRaw>(1 * 1024));
xiongziliang committed
121 122 123 124 125 126 127 128
    sendAnnounce();
}

void RtspPusher::onRecv(const Buffer::Ptr &pBuf){
    try {
        input(pBuf->data(), pBuf->size());
    } catch (exception &e) {
        SockException ex(Err_other, e.what());
129 130
        //定时器_pPublishTimer为空后表明握手结束了
        onPublishResult(ex,!_pPublishTimer);
xiongziliang committed
131 132 133 134 135 136 137 138 139 140 141 142 143
    }
}

void RtspPusher::onWholeRtspPacket(Parser &parser) {
    decltype(_onHandshake) fun;
    _onHandshake.swap(fun);
    if(fun){
        fun(parser);
    }
    parser.Clear();
}


xiongziliang committed
144
void RtspPusher::sendAnnounce() {
xiongziliang committed
145 146 147 148 149
    auto src = _pMediaSrc.lock();
    if (!src) {
        throw std::runtime_error("the media source was released");
    }
    //解析sdp
xiongziliang committed
150 151
    _sdpParser.load(src->getSdp());
    _aTrackInfo = _sdpParser.getAvailableTrack();
xiongziliang committed
152 153 154 155 156 157

    if (_aTrackInfo.empty()) {
        throw std::runtime_error("无有效的Sdp Track");
    }

    _onHandshake = std::bind(&RtspPusher::handleResAnnounce,this, placeholders::_1);
xiongziliang committed
158
    sendRtspRequest("ANNOUNCE",_strUrl,{},src->getSdp());
xiongziliang committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
}

void RtspPusher::handleResAnnounce(const Parser &parser) {
    string authInfo = parser["WWW-Authenticate"];
    //发送DESCRIBE命令后的回复
    if ((parser.Url() == "401") && handleAuthenticationFailure(authInfo)) {
        sendAnnounce();
        return;
    }
    if(parser.Url() == "302"){
        auto newUrl = parser["Location"];
        if(newUrl.empty()){
            throw std::runtime_error("未找到Location字段(跳转url)");
        }
        publish(newUrl);
        return;
    }
    if (parser.Url() != "200") {
        throw std::runtime_error(StrPrinter << "ANNOUNCE:" << parser.Url() << " " << parser.Tail());
    }
    _strContentBase = parser["Content-Base"];

    if(_strContentBase.empty()){
        _strContentBase = _strUrl;
    }
    if (_strContentBase.back() == '/') {
        _strContentBase.pop_back();
    }

    sendSetup(0);
}

bool RtspPusher::handleAuthenticationFailure(const string &paramsStr) {
    if(!_rtspRealm.empty()){
        //已经认证过了
        return false;
    }

    char *realm = new char[paramsStr.size()];
    char *nonce = new char[paramsStr.size()];
    char *stale = new char[paramsStr.size()];
    onceToken token(nullptr,[&](){
        delete[] realm;
        delete[] nonce;
        delete[] stale;
    });

    if (sscanf(paramsStr.data(), "Digest realm=\"%[^\"]\", nonce=\"%[^\"]\", stale=%[a-zA-Z]", realm, nonce, stale) == 3) {
        _rtspRealm = (const char *)realm;
        _rtspMd5Nonce = (const char *)nonce;
        return true;
    }
    if (sscanf(paramsStr.data(), "Digest realm=\"%[^\"]\", nonce=\"%[^\"]\"", realm, nonce) == 2) {
        _rtspRealm = (const char *)realm;
        _rtspMd5Nonce = (const char *)nonce;
        return true;
    }
    if (sscanf(paramsStr.data(), "Basic realm=\"%[^\"]\"", realm) == 1) {
        _rtspRealm = (const char *)realm;
        return true;
    }
    return false;
}

xiongziliang committed
223
//有必要的情况下创建udp端口
224 225 226 227
void RtspPusher::createUdpSockIfNecessary(int track_idx){
    auto &rtpSockRef = _apUdpSock[track_idx];
    if(!rtpSockRef){
        rtpSockRef.reset(new Socket(getPoller()));
xiongziliang committed
228
        //rtp随机端口
229 230 231 232 233 234 235
        if (!rtpSockRef->bindUdpSock(0, get_local_ip().data())) {
            rtpSockRef.reset();
            throw std::runtime_error("open rtp sock failed");
        }
    }
}

xiongziliang committed
236
void RtspPusher::sendSetup(unsigned int trackIndex) {
xiongziliang committed
237 238 239 240 241
    _onHandshake = std::bind(&RtspPusher::handleResSetup,this, placeholders::_1,trackIndex);
    auto &track = _aTrackInfo[trackIndex];
    auto baseUrl = _strContentBase + "/" + track->_control_surffix;
    switch (_eType) {
        case Rtsp::RTP_TCP: {
xiongziliang committed
242
            sendRtspRequest("SETUP",baseUrl,{"Transport",StrPrinter << "RTP/AVP/TCP;unicast;interleaved=" << track->_type * 2 << "-" << track->_type * 2 + 1});
xiongziliang committed
243
        }
xiongziliang committed
244
            break;
xiongziliang committed
245
        case Rtsp::RTP_UDP: {
246
            createUdpSockIfNecessary(trackIndex);
xiongziliang committed
247
            int port = _apUdpSock[trackIndex]->get_local_port();
xiongziliang committed
248
            sendRtspRequest("SETUP",baseUrl,{"Transport",StrPrinter << "RTP/AVP;unicast;client_port=" << port << "-" << port + 1});
xiongziliang committed
249
        }
xiongziliang committed
250
            break;
xiongziliang committed
251
        default:
xiongziliang committed
252
            break;
xiongziliang committed
253 254 255
    }
}

256

xiongziliang committed
257 258 259 260 261 262 263 264 265 266 267 268
void RtspPusher::handleResSetup(const Parser &parser, unsigned int uiTrackIndex) {
    if (parser.Url() != "200") {
        throw std::runtime_error(
                StrPrinter << "SETUP:" << parser.Url() << " " << parser.Tail() << endl);
    }
    if (uiTrackIndex == 0) {
        _strSession = parser["Session"];
        _strSession.append(";");
        _strSession = FindField(_strSession.data(), nullptr, ";");
    }

    auto strTransport = parser["Transport"];
269
    if(strTransport.find("TCP") != string::npos || strTransport.find("interleaved") != string::npos){
xiongziliang committed
270 271 272 273 274 275 276
        _eType = Rtsp::RTP_TCP;
        string interleaved = FindField( FindField((strTransport + ";").data(), "interleaved=", ";").data(), NULL, "-");
        _aTrackInfo[uiTrackIndex]->_interleaved = atoi(interleaved.data());
    }else if(strTransport.find("multicast") != string::npos){
        throw std::runtime_error("SETUP rtsp pusher can not support multicast!");
    }else{
        _eType = Rtsp::RTP_UDP;
277
        createUdpSockIfNecessary(uiTrackIndex);
xiongziliang committed
278 279 280 281 282 283 284
        const char *strPos = "server_port=" ;
        auto port_str = FindField((strTransport + ";").data(), strPos, ";");
        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());
285
        _apUdpSock[uiTrackIndex]->setSendPeerAddr((struct sockaddr *)&(rtpto));
xiongziliang committed
286 287 288 289 290 291 292 293 294 295 296 297 298
    }

    RtspSplitter::enableRecvRtp(_eType == Rtsp::RTP_TCP);

    if (uiTrackIndex < _aTrackInfo.size() - 1) {
        //需要继续发送SETUP命令
        sendSetup(uiTrackIndex + 1);
        return;
    }

    sendRecord();
}

xiongziliang committed
299
void RtspPusher::sendOptions() {
xiongziliang committed
300
    _onHandshake = [this](const Parser& parser){};
xiongziliang committed
301
    sendRtspRequest("OPTIONS",_strContentBase);
xiongziliang committed
302 303
}

304
inline void RtspPusher::sendRtpPacket(const RtspMediaSource::RingDataType &pkt) {
xiongziliang committed
305 306 307
    //InfoL<<(int)pkt.Interleaved;
    switch (_eType) {
        case Rtsp::RTP_TCP: {
308 309 310 311 312 313 314 315 316 317
            int i = 0;
            int size = pkt->size();
            setSendFlushFlag(false);
            pkt->for_each([&](const RtpPacket::Ptr &rtp) {
                if (++i == size) {
                    setSendFlushFlag(true);
                }
                BufferRtp::Ptr buffer(new BufferRtp(rtp));
                send(buffer);
            });
xiongziliang committed
318 319 320
        }
            break;
        case Rtsp::RTP_UDP: {
321 322 323 324 325 326 327 328 329 330 331 332 333
            int i = 0;
            int size = pkt->size();
            pkt->for_each([&](const RtpPacket::Ptr &rtp) {
                int iTrackIndex = getTrackIndexByTrackType(rtp->type);
                auto &pSock = _apUdpSock[iTrackIndex];
                if (!pSock) {
                    shutdown(SockException(Err_shutdown,"udp sock not opened yet"));
                    return;
                }

                BufferRtp::Ptr buffer(new BufferRtp(rtp,4));
                pSock->send(buffer, nullptr, 0, ++i == size);
            });
xiongziliang committed
334 335 336 337 338 339 340 341 342 343 344 345 346
        }
            break;
        default:
            break;
    }
}

inline int RtspPusher::getTrackIndexByTrackType(TrackType type) {
    for (unsigned int i = 0; i < _aTrackInfo.size(); i++) {
        if (type == _aTrackInfo[i]->_type) {
            return i;
        }
    }
xiongziliang committed
347 348 349
    if(_aTrackInfo.size() == 1){
        return 0;
    }
350
    throw SockException(Err_shutdown, StrPrinter << "no such track with type:" << (int) type);
xiongziliang committed
351 352
}

xiongziliang committed
353
void RtspPusher::sendRecord() {
xiongziliang committed
354 355 356 357 358 359 360 361
    _onHandshake = [this](const Parser& parser){
        auto src = _pMediaSrc.lock();
        if (!src) {
            throw std::runtime_error("the media source was released");
        }

        _pRtspReader = src->getRing()->attach(getPoller());
        weak_ptr<RtspPusher> weakSelf = dynamic_pointer_cast<RtspPusher>(shared_from_this());
362
        _pRtspReader->setReadCB([weakSelf](const RtspMediaSource::RingDataType &pkt){
xiongziliang committed
363 364 365 366 367 368 369 370 371
            auto strongSelf = weakSelf.lock();
            if(!strongSelf) {
                return;
            }
            strongSelf->sendRtpPacket(pkt);
        });
        _pRtspReader->setDetachCB([weakSelf](){
            auto strongSelf = weakSelf.lock();
            if(strongSelf){
372
                strongSelf->onPublishResult(SockException(Err_other,"媒体源被释放"), !strongSelf->_pPublishTimer);
xiongziliang committed
373 374 375 376 377 378 379 380 381 382
            }
        });
        if(_eType != Rtsp::RTP_TCP){
            /////////////////////////心跳/////////////////////////////////
            weak_ptr<RtspPusher> weakSelf = dynamic_pointer_cast<RtspPusher>(shared_from_this());
            _pBeatTimer.reset(new Timer((*this)[kBeatIntervalMS].as<int>() / 1000.0, [weakSelf](){
                auto strongSelf = weakSelf.lock();
                if (!strongSelf){
                    return false;
                }
xiongziliang committed
383 384
                strongSelf->sendOptions();
                return true;
xiongziliang committed
385 386
            },getPoller()));
        }
387
        onPublishResult(SockException(Err_success,"success"), false);
388 389
        //提升发送性能
        setSocketFlags();
xiongziliang committed
390
    };
xiongziliang committed
391
    sendRtspRequest("RECORD",_strContentBase,{"Range","npt=0.000-"});
xiongziliang committed
392 393
}

394
void RtspPusher::setSocketFlags(){
395 396
    GET_CONFIG(int, mergeWriteMS, General::kMergeWriteMS);
    if(mergeWriteMS > 0) {
397
        //提高发送性能
xiongziliang committed
398
        setSendFlags(SOCKET_DEFAULE_FLAGS | FLAG_MORE);
399 400 401 402
        SockUtil::setNoDelay(_sock->rawFD(), false);
    }
}

xiongziliang committed
403
void RtspPusher::sendRtspRequest(const string &cmd, const string &url, const std::initializer_list<string> &header,const string &sdp ) {
xiongziliang committed
404 405 406 407 408 409 410 411 412 413
    string key;
    StrCaseMap header_map;
    int i = 0;
    for(auto &val : header){
        if(++i % 2 == 0){
            header_map.emplace(key,val);
        }else{
            key = val;
        }
    }
xiongziliang committed
414
    sendRtspRequest(cmd,url,header_map,sdp);
xiongziliang committed
415
}
xiongziliang committed
416
void RtspPusher::sendRtspRequest(const string &cmd, const string &url,const StrCaseMap &header_const,const string &sdp ) {
xiongziliang committed
417 418
    auto header = header_const;
    header.emplace("CSeq",StrPrinter << _uiCseq++);
xiongziliang committed
419
    header.emplace("User-Agent",SERVER_NAME);
xiongziliang committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

    if(!_strSession.empty()){
        header.emplace("Session",_strSession);
    }

    if(!_rtspRealm.empty() && !(*this)[kRtspUser].empty()){
        if(!_rtspMd5Nonce.empty()){
            //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];
            if(!(*this)[kRtspPwdIsMD5].as<bool>()){
                encrypted_pwd = MD5((*this)[kRtspUser]+ ":" + _rtspRealm + ":" + encrypted_pwd).hexdigest();
            }
            auto response = MD5( encrypted_pwd + ":" + _rtspMd5Nonce  + ":" + MD5(cmd + ":" + url).hexdigest()).hexdigest();
            _StrPrinter printer;
            printer << "Digest ";
            printer << "username=\"" << (*this)[kRtspUser] << "\", ";
            printer << "realm=\"" << _rtspRealm << "\", ";
            printer << "nonce=\"" << _rtspMd5Nonce << "\", ";
            printer << "uri=\"" << url << "\", ";
            printer << "response=\"" << response << "\"";
            header.emplace("Authorization",printer);
        }else if(!(*this)[kRtspPwdIsMD5].as<bool>()){
            //base64认证
            string authStr = StrPrinter << (*this)[kRtspUser] << ":" << (*this)[kRtspPwd];
            char authStrBase64[1024] = {0};
            av_base64_encode(authStrBase64,sizeof(authStrBase64),(uint8_t *)authStr.data(),authStr.size());
            header.emplace("Authorization",StrPrinter << "Basic " << authStrBase64 );
        }
    }

    if(!sdp.empty()){
        header.emplace("Content-Length",StrPrinter << sdp.size());
        header.emplace("Content-Type","application/sdp");
    }

    _StrPrinter printer;
    printer << cmd << " " << url << " RTSP/1.0\r\n";
    for (auto &pr : header){
        printer << pr.first << ": " << pr.second << "\r\n";
    }

    printer << "\r\n";

    if(!sdp.empty()){
        printer << sdp;
    }
xiongziliang committed
474
    SockSender::send(printer);
xiongziliang committed
475 476 477 478
}


} /* namespace mediakit */