main.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <iostream>
  2. #include <memory>
  3. #include <rtc/log.hpp>
  4. #include <rtc/rtc.hpp>
  5. #include <rtc/rtp.hpp>
  6. #include <nlohmann/json.hpp>
  7. #include <utility>
  8. #include <arpa/inet.h>
  9. using nlohmann::json;
  10. int main() {
  11. rtc::InitLogger(rtc::LogLevel::Debug);
  12. auto pc = std::make_shared<rtc::PeerConnection>();
  13. pc->onStateChange([](rtc::PeerConnection::State state) { std::cout << "State: " << state << std::endl; });
  14. pc->onGatheringStateChange( [pc](rtc::PeerConnection::GatheringState state) {
  15. std::cout << "Gathering State: " << state << std::endl;
  16. if (state == rtc::PeerConnection::GatheringState::Complete) {
  17. auto description = pc->localDescription();
  18. json message = {
  19. {"type", description->typeString()}, {"sdp", std::string(description.value())}
  20. };
  21. std::cout << message << std::endl;
  22. }
  23. });
  24. int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
  25. sockaddr_in addr;
  26. addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  27. addr.sin_port = htons(5000);
  28. addr.sin_family = AF_INET;
  29. RTCPSession session;
  30. session.setOutgoingCallback([&pc](const rtc::message_ptr& ptr) {
  31. // There is a chance we could send an RTCP packet before we connect (i.e. REMB)
  32. if (pc->state() == rtc::PeerConnection::State::Connected) {
  33. pc->sendMedia(ptr);
  34. }
  35. });
  36. // session.requestBitrate(4000000); // Request 3Mbps (Browsers do not encode more than 2.5MBps from a webcam)
  37. pc->onMedia([&session, &sock_fd, &addr](const rtc::message_ptr& ptr) {
  38. auto resp = session.onData(ptr);
  39. if (resp.has_value()) {
  40. // This is an RTP packet
  41. sendto(sock_fd, resp.value()->data(), resp.value()->size(), 0, (const struct sockaddr*) &addr, sizeof(addr));
  42. }
  43. });
  44. rtc::Description offer;
  45. rtc::Description::Media &m = offer.addVideoMedia(rtc::Description::RecvOnly);
  46. m.addH264Codec(96);
  47. m.setBitrate(3000); // Request 3Mbps (Browsers do not encode more than 2.5MBps from a webcam)
  48. // m.setBitrate(5000000);
  49. pc->setLocalDescription(offer);
  50. auto dc = pc->createDataChannel("test");
  51. std::cout << "Expect RTP video traffic on localhost:5000" << std::endl;
  52. std::cout << "Please copy/paste the answer provided by the browser: " << std::endl;
  53. std::string sdp;
  54. std::getline (std::cin,sdp);
  55. std::cout << "Got answer" << sdp << std::endl;
  56. json j = json::parse(sdp);
  57. rtc::Description answer(j["sdp"].get<std::string>(), j["type"].get<std::string>());
  58. pc->setRemoteDescription(answer, answer);
  59. std::cout << "Press any key to exit." << std::endl;
  60. std::cin >> sdp;
  61. }