main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /**
  2. * libdatachannel client example
  3. * Copyright (c) 2019-2020 Paul-Louis Ageneau
  4. * Copyright (c) 2019 Murat Dogan
  5. * Copyright (c) 2020 Will Munn
  6. * Copyright (c) 2020 Nico Chatzi
  7. * Copyright (c) 2020 Lara Mackey
  8. * Copyright (c) 2020 Erik Cota-Robles
  9. * Copyright (c) 2020 Filip Klembara (in2core)
  10. *
  11. * This Source Code Form is subject to the terms of the Mozilla Public
  12. * License, v. 2.0. If a copy of the MPL was not distributed with this
  13. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  14. */
  15. #include "nlohmann/json.hpp"
  16. #include "h264fileparser.hpp"
  17. #include "opusfileparser.hpp"
  18. #include "helpers.hpp"
  19. #include "ArgParser.hpp"
  20. using namespace rtc;
  21. using namespace std;
  22. using namespace std::chrono_literals;
  23. using json = nlohmann::json;
  24. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  25. /// all connected clients
  26. unordered_map<string, shared_ptr<Client>> clients{};
  27. /// Creates peer connection and client representation
  28. /// @param config Configuration
  29. /// @param wws Websocket for signaling
  30. /// @param id Client ID
  31. /// @returns Client
  32. shared_ptr<Client> createPeerConnection(const Configuration &config,
  33. weak_ptr<WebSocket> wws,
  34. string id);
  35. /// Creates stream
  36. /// @param h264Samples Directory with H264 samples
  37. /// @param fps Video FPS
  38. /// @param opusSamples Directory with opus samples
  39. /// @returns Stream object
  40. shared_ptr<Stream> createStream(const string h264Samples, const unsigned fps, const string opusSamples);
  41. /// Add client to stream
  42. /// @param client Client
  43. /// @param adding_video True if adding video
  44. void addToStream(shared_ptr<Client> client, bool isAddingVideo);
  45. /// Start stream
  46. void startStream();
  47. /// Main dispatch queue
  48. DispatchQueue MainThread("Main");
  49. /// Audio and video stream
  50. optional<shared_ptr<Stream>> avStream = nullopt;
  51. const string defaultRootDirectory = "../../../examples/streamer/samples/";
  52. const string defaultH264SamplesDirectory = defaultRootDirectory + "h264/";
  53. string h264SamplesDirectory = defaultH264SamplesDirectory;
  54. const string defaultOpusSamplesDirectory = defaultRootDirectory + "opus/";
  55. string opusSamplesDirectory = defaultOpusSamplesDirectory;
  56. const string defaultIPAddress = "127.0.0.1";
  57. const uint16_t defaultPort = 8000;
  58. string ip_address = defaultIPAddress;
  59. uint16_t port = defaultPort;
  60. /// Incomming message handler for websocket
  61. /// @param message Incommint message
  62. /// @param config Configuration
  63. /// @param ws Websocket
  64. void wsOnMessage(json message, Configuration config, shared_ptr<WebSocket> ws) {
  65. auto it = message.find("id");
  66. if (it == message.end())
  67. return;
  68. string id = it->get<string>();
  69. it = message.find("type");
  70. if (it == message.end())
  71. return;
  72. string type = it->get<string>();
  73. if (type == "request") {
  74. clients.emplace(id, createPeerConnection(config, make_weak_ptr(ws), id));
  75. } else if (type == "answer") {
  76. if (auto jt = clients.find(id); jt != clients.end()) {
  77. auto pc = jt->second->peerConnection;
  78. auto sdp = message["sdp"].get<string>();
  79. auto description = Description(sdp, type);
  80. pc->setRemoteDescription(description);
  81. }
  82. }
  83. }
  84. int main(int argc, char **argv) try {
  85. bool enableDebugLogs = false;
  86. bool printHelp = false;
  87. int c = 0;
  88. auto parser = ArgParser({{"a", "audio"}, {"b", "video"}, {"d", "ip"}, {"p","port"}}, {{"h", "help"}, {"v", "verbose"}});
  89. auto parsingResult = parser.parse(argc, argv, [](string key, string value) {
  90. if (key == "audio") {
  91. opusSamplesDirectory = value + "/";
  92. } else if (key == "video") {
  93. h264SamplesDirectory = value + "/";
  94. } else if (key == "ip") {
  95. ip_address = value;
  96. } else if (key == "port") {
  97. port = atoi(value.data());
  98. } else {
  99. cerr << "Invalid option --" << key << " with value " << value << endl;
  100. return false;
  101. }
  102. return true;
  103. }, [&enableDebugLogs, &printHelp](string flag){
  104. if (flag == "verbose") {
  105. enableDebugLogs = true;
  106. } else if (flag == "help") {
  107. printHelp = true;
  108. } else {
  109. cerr << "Invalid flag --" << flag << endl;
  110. return false;
  111. }
  112. return true;
  113. });
  114. if (!parsingResult) {
  115. return 1;
  116. }
  117. if (printHelp) {
  118. cout << "usage: stream-h264 [-a opus_samples_folder] [-b h264_samples_folder] [-d ip_address] [-p port] [-v] [-h]" << endl
  119. << "Arguments:" << endl
  120. << "\t -a " << "Directory with opus samples (default: " << defaultOpusSamplesDirectory << ")." << endl
  121. << "\t -b " << "Directory with H264 samples (default: " << defaultH264SamplesDirectory << ")." << endl
  122. << "\t -d " << "Signaling server IP address (default: " << defaultIPAddress << ")." << endl
  123. << "\t -p " << "Signaling server port (default: " << defaultPort << ")." << endl
  124. << "\t -v " << "Enable debug logs." << endl
  125. << "\t -h " << "Print this help and exit." << endl;
  126. return 0;
  127. }
  128. if (enableDebugLogs) {
  129. InitLogger(LogLevel::Debug);
  130. }
  131. Configuration config;
  132. string stunServer = "stun:stun.l.google.com:19302";
  133. cout << "STUN server is " << stunServer << endl;
  134. config.iceServers.emplace_back(stunServer);
  135. config.disableAutoNegotiation = true;
  136. string localId = "server";
  137. cout << "The local ID is: " << localId << endl;
  138. auto ws = make_shared<WebSocket>();
  139. ws->onOpen([]() { cout << "WebSocket connected, signaling ready" << endl; });
  140. ws->onClosed([]() { cout << "WebSocket closed" << endl; });
  141. ws->onError([](const string &error) { cout << "WebSocket failed: " << error << endl; });
  142. ws->onMessage([&](variant<binary, string> data) {
  143. if (!holds_alternative<string>(data))
  144. return;
  145. json message = json::parse(get<string>(data));
  146. MainThread.dispatch([message, config, ws]() {
  147. wsOnMessage(message, config, ws);
  148. });
  149. });
  150. const string url = "ws://" + ip_address + ":" + to_string(port) + "/" + localId;
  151. cout << "URL is " << url << endl;
  152. ws->open(url);
  153. cout << "Waiting for signaling to be connected..." << endl;
  154. while (!ws->isOpen()) {
  155. if (ws->isClosed())
  156. return 1;
  157. this_thread::sleep_for(100ms);
  158. }
  159. while (true) {
  160. string id;
  161. cout << "Enter to exit" << endl;
  162. cin >> id;
  163. cin.ignore();
  164. cout << "exiting" << endl;
  165. break;
  166. }
  167. cout << "Cleaning up..." << endl;
  168. return 0;
  169. } catch (const std::exception &e) {
  170. std::cout << "Error: " << e.what() << std::endl;
  171. return -1;
  172. }
  173. shared_ptr<ClientTrackData> addVideo(const shared_ptr<PeerConnection> pc, const uint8_t payloadType, const uint32_t ssrc, const string cname, const string msid, const function<void (void)> onOpen) {
  174. auto video = Description::Video(cname);
  175. video.addH264Codec(payloadType);
  176. video.addSSRC(ssrc, cname, msid, cname);
  177. auto track = pc->addTrack(video);
  178. // create RTP configuration
  179. auto rtpConfig = make_shared<RtpPacketizationConfig>(ssrc, cname, payloadType, H264RtpPacketizer::defaultClockRate);
  180. // create packetizer
  181. auto packetizer = make_shared<H264RtpPacketizer>(NalUnit::Separator::Length, rtpConfig);
  182. // add RTCP SR handler
  183. auto srReporter = make_shared<RtcpSrReporter>(rtpConfig);
  184. packetizer->addToChain(srReporter);
  185. // add RTCP NACK handler
  186. auto nackResponder = make_shared<RtcpNackResponder>();
  187. packetizer->addToChain(nackResponder);
  188. // set handler
  189. track->setMediaHandler(packetizer);
  190. track->onOpen(onOpen);
  191. auto trackData = make_shared<ClientTrackData>(track, srReporter);
  192. return trackData;
  193. }
  194. shared_ptr<ClientTrackData> addAudio(const shared_ptr<PeerConnection> pc, const uint8_t payloadType, const uint32_t ssrc, const string cname, const string msid, const function<void (void)> onOpen) {
  195. auto audio = Description::Audio(cname);
  196. audio.addOpusCodec(payloadType);
  197. audio.addSSRC(ssrc, cname, msid, cname);
  198. auto track = pc->addTrack(audio);
  199. // create RTP configuration
  200. auto rtpConfig = make_shared<RtpPacketizationConfig>(ssrc, cname, payloadType, OpusRtpPacketizer::DefaultClockRate);
  201. // create packetizer
  202. auto packetizer = make_shared<OpusRtpPacketizer>(rtpConfig);
  203. // add RTCP SR handler
  204. auto srReporter = make_shared<RtcpSrReporter>(rtpConfig);
  205. packetizer->addToChain(srReporter);
  206. // add RTCP NACK handler
  207. auto nackResponder = make_shared<RtcpNackResponder>();
  208. packetizer->addToChain(nackResponder);
  209. // set handler
  210. track->setMediaHandler(packetizer);
  211. track->onOpen(onOpen);
  212. auto trackData = make_shared<ClientTrackData>(track, srReporter);
  213. return trackData;
  214. }
  215. // Create and setup a PeerConnection
  216. shared_ptr<Client> createPeerConnection(const Configuration &config,
  217. weak_ptr<WebSocket> wws,
  218. string id) {
  219. auto pc = make_shared<PeerConnection>(config);
  220. auto client = make_shared<Client>(pc);
  221. pc->onStateChange([id](PeerConnection::State state) {
  222. cout << "State: " << state << endl;
  223. if (state == PeerConnection::State::Disconnected ||
  224. state == PeerConnection::State::Failed ||
  225. state == PeerConnection::State::Closed) {
  226. // remove disconnected client
  227. MainThread.dispatch([id]() {
  228. clients.erase(id);
  229. });
  230. }
  231. });
  232. pc->onGatheringStateChange(
  233. [wpc = make_weak_ptr(pc), id, wws](PeerConnection::GatheringState state) {
  234. cout << "Gathering State: " << state << endl;
  235. if (state == PeerConnection::GatheringState::Complete) {
  236. if(auto pc = wpc.lock()) {
  237. auto description = pc->localDescription();
  238. json message = {
  239. {"id", id},
  240. {"type", description->typeString()},
  241. {"sdp", string(description.value())}
  242. };
  243. // Gathering complete, send answer
  244. if (auto ws = wws.lock()) {
  245. ws->send(message.dump());
  246. }
  247. }
  248. }
  249. });
  250. client->video = addVideo(pc, 102, 1, "video-stream", "stream1", [id, wc = make_weak_ptr(client)]() {
  251. MainThread.dispatch([wc]() {
  252. if (auto c = wc.lock()) {
  253. addToStream(c, true);
  254. }
  255. });
  256. cout << "Video from " << id << " opened" << endl;
  257. });
  258. client->audio = addAudio(pc, 111, 2, "audio-stream", "stream1", [id, wc = make_weak_ptr(client)]() {
  259. MainThread.dispatch([wc]() {
  260. if (auto c = wc.lock()) {
  261. addToStream(c, false);
  262. }
  263. });
  264. cout << "Audio from " << id << " opened" << endl;
  265. });
  266. auto dc = pc->createDataChannel("ping-pong");
  267. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  268. if (auto dc = wdc.lock()) {
  269. dc->send("Ping");
  270. }
  271. });
  272. dc->onMessage(nullptr, [id, wdc = make_weak_ptr(dc)](string msg) {
  273. cout << "Message from " << id << " received: " << msg << endl;
  274. if (auto dc = wdc.lock()) {
  275. dc->send("Ping");
  276. }
  277. });
  278. client->dataChannel = dc;
  279. pc->setLocalDescription();
  280. return client;
  281. };
  282. /// Create stream
  283. shared_ptr<Stream> createStream(const string h264Samples, const unsigned fps, const string opusSamples) {
  284. // video source
  285. auto video = make_shared<H264FileParser>(h264Samples, fps, true);
  286. // audio source
  287. auto audio = make_shared<OPUSFileParser>(opusSamples, true);
  288. auto stream = make_shared<Stream>(video, audio);
  289. // set callback responsible for sample sending
  290. stream->onSample([ws = make_weak_ptr(stream)](Stream::StreamSourceType type, uint64_t sampleTime, rtc::binary sample) {
  291. vector<ClientTrack> tracks{};
  292. string streamType = type == Stream::StreamSourceType::Video ? "video" : "audio";
  293. // get track for given type
  294. function<optional<shared_ptr<ClientTrackData>> (shared_ptr<Client>)> getTrackData = [type](shared_ptr<Client> client) {
  295. return type == Stream::StreamSourceType::Video ? client->video : client->audio;
  296. };
  297. // get all clients with Ready state
  298. for(auto id_client: clients) {
  299. auto id = id_client.first;
  300. auto client = id_client.second;
  301. auto optTrackData = getTrackData(client);
  302. if (client->getState() == Client::State::Ready && optTrackData.has_value()) {
  303. auto trackData = optTrackData.value();
  304. tracks.push_back(ClientTrack(id, trackData));
  305. }
  306. }
  307. if (!tracks.empty()) {
  308. for (auto clientTrack: tracks) {
  309. auto client = clientTrack.id;
  310. auto trackData = clientTrack.trackData;
  311. auto rtpConfig = trackData->sender->rtpConfig;
  312. // sample time is in us, we need to convert it to seconds
  313. auto elapsedSeconds = double(sampleTime) / (1000 * 1000);
  314. // get elapsed time in clock rate
  315. uint32_t elapsedTimestamp = rtpConfig->secondsToTimestamp(elapsedSeconds);
  316. // set new timestamp
  317. rtpConfig->timestamp = rtpConfig->startTimestamp + elapsedTimestamp;
  318. // get elapsed time in clock rate from last RTCP sender report
  319. auto reportElapsedTimestamp = rtpConfig->timestamp - trackData->sender->lastReportedTimestamp();
  320. // check if last report was at least 1 second ago
  321. if (rtpConfig->timestampToSeconds(reportElapsedTimestamp) > 1) {
  322. trackData->sender->setNeedsToReport();
  323. }
  324. cout << "Sending " << streamType << " sample with size: " << to_string(sample.size()) << " to " << client << endl;
  325. try {
  326. // send sample
  327. trackData->track->send(sample);
  328. } catch (const std::exception &e) {
  329. cerr << "Unable to send "<< streamType << " packet: " << e.what() << endl;
  330. }
  331. }
  332. }
  333. MainThread.dispatch([ws]() {
  334. if (clients.empty()) {
  335. // we have no clients, stop the stream
  336. if (auto stream = ws.lock()) {
  337. stream->stop();
  338. }
  339. }
  340. });
  341. });
  342. return stream;
  343. }
  344. /// Start stream
  345. void startStream() {
  346. shared_ptr<Stream> stream;
  347. if (avStream.has_value()) {
  348. stream = avStream.value();
  349. if (stream->isRunning) {
  350. // stream is already running
  351. return;
  352. }
  353. } else {
  354. stream = createStream(h264SamplesDirectory, 30, opusSamplesDirectory);
  355. avStream = stream;
  356. }
  357. stream->start();
  358. }
  359. /// Send previous key frame so browser can show something to user
  360. /// @param stream Stream
  361. /// @param video Video track data
  362. void sendInitialNalus(shared_ptr<Stream> stream, shared_ptr<ClientTrackData> video) {
  363. auto h264 = dynamic_cast<H264FileParser *>(stream->video.get());
  364. auto initialNalus = h264->initialNALUS();
  365. // send previous NALU key frame so users don't have to wait to see stream works
  366. if (!initialNalus.empty()) {
  367. const double frameDuration_s = double(h264->getSampleDuration_us()) / (1000 * 1000);
  368. const uint32_t frameTimestampDuration = video->sender->rtpConfig->secondsToTimestamp(frameDuration_s);
  369. video->sender->rtpConfig->timestamp = video->sender->rtpConfig->startTimestamp - frameTimestampDuration * 2;
  370. video->track->send(initialNalus);
  371. video->sender->rtpConfig->timestamp += frameTimestampDuration;
  372. // Send initial NAL units again to start stream in firefox browser
  373. video->track->send(initialNalus);
  374. }
  375. }
  376. /// Add client to stream
  377. /// @param client Client
  378. /// @param adding_video True if adding video
  379. void addToStream(shared_ptr<Client> client, bool isAddingVideo) {
  380. if (client->getState() == Client::State::Waiting) {
  381. client->setState(isAddingVideo ? Client::State::WaitingForAudio : Client::State::WaitingForVideo);
  382. } else if ((client->getState() == Client::State::WaitingForAudio && !isAddingVideo)
  383. || (client->getState() == Client::State::WaitingForVideo && isAddingVideo)) {
  384. // Audio and video tracks are collected now
  385. assert(client->video.has_value() && client->audio.has_value());
  386. auto video = client->video.value();
  387. if (avStream.has_value()) {
  388. sendInitialNalus(avStream.value(), video);
  389. }
  390. client->setState(Client::State::Ready);
  391. }
  392. if (client->getState() == Client::State::Ready) {
  393. startStream();
  394. }
  395. }