RtpSender.cpp 6.08 KB
Newer Older
xiongziliang committed
1
/*
2 3 4 5 6 7 8 9 10
 * 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.
 */

11
#if defined(ENABLE_RTPPROXY)
xiongziliang committed
12
#include "RtpSender.h"
13 14
#include "Rtsp/RtspSession.h"
#include "Thread/WorkThreadPool.h"
xiongziliang committed
15
#include "RtpCache.h"
16 17 18

namespace mediakit{

xiongziliang committed
19
RtpSender::RtpSender(uint32_t ssrc, uint8_t payload_type) {
20
    _poller = EventPollerPool::Instance().getPoller();
xiongziliang committed
21 22 23
    _interface = std::make_shared<RtpCachePS>([this](std::shared_ptr<List<Buffer::Ptr> > list) {
        onFlushRtpList(std::move(list));
    }, ssrc, payload_type);
24 25
}

xiongziliang committed
26
RtpSender::~RtpSender() {
27 28
}

29
void RtpSender::startSend(const string &dst_url, uint16_t dst_port, bool is_udp, uint16_t src_port, const function<void(uint16_t local_port, const SockException &ex)> &cb){
30
    _is_udp = is_udp;
31
    _socket = Socket::createSocket(_poller, false);
32 33
    _dst_url = dst_url;
    _dst_port = dst_port;
34
	_src_port = src_port;
xiongziliang committed
35
    weak_ptr<RtpSender> weak_self = shared_from_this();
36
    if (is_udp) {
37
        _socket->bindUdpSock(src_port);
38
        auto poller = _poller;
39 40
        auto local_port = _socket->get_local_port();
        WorkThreadPool::Instance().getPoller()->async([cb, dst_url, dst_port, weak_self, poller, local_port]() {
41
            struct sockaddr addr;
42
            //切换线程目的是为了dns解析放在后台线程执行
43
            if (!SockUtil::getDomainIP(dst_url.data(), dst_port, addr)) {
44
                poller->async([dst_url, cb, local_port]() {
45
                    //切回自己的线程
46
                    cb(local_port, SockException(Err_dns, StrPrinter << "dns解析域名失败:" << dst_url));
47
                });
48 49
                return;
            }
50 51

            //dns解析成功
52
            poller->async([addr, weak_self, cb, local_port]() {
53
                //切回自己的线程
54
                cb(local_port, SockException());
55 56 57 58 59 60
                auto strong_self = weak_self.lock();
                if (strong_self) {
                    strong_self->_socket->setSendPeerAddr(&addr);
                    strong_self->onConnect();
                }
            });
61 62 63 64
        });
    } else {
        _socket->connect(dst_url, dst_port, [cb, weak_self](const SockException &err) {
            auto strong_self = weak_self.lock();
65 66 67 68 69 70 71 72
            if (strong_self) {
                if (!err) {
                    //tcp连接成功
                    strong_self->onConnect();
                }
                cb(strong_self->_socket->get_local_port(), err);
            } else {
                cb(0, err);
73
            }
74
        }, 5.0F, "0.0.0.0", src_port);
75 76 77
    }
}

xiongziliang committed
78
void RtpSender::onConnect(){
79 80 81
    _is_connect = true;
    //加大发送缓存,防止udp丢包之类的问题
    SockUtil::setSendBuf(_socket->rawFD(), 4 * 1024 * 1024);
82
    if (!_is_udp) {
83 84 85 86 87
        //关闭tcp no_delay并开启MSG_MORE, 提高发送性能
        SockUtil::setNoDelay(_socket->rawFD(), false);
        _socket->setSendFlags(SOCKET_DEFAULE_FLAGS | FLAG_MORE);
    }
    //连接建立成功事件
xiongziliang committed
88
    weak_ptr<RtpSender> weak_self = shared_from_this();
89 90 91 92 93 94
    _socket->setOnErr([weak_self](const SockException &err) {
        auto strong_self = weak_self.lock();
        if (strong_self) {
            strong_self->onErr(err);
        }
    });
95 96
    //获取本地端口,断开重连后确保端口不变
    _src_port = _socket->get_local_port();
xiongziliang committed
97
    InfoL << "开始发送 rtp:" << _socket->get_peer_ip() << ":" << _socket->get_peer_port() << ", 是否为udp方式:" << _is_udp;
98 99
}

xiongziliang committed
100 101
void RtpSender::addTrack(const Track::Ptr &track){
    _interface->addTrack(track);
102
}
103

xiongziliang committed
104 105 106 107 108 109
void RtpSender::addTrackCompleted(){
    _interface->addTrackCompleted();
}

void RtpSender::resetTracks(){
    _interface->resetTracks();
110 111 112
}

//此函数在其他线程执行
xiongziliang committed
113 114 115 116 117
void RtpSender::inputFrame(const Frame::Ptr &frame) {
    if (_is_connect) {
        //连接成功后才做实质操作(节省cpu资源)
        _interface->inputFrame(frame);
    }
118 119
}

120
//此函数在其他线程执行
xiongziliang committed
121
void RtpSender::onFlushRtpList(shared_ptr<List<Buffer::Ptr> > rtp_list) {
122 123 124 125 126 127 128 129 130 131
    if(!_is_connect){
        //连接成功后才能发送数据
        return;
    }

    auto is_udp = _is_udp;
    auto socket = _socket;
    _poller->async([rtp_list, is_udp, socket]() {
        int i = 0;
        int size = rtp_list->size();
xiongziliang committed
132
        rtp_list->for_each([&](Buffer::Ptr &packet) {
133 134
            if (is_udp) {
                //udp模式,rtp over tcp前4个字节可以忽略
xiongziliang committed
135
                socket->send(std::make_shared<BufferRtp>(std::move(packet), 4), nullptr, 0, ++i == size);
136 137
            } else {
                //tcp模式, rtp over tcp前2个字节可以忽略,只保留后续rtp长度的2个字节
xiongziliang committed
138
                socket->send(std::make_shared<BufferRtp>(std::move(packet), 2), nullptr, 0, ++i == size);
139 140
            }
        });
141 142 143
    });
}

xiongziliang committed
144
void RtpSender::onErr(const SockException &ex, bool is_connect) {
145 146 147 148 149 150
    _is_connect = false;

    //监听socket断开事件,方便重连
    if (is_connect) {
        WarnL << "重连" << _dst_url << ":" << _dst_port << "失败, 原因为:" << ex.what();
    } else {
xiongziliang committed
151
        WarnL << "停止发送 rtp:" <<  _dst_url << ":" << _dst_port << ", 原因为:" << ex.what();
152 153
    }

xiongziliang committed
154
    weak_ptr<RtpSender> weak_self = shared_from_this();
155 156 157 158 159
    _connect_timer = std::make_shared<Timer>(10.0, [weak_self]() {
        auto strong_self = weak_self.lock();
        if (!strong_self) {
            return false;
        }
160
        strong_self->startSend(strong_self->_dst_url, strong_self->_dst_port, strong_self->_is_udp, strong_self->_src_port, [weak_self](uint16_t local_port, const SockException &ex){
161 162 163 164 165 166 167 168 169 170
            auto strong_self = weak_self.lock();
            if (strong_self && ex) {
                //连接失败且本对象未销毁,那么重试连接
                strong_self->onErr(ex, true);
            }
        });
        return false;
    }, _poller);
}

171 172
}//namespace mediakit
#endif// defined(ENABLE_RTPPROXY)