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.
 
 
 
 
 
 

543 lines
15 KiB

#include "rtspSource.h"
#include <BasicUsageEnvironment.hh>
#include <GroupsockHelper.hh>
#include <liveMedia.hh>
#include <type_traits>
#include <codecs/h264/h264.h>
namespace mtx {
namespace {
// live555 changed the event loop watch variable from "char volatile" to std::atomic_char: take the type
// from TaskScheduler::doEventLoop so both versions build.
template <class C, class A> A watchArgType(void (C::*)(A));
typedef std::remove_pointer<decltype(watchArgType(&TaskScheduler::doEventLoop))>::type WatchVar;
const unsigned SINK_BUFFER_SIZE = 4 * 1024 * 1024;
const unsigned UDP_RECEIVE_BUFFER = 4 * 1024 * 1024;
const unsigned CHECK_INTERVAL_US = 200 * 1000;
const char * APPLICATION_NAME = "MediaMtx";
class RtspSession;
class MtxRTSPClient : public RTSPClient
{
public:
static MtxRTSPClient * createNew(UsageEnvironment & env, const char * url, RtspSession * owner)
{
return new MtxRTSPClient(env, url, owner);
}
RtspSession * owner;
protected:
MtxRTSPClient(UsageEnvironment & env, const char * url, RtspSession * o) : RTSPClient(env, url, 0, APPLICATION_NAME, 0, -1), owner(o) {}
};
class H264Sink : public MediaSink
{
public:
static H264Sink * createNew(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp) { return new H264Sink(env, owner, rtp); }
protected:
H264Sink(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp);
~H264Sink() override { delete[] m_pBuffer; }
private:
static void afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned);
void afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime);
Boolean continuePlaying() override;
void flush();
RtspSession * m_pOwner;
RTPSource * m_pRtp;
uint8_t * m_pBuffer;
std::vector<Bytes> m_vNalus;
int64_t m_nPtUs = 0; // presentation time of the access unit being collected
bool m_bHavePts = false;
bool m_bSynced = false; // presentation times are RTCP synchronised
int64_t m_nOffset = 0; // keeps pts continuous over the RTCP sync jump
int64_t m_nLastRaw = 0;
int64_t m_nLastPts = 0;
int64_t m_nLastDelta = 3000;
unsigned m_nTruncLogs = 0;
};
class RtspSession
{
public:
explicit RtspSession(RtspSource * src) : m_pSrc(src) {}
void run();
void end(const std::string & error);
void onUnit(std::vector<Bytes> && nalus, int64_t pts, int64_t ntpUs);
void dataReceived() { m_tLastData = nowMs(); }
RtspSource * source() { return m_pSrc; }
static void continueAfterDescribe(RTSPClient * c, int resultCode, char * resultString);
static void continueAfterSetup(RTSPClient * c, int resultCode, char * resultString);
static void continueAfterPlay(RTSPClient * c, int resultCode, char * resultString);
static void ignoreResponse(RTSPClient *, int, char * resultString) { delete[] resultString; }
static void onSubsessionBye(void * clientData);
static void onSinkClosed(void * clientData);
static void periodicCheck(void * clientData);
static void sendKeepalive(void * clientData);
private:
void afterDescribe(int resultCode, char * resultString);
void afterSetup(int resultCode, char * resultString);
void afterPlay(int resultCode, char * resultString);
void cleanup();
RtspSource * m_pSrc;
TaskScheduler * m_pScheduler = nullptr;
UsageEnvironment * m_pEnv = nullptr;
MtxRTSPClient * m_pClient = nullptr;
MediaSession * m_pSession = nullptr;
MediaSubsession * m_pVideo = nullptr;
WatchVar m_watch{0};
bool m_bEnded = false;
bool m_bPlaying = false;
bool m_bReady = false;
StreamDesc m_desc;
int64_t m_tStart = 0;
int64_t m_tLastData = 0;
TaskToken m_checkTask = nullptr;
TaskToken m_aliveTask = nullptr;
};
// ---------------------------------------------------------------- sink
H264Sink::H264Sink(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp) : MediaSink(env), m_pOwner(owner), m_pRtp(rtp)
{
m_pBuffer = new uint8_t[SINK_BUFFER_SIZE];
}
Boolean H264Sink::continuePlaying()
{
if (fSource == nullptr)
{
return False;
}
fSource->getNextFrame(m_pBuffer, SINK_BUFFER_SIZE, afterGettingFrame, this, RtspSession::onSinkClosed, m_pOwner);
return True;
}
void H264Sink::afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned)
{
static_cast<H264Sink *>(clientData)->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime);
}
void H264Sink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime)
{
m_pOwner->dataReceived();
// live555 keeps the RTP timestamp private: the presentation time is derived from it (exact, until the
// first RTCP sender report moves it onto the sender's wall clock - see flush())
int64_t tPtUs = (int64_t) presentationTime.tv_sec * 1000000 + presentationTime.tv_usec;
bool tMarker = m_pRtp->curPacketMarkerBit();
if (numTruncatedBytes > 0 && m_nTruncLogs++ < 5)
{
m_pOwner->source()->log(LogLevel::Warn, "NAL unit truncated by %u bytes", numTruncatedBytes);
}
// An access unit ends with the RTP marker bit. A camera that does not set it: a new presentation time
// starts a new unit. Small changes are not a new unit: every RTCP sender report moves live555's
// mapping of RTP time to presentation time a little, also between packets of the same picture.
if (! m_vNalus.empty() && (tPtUs - m_nPtUs > 2000 || m_nPtUs - tPtUs > 2000))
{
flush();
}
if (frameSize > 0)
{
int tType = m_pBuffer[0] & 0x1f;
if (tType != h264::NALU_AUD && tType != 0)
{
m_vNalus.emplace_back(m_pBuffer, m_pBuffer + frameSize);
}
}
if (m_vNalus.size() <= 1)
{
m_nPtUs = tPtUs; // the time of the unit is the time of its first NAL unit
}
if (tMarker)
{
flush();
}
continuePlaying();
}
void H264Sink::flush()
{
if (m_vNalus.empty())
{
return;
}
// 90 kHz pts starting at 0. When live555 synchronises with the first RTCP sender report the presentation
// times jump onto the sender's clock: the offset keeps the pts continuous (one frame interval).
int64_t tRaw = m_nPtUs * 9 / 100;
bool tSynced = m_pRtp->hasBeenSynchronizedUsingRTCP();
if (! m_bHavePts)
{
m_bHavePts = true;
m_bSynced = tSynced;
m_nOffset = -tRaw;
}
else if (tSynced != m_bSynced)
{
m_bSynced = tSynced;
m_nOffset = m_nLastPts + m_nLastDelta - tRaw;
}
int64_t tPts = tRaw + m_nOffset;
if (tPts > m_nLastPts && tPts - m_nLastPts < 90000)
{
m_nLastDelta = tPts - m_nLastPts;
}
m_nLastRaw = tRaw;
m_nLastPts = tPts;
m_pOwner->onUnit(std::move(m_vNalus), tPts, m_nPtUs);
m_vNalus.clear();
}
// ---------------------------------------------------------------- session
void RtspSession::run()
{
m_pScheduler = BasicTaskScheduler::createNew();
m_pEnv = BasicUsageEnvironment::createNew(*m_pScheduler);
m_tStart = nowMs();
m_pSrc->log(LogLevel::Info, "started");
m_pClient = MtxRTSPClient::createNew(*m_pEnv, m_pSrc->pathConf().source.c_str(), this);
if (m_pClient == nullptr)
{
end(std::string("cannot create the RTSP client: ") + m_pEnv->getResultMsg());
}
else
{
m_pClient->sendDescribeCommand(continueAfterDescribe);
m_checkTask = m_pScheduler->scheduleDelayedTask(CHECK_INTERVAL_US, periodicCheck, this);
m_pScheduler->doEventLoop(&m_watch);
}
cleanup();
}
void RtspSession::end(const std::string & error)
{
if (m_bEnded)
{
return;
}
m_bEnded = true;
if (! error.empty())
{
m_pSrc->log(LogLevel::Error, "%s", error.c_str());
}
m_watch = 1;
}
void RtspSession::cleanup()
{
if (m_pScheduler != nullptr)
{
m_pScheduler->unscheduleDelayedTask(m_checkTask);
m_pScheduler->unscheduleDelayedTask(m_aliveTask);
}
if (m_pSession != nullptr)
{
if (m_pClient != nullptr && m_bPlaying)
{
m_pClient->sendTeardownCommand(*m_pSession, ignoreResponse);
}
MediaSubsessionIterator tIter(*m_pSession);
MediaSubsession * tSub;
while ((tSub = tIter.next()) != nullptr)
{
if (tSub->sink != nullptr)
{
tSub->sink->stopPlaying();
Medium::close(tSub->sink);
tSub->sink = nullptr;
}
}
Medium::close(m_pSession);
m_pSession = nullptr;
}
if (m_pClient != nullptr)
{
Medium::close(m_pClient);
m_pClient = nullptr;
}
if (m_bReady)
{
m_pSrc->parent()->sourceSetNotReady();
m_bReady = false;
}
if (m_pEnv != nullptr)
{
m_pEnv->reclaim();
m_pEnv = nullptr;
}
delete m_pScheduler;
m_pScheduler = nullptr;
}
void RtspSession::continueAfterDescribe(RTSPClient * c, int resultCode, char * resultString)
{
static_cast<MtxRTSPClient *>(c)->owner->afterDescribe(resultCode, resultString);
}
void RtspSession::continueAfterSetup(RTSPClient * c, int resultCode, char * resultString)
{
static_cast<MtxRTSPClient *>(c)->owner->afterSetup(resultCode, resultString);
}
void RtspSession::continueAfterPlay(RTSPClient * c, int resultCode, char * resultString)
{
static_cast<MtxRTSPClient *>(c)->owner->afterPlay(resultCode, resultString);
}
static std::string resultText(int resultCode, const char * resultString, UsageEnvironment * env)
{
if (resultCode < 0)
{
// network error, the message is in the environment
return std::string(env->getResultMsg());
}
return "bad status code: " + std::to_string(resultCode) + (resultString ? std::string(" (") + resultString + ")" : std::string());
}
void RtspSession::afterDescribe(int resultCode, char * resultString)
{
if (resultCode != 0)
{
end("DESCRIBE failed: " + resultText(resultCode, resultString, m_pEnv));
delete[] resultString;
return;
}
m_pSession = MediaSession::createNew(*m_pEnv, resultString);
delete[] resultString;
if (m_pSession == nullptr || ! m_pSession->hasSubsessions())
{
end(std::string("invalid SDP: ") + m_pEnv->getResultMsg());
return;
}
MediaSubsessionIterator tIter(*m_pSession);
MediaSubsession * tSub;
while ((tSub = tIter.next()) != nullptr)
{
if (m_pVideo == nullptr && strcmp(tSub->mediumName(), "video") == 0 && strcmp(tSub->codecName(), "H264") == 0)
{
m_pVideo = tSub;
}
else
{
m_pSrc->log(LogLevel::Warn, "skipping track %s/%s (only H264 video is supported)", tSub->mediumName(), tSub->codecName());
}
}
if (m_pVideo == nullptr)
{
end("the stream has no H264 video track");
return;
}
if (! m_pVideo->initiate())
{
end(std::string("cannot initiate the video track: ") + m_pEnv->getResultMsg());
return;
}
if (m_pSrc->pathConf().transport == RtspTransport::Udp && m_pVideo->rtpSource() != nullptr)
{
increaseReceiveBufferTo(*m_pEnv, m_pVideo->rtpSource()->RTPgs()->socketNum(), UDP_RECEIVE_BUFFER);
}
// codec parameters from the SDP (sprop-parameter-sets), if any
for (const Bytes & n : h264::decodeSpropParameterSets(m_pVideo->fmtp_spropparametersets()))
{
if (h264::naluType(n) == h264::NALU_SPS)
{
m_desc.sps = n;
}
else if (h264::naluType(n) == h264::NALU_PPS)
{
m_desc.pps = n;
}
}
m_pClient->sendSetupCommand(*m_pVideo, continueAfterSetup, False, m_pSrc->pathConf().transport == RtspTransport::Tcp ? True : False);
}
void RtspSession::afterSetup(int resultCode, char * resultString)
{
delete[] resultString;
if (resultCode != 0)
{
end("SETUP failed: " + resultText(resultCode, nullptr, m_pEnv));
return;
}
H264Sink * tSink = H264Sink::createNew(*m_pEnv, this, m_pVideo->rtpSource());
m_pVideo->sink = tSink;
if (m_pVideo->rtcpInstance() != nullptr)
{
m_pVideo->rtcpInstance()->setByeHandler(onSubsessionBye, this);
}
tSink->startPlaying(*m_pVideo->readSource(), nullptr, nullptr);
m_pClient->sendPlayCommand(*m_pSession, continueAfterPlay);
}
void RtspSession::afterPlay(int resultCode, char * resultString)
{
delete[] resultString;
if (resultCode != 0)
{
end("PLAY failed: " + resultText(resultCode, nullptr, m_pEnv));
return;
}
m_bPlaying = true;
m_tLastData = nowMs();
m_pSrc->log(LogLevel::Info, "ready: 1 track (H264)");
unsigned tTimeout = m_pClient->sessionTimeoutParameter();
unsigned tEvery = (tTimeout > 10) ? tTimeout / 2 : 30;
m_aliveTask = m_pScheduler->scheduleDelayedTask((int64_t) tEvery * 1000000, sendKeepalive, this);
}
void RtspSession::onUnit(std::vector<Bytes> && nalus, int64_t pts, int64_t ntpUs)
{
if (! m_bReady)
{
for (const Bytes & n : nalus)
{
if (h264::naluType(n) == h264::NALU_SPS)
{
m_desc.sps = n;
}
else if (h264::naluType(n) == h264::NALU_PPS)
{
m_desc.pps = n;
}
}
if (m_desc.sps.empty() || m_desc.pps.empty())
{
return; // a reader cannot use the stream without the codec parameters
}
h264::SpsInfo tInfo;
if (h264::parseSps(m_desc.sps, tInfo))
{
m_desc.width = tInfo.width;
m_desc.height = tInfo.height;
}
m_bReady = true;
m_pSrc->parent()->sourceSetReady(m_desc);
}
auto tUnit = std::make_shared<Unit>();
tUnit->pts = pts;
tUnit->ntpUs = ntpUs;
tUnit->nalus = std::move(nalus);
for (const Bytes & n : tUnit->nalus)
{
if (h264::naluType(n) == h264::NALU_IDR)
{
tUnit->idr = true;
break;
}
}
m_pSrc->parent()->sourceWriteUnit(tUnit);
}
void RtspSession::onSubsessionBye(void * clientData)
{
static_cast<RtspSession *>(clientData)->end("received RTCP BYE");
}
void RtspSession::onSinkClosed(void * clientData)
{
static_cast<RtspSession *>(clientData)->end("the stream was closed by the server");
}
void RtspSession::periodicCheck(void * clientData)
{
RtspSession * s = static_cast<RtspSession *>(clientData);
s->m_checkTask = nullptr;
if (s->m_pSrc->stopRequested())
{
s->end("");
return;
}
int64_t tNow = nowMs();
int64_t tTimeout = s->m_pSrc->global().readTimeoutMs;
if (s->m_bPlaying && tNow - s->m_tLastData > tTimeout)
{
s->end("no data for " + std::to_string((tNow - s->m_tLastData) / 1000) + " s");
return;
}
if (! s->m_bPlaying && tNow - s->m_tStart > tTimeout)
{
s->end("timed out waiting for the server");
return;
}
s->m_checkTask = s->m_pScheduler->scheduleDelayedTask(CHECK_INTERVAL_US, periodicCheck, s);
}
void RtspSession::sendKeepalive(void * clientData)
{
RtspSession * s = static_cast<RtspSession *>(clientData);
s->m_aliveTask = nullptr;
s->m_pClient->sendOptionsCommand(ignoreResponse);
unsigned tTimeout = s->m_pClient->sessionTimeoutParameter();
unsigned tEvery = (tTimeout > 10) ? tTimeout / 2 : 30;
s->m_aliveTask = s->m_pScheduler->scheduleDelayedTask((int64_t) tEvery * 1000000, sendKeepalive, s);
}
} // namespace
// ---------------------------------------------------------------- source
RtspSource::RtspSource(const PathConf & conf, const Conf & global, SourceParent * parent)
: LogParent("[path " + conf.name + "] [RTSP source] "), m_conf(conf), m_global(global), m_pParent(parent)
{
}
RtspSource::~RtspSource()
{
stop();
}
void RtspSource::start()
{
m_bStop = false;
m_thread = std::thread(&RtspSource::run, this);
}
void RtspSource::stop()
{
m_bStop = true;
m_cond.notify_all();
if (m_thread.joinable())
{
m_thread.join();
log(LogLevel::Info, "stopped");
}
}
void RtspSource::run()
{
while (! m_bStop)
{
runSession();
if (! m_bStop)
{
waitRetry();
}
}
}
void RtspSource::runSession()
{
RtspSession tSession(this);
tSession.run();
}
void RtspSource::waitRetry()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait_for(lock, std::chrono::milliseconds(m_global.sourceRetryPauseMs), [this] { return m_bStop.load(); });
}
} // namespace mtx