main.cpp 16 KB

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