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

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "session.h"
  2. #include <sstream>
  3. #include <strings.h>
  4. #include "../../codecs/h264/h264.h"
  5. namespace mtx {
  6. namespace {
  7. std::string fmtpValue(const std::string & fmtp, const std::string & key)
  8. {
  9. std::istringstream tIn(fmtp);
  10. std::string tPart;
  11. while (std::getline(tIn, tPart, ';'))
  12. {
  13. size_t b = tPart.find_first_not_of(' ');
  14. if (b == std::string::npos)
  15. {
  16. continue;
  17. }
  18. tPart = tPart.substr(b);
  19. size_t e = tPart.find('=');
  20. if (e != std::string::npos && tPart.substr(0, e) == key)
  21. {
  22. return tPart.substr(e + 1);
  23. }
  24. }
  25. return std::string();
  26. }
  27. } // namespace
  28. WebrtcSession::WebrtcSession(const std::string & secret, std::shared_ptr<Path> path, const Conf & global, const std::string & remoteAddr)
  29. : LogParent("[WebRTC] [session " + secret.substr(0, 8) + "] "), m_sSecret(secret), m_pPath(std::move(path)), m_global(global), m_sRemote(remoteAddr),
  30. m_reader(this, 512)
  31. {
  32. m_tCreated = nowMs();
  33. }
  34. WebrtcSession::~WebrtcSession()
  35. {
  36. close();
  37. }
  38. bool WebrtcSession::create(const std::string & offerSdp, std::string & answer, int & status, std::string & err)
  39. {
  40. log(LogLevel::Info, "created by %s", m_sRemote.c_str());
  41. status = 400;
  42. rtc::Description tOffer("", rtc::Description::Type::Offer);
  43. try
  44. {
  45. tOffer = rtc::Description(offerSdp, rtc::Description::Type::Offer);
  46. }
  47. catch (const std::exception & e)
  48. {
  49. err = std::string("invalid SDP offer: ") + e.what();
  50. return false;
  51. }
  52. if (! m_pPath->addReader(this, m_desc, err))
  53. {
  54. status = 404;
  55. return false;
  56. }
  57. m_bReading = true;
  58. // The video section of the offer and its best H264 payload type
  59. std::string tMid;
  60. int tPt = -1;
  61. std::string tFmtp;
  62. int tBest = -1;
  63. int tStreamPrf = m_desc.sps.size() > 1 ? m_desc.sps[1] : 66;
  64. for (int i = 0; i < tOffer.mediaCount() && tMid.empty(); i++)
  65. {
  66. auto tM = tOffer.media(i);
  67. if (! std::holds_alternative<rtc::Description::Media *>(tM))
  68. {
  69. continue;
  70. }
  71. rtc::Description::Media * tMedia = std::get<rtc::Description::Media *>(tM);
  72. if (tMedia->type() != "video")
  73. {
  74. continue;
  75. }
  76. if (tMedia->direction() != rtc::Description::Direction::RecvOnly && tMedia->direction() != rtc::Description::Direction::SendRecv)
  77. {
  78. continue;
  79. }
  80. for (int pt : tMedia->payloadTypes())
  81. {
  82. const rtc::Description::Media::RtpMap * tMap = tMedia->rtpMap(pt);
  83. if (tMap == nullptr || strcasecmp(tMap->format.c_str(), "H264") != 0)
  84. {
  85. continue;
  86. }
  87. std::string tF = tMap->fmtps.empty() ? std::string() : tMap->fmtps[0];
  88. if (fmtpValue(tF, "packetization-mode") != "1")
  89. {
  90. continue;
  91. }
  92. std::string tPrf = fmtpValue(tF, "profile-level-id");
  93. int tIdc = tPrf.size() >= 2 ? (int) strtol(tPrf.substr(0, 2).c_str(), nullptr, 16) : 66;
  94. int tScore = (tIdc == tStreamPrf) ? 3 : (tPrf.compare(0, 4, "42e0") == 0 ? 2 : 1);
  95. if (tScore > tBest)
  96. {
  97. tBest = tScore;
  98. tPt = pt;
  99. tFmtp = tF;
  100. }
  101. }
  102. if (tPt >= 0)
  103. {
  104. tMid = tMedia->mid();
  105. }
  106. }
  107. if (tPt < 0)
  108. {
  109. err = "the offer has no H264 (packetization-mode=1) video section";
  110. return false;
  111. }
  112. rtc::Configuration tCfg;
  113. for (const std::string & s : m_global.webrtcICEServers)
  114. {
  115. tCfg.iceServers.emplace_back(s);
  116. }
  117. if (! m_global.webrtcBindAddress.empty())
  118. {
  119. tCfg.bindAddress = m_global.webrtcBindAddress;
  120. }
  121. tCfg.portRangeBegin = m_global.webrtcUDPPortMin;
  122. tCfg.portRangeEnd = m_global.webrtcUDPPortMax;
  123. tCfg.disableAutoNegotiation = true;
  124. m_pPc = std::make_shared<rtc::PeerConnection>(tCfg);
  125. m_pPc->onGatheringStateChange([this](rtc::PeerConnection::GatheringState s) {
  126. if (s == rtc::PeerConnection::GatheringState::Complete)
  127. {
  128. std::lock_guard<std::mutex> lock(m_mutex);
  129. m_bGathered = true;
  130. m_cond.notify_all();
  131. }
  132. });
  133. m_pPc->onStateChange([this](rtc::PeerConnection::State s) {
  134. if (s == rtc::PeerConnection::State::Connected)
  135. {
  136. if (! m_bConnected.exchange(true))
  137. {
  138. log(LogLevel::Info, "peer connection established");
  139. }
  140. }
  141. else if (s == rtc::PeerConnection::State::Failed || s == rtc::PeerConnection::State::Closed || s == rtc::PeerConnection::State::Disconnected)
  142. {
  143. if (! m_bClosing.exchange(true))
  144. {
  145. log(LogLevel::Info, "peer connection %s", s == rtc::PeerConnection::State::Failed ? "failed" : "closed");
  146. }
  147. }
  148. });
  149. uint32_t tSsrc = (uint32_t) (std::hash<std::string>()(m_sSecret) & 0x7fffffff) | 1;
  150. rtc::Description::Video tVideo(tMid, rtc::Description::Direction::SendOnly);
  151. tVideo.addH264Codec(tPt, tFmtp);
  152. tVideo.addSSRC(tSsrc, "mediamtx", "mediamtx", "video");
  153. m_pTrack = m_pPc->addTrack(tVideo);
  154. m_pRtpConfig = std::make_shared<rtc::RtpPacketizationConfig>(tSsrc, "mediamtx", (uint8_t) tPt, rtc::H264RtpPacketizer::defaultClockRate);
  155. auto tPacketizer = std::make_shared<rtc::H264RtpPacketizer>(rtc::H264RtpPacketizer::Separator::LongStartSequence, m_pRtpConfig, 1200);
  156. m_pSrReporter = std::make_shared<rtc::RtcpSrReporter>(m_pRtpConfig);
  157. tPacketizer->addToChain(m_pSrReporter);
  158. tPacketizer->addToChain(std::make_shared<rtc::RtcpNackResponder>());
  159. m_pTrack->setMediaHandler(tPacketizer);
  160. m_pTrack->onOpen([this]() { m_bTrackOpen = true; });
  161. try
  162. {
  163. m_pPc->setRemoteDescription(tOffer);
  164. m_pPc->setLocalDescription(rtc::Description::Type::Answer);
  165. }
  166. catch (const std::exception & e)
  167. {
  168. err = std::string("negotiation failed: ") + e.what();
  169. return false;
  170. }
  171. {
  172. std::unique_lock<std::mutex> lock(m_mutex);
  173. m_cond.wait_for(lock, std::chrono::seconds(5), [this] { return m_bGathered; });
  174. }
  175. auto tLocal = m_pPc->localDescription();
  176. if (! tLocal)
  177. {
  178. status = 500;
  179. err = "no local description";
  180. return false;
  181. }
  182. answer = std::string(*tLocal);
  183. m_reader.start([this](const UnitPtr & u) { onUnit(u); });
  184. 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);
  185. status = 201;
  186. return true;
  187. }
  188. bool WebrtcSession::addRemoteCandidates(const std::string & sdpFrag, std::string & err)
  189. {
  190. if (! m_pPc)
  191. {
  192. err = "session not ready";
  193. return false;
  194. }
  195. std::istringstream tIn(sdpFrag);
  196. std::string tLine;
  197. std::string tMid;
  198. while (std::getline(tIn, tLine))
  199. {
  200. if (! tLine.empty() && tLine.back() == '\r')
  201. {
  202. tLine.pop_back();
  203. }
  204. if (tLine.compare(0, 6, "a=mid:") == 0)
  205. {
  206. tMid = tLine.substr(6);
  207. }
  208. else if (tLine.compare(0, 12, "a=candidate:") == 0)
  209. {
  210. try
  211. {
  212. m_pPc->addRemoteCandidate(tMid.empty() ? rtc::Candidate(tLine.substr(2)) : rtc::Candidate(tLine.substr(2), tMid));
  213. }
  214. catch (const std::exception & e)
  215. {
  216. err = std::string("invalid candidate: ") + e.what();
  217. return false;
  218. }
  219. }
  220. }
  221. return true;
  222. }
  223. void WebrtcSession::pathNotReady()
  224. {
  225. // called with the path locked: only mark, the server closes the session
  226. m_bReading = false;
  227. if (! m_bClosing.exchange(true))
  228. {
  229. log(LogLevel::Info, "the source of path '%s' is gone", m_pPath->conf().name.c_str());
  230. }
  231. }
  232. void WebrtcSession::close()
  233. {
  234. if (m_bClosed)
  235. {
  236. return;
  237. }
  238. m_bClosed = true;
  239. m_bClosing = true;
  240. if (m_bReading)
  241. {
  242. m_pPath->removeReader(this);
  243. m_bReading = false;
  244. }
  245. m_reader.stop();
  246. if (m_pPc)
  247. {
  248. m_pPc->onStateChange(nullptr);
  249. m_pPc->onGatheringStateChange(nullptr);
  250. if (m_pTrack)
  251. {
  252. m_pTrack->onOpen(nullptr);
  253. }
  254. m_pPc->close();
  255. }
  256. m_pTrack.reset();
  257. m_pPc.reset();
  258. log(LogLevel::Info, "closed (%llu bytes sent)", (unsigned long long) m_nBytesSent);
  259. }
  260. void WebrtcSession::onUnit(const UnitPtr & unit)
  261. {
  262. if (! m_bTrackOpen || m_bClosing)
  263. {
  264. return;
  265. }
  266. if (! m_bStarted)
  267. {
  268. if (! unit->idr)
  269. {
  270. return; // the browser needs a random access point
  271. }
  272. m_bStarted = true;
  273. m_nFirstPts = unit->pts;
  274. }
  275. std::vector<Bytes> tNalus;
  276. if (unit->idr)
  277. {
  278. // make sure every IDR carries the parameter sets (cameras often send them only in the SDP)
  279. bool tSps = false, tPps = false;
  280. for (const Bytes & n : unit->nalus)
  281. {
  282. tSps |= h264::naluType(n) == h264::NALU_SPS;
  283. tPps |= h264::naluType(n) == h264::NALU_PPS;
  284. }
  285. if (! tSps && ! m_desc.sps.empty())
  286. {
  287. tNalus.push_back(m_desc.sps);
  288. }
  289. if (! tPps && ! m_desc.pps.empty())
  290. {
  291. tNalus.push_back(m_desc.pps);
  292. }
  293. }
  294. for (const Bytes & n : unit->nalus)
  295. {
  296. int t = h264::naluType(n);
  297. if (t == h264::NALU_SPS)
  298. {
  299. m_desc.sps = n;
  300. }
  301. else if (t == h264::NALU_PPS)
  302. {
  303. m_desc.pps = n;
  304. }
  305. tNalus.push_back(n);
  306. }
  307. Bytes tFrame = h264::toAnnexB(tNalus);
  308. m_pRtpConfig->timestamp = m_pRtpConfig->startTimestamp + (uint32_t) (unit->pts - m_nFirstPts);
  309. int64_t tNow = nowMs();
  310. if (tNow - m_tLastSr > 1000)
  311. {
  312. m_tLastSr = tNow;
  313. m_pSrReporter->setNeedsToReport();
  314. }
  315. try
  316. {
  317. m_pTrack->send(reinterpret_cast<const rtc::byte *>(tFrame.data()), tFrame.size());
  318. m_nBytesSent += tFrame.size();
  319. }
  320. catch (const std::exception & e)
  321. {
  322. if (! m_bClosing.exchange(true))
  323. {
  324. log(LogLevel::Warn, "send failed: %s", e.what());
  325. }
  326. }
  327. }
  328. } // namespace mtx