main.cpp 18 KB

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