Commit aa2ff01d by xiongguangjie

first commit for srt intergrate

parent 59dcd03b
...@@ -106,6 +106,7 @@ option(ENABLE_FFMPEG "Enable FFmpeg" true) ...@@ -106,6 +106,7 @@ option(ENABLE_FFMPEG "Enable FFmpeg" true)
option(ENABLE_MSVC_MT "Enable MSVC Mt/Mtd lib" true) option(ENABLE_MSVC_MT "Enable MSVC Mt/Mtd lib" true)
option(ENABLE_API_STATIC_LIB "Enable mk_api static lib" false) option(ENABLE_API_STATIC_LIB "Enable mk_api static lib" false)
option(USE_SOLUTION_FOLDERS "Enable solution dir supported" ON) option(USE_SOLUTION_FOLDERS "Enable solution dir supported" ON)
option(ENABLE_SRT "Enable SRT" true)
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# Solution folders: # Solution folders:
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
...@@ -486,6 +487,15 @@ if (ENABLE_WEBRTC) ...@@ -486,6 +487,15 @@ if (ENABLE_WEBRTC)
endif () endif ()
endif () endif ()
if (ENABLE_SRT)
add_definitions(-DENABLE_SRT)
include_directories(./srt)
file(GLOB SRC_SRT_LIST ./srt/*.cpp ./srt/*.h ./srt/*.hpp)
add_library(srt ${SRC_SRT_LIST})
list(APPEND LINK_LIB_LIST srt)
message(STATUS "srt 功能已开启")
endif()
#添加c库 #添加c库
if (ENABLE_API) if (ENABLE_API)
add_subdirectory(api) add_subdirectory(api)
......
...@@ -284,6 +284,14 @@ preferredCodecA=PCMU,PCMA,opus,mpeg4-generic ...@@ -284,6 +284,14 @@ preferredCodecA=PCMU,PCMA,opus,mpeg4-generic
#以下范例为所有支持的视频codec #以下范例为所有支持的视频codec
preferredCodecV=H264,H265,AV1X,VP9,VP8 preferredCodecV=H264,H265,AV1X,VP9,VP8
[srt]
#srt播放推流、播放超时时间,单位秒
timeoutSec=5
#srt udp服务器监听端口号,所有srt客户端将通过该端口传输srt数据,
#该端口是多线程的,同时支持客户端网络切换导致的连接迁移
port=9000
[rtsp] [rtsp]
#rtsp专有鉴权方式是采用base64还是md5方式 #rtsp专有鉴权方式是采用base64还是md5方式
authBasic=0 authBasic=0
......
...@@ -32,6 +32,11 @@ ...@@ -32,6 +32,11 @@
#include "../webrtc/WebRtcSession.h" #include "../webrtc/WebRtcSession.h"
#endif #endif
#if defined(ENABLE_SRT)
#include "../srt/SrtSession.hpp"
#include "../srt/SrtTransport.hpp"
#endif
#if defined(ENABLE_VERSION) #if defined(ENABLE_VERSION)
#include "version.h" #include "version.h"
#endif #endif
...@@ -284,6 +289,24 @@ int start_main(int argc,char *argv[]) { ...@@ -284,6 +289,24 @@ int start_main(int argc,char *argv[]) {
uint16_t rtcPort = mINI::Instance()[RTC::kPort]; uint16_t rtcPort = mINI::Instance()[RTC::kPort];
#endif//defined(ENABLE_WEBRTC) #endif//defined(ENABLE_WEBRTC)
#if defined(ENABLE_SRT)
auto srtSrv = std::make_shared<UdpServer>();
srtSrv->setOnCreateSocket([](const EventPoller::Ptr &poller, const Buffer::Ptr &buf, struct sockaddr *, int) {
if (!buf) {
return Socket::createSocket(poller, false);
}
auto new_poller = SRT::SrtSession::queryPoller(buf);
if (!new_poller) {
//握手第一阶段
return Socket::createSocket(poller, false);
}
return Socket::createSocket(new_poller, false);
});
uint16_t srtPort = mINI::Instance()[SRT::kPort];
#endif //defined(ENABLE_SRT)
try { try {
//rtsp服务器,端口默认554 //rtsp服务器,端口默认554
if (rtspPort) { rtspSrv->start<RtspSession>(rtspPort); } if (rtspPort) { rtspSrv->start<RtspSession>(rtspPort); }
...@@ -313,6 +336,14 @@ int start_main(int argc,char *argv[]) { ...@@ -313,6 +336,14 @@ int start_main(int argc,char *argv[]) {
if (rtcPort) { rtcSrv->start<WebRtcSession>(rtcPort); } if (rtcPort) { rtcSrv->start<WebRtcSession>(rtcPort); }
#endif//defined(ENABLE_WEBRTC) #endif//defined(ENABLE_WEBRTC)
#if defined(ENABLE_SRT)
// srt udp服务器
if(srtPort){
srtSrv->start<SRT::SrtSession>(srtPort);
}
#endif//defined(ENABLE_SRT)
} catch (std::exception &ex) { } catch (std::exception &ex) {
WarnL << "端口占用或无权限:" << ex.what() << endl; WarnL << "端口占用或无权限:" << ex.what() << endl;
ErrorL << "程序启动失败,请修改配置文件中端口号后重试!" << endl; ErrorL << "程序启动失败,请修改配置文件中端口号后重试!" << endl;
......
#include "Ack.hpp"
#include "Common.hpp"
namespace SRT {
bool ACKPacket::loadFromData(uint8_t *buf, size_t len) {
if(len < ACK_CIF_SIZE + ControlPacket::HEADER_SIZE){
return false;
}
_data = BufferRaw::create();
_data->assign((char *)(buf), len);
ControlPacket::loadHeader();
ack_number = loadUint32(type_specific_info);
uint8_t* ptr = (uint8_t*)_data->data()+ControlPacket::HEADER_SIZE;
last_ack_pkt_seq_number = loadUint32(ptr);
ptr += 4;
rtt = loadUint32(ptr);
ptr += 4;
rtt_variance = loadUint32(ptr);
ptr += 4;
available_buf_size = loadUint32(ptr);
ptr += 4;
pkt_recv_rate = loadUint32(ptr);
ptr += 4;
estimated_link_capacity = loadUint32(ptr);
ptr += 4;
recv_rate = loadUint32(ptr);
ptr += 4;
return true;
}
bool ACKPacket::storeToData() {
_data = BufferRaw::create();
_data->setCapacity(HEADER_SIZE + ACK_CIF_SIZE);
_data->setSize(HEADER_SIZE + ACK_CIF_SIZE);
control_type = ControlPacket::ACK;
sub_type = 0;
storeUint32(type_specific_info,ack_number);
storeToHeader();
uint8_t* ptr = (uint8_t*)_data->data()+ControlPacket::HEADER_SIZE;
storeUint32(ptr,last_ack_pkt_seq_number);
ptr += 4;
storeUint32(ptr,rtt);
ptr += 4;
storeUint32(ptr,rtt_variance);
ptr += 4;
storeUint32(ptr,pkt_recv_rate);
ptr += 4;
storeUint32(ptr,available_buf_size);
ptr += 4;
storeUint32(ptr,estimated_link_capacity);
ptr += 4;
storeUint32(ptr,recv_rate);
ptr += 4;
return true;
}
} // namespace
\ No newline at end of file
#ifndef ZLMEDIAKIT_SRT_ACK_H
#define ZLMEDIAKIT_SRT_ACK_H
#include "Packet.hpp"
namespace SRT{
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+- SRT Header +-+-+-+-+-+-+-+-+-+-+-+-+-+
|1| Control Type | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgement Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Timestamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination Socket ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- CIF -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Last Acknowledged Packet Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| RTT |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| RTT Variance |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Available Buffer Size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Packets Receiving Rate |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Estimated Link Capacity |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Receiving Rate |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Figure 13: ACK control packet
https://haivision.github.io/srt-rfc/draft-sharabayko-srt.html#name-ack-acknowledgment
*/
class ACKPacket : public ControlPacket
{
public:
using Ptr = std::shared_ptr<ACKPacket>;
ACKPacket() = default;
~ACKPacket() = default;
enum{
ACK_CIF_SIZE = 7*4
};
///////ControlPacket override///////
bool loadFromData(uint8_t *buf, size_t len) override;
bool storeToData() override;
uint32_t ack_number;
uint32_t last_ack_pkt_seq_number;
uint32_t rtt;
uint32_t rtt_variance;
uint32_t available_buf_size;
uint32_t pkt_recv_rate;
uint32_t estimated_link_capacity;
uint32_t recv_rate;
};
class ACKACKPacket : public ControlPacket{
public:
using Ptr = std::shared_ptr<ACKACKPacket>;
ACKACKPacket() = default;
~ACKACKPacket() = default;
///////ControlPacket override///////
bool loadFromData(uint8_t *buf, size_t len) override{
if(len < ControlPacket::HEADER_SIZE){
return false;
}
_data = BufferRaw::create();
_data->assign((char *)(buf), len);
ControlPacket::loadHeader();
ack_number = loadUint32(type_specific_info);
return true;
}
bool storeToData() override{
_data = BufferRaw::create();
_data->setCapacity(HEADER_SIZE);
_data->setSize(HEADER_SIZE );
control_type = ControlPacket::ACKACK;
sub_type = 0;
storeUint32(type_specific_info,ack_number);
storeToHeader();
return true;
}
uint32_t ack_number;
};
} //namespace SRT
#endif // ZLMEDIAKIT_SRT_ACK_H
\ No newline at end of file
#ifndef ZLMEDIAKIT_SRT_COMMON_H
#define ZLMEDIAKIT_SRT_COMMON_H
#include <chrono>
namespace SRT
{
using SteadyClock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<SteadyClock>;
using Microseconds = std::chrono::microseconds;
using Milliseconds = std::chrono::milliseconds;
inline int64_t DurationCountMicroseconds( SteadyClock::duration dur){
return std::chrono::duration_cast<std::chrono::microseconds>(dur).count();
}
inline uint32_t loadUint32(uint8_t *ptr) {
return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
}
inline uint16_t loadUint16(uint8_t *ptr) {
return ptr[0] << 8 | ptr[1];
}
inline void storeUint32(uint8_t *buf, uint32_t val) {
buf[0] = val >> 24;
buf[1] = (val >> 16) & 0xff;
buf[2] = (val >> 8) & 0xff;
buf[3] = val & 0xff;
}
inline void storeUint16(uint8_t *buf, uint16_t val) {
buf[0] = (val >> 8) & 0xff;
buf[1] = val & 0xff;
}
inline void storeUint32LE(uint8_t *buf, uint32_t val) {
buf[0] = val & 0xff;
buf[1] = (val >> 8) & 0xff;
buf[2] = (val >> 16) & 0xff;
buf[3] = (val >>24) & 0xff;
}
inline void storeUint16LE(uint8_t *buf, uint16_t val) {
buf[0] = val & 0xff;
buf[1] = (val>>8) & 0xff;
}
inline uint32_t srtVersion(int major, int minor, int patch)
{
return patch + minor*0x100 + major*0x10000;
}
} // namespace SRT
#endif //ZLMEDIAKIT_SRT_COMMON_H
\ No newline at end of file
#include "HSExt.hpp"
namespace SRT {
bool HSExtMessage::loadFromData(uint8_t *buf, size_t len) {
if(buf == NULL || len != HSEXT_MSG_SIZE){
return false;
}
_data = BufferRaw::create();
_data->assign((char*)buf,len);
extension_length = 3;
HSExt::loadHeader();
assert(extension_type == SRT_CMD_HSREQ || extension_type == SRT_CMD_HSRSP);
uint8_t* ptr = (uint8_t*)_data->data()+4;
srt_version = loadUint32(ptr);
ptr += 4;
srt_flag = loadUint32(ptr);
ptr += 4;
recv_tsbpd_delay = loadUint16(ptr);
ptr += 2;
send_tsbpd_delay = loadUint16(ptr);
ptr += 2;
return true;
}
std::string HSExtMessage::dump(){
_StrPrinter printer;
printer << "srt version : "<<std::hex<<srt_version<<" srt flag : "<<std::hex<<srt_flag<<\
" recv_tsbpd_delay="<<recv_tsbpd_delay<<" send_tsbpd_delay = "<<send_tsbpd_delay;
return std::move(printer);
}
bool HSExtMessage::storeToData() {
_data = BufferRaw::create();
_data->setCapacity(HSEXT_MSG_SIZE);
_data->setSize(HSEXT_MSG_SIZE);
extension_length = 3;
HSExt::storeHeader();
uint8_t* ptr = (uint8_t*)_data->data()+4;
storeUint32(ptr,srt_version);
ptr += 4;
storeUint32(ptr,srt_flag);
ptr += 4;
storeUint16(ptr,recv_tsbpd_delay);
ptr += 2;
storeUint16(ptr,send_tsbpd_delay);
ptr += 2;
return true;
}
bool HSExtStreamID::loadFromData(uint8_t *buf, size_t len) {
if(buf == NULL || len < 4){
return false;
}
_data = BufferRaw::create();
_data->assign((char*)buf,len);
HSExt::loadHeader();
size_t content_size = extension_length*4;
if(len < content_size+4){
return false;
}
streamid.clear();
char* ptr = _data->data()+4;
for(size_t i = 0; i<extension_length; ++i){
streamid.push_back(*(ptr+3));
streamid.push_back(*(ptr+2));
streamid.push_back(*(ptr+1));
streamid.push_back(*(ptr));
ptr+=4;
}
return true;
}
bool HSExtStreamID::storeToData() {
size_t content_size = ((streamid.length()+4)+3)/4*4;
_data = BufferRaw::create();
_data->setCapacity(content_size);
_data->setSize(content_size);
extension_length = (content_size-4)/4;
extension_type = SRT_CMD_SID;
HSExt::storeHeader();
auto ptr = _data->data()+4;
memset(ptr,0,extension_length*4);
const char* src = streamid.c_str();
for(size_t i = 0; i< streamid.length()/4;++i){
*ptr = *(src+3+i*4);
ptr++;
*ptr = *(src+2+i*4);
ptr++;
*ptr = *(src+1+i*4);
ptr++;
*ptr = *(src+0+i*4);
ptr++;
}
ptr += 3;
size_t offset = streamid.length()/4*4;
for(size_t i = 0; i<streamid.length()%4;++i){
*ptr = *(src+offset+i);
ptr -= 1;
}
return true;
}
std::string HSExtStreamID::dump(){
_StrPrinter printer;
printer << " streamid : "<< streamid;
return std::move(printer);
}
} // namespace SRT
\ No newline at end of file
#ifndef ZLMEDIAKIT_SRT_HS_EXT_H
#define ZLMEDIAKIT_SRT_HS_EXT_H
#include "Network/Buffer.h"
#include "Common.hpp"
namespace SRT {
using namespace toolkit;
class HSExt : public Buffer {
public:
HSExt() = default;
virtual ~HSExt() = default;
enum {
SRT_CMD_REJECT = 0,
SRT_CMD_HSREQ = 1,
SRT_CMD_HSRSP = 2,
SRT_CMD_KMREQ = 3,
SRT_CMD_KMRSP = 4,
SRT_CMD_SID = 5,
SRT_CMD_CONGESTION = 6,
SRT_CMD_FILTER = 7,
SRT_CMD_GROUP = 8,
SRT_CMD_NONE = -1
};
using Ptr = std::shared_ptr<HSExt>;
uint16_t extension_type;
uint16_t extension_length;
virtual bool loadFromData(uint8_t *buf, size_t len) = 0;
virtual bool storeToData() = 0;
virtual std::string dump() = 0;
///////Buffer override///////
char *data() const override {
if (_data) {
return _data->data();
}
return nullptr;
};
size_t size() const override {
if (_data) {
return _data->size();
}
return 0;
};
protected:
void loadHeader() {
uint8_t *ptr = (uint8_t *)_data->data();
extension_type = loadUint16(ptr);
ptr += 2;
extension_length = loadUint16(ptr);
ptr += 2;
}
void storeHeader() {
uint8_t *ptr = (uint8_t *)_data->data();
SRT::storeUint16(ptr, extension_type);
ptr += 2;
storeUint16(ptr, extension_length);
}
protected:
BufferRaw::Ptr _data;
};
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SRT Version |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SRT Flags |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Receiver TSBPD Delay | Sender TSBPD Delay |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Figure 6: Handshake Extension Message structure
https://haivision.github.io/srt-rfc/draft-sharabayko-srt.html#name-handshake-extension-message
*/
class HSExtMessage : public HSExt {
public:
using Ptr = std::shared_ptr<HSExtMessage>;
enum {
HS_EXT_MSG_TSBPDSND = 0x00000001,
HS_EXT_MSG_TSBPDRCV = 0x00000002,
HS_EXT_MSG_CRYPT = 0x00000004,
HS_EXT_MSG_TLPKTDROP = 0x00000008,
HS_EXT_MSG_PERIODICNAK = 0x00000010,
HS_EXT_MSG_REXMITFLG = 0x00000020,
HS_EXT_MSG_STREAM = 0x00000040,
HS_EXT_MSG_PACKET_FILTER = 0x00000080
};
enum { HSEXT_MSG_SIZE = 16 };
HSExtMessage() = default;
~HSExtMessage() = default;
bool loadFromData(uint8_t *buf, size_t len) override;
bool storeToData() override;
std::string dump() override;
uint32_t srt_version;
uint32_t srt_flag;
uint16_t recv_tsbpd_delay;
uint16_t send_tsbpd_delay;
};
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Stream ID |
...
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Figure 7: Stream ID Extension Message
https://haivision.github.io/srt-rfc/draft-sharabayko-srt.html#name-stream-id-extension-message
*/
class HSExtStreamID : public HSExt {
public:
using Ptr = std::shared_ptr<HSExtStreamID>;
HSExtStreamID() = default;
~HSExtStreamID() = default;
bool loadFromData(uint8_t *buf, size_t len) override;
bool storeToData() override;
std::string dump() override;
std::string streamid;
};
} // namespace SRT
#endif // ZLMEDIAKIT_SRT_HS_EXT_H
\ No newline at end of file
#include "PacketQueue.hpp"
namespace SRT {
PacketQueue::PacketQueue(uint32_t max_size, uint32_t init_seq, uint32_t lantency)
: _pkt_expected_seq(init_seq)
, _pkt_cap(max_size)
, _pkt_lantency(lantency) {
}
bool PacketQueue::inputPacket(DataPacket::Ptr pkt) {
if (pkt->packet_seq_number < _pkt_expected_seq) {
// TOO later drop this packet
return false;
}
_pkt_map[pkt->packet_seq_number] = pkt;
return true;
}
std::list<DataPacket::Ptr> PacketQueue::tryGetPacket() {
std::list<DataPacket::Ptr> re;
while (_pkt_map.find(_pkt_expected_seq) != _pkt_map.end()) {
re.push_back(_pkt_map[_pkt_expected_seq]);
_pkt_map.erase(_pkt_expected_seq);
_pkt_expected_seq++;
}
while (_pkt_map.size() > _pkt_cap) {
// force pop some packet
auto it = _pkt_map.begin();
re.push_back(it->second);
_pkt_expected_seq = it->second->packet_seq_number + 1;
_pkt_map.erase(it);
}
while (timeLantency() > _pkt_lantency) {
auto it = _pkt_map.begin();
re.push_back(it->second);
_pkt_expected_seq = it->second->packet_seq_number + 1;
_pkt_map.erase(it);
}
return std::move(re);
}
bool PacketQueue::dropForRecv(uint32_t first,uint32_t last){
if(first >= last){
return false;
}
if(_pkt_expected_seq <= last){
_pkt_expected_seq = last+1;
return true;
}
return false;
}
uint32_t PacketQueue::timeLantency() {
if (_pkt_map.empty()) {
return 0;
}
auto first = _pkt_map.begin()->second;
auto last = _pkt_map.rbegin()->second;
return last->timestamp - first->timestamp;
}
std::list<PacketQueue::LostPair> PacketQueue::getLostSeq() {
std::list<PacketQueue::LostPair> re;
if(_pkt_map.empty()){
return re;
}
if(getExpectedSize() == getSize()){
return re;
}
PacketQueue::LostPair lost;
lost.first = 0;
lost.second = 0;
uint32_t i = _pkt_expected_seq;
bool finish = true;
for(i = _pkt_expected_seq;i<=_pkt_map.rbegin()->first;++i){
if(_pkt_map.find(i) == _pkt_map.end()){
if(finish){
finish = false;
lost.first = i;
lost.second = i+1;
}else{
lost.second = i+1;
}
}else{
if(!finish){
finish = true;
re.push_back(lost);
}
}
}
return re;
}
size_t PacketQueue::getSize(){
return _pkt_map.size();
}
size_t PacketQueue::getExpectedSize() {
if(_pkt_map.empty()){
return 0;
}
return _pkt_map.rbegin()->first - _pkt_expected_seq+1;
}
size_t PacketQueue::getAvailableBufferSize(){
return _pkt_cap - getExpectedSize();
}
uint32_t PacketQueue::getExpectedSeq(){
return _pkt_expected_seq;
}
} // namespace SRT
\ No newline at end of file
#ifndef ZLMEDIAKIT_SRT_PACKET_QUEUE_H
#define ZLMEDIAKIT_SRT_PACKET_QUEUE_H
#include <memory>
#include <map>
#include <list>
#include <utility>
#include <tuple>
#include "Packet.hpp"
namespace SRT{
class PacketQueue
{
public:
using Ptr = std::shared_ptr<PacketQueue>;
using LostPair = std::pair<uint32_t,uint32_t>;
PacketQueue(uint32_t max_size,uint32_t init_seq,uint32_t lantency);
~PacketQueue() = default;
bool inputPacket(DataPacket::Ptr pkt);
std::list<DataPacket::Ptr> tryGetPacket();
uint32_t timeLantency();
std::list<LostPair> getLostSeq();
size_t getSize();
size_t getExpectedSize();
size_t getAvailableBufferSize();
uint32_t getExpectedSeq();
bool dropForRecv(uint32_t first,uint32_t last);
private:
std::map<uint32_t,DataPacket::Ptr> _pkt_map;
uint32_t _pkt_expected_seq = 0;
uint32_t _pkt_cap;
uint32_t _pkt_lantency;
};
}
#endif //ZLMEDIAKIT_SRT_PACKET_QUEUE_H
\ No newline at end of file
#include "SrtSession.hpp"
#include "Packet.hpp"
#include "SrtTransport.hpp"
#include "Common/config.h"
namespace SRT {
using namespace mediakit;
SrtSession::SrtSession(const Socket::Ptr &sock)
: UdpSession(sock) {
socklen_t addr_len = sizeof(_peer_addr);
getpeername(sock->rawFD(), (struct sockaddr *)&_peer_addr, &addr_len);
}
SrtSession::~SrtSession() {
InfoP(this);
}
EventPoller::Ptr SrtSession::queryPoller(const Buffer::Ptr &buffer) {
uint8_t* data = (uint8_t*)buffer->data();
size_t size = buffer->size();
if(DataPacket::isDataPacket(data,size)){
uint32_t socket_id = DataPacket::getSocketID(data,size);
auto trans = SrtTransportManager::Instance().getItem(std::to_string(socket_id));
return trans ? trans->getPoller() : nullptr;
}
if(HandshakePacket::isHandshakePacket(data,size)){
auto type = HandshakePacket::getHandshakeType(data,size);
if(type == HandshakePacket::HS_TYPE_INDUCTION){
// 握手第一阶段
return nullptr;
}else if(type == HandshakePacket::HS_TYPE_CONCLUSION){
// 握手第二阶段
uint32_t sync_cookie = HandshakePacket::getSynCookie(data,size);
auto trans = SrtTransportManager::Instance().getHandshakeItem(std::to_string(sync_cookie));
return trans ? trans->getPoller() : nullptr;
}else{
WarnL<<" not reach there";
}
}else{
uint32_t socket_id = ControlPacket::getSocketID(data,size);
auto trans = SrtTransportManager::Instance().getItem(std::to_string(socket_id));
return trans ? trans->getPoller() : nullptr;
}
return nullptr;
}
void SrtSession::onRecv(const Buffer::Ptr &buffer) {
uint8_t* data = (uint8_t*)buffer->data();
size_t size = buffer->size();
if (_find_transport) {
//只允许寻找一次transport
_find_transport = false;
if (DataPacket::isDataPacket(data, size)) {
uint32_t socket_id = DataPacket::getSocketID(data, size);
auto trans = SrtTransportManager::Instance().getItem(std::to_string(socket_id));
if(trans){
_transport = std::move(trans);
}else{
WarnL<<" data packet not find transport ";
}
}
if (HandshakePacket::isHandshakePacket(data, size)) {
auto type = HandshakePacket::getHandshakeType(data, size);
if (type == HandshakePacket::HS_TYPE_INDUCTION) {
// 握手第一阶段
_transport = std::make_shared<SrtTransport>(getPoller());
} else if (type == HandshakePacket::HS_TYPE_CONCLUSION) {
// 握手第二阶段
uint32_t sync_cookie = HandshakePacket::getSynCookie(data, size);
auto trans = SrtTransportManager::Instance().getHandshakeItem(std::to_string(sync_cookie));
if (trans) {
_transport = std::move(trans);
} else {
WarnL << " hanshake packet not find transport ";
}
} else {
WarnL << " not reach there";
}
} else {
uint32_t socket_id = ControlPacket::getSocketID(data, size);
auto trans = SrtTransportManager::Instance().getItem(std::to_string(socket_id));
if(trans){
_transport = std::move(trans);
}else{
WarnL << " not find transport";
}
}
if(_transport){
_transport->setSession(shared_from_this());
}
InfoP(this);
}
_ticker.resetTime();
if(_transport){
_transport->inputSockData(data,size,&_peer_addr);
}else{
WarnL<< "ingore data";
}
}
void SrtSession::onError(const SockException &err) {
// udp链接超时,但是srt链接不一定超时,因为可能存在udp链接迁移的情况
//在udp链接迁移时,新的SrtSession对象将接管SrtSession对象的生命周期
//本SrtSession对象将在超时后自动销毁
WarnP(this) << err.what();
if (!_transport) {
return;
}
// 防止互相引用导致不释放
auto transport = std::move(_transport);
getPoller()->async([transport,err] {
//延时减引用,防止使用transport对象时,销毁对象
transport->onShutdown(err);
}, false);
}
void SrtSession::onManager() {
GET_CONFIG(float, timeoutSec, kTimeOutSec);
if (_ticker.elapsedTime() > timeoutSec*1000) {
shutdown(SockException(Err_timeout, "srt connection timeout"));
return;
}
}
} // namespace SRT
\ No newline at end of file
#ifndef ZLMEDIAKIT_SRT_SESSION_H
#define ZLMEDIAKIT_SRT_SESSION_H
#include "Network/Session.h"
#include "SrtTransport.hpp"
namespace SRT {
using namespace toolkit;
class SrtSession : public UdpSession {
public:
SrtSession(const Socket::Ptr &sock);
~SrtSession() override;
void onRecv(const Buffer::Ptr &) override;
void onError(const SockException &err) override;
void onManager() override;
static EventPoller::Ptr queryPoller(const Buffer::Ptr &buffer);
private:
bool _find_transport = true;
Ticker _ticker;
struct sockaddr_storage _peer_addr;
SrtTransport::Ptr _transport;
};
} // namespace SRT
#endif //ZLMEDIAKIT_SRT_SESSION_H
\ No newline at end of file
#ifndef ZLMEDIAKIT_SRT_TRANSPORT_H
#define ZLMEDIAKIT_SRT_TRANSPORT_H
#include <mutex>
#include <chrono>
#include <memory>
#include <atomic>
#include "Network/Session.h"
#include "Poller/EventPoller.h"
#include "Util/TimeTicker.h"
#include "Common.hpp"
#include "Packet.hpp"
#include "PacketQueue.hpp"
#include "Statistic.hpp"
namespace SRT {
using namespace toolkit;
extern const std::string kPort;
extern const std::string kTimeOutSec;
class SrtTransport : public std::enable_shared_from_this<SrtTransport> {
public:
friend class SrtSession;
using Ptr = std::shared_ptr<SrtTransport>;
SrtTransport(const EventPoller::Ptr &poller);
virtual ~SrtTransport();
const EventPoller::Ptr &getPoller() const;
void setSession(Session::Ptr session);
const Session::Ptr &getSession() const;
/**
* socket收到udp数据
* @param buf 数据指针
* @param len 数据长度
* @param addr 数据来源地址
*/
void inputSockData(uint8_t *buf, int len, struct sockaddr_storage *addr);
std::string getIdentifier();
void unregisterSelfHandshake();
void unregisterSelf();
protected:
virtual void onHandShakeFinished(std::string& streamid){};
virtual void onSRTData(DataPacket::Ptr pkt){};
virtual void onShutdown(const SockException &ex);
private:
void registerSelfHandshake();
void registerSelf();
void switchToOtherTransport(uint8_t *buf, int len,uint32_t socketid, struct sockaddr_storage *addr);
void handleHandshake(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleHandshakeInduction(HandshakePacket& pkt,struct sockaddr_storage *addr);
void handleHandshakeConclusion(HandshakePacket& pkt,struct sockaddr_storage *addr);
void handleKeeplive(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleACK(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleACKACK(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleNAK(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleCongestionWarning(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleShutDown(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleDropReq(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleUserDefinedType(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handlePeerError(uint8_t *buf, int len, struct sockaddr_storage *addr);
void handleDataPacket(uint8_t *buf, int len, struct sockaddr_storage *addr);
void sendNAKPacket(std::list<PacketQueue::LostPair>& lost_list);
void sendACKPacket();
void sendLightACKPacket();
protected:
void sendDataPacket(DataPacket::Ptr pkt,char* buf,int len,bool flush = false);
void sendControlPacket(ControlPacket::Ptr pkt,bool flush = true);
void sendPacket(Buffer::Ptr pkt,bool flush = true);
private:
//当前选中的udp链接
Session::Ptr _selected_session;
//链接迁移前后使用过的udp链接
std::unordered_map<Session *, std::weak_ptr<Session> > _history_sessions;
EventPoller::Ptr _poller;
uint32_t _peer_socket_id;
uint32_t _socket_id = 0;
TimePoint _start_timestamp;
uint32_t _mtu = 1500;
uint32_t _max_window_size = 8192;
uint32_t _init_seq_number = 0;
std::string _stream_id;
uint32_t _sync_cookie = 0;
PacketQueue::Ptr _recv_buf;
uint32_t _rtt = 100*1000;
uint32_t _rtt_variance =50*1000;
uint32_t _light_ack_pkt_count = 0;
uint32_t _ack_number_count = 0;
Ticker _ack_ticker;
std::map<uint32_t,TimePoint> _ack_send_timestamp;
PacketRecvRateContext _pkt_recv_rate_context;
EstimatedLinkCapacityContext _estimated_link_capacity_context;
RecvRateContext _recv_rate_context;
Ticker _nak_ticker;
//保持发送的握手消息,防止丢失重发
HandshakePacket::Ptr _handleshake_res;
ResourcePool<BufferRaw> _packet_pool;
};
class SrtTransportManager {
public:
static SrtTransportManager &Instance();
SrtTransport::Ptr getItem(const std::string &key);
void addItem(const std::string &key, const SrtTransport::Ptr &ptr);
void removeItem(const std::string &key);
void addHandshakeItem(const std::string &key, const SrtTransport::Ptr &ptr);
void removeHandshakeItem(const std::string &key);
SrtTransport::Ptr getHandshakeItem(const std::string &key);
private:
SrtTransportManager() = default;
private:
std::mutex _mtx;
std::unordered_map<std::string, std::weak_ptr<SrtTransport>> _map;
std::mutex _handshake_mtx;
std::unordered_map<std::string, std::weak_ptr<SrtTransport>> _handshake_map;
};
} // namespace SRT
#endif // ZLMEDIAKIT_SRT_TRANSPORT_H
\ No newline at end of file
#include <algorithm>
#include "Statistic.hpp"
namespace SRT {
void PacketRecvRateContext::inputPacket(TimePoint ts) {
if(_pkt_map.size()>100){
_pkt_map.erase(_pkt_map.begin());
}
_pkt_map.emplace(ts,ts);
}
uint32_t PacketRecvRateContext::getPacketRecvRate() {
if(_pkt_map.size()<2){
return 0;
}
auto first = _pkt_map.begin();
auto last = _pkt_map.rbegin();
double dur = DurationCountMicroseconds(last->first - first->first)/1000000.0;
double rate = _pkt_map.size()/dur;
return (uint32_t)rate;
}
void EstimatedLinkCapacityContext::inputPacket(TimePoint ts) {
if(_pkt_map.size()>16){
_pkt_map.erase(_pkt_map.begin());
}
_pkt_map.emplace(ts,ts);
}
uint32_t EstimatedLinkCapacityContext::getEstimatedLinkCapacity() {
decltype(_pkt_map.begin()) next;
std::vector<SteadyClock::duration> tmp;
for(auto it = _pkt_map.begin();it != _pkt_map.end();++it){
next = it;
++next;
if(next != _pkt_map.end()){
tmp.push_back(next->first -it->first);
}else{
break;
}
}
std::sort(tmp.begin(),tmp.end());
if(tmp.empty()){
return 0;
}
double dur =DurationCountMicroseconds(tmp[tmp.size()/2])/1e6;
return (uint32_t)(1.0/dur);
}
void RecvRateContext::inputPacket(TimePoint ts, size_t size ) {
if (_pkt_map.size() > 100) {
_pkt_map.erase(_pkt_map.begin());
}
_pkt_map.emplace(ts, size);
}
uint32_t RecvRateContext::getRecvRate() {
if(_pkt_map.size()<2){
return 0;
}
auto first = _pkt_map.begin();
auto last = _pkt_map.rbegin();
double dur = DurationCountMicroseconds(last->first - first->first)/1000000.0;
size_t bytes = 0;
for(auto it : _pkt_map){
bytes += it.second;
}
double rate = (double)bytes/dur;
return (uint32_t)rate;
}
} // namespace SRT
\ No newline at end of file
#ifndef ZLMEDIAKIT_SRT_STATISTIC_H
#define ZLMEDIAKIT_SRT_STATISTIC_H
#include <map>
#include "Common.hpp"
#include "Packet.hpp"
namespace SRT {
class PacketRecvRateContext {
public:
PacketRecvRateContext() = default;
~PacketRecvRateContext() = default;
void inputPacket(TimePoint ts);
uint32_t getPacketRecvRate();
private:
std::map<TimePoint,TimePoint> _pkt_map;
};
class EstimatedLinkCapacityContext {
public:
EstimatedLinkCapacityContext() = default;
~EstimatedLinkCapacityContext() = default;
void inputPacket(TimePoint ts);
uint32_t getEstimatedLinkCapacity();
private:
std::map<TimePoint,TimePoint> _pkt_map;
};
class RecvRateContext {
public:
RecvRateContext() = default;
~RecvRateContext() = default;
void inputPacket(TimePoint ts,size_t size);
uint32_t getRecvRate();
private:
std::map<TimePoint,size_t> _pkt_map;
};
} // namespace SRT
#endif // ZLMEDIAKIT_SRT_STATISTIC_H
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论