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

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "rtspSource.h"
  2. #include <BasicUsageEnvironment.hh>
  3. #include <GroupsockHelper.hh>
  4. #include <liveMedia.hh>
  5. #include <type_traits>
  6. #include <codecs/h264/h264.h>
  7. namespace mtx {
  8. namespace {
  9. // live555 changed the event loop watch variable from "char volatile" to std::atomic_char: take the type
  10. // from TaskScheduler::doEventLoop so both versions build.
  11. template <class C, class A> A watchArgType(void (C::*)(A));
  12. typedef std::remove_pointer<decltype(watchArgType(&TaskScheduler::doEventLoop))>::type WatchVar;
  13. const unsigned SINK_BUFFER_SIZE = 4 * 1024 * 1024;
  14. const unsigned UDP_RECEIVE_BUFFER = 4 * 1024 * 1024;
  15. const unsigned CHECK_INTERVAL_US = 200 * 1000;
  16. const char * APPLICATION_NAME = "MediaMtx";
  17. class RtspSession;
  18. class MtxRTSPClient : public RTSPClient
  19. {
  20. public:
  21. static MtxRTSPClient * createNew(UsageEnvironment & env, const char * url, RtspSession * owner)
  22. {
  23. return new MtxRTSPClient(env, url, owner);
  24. }
  25. RtspSession * owner;
  26. protected:
  27. MtxRTSPClient(UsageEnvironment & env, const char * url, RtspSession * o) : RTSPClient(env, url, 0, APPLICATION_NAME, 0, -1), owner(o) {}
  28. };
  29. class H264Sink : public MediaSink
  30. {
  31. public:
  32. static H264Sink * createNew(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp) { return new H264Sink(env, owner, rtp); }
  33. protected:
  34. H264Sink(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp);
  35. ~H264Sink() override { delete[] m_pBuffer; }
  36. private:
  37. static void afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned);
  38. void afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime);
  39. Boolean continuePlaying() override;
  40. void flush();
  41. RtspSession * m_pOwner;
  42. RTPSource * m_pRtp;
  43. uint8_t * m_pBuffer;
  44. std::vector<Bytes> m_vNalus;
  45. int64_t m_nPtUs = 0; // presentation time of the access unit being collected
  46. bool m_bHavePts = false;
  47. bool m_bSynced = false; // presentation times are RTCP synchronised
  48. int64_t m_nOffset = 0; // keeps pts continuous over the RTCP sync jump
  49. int64_t m_nLastRaw = 0;
  50. int64_t m_nLastPts = 0;
  51. int64_t m_nLastDelta = 3000;
  52. unsigned m_nTruncLogs = 0;
  53. };
  54. class RtspSession
  55. {
  56. public:
  57. explicit RtspSession(RtspSource * src) : m_pSrc(src) {}
  58. void run();
  59. void end(const std::string & error);
  60. void onUnit(std::vector<Bytes> && nalus, int64_t pts, int64_t ntpUs);
  61. void dataReceived() { m_tLastData = nowMs(); }
  62. RtspSource * source() { return m_pSrc; }
  63. static void continueAfterDescribe(RTSPClient * c, int resultCode, char * resultString);
  64. static void continueAfterSetup(RTSPClient * c, int resultCode, char * resultString);
  65. static void continueAfterPlay(RTSPClient * c, int resultCode, char * resultString);
  66. static void ignoreResponse(RTSPClient *, int, char * resultString) { delete[] resultString; }
  67. static void onSubsessionBye(void * clientData);
  68. static void onSinkClosed(void * clientData);
  69. static void periodicCheck(void * clientData);
  70. static void sendKeepalive(void * clientData);
  71. private:
  72. void afterDescribe(int resultCode, char * resultString);
  73. void afterSetup(int resultCode, char * resultString);
  74. void afterPlay(int resultCode, char * resultString);
  75. void cleanup();
  76. RtspSource * m_pSrc;
  77. TaskScheduler * m_pScheduler = nullptr;
  78. UsageEnvironment * m_pEnv = nullptr;
  79. MtxRTSPClient * m_pClient = nullptr;
  80. MediaSession * m_pSession = nullptr;
  81. MediaSubsession * m_pVideo = nullptr;
  82. WatchVar m_watch{0};
  83. bool m_bEnded = false;
  84. bool m_bPlaying = false;
  85. bool m_bReady = false;
  86. StreamDesc m_desc;
  87. int64_t m_tStart = 0;
  88. int64_t m_tLastData = 0;
  89. TaskToken m_checkTask = nullptr;
  90. TaskToken m_aliveTask = nullptr;
  91. };
  92. // ---------------------------------------------------------------- sink
  93. H264Sink::H264Sink(UsageEnvironment & env, RtspSession * owner, RTPSource * rtp) : MediaSink(env), m_pOwner(owner), m_pRtp(rtp)
  94. {
  95. m_pBuffer = new uint8_t[SINK_BUFFER_SIZE];
  96. }
  97. Boolean H264Sink::continuePlaying()
  98. {
  99. if (fSource == nullptr)
  100. {
  101. return False;
  102. }
  103. fSource->getNextFrame(m_pBuffer, SINK_BUFFER_SIZE, afterGettingFrame, this, RtspSession::onSinkClosed, m_pOwner);
  104. return True;
  105. }
  106. void H264Sink::afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned)
  107. {
  108. static_cast<H264Sink *>(clientData)->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime);
  109. }
  110. void H264Sink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime)
  111. {
  112. m_pOwner->dataReceived();
  113. // live555 keeps the RTP timestamp private: the presentation time is derived from it (exact, until the
  114. // first RTCP sender report moves it onto the sender's wall clock - see flush())
  115. int64_t tPtUs = (int64_t) presentationTime.tv_sec * 1000000 + presentationTime.tv_usec;
  116. bool tMarker = m_pRtp->curPacketMarkerBit();
  117. if (numTruncatedBytes > 0 && m_nTruncLogs++ < 5)
  118. {
  119. m_pOwner->source()->log(LogLevel::Warn, "NAL unit truncated by %u bytes", numTruncatedBytes);
  120. }
  121. // An access unit ends with the RTP marker bit. A camera that does not set it: a new presentation time
  122. // starts a new unit. Small changes are not a new unit: every RTCP sender report moves live555's
  123. // mapping of RTP time to presentation time a little, also between packets of the same picture.
  124. if (! m_vNalus.empty() && (tPtUs - m_nPtUs > 2000 || m_nPtUs - tPtUs > 2000))
  125. {
  126. flush();
  127. }
  128. if (frameSize > 0)
  129. {
  130. int tType = m_pBuffer[0] & 0x1f;
  131. if (tType != h264::NALU_AUD && tType != 0)
  132. {
  133. m_vNalus.emplace_back(m_pBuffer, m_pBuffer + frameSize);
  134. }
  135. }
  136. if (m_vNalus.size() <= 1)
  137. {
  138. m_nPtUs = tPtUs; // the time of the unit is the time of its first NAL unit
  139. }
  140. if (tMarker)
  141. {
  142. flush();
  143. }
  144. continuePlaying();
  145. }
  146. void H264Sink::flush()
  147. {
  148. if (m_vNalus.empty())
  149. {
  150. return;
  151. }
  152. // 90 kHz pts starting at 0. When live555 synchronises with the first RTCP sender report the presentation
  153. // times jump onto the sender's clock: the offset keeps the pts continuous (one frame interval).
  154. int64_t tRaw = m_nPtUs * 9 / 100;
  155. bool tSynced = m_pRtp->hasBeenSynchronizedUsingRTCP();
  156. if (! m_bHavePts)
  157. {
  158. m_bHavePts = true;
  159. m_bSynced = tSynced;
  160. m_nOffset = -tRaw;
  161. }
  162. else if (tSynced != m_bSynced)
  163. {
  164. m_bSynced = tSynced;
  165. m_nOffset = m_nLastPts + m_nLastDelta - tRaw;
  166. }
  167. int64_t tPts = tRaw + m_nOffset;
  168. if (tPts > m_nLastPts && tPts - m_nLastPts < 90000)
  169. {
  170. m_nLastDelta = tPts - m_nLastPts;
  171. }
  172. m_nLastRaw = tRaw;
  173. m_nLastPts = tPts;
  174. m_pOwner->onUnit(std::move(m_vNalus), tPts, m_nPtUs);
  175. m_vNalus.clear();
  176. }
  177. // ---------------------------------------------------------------- session
  178. void RtspSession::run()
  179. {
  180. m_pScheduler = BasicTaskScheduler::createNew();
  181. m_pEnv = BasicUsageEnvironment::createNew(*m_pScheduler);
  182. m_tStart = nowMs();
  183. m_pSrc->log(LogLevel::Info, "started");
  184. m_pClient = MtxRTSPClient::createNew(*m_pEnv, m_pSrc->pathConf().source.c_str(), this);
  185. if (m_pClient == nullptr)
  186. {
  187. end(std::string("cannot create the RTSP client: ") + m_pEnv->getResultMsg());
  188. }
  189. else
  190. {
  191. m_pClient->sendDescribeCommand(continueAfterDescribe);
  192. m_checkTask = m_pScheduler->scheduleDelayedTask(CHECK_INTERVAL_US, periodicCheck, this);
  193. m_pScheduler->doEventLoop(&m_watch);
  194. }
  195. cleanup();
  196. }
  197. void RtspSession::end(const std::string & error)
  198. {
  199. if (m_bEnded)
  200. {
  201. return;
  202. }
  203. m_bEnded = true;
  204. if (! error.empty())
  205. {
  206. m_pSrc->log(LogLevel::Error, "%s", error.c_str());
  207. }
  208. m_watch = 1;
  209. }
  210. void RtspSession::cleanup()
  211. {
  212. if (m_pScheduler != nullptr)
  213. {
  214. m_pScheduler->unscheduleDelayedTask(m_checkTask);
  215. m_pScheduler->unscheduleDelayedTask(m_aliveTask);
  216. }
  217. if (m_pSession != nullptr)
  218. {
  219. if (m_pClient != nullptr && m_bPlaying)
  220. {
  221. m_pClient->sendTeardownCommand(*m_pSession, ignoreResponse);
  222. }
  223. MediaSubsessionIterator tIter(*m_pSession);
  224. MediaSubsession * tSub;
  225. while ((tSub = tIter.next()) != nullptr)
  226. {
  227. if (tSub->sink != nullptr)
  228. {
  229. tSub->sink->stopPlaying();
  230. Medium::close(tSub->sink);
  231. tSub->sink = nullptr;
  232. }
  233. }
  234. Medium::close(m_pSession);
  235. m_pSession = nullptr;
  236. }
  237. if (m_pClient != nullptr)
  238. {
  239. Medium::close(m_pClient);
  240. m_pClient = nullptr;
  241. }
  242. if (m_bReady)
  243. {
  244. m_pSrc->parent()->sourceSetNotReady();
  245. m_bReady = false;
  246. }
  247. if (m_pEnv != nullptr)
  248. {
  249. m_pEnv->reclaim();
  250. m_pEnv = nullptr;
  251. }
  252. delete m_pScheduler;
  253. m_pScheduler = nullptr;
  254. }
  255. void RtspSession::continueAfterDescribe(RTSPClient * c, int resultCode, char * resultString)
  256. {
  257. static_cast<MtxRTSPClient *>(c)->owner->afterDescribe(resultCode, resultString);
  258. }
  259. void RtspSession::continueAfterSetup(RTSPClient * c, int resultCode, char * resultString)
  260. {
  261. static_cast<MtxRTSPClient *>(c)->owner->afterSetup(resultCode, resultString);
  262. }
  263. void RtspSession::continueAfterPlay(RTSPClient * c, int resultCode, char * resultString)
  264. {
  265. static_cast<MtxRTSPClient *>(c)->owner->afterPlay(resultCode, resultString);
  266. }
  267. static std::string resultText(int resultCode, const char * resultString, UsageEnvironment * env)
  268. {
  269. if (resultCode < 0)
  270. {
  271. // network error, the message is in the environment
  272. return std::string(env->getResultMsg());
  273. }
  274. return "bad status code: " + std::to_string(resultCode) + (resultString ? std::string(" (") + resultString + ")" : std::string());
  275. }
  276. void RtspSession::afterDescribe(int resultCode, char * resultString)
  277. {
  278. if (resultCode != 0)
  279. {
  280. end("DESCRIBE failed: " + resultText(resultCode, resultString, m_pEnv));
  281. delete[] resultString;
  282. return;
  283. }
  284. m_pSession = MediaSession::createNew(*m_pEnv, resultString);
  285. delete[] resultString;
  286. if (m_pSession == nullptr || ! m_pSession->hasSubsessions())
  287. {
  288. end(std::string("invalid SDP: ") + m_pEnv->getResultMsg());
  289. return;
  290. }
  291. MediaSubsessionIterator tIter(*m_pSession);
  292. MediaSubsession * tSub;
  293. while ((tSub = tIter.next()) != nullptr)
  294. {
  295. if (m_pVideo == nullptr && strcmp(tSub->mediumName(), "video") == 0 && strcmp(tSub->codecName(), "H264") == 0)
  296. {
  297. m_pVideo = tSub;
  298. }
  299. else
  300. {
  301. m_pSrc->log(LogLevel::Warn, "skipping track %s/%s (only H264 video is supported)", tSub->mediumName(), tSub->codecName());
  302. }
  303. }
  304. if (m_pVideo == nullptr)
  305. {
  306. end("the stream has no H264 video track");
  307. return;
  308. }
  309. if (! m_pVideo->initiate())
  310. {
  311. end(std::string("cannot initiate the video track: ") + m_pEnv->getResultMsg());
  312. return;
  313. }
  314. if (m_pSrc->pathConf().transport == RtspTransport::Udp && m_pVideo->rtpSource() != nullptr)
  315. {
  316. increaseReceiveBufferTo(*m_pEnv, m_pVideo->rtpSource()->RTPgs()->socketNum(), UDP_RECEIVE_BUFFER);
  317. }
  318. // codec parameters from the SDP (sprop-parameter-sets), if any
  319. for (const Bytes & n : h264::decodeSpropParameterSets(m_pVideo->fmtp_spropparametersets()))
  320. {
  321. if (h264::naluType(n) == h264::NALU_SPS)
  322. {
  323. m_desc.sps = n;
  324. }
  325. else if (h264::naluType(n) == h264::NALU_PPS)
  326. {
  327. m_desc.pps = n;
  328. }
  329. }
  330. m_pClient->sendSetupCommand(*m_pVideo, continueAfterSetup, False, m_pSrc->pathConf().transport == RtspTransport::Tcp ? True : False);
  331. }
  332. void RtspSession::afterSetup(int resultCode, char * resultString)
  333. {
  334. delete[] resultString;
  335. if (resultCode != 0)
  336. {
  337. end("SETUP failed: " + resultText(resultCode, nullptr, m_pEnv));
  338. return;
  339. }
  340. H264Sink * tSink = H264Sink::createNew(*m_pEnv, this, m_pVideo->rtpSource());
  341. m_pVideo->sink = tSink;
  342. if (m_pVideo->rtcpInstance() != nullptr)
  343. {
  344. m_pVideo->rtcpInstance()->setByeHandler(onSubsessionBye, this);
  345. }
  346. tSink->startPlaying(*m_pVideo->readSource(), nullptr, nullptr);
  347. m_pClient->sendPlayCommand(*m_pSession, continueAfterPlay);
  348. }
  349. void RtspSession::afterPlay(int resultCode, char * resultString)
  350. {
  351. delete[] resultString;
  352. if (resultCode != 0)
  353. {
  354. end("PLAY failed: " + resultText(resultCode, nullptr, m_pEnv));
  355. return;
  356. }
  357. m_bPlaying = true;
  358. m_tLastData = nowMs();
  359. m_pSrc->log(LogLevel::Info, "ready: 1 track (H264)");
  360. unsigned tTimeout = m_pClient->sessionTimeoutParameter();
  361. unsigned tEvery = (tTimeout > 10) ? tTimeout / 2 : 30;
  362. m_aliveTask = m_pScheduler->scheduleDelayedTask((int64_t) tEvery * 1000000, sendKeepalive, this);
  363. }
  364. void RtspSession::onUnit(std::vector<Bytes> && nalus, int64_t pts, int64_t ntpUs)
  365. {
  366. if (! m_bReady)
  367. {
  368. for (const Bytes & n : nalus)
  369. {
  370. if (h264::naluType(n) == h264::NALU_SPS)
  371. {
  372. m_desc.sps = n;
  373. }
  374. else if (h264::naluType(n) == h264::NALU_PPS)
  375. {
  376. m_desc.pps = n;
  377. }
  378. }
  379. if (m_desc.sps.empty() || m_desc.pps.empty())
  380. {
  381. return; // a reader cannot use the stream without the codec parameters
  382. }
  383. h264::SpsInfo tInfo;
  384. if (h264::parseSps(m_desc.sps, tInfo))
  385. {
  386. m_desc.width = tInfo.width;
  387. m_desc.height = tInfo.height;
  388. }
  389. m_bReady = true;
  390. m_pSrc->parent()->sourceSetReady(m_desc);
  391. }
  392. auto tUnit = std::make_shared<Unit>();
  393. tUnit->pts = pts;
  394. tUnit->ntpUs = ntpUs;
  395. tUnit->nalus = std::move(nalus);
  396. for (const Bytes & n : tUnit->nalus)
  397. {
  398. if (h264::naluType(n) == h264::NALU_IDR)
  399. {
  400. tUnit->idr = true;
  401. break;
  402. }
  403. }
  404. m_pSrc->parent()->sourceWriteUnit(tUnit);
  405. }
  406. void RtspSession::onSubsessionBye(void * clientData)
  407. {
  408. static_cast<RtspSession *>(clientData)->end("received RTCP BYE");
  409. }
  410. void RtspSession::onSinkClosed(void * clientData)
  411. {
  412. static_cast<RtspSession *>(clientData)->end("the stream was closed by the server");
  413. }
  414. void RtspSession::periodicCheck(void * clientData)
  415. {
  416. RtspSession * s = static_cast<RtspSession *>(clientData);
  417. s->m_checkTask = nullptr;
  418. if (s->m_pSrc->stopRequested())
  419. {
  420. s->end("");
  421. return;
  422. }
  423. int64_t tNow = nowMs();
  424. int64_t tTimeout = s->m_pSrc->global().readTimeoutMs;
  425. if (s->m_bPlaying && tNow - s->m_tLastData > tTimeout)
  426. {
  427. s->end("no data for " + std::to_string((tNow - s->m_tLastData) / 1000) + " s");
  428. return;
  429. }
  430. if (! s->m_bPlaying && tNow - s->m_tStart > tTimeout)
  431. {
  432. s->end("timed out waiting for the server");
  433. return;
  434. }
  435. s->m_checkTask = s->m_pScheduler->scheduleDelayedTask(CHECK_INTERVAL_US, periodicCheck, s);
  436. }
  437. void RtspSession::sendKeepalive(void * clientData)
  438. {
  439. RtspSession * s = static_cast<RtspSession *>(clientData);
  440. s->m_aliveTask = nullptr;
  441. s->m_pClient->sendOptionsCommand(ignoreResponse);
  442. unsigned tTimeout = s->m_pClient->sessionTimeoutParameter();
  443. unsigned tEvery = (tTimeout > 10) ? tTimeout / 2 : 30;
  444. s->m_aliveTask = s->m_pScheduler->scheduleDelayedTask((int64_t) tEvery * 1000000, sendKeepalive, s);
  445. }
  446. } // namespace
  447. // ---------------------------------------------------------------- source
  448. RtspSource::RtspSource(const PathConf & conf, const Conf & global, SourceParent * parent)
  449. : LogParent("[path " + conf.name + "] [RTSP source] "), m_conf(conf), m_global(global), m_pParent(parent)
  450. {
  451. }
  452. RtspSource::~RtspSource()
  453. {
  454. stop();
  455. }
  456. void RtspSource::start()
  457. {
  458. m_bStop = false;
  459. m_thread = std::thread(&RtspSource::run, this);
  460. }
  461. void RtspSource::stop()
  462. {
  463. m_bStop = true;
  464. m_cond.notify_all();
  465. if (m_thread.joinable())
  466. {
  467. m_thread.join();
  468. log(LogLevel::Info, "stopped");
  469. }
  470. }
  471. void RtspSource::run()
  472. {
  473. while (! m_bStop)
  474. {
  475. runSession();
  476. if (! m_bStop)
  477. {
  478. waitRetry();
  479. }
  480. }
  481. }
  482. void RtspSource::runSession()
  483. {
  484. RtspSession tSession(this);
  485. tSession.run();
  486. }
  487. void RtspSource::waitRetry()
  488. {
  489. std::unique_lock<std::mutex> lock(m_mutex);
  490. m_cond.wait_for(lock, std::chrono::milliseconds(m_global.sourceRetryPauseMs), [this] { return m_bStop.load(); });
  491. }
  492. } // namespace mtx