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

#include <stdlib.h>
xiongzilaing committed
12
#include "Rtsp.h"
xiongziliang committed
13
#include "Common/Parser.h"
xiongzilaing committed
14

xiongziliang committed
15 16
namespace mediakit{

xiongziliang committed
17 18
int RtpPayload::getClockRate(int pt){
    switch (pt){
19
#define SWITCH_CASE(name, type, value, clock_rate, channel, codec_id) case value :  return clock_rate;
xiongziliang committed
20 21 22 23 24 25 26 27
        RTP_PT_MAP(SWITCH_CASE)
#undef SWITCH_CASE
        default: return 90000;
    }
}

TrackType RtpPayload::getTrackType(int pt){
    switch (pt){
28
#define SWITCH_CASE(name, type, value, clock_rate, channel, codec_id) case value :  return type;
xiongziliang committed
29 30 31 32 33 34 35 36
        RTP_PT_MAP(SWITCH_CASE)
#undef SWITCH_CASE
        default: return TrackInvalid;
    }
}

int RtpPayload::getAudioChannel(int pt){
    switch (pt){
37
#define SWITCH_CASE(name, type, value, clock_rate, channel, codec_id) case value :  return channel;
xiongziliang committed
38 39 40 41 42 43 44 45
        RTP_PT_MAP(SWITCH_CASE)
#undef SWITCH_CASE
        default: return 1;
    }
}

const char * RtpPayload::getName(int pt){
    switch (pt){
46
#define SWITCH_CASE(name, type, value, clock_rate, channel, codec_id) case value :  return #name;
xiongziliang committed
47 48 49 50 51 52
        RTP_PT_MAP(SWITCH_CASE)
#undef SWITCH_CASE
        default: return "unknown payload type";
    }
}

53 54 55 56 57 58 59 60 61
CodecId RtpPayload::getCodecId(int pt) {
    switch (pt) {
#define SWITCH_CASE(name, type, value, clock_rate, channel, codec_id) case value :  return codec_id;
        RTP_PT_MAP(SWITCH_CASE)
#undef SWITCH_CASE
        default : return CodecInvalid;
    }
}

62
static void getAttrSdp(const map<string, string> &attr, _StrPrinter &printer){
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    const map<string, string>::value_type *ptr = nullptr;
    for(auto &pr : attr){
        if(pr.first == "control"){
            ptr = &pr;
            continue;
        }
        if(pr.second.empty()){
            printer << "a=" << pr.first << "\r\n";
        }else{
            printer << "a=" << pr.first << ":" << pr.second << "\r\n";
        }
    }
    if(ptr){
        printer << "a=" << ptr->first << ":" << ptr->second << "\r\n";
    }
78
}
xiongziliang committed
79 80 81

string SdpTrack::getName() const{
    switch (_pt){
82
#define SWITCH_CASE(name, type, value, clock_rate, channel, codec_id) case value :  return #name;
xiongziliang committed
83 84 85 86 87 88
        RTP_PT_MAP(SWITCH_CASE)
#undef SWITCH_CASE
        default: return _codec;
    }
}

xia-chu committed
89 90 91 92 93 94 95 96
string SdpTrack::getControlUrl(const string &base_url) const{
    if (_control.find("://") != string::npos) {
        //以rtsp://开头
        return _control;
    }
    return base_url +"/" + _control;
}

97
string SdpTrack::toString() const {
98 99 100 101 102 103 104 105 106 107 108 109 110
    _StrPrinter _printer;
    switch (_type){
        case TrackTitle:{
            _printer << "v=" << 0 << "\r\n";
            if(!_o.empty()){
                _printer << "o="<< _o << "\r\n";
            }
            if(!_c.empty()){
                _printer << "c=" << _c << "\r\n";
            }
            if(!_t.empty()){
                _printer << "t=" << _t << "\r\n";
            }
111

xiongziliang committed
112
            _printer << "s=Streamed by " << SERVER_NAME << "\r\n";
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
            getAttrSdp(_attr,_printer);
        }
            break;
        case TrackAudio:
        case TrackVideo:{
            if(_type == TrackAudio){
                _printer << "m=audio 0 RTP/AVP " << _pt << "\r\n";
            }else{
                _printer << "m=video 0 RTP/AVP " << _pt << "\r\n";
            }
            if(!_b.empty()){
                _printer << "b=" <<_b << "\r\n";
            }
            getAttrSdp(_attr,_printer);
        }
            break;
        default:
            break;
    }
xiongziliang committed
132
    return std::move(_printer);
133
}
134 135

static TrackType toTrackType(const string &str) {
136 137 138
    if (str == "") {
        return TrackTitle;
    }
139

140 141 142
    if (str == "video") {
        return TrackVideo;
    }
143

144 145 146
    if (str == "audio") {
        return TrackAudio;
    }
147

148
    return TrackInvalid;
149 150
}

xiongziliang committed
151
void SdpParser::load(const string &sdp) {
152 153 154
    {
        _track_vec.clear();
        SdpTrack::Ptr track = std::make_shared<SdpTrack>();
xiongziliang committed
155 156
        track->_type = TrackTitle;
        _track_vec.emplace_back(track);
xiongziliang committed
157

158 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
        auto lines = split(sdp, "\n");
        for (auto &line : lines) {
            trim(line);
            if (line.size() < 2 || line[1] != '=') {
                continue;
            }
            char opt = line[0];
            string opt_val = line.substr(2);
            switch (opt) {
                case 'o':
                    track->_o = opt_val;
                    break;
                case 's':
                    track->_s = opt_val;
                    break;
                case 'i':
                    track->_i = opt_val;
                    break;
                case 'c':
                    track->_c = opt_val;
                    break;
                case 't':
                    track->_t = opt_val;
                    break;
                case 'b':
                    track->_b = opt_val;
                    break;
                case 'm': {
                    track = std::make_shared<SdpTrack>();
xiongziliang committed
187 188 189 190
                    int pt, port;
                    char rtp[16] = {0}, type[16];
                    if (4 == sscanf(opt_val.data(), " %15[^ ] %d %15[^ ] %d", type, &port, rtp, &pt)) {
                        track->_pt = pt;
xia-chu committed
191
                        track->_samplerate = RtpPayload::getClockRate(pt);
xiongziliang committed
192
                        track->_channel = RtpPayload::getAudioChannel(pt);
xiongziliang committed
193 194 195 196 197
                        track->_type = toTrackType(type);
                        track->_m = opt_val;
                        track->_port = port;
                        _track_vec.emplace_back(track);
                    }
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
                }
                    break;
                case 'a': {
                    string attr = FindField(opt_val.data(), nullptr, ":");
                    if (attr.empty()) {
                        track->_attr[opt_val] = "";
                    } else {
                        track->_attr[attr] = FindField(opt_val.data(), ":", nullptr);
                    }
                }
                    break;
                default:
                    track->_other[opt] = opt_val;
                    break;
            }
        }
    }
xiongziliang committed
215

216 217 218 219 220 221 222 223 224 225
    for (auto &track_ptr : _track_vec) {
        auto &track = *track_ptr;
        auto it = track._attr.find("range");
        if (it != track._attr.end()) {
            char name[16] = {0}, start[16] = {0}, end[16] = {0};
            int ret = sscanf(it->second.data(), "%15[^=]=%15[^-]-%15s", name, start, end);
            if (3 == ret || 2 == ret) {
                if (strcmp(start, "now") == 0) {
                    strcpy(start, "0");
                }
xia-chu committed
226 227
                track._start = (float) atof(start);
                track._end = (float) atof(end);
228 229 230
                track._duration = track._end - track._start;
            }
        }
xiongziliang committed
231

232
        it = track._attr.find("rtpmap");
xia-chu committed
233
        if (it != track._attr.end()) {
234
            auto rtpmap = it->second;
xiongziliang committed
235
            int pt, samplerate, channel;
236
            char codec[16] = {0};
xiongziliang committed
237 238 239 240 241
            if (4 == sscanf(rtpmap.data(), "%d %15[^/]/%d/%d", &pt, codec, &samplerate, &channel)) {
                track._pt = pt;
                track._codec = codec;
                track._samplerate = samplerate;
                track._channel = channel;
xia-chu committed
242
            } else if (3 == sscanf(rtpmap.data(), "%d %15[^/]/%d", &pt, codec, &samplerate)) {
243 244 245 246
                track._pt = pt;
                track._codec = codec;
                track._samplerate = samplerate;
            }
xia-chu committed
247 248 249 250
            if (!track._samplerate && track._type == TrackVideo) {
                //未设置视频采样率时,赋值为90000
                track._samplerate = 90000;
            }
251
        }
252

253
        it = track._attr.find("fmtp");
xia-chu committed
254
        if (it != track._attr.end()) {
255 256
            track._fmtp = it->second;
        }
xiongziliang committed
257

258
        it = track._attr.find("control");
xia-chu committed
259
        if (it != track._attr.end()) {
260 261 262
            track._control = it->second;
        }
    }
263
}
xiongziliang committed
264

xiongziliang committed
265
bool SdpParser::available() const {
xiongziliang committed
266 267 268
    return getTrack(TrackAudio) || getTrack(TrackVideo);
}

xiongziliang committed
269
SdpTrack::Ptr SdpParser::getTrack(TrackType type) const {
270 271 272 273 274 275
    for (auto &track : _track_vec){
        if(track->_type == type){
            return track;
        }
    }
    return nullptr;
276
}
xiongziliang committed
277

xiongziliang committed
278
vector<SdpTrack::Ptr> SdpParser::getAvailableTrack() const {
279 280 281 282 283 284 285 286 287 288 289
    vector<SdpTrack::Ptr> ret;
    bool audio_added = false;
    bool video_added = false;
    for (auto &track : _track_vec){
        if(track->_type == TrackAudio ){
            if(!audio_added){
                ret.emplace_back(track);
                audio_added = true;
            }
            continue;
        }
290

291 292 293 294 295 296 297 298
        if(track->_type == TrackVideo ){
            if(!video_added){
                ret.emplace_back(track);
                video_added = true;
            }
            continue;
        }
    }
299
    return ret;
xzl committed
300
}
xiongziliang committed
301

302
string SdpParser::toString() const {
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    string title,audio,video;
    for(auto &track : _track_vec){
        switch (track->_type){
            case TrackTitle:{
                title = track->toString();
            }
                break;
            case TrackVideo:{
                video = track->toString();
            }
                break;
            case TrackAudio:{
                audio = track->toString();
            }
                break;
            default:
                break;
        }
    }
    return title + video + audio;
323 324
}

325
bool RtspUrl::parse(const string &strUrl) {
326 327 328 329 330 331 332 333 334 335 336 337
    auto schema = FindField(strUrl.data(), nullptr, "://");
    bool isSSL = strcasecmp(schema.data(), "rtsps") == 0;
    //查找"://"与"/"之间的字符串,用于提取用户名密码
    auto middle_url = FindField(strUrl.data(), "://", "/");
    if (middle_url.empty()) {
        middle_url = FindField(strUrl.data(), "://", nullptr);
    }
    auto pos = middle_url.rfind('@');
    if (pos == string::npos) {
        //并没有用户名密码
        return setup(isSSL, strUrl, "", "");
    }
338

339 340 341 342 343 344 345 346 347 348
    //包含用户名密码
    auto user_pwd = middle_url.substr(0, pos);
    auto suffix = strUrl.substr(schema.size() + 3 + pos + 1);
    auto url = StrPrinter << "rtsp://" << suffix << endl;
    if (user_pwd.find(":") == string::npos) {
        return setup(isSSL, url, user_pwd, "");
    }
    auto user = FindField(user_pwd.data(), nullptr, ":");
    auto pwd = FindField(user_pwd.data(), ":", nullptr);
    return setup(isSSL, url, user, pwd);
349 350 351
}

bool RtspUrl::setup(bool isSSL, const string &strUrl, const string &strUser, const string &strPwd) {
352 353 354 355 356 357 358 359 360 361 362 363
    auto ip = FindField(strUrl.data(), "://", "/");
    if (ip.empty()) {
        ip = split(FindField(strUrl.data(), "://", NULL), "?")[0];
    }
    auto port = atoi(FindField(ip.data(), ":", NULL).data());
    if (port <= 0 || port > UINT16_MAX) {
        //rtsp 默认端口554
        port = isSSL ? 322 : 554;
    } else {
        //服务器域名
        ip = FindField(ip.data(), NULL, ":");
    }
364

365 366 367
    if (ip.empty()) {
        return false;
    }
368

369 370 371 372 373 374 375
    _url = std::move(strUrl);
    _user = std::move(strUser);
    _passwd = std::move(strPwd);
    _host = std::move(ip);
    _port = port;
    _is_ssl = isSSL;
    return true;
376 377
}

378 379 380 381
static void makeSockPair_l(std::pair<Socket::Ptr, Socket::Ptr> &pair, const string &local_ip){
    auto &pSockRtp = pair.first;
    auto &pSockRtcp = pair.second;

382 383 384 385 386 387
    if (!pSockRtp->bindUdpSock(0, local_ip.data())) {
        //分配端口失败
        throw runtime_error("open udp socket failed");
    }

    //是否是偶数
388
    bool even_numbers = pSockRtp->get_local_port() % 2 == 0;
389 390 391 392 393 394 395 396 397 398 399 400 401
    if (!pSockRtcp->bindUdpSock(pSockRtp->get_local_port() + (even_numbers ? 1 : -1), local_ip.data())) {
        //分配端口失败
        throw runtime_error("open udp socket failed");
    }

    if (!even_numbers) {
        //如果rtp端口不是偶数,那么与rtcp端口互换,目的是兼容一些要求严格的播放器或服务器
        Socket::Ptr tmp = pSockRtp;
        pSockRtp = pSockRtcp;
        pSockRtcp = tmp;
    }
}

402 403 404 405 406 407 408 409 410 411 412 413 414
 void makeSockPair(std::pair<Socket::Ptr, Socket::Ptr> &pair, const string &local_ip){
     int try_count = 0;
     while (true) {
         try {
             makeSockPair_l(pair, local_ip);
             break;
         } catch (...) {
             if (++try_count == 3) {
                 throw;
             }
             WarnL << "open udp socket failed, retry: " << try_count;
         }
     }
415
}
416

xiongziliang committed
417 418 419 420 421 422 423 424 425 426
string printSSRC(uint32_t ui32Ssrc) {
    char tmp[9] = { 0 };
    ui32Ssrc = htonl(ui32Ssrc);
    uint8_t *pSsrc = (uint8_t *) &ui32Ssrc;
    for (int i = 0; i < 4; i++) {
        sprintf(tmp + 2 * i, "%02X", pSsrc[i]);
    }
    return tmp;
}

xiongziliang committed
427
Buffer::Ptr makeRtpOverTcpPrefix(uint16_t size, uint8_t interleaved){
428 429
    auto rtp_tcp = BufferRaw::create();
    rtp_tcp->setCapacity(RtpPacket::kRtpTcpHeaderSize);
xiongziliang committed
430
    rtp_tcp->setSize(RtpPacket::kRtpTcpHeaderSize);
xiongziliang committed
431 432 433 434 435 436 437 438
    auto ptr = rtp_tcp->data();
    ptr[0] = '$';
    ptr[1] = interleaved;
    ptr[2] = (size >> 8) & 0xFF;
    ptr[3] = size & 0xFF;
    return rtp_tcp;
}

xiongziliang committed
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 474 475 476 477 478 479 480 481 482 483 484 485 486 487
#define AV_RB16(x)                           \
    ((((const uint8_t*)(x))[0] << 8) |          \
      ((const uint8_t*)(x))[1])

size_t RtpHeader::getCsrcSize() const {
    //每个csrc占用4字节
    return csrc << 2;
}

uint8_t *RtpHeader::getCsrcData() {
    if (!csrc) {
        return nullptr;
    }
    return &payload;
}

size_t RtpHeader::getExtSize() const {
    //rtp有ext
    if (!ext) {
        return 0;
    }
    auto ext_ptr = &payload + getCsrcSize();
    uint16_t reserved = AV_RB16(ext_ptr);
    //每个ext占用4字节
    return AV_RB16(ext_ptr + 2) << 2;
}

uint8_t *RtpHeader::getExtData() {
    if (!ext) {
        return nullptr;
    }
    auto ext_ptr = &payload + getCsrcSize();
    //多出的4个字节分别为reserved、ext_len
    return ext_ptr + 4 + getExtSize();
}

size_t RtpHeader::getPayloadOffset() const {
    //有ext时,还需要忽略reserved、ext_len 4个字节
    return getCsrcSize() + (ext ? (4 + getExtSize()) : 0);
}

uint8_t *RtpHeader::getPayloadData() {
    return &payload + getPayloadOffset();
}

size_t RtpHeader::getPaddingSize(size_t rtp_size) const {
    if (!padding) {
        return 0;
    }
488
    auto end = (uint8_t *) this + rtp_size - 1;
xiongziliang committed
489 490 491
    return *end;
}

xia-chu committed
492
size_t RtpHeader::getPayloadSize(size_t rtp_size) const{
xiongziliang committed
493 494 495 496 497 498 499
    auto invalid_size = getPayloadOffset() + getPaddingSize(rtp_size);
    if (invalid_size + RtpPacket::kRtpHeaderSize >= rtp_size) {
        return 0;
    }
    return rtp_size - invalid_size - RtpPacket::kRtpHeaderSize;
}

xia-chu committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
string RtpHeader::dumpString(size_t rtp_size) const{
    _StrPrinter printer;
    printer << "version:" << (int)version << "\r\n";
    printer << "padding:" << getPaddingSize(rtp_size) << "\r\n";
    printer << "ext:" << getExtSize() << "\r\n";
    printer << "csrc:" << getCsrcSize() << "\r\n";
    printer << "mark:" << (int)mark << "\r\n";
    printer << "pt:" << (int)pt << "\r\n";
    printer << "seq:" << ntohs(seq) << "\r\n";
    printer << "stamp:" << ntohl(stamp) << "\r\n";
    printer << "ssrc:" << ntohl(ssrc) << "\r\n";
    printer << "rtp size:" << rtp_size << "\r\n";
    printer << "payload offset:" << getPayloadOffset() << "\r\n";
    printer << "payload size:" << getPayloadSize(rtp_size) << "\r\n";
    return std::move(printer);
}

///////////////////////////////////////////////////////////////////////

xiongziliang committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
RtpHeader* RtpPacket::getHeader(){
    //需除去rtcp over tcp 4个字节长度
    return (RtpHeader*)(data() + RtpPacket::kRtpTcpHeaderSize);
}

uint16_t RtpPacket::getSeq(){
    return ntohs(getHeader()->seq);
}

uint32_t RtpPacket::getStampMS(){
    return ntohl(getHeader()->stamp) * uint64_t(1000) / sample_rate;
}

uint32_t RtpPacket::getSSRC(){
    return ntohl(getHeader()->ssrc);
}

uint8_t* RtpPacket::getPayload(){
    return getHeader()->getPayloadData();
}

size_t RtpPacket::getPayloadSize(){
    //需除去rtcp over tcp 4个字节长度
    return getHeader()->getPayloadSize(size() - kRtpTcpHeaderSize);
}

xia-chu committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558
RtpPacket::Ptr RtpPacket::create(){
#if 0
    static ResourcePool<RtpPacket> packet_pool;
    static onceToken token([]() {
        packet_pool.setSize(1024);
    });
    auto ret = packet_pool.obtain();
    ret->setSize(0);
    return ret;
#else
    return Ptr(new RtpPacket);
#endif
}

xia-chu committed
559 560 561 562 563
}//namespace mediakit

namespace toolkit {
    StatisticImp(mediakit::RtpPacket);
}