You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

349 lines
8.7 KiB

#include "session.h"
#include <sstream>
#include <strings.h>
#include "../../codecs/h264/h264.h"
namespace mtx {
namespace {
std::string fmtpValue(const std::string & fmtp, const std::string & key)
{
std::istringstream tIn(fmtp);
std::string tPart;
while (std::getline(tIn, tPart, ';'))
{
size_t b = tPart.find_first_not_of(' ');
if (b == std::string::npos)
{
continue;
}
tPart = tPart.substr(b);
size_t e = tPart.find('=');
if (e != std::string::npos && tPart.substr(0, e) == key)
{
return tPart.substr(e + 1);
}
}
return std::string();
}
} // namespace
WebrtcSession::WebrtcSession(const std::string & secret, std::shared_ptr<Path> path, const Conf & global, const std::string & remoteAddr)
: LogParent("[WebRTC] [session " + secret.substr(0, 8) + "] "), m_sSecret(secret), m_pPath(std::move(path)), m_global(global), m_sRemote(remoteAddr),
m_reader(this, 512)
{
m_tCreated = nowMs();
}
WebrtcSession::~WebrtcSession()
{
close();
}
bool WebrtcSession::create(const std::string & offerSdp, std::string & answer, int & status, std::string & err)
{
log(LogLevel::Info, "created by %s", m_sRemote.c_str());
status = 400;
rtc::Description tOffer("", rtc::Description::Type::Offer);
try
{
tOffer = rtc::Description(offerSdp, rtc::Description::Type::Offer);
}
catch (const std::exception & e)
{
err = std::string("invalid SDP offer: ") + e.what();
return false;
}
if (! m_pPath->addReader(this, m_desc, err))
{
status = 404;
return false;
}
m_bReading = true;
// The video section of the offer and its best H264 payload type
std::string tMid;
int tPt = -1;
std::string tFmtp;
int tBest = -1;
int tStreamPrf = m_desc.sps.size() > 1 ? m_desc.sps[1] : 66;
for (int i = 0; i < tOffer.mediaCount() && tMid.empty(); i++)
{
auto tM = tOffer.media(i);
if (! std::holds_alternative<rtc::Description::Media *>(tM))
{
continue;
}
rtc::Description::Media * tMedia = std::get<rtc::Description::Media *>(tM);
if (tMedia->type() != "video")
{
continue;
}
if (tMedia->direction() != rtc::Description::Direction::RecvOnly && tMedia->direction() != rtc::Description::Direction::SendRecv)
{
continue;
}
for (int pt : tMedia->payloadTypes())
{
const rtc::Description::Media::RtpMap * tMap = tMedia->rtpMap(pt);
if (tMap == nullptr || strcasecmp(tMap->format.c_str(), "H264") != 0)
{
continue;
}
std::string tF = tMap->fmtps.empty() ? std::string() : tMap->fmtps[0];
if (fmtpValue(tF, "packetization-mode") != "1")
{
continue;
}
std::string tPrf = fmtpValue(tF, "profile-level-id");
int tIdc = tPrf.size() >= 2 ? (int) strtol(tPrf.substr(0, 2).c_str(), nullptr, 16) : 66;
int tScore = (tIdc == tStreamPrf) ? 3 : (tPrf.compare(0, 4, "42e0") == 0 ? 2 : 1);
if (tScore > tBest)
{
tBest = tScore;
tPt = pt;
tFmtp = tF;
}
}
if (tPt >= 0)
{
tMid = tMedia->mid();
}
}
if (tPt < 0)
{
err = "the offer has no H264 (packetization-mode=1) video section";
return false;
}
rtc::Configuration tCfg;
for (const std::string & s : m_global.webrtcICEServers)
{
tCfg.iceServers.emplace_back(s);
}
if (! m_global.webrtcBindAddress.empty())
{
tCfg.bindAddress = m_global.webrtcBindAddress;
}
tCfg.portRangeBegin = m_global.webrtcUDPPortMin;
tCfg.portRangeEnd = m_global.webrtcUDPPortMax;
tCfg.disableAutoNegotiation = true;
m_pPc = std::make_shared<rtc::PeerConnection>(tCfg);
m_pPc->onGatheringStateChange([this](rtc::PeerConnection::GatheringState s) {
if (s == rtc::PeerConnection::GatheringState::Complete)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_bGathered = true;
m_cond.notify_all();
}
});
m_pPc->onStateChange([this](rtc::PeerConnection::State s) {
if (s == rtc::PeerConnection::State::Connected)
{
if (! m_bConnected.exchange(true))
{
log(LogLevel::Info, "peer connection established");
}
}
else if (s == rtc::PeerConnection::State::Failed || s == rtc::PeerConnection::State::Closed || s == rtc::PeerConnection::State::Disconnected)
{
if (! m_bClosing.exchange(true))
{
log(LogLevel::Info, "peer connection %s", s == rtc::PeerConnection::State::Failed ? "failed" : "closed");
}
}
});
uint32_t tSsrc = (uint32_t) (std::hash<std::string>()(m_sSecret) & 0x7fffffff) | 1;
rtc::Description::Video tVideo(tMid, rtc::Description::Direction::SendOnly);
tVideo.addH264Codec(tPt, tFmtp);
tVideo.addSSRC(tSsrc, "mediamtx", "mediamtx", "video");
m_pTrack = m_pPc->addTrack(tVideo);
m_pRtpConfig = std::make_shared<rtc::RtpPacketizationConfig>(tSsrc, "mediamtx", (uint8_t) tPt, rtc::H264RtpPacketizer::defaultClockRate);
auto tPacketizer = std::make_shared<rtc::H264RtpPacketizer>(rtc::H264RtpPacketizer::Separator::LongStartSequence, m_pRtpConfig, 1200);
m_pSrReporter = std::make_shared<rtc::RtcpSrReporter>(m_pRtpConfig);
tPacketizer->addToChain(m_pSrReporter);
tPacketizer->addToChain(std::make_shared<rtc::RtcpNackResponder>());
m_pTrack->setMediaHandler(tPacketizer);
m_pTrack->onOpen([this]() { m_bTrackOpen = true; });
try
{
m_pPc->setRemoteDescription(tOffer);
m_pPc->setLocalDescription(rtc::Description::Type::Answer);
}
catch (const std::exception & e)
{
err = std::string("negotiation failed: ") + e.what();
return false;
}
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait_for(lock, std::chrono::seconds(5), [this] { return m_bGathered; });
}
auto tLocal = m_pPc->localDescription();
if (! tLocal)
{
status = 500;
err = "no local description";
return false;
}
answer = std::string(*tLocal);
m_reader.start([this](const UnitPtr & u) { onUnit(u); });
log(LogLevel::Info, "is reading from path '%s', 1 track (H264 %dx%d, payload type %d)", m_pPath->conf().name.c_str(), m_desc.width, m_desc.height, tPt);
status = 201;
return true;
}
bool WebrtcSession::addRemoteCandidates(const std::string & sdpFrag, std::string & err)
{
if (! m_pPc)
{
err = "session not ready";
return false;
}
std::istringstream tIn(sdpFrag);
std::string tLine;
std::string tMid;
while (std::getline(tIn, tLine))
{
if (! tLine.empty() && tLine.back() == '\r')
{
tLine.pop_back();
}
if (tLine.compare(0, 6, "a=mid:") == 0)
{
tMid = tLine.substr(6);
}
else if (tLine.compare(0, 12, "a=candidate:") == 0)
{
try
{
m_pPc->addRemoteCandidate(tMid.empty() ? rtc::Candidate(tLine.substr(2)) : rtc::Candidate(tLine.substr(2), tMid));
}
catch (const std::exception & e)
{
err = std::string("invalid candidate: ") + e.what();
return false;
}
}
}
return true;
}
void WebrtcSession::pathNotReady()
{
// called with the path locked: only mark, the server closes the session
m_bReading = false;
if (! m_bClosing.exchange(true))
{
log(LogLevel::Info, "the source of path '%s' is gone", m_pPath->conf().name.c_str());
}
}
void WebrtcSession::close()
{
if (m_bClosed)
{
return;
}
m_bClosed = true;
m_bClosing = true;
if (m_bReading)
{
m_pPath->removeReader(this);
m_bReading = false;
}
m_reader.stop();
if (m_pPc)
{
m_pPc->onStateChange(nullptr);
m_pPc->onGatheringStateChange(nullptr);
if (m_pTrack)
{
m_pTrack->onOpen(nullptr);
}
m_pPc->close();
}
m_pTrack.reset();
m_pPc.reset();
log(LogLevel::Info, "closed (%llu bytes sent)", (unsigned long long) m_nBytesSent);
}
void WebrtcSession::onUnit(const UnitPtr & unit)
{
if (! m_bTrackOpen || m_bClosing)
{
return;
}
if (! m_bStarted)
{
if (! unit->idr)
{
return; // the browser needs a random access point
}
m_bStarted = true;
m_nFirstPts = unit->pts;
}
std::vector<Bytes> tNalus;
if (unit->idr)
{
// make sure every IDR carries the parameter sets (cameras often send them only in the SDP)
bool tSps = false, tPps = false;
for (const Bytes & n : unit->nalus)
{
tSps |= h264::naluType(n) == h264::NALU_SPS;
tPps |= h264::naluType(n) == h264::NALU_PPS;
}
if (! tSps && ! m_desc.sps.empty())
{
tNalus.push_back(m_desc.sps);
}
if (! tPps && ! m_desc.pps.empty())
{
tNalus.push_back(m_desc.pps);
}
}
for (const Bytes & n : unit->nalus)
{
int t = h264::naluType(n);
if (t == h264::NALU_SPS)
{
m_desc.sps = n;
}
else if (t == h264::NALU_PPS)
{
m_desc.pps = n;
}
tNalus.push_back(n);
}
Bytes tFrame = h264::toAnnexB(tNalus);
m_pRtpConfig->timestamp = m_pRtpConfig->startTimestamp + (uint32_t) (unit->pts - m_nFirstPts);
int64_t tNow = nowMs();
if (tNow - m_tLastSr > 1000)
{
m_tLastSr = tNow;
m_pSrReporter->setNeedsToReport();
}
try
{
m_pTrack->send(reinterpret_cast<const rtc::byte *>(tFrame.data()), tFrame.size());
m_nBytesSent += tFrame.size();
}
catch (const std::exception & e)
{
if (! m_bClosing.exchange(true))
{
log(LogLevel::Warn, "send failed: %s", e.what());
}
}
}
} // namespace mtx