main.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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(3000000); // 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::RECV_ONLY);
  46. m.addH264Codec(96);
  47. pc->setLocalDescription(offer);
  48. auto dc = pc->createDataChannel("test");
  49. std::cout << "Expect RTP video traffic on localhost:5000" << std::endl;
  50. std::cout << "Please copy/paste the answer provided by the browser: " << std::endl;
  51. std::string sdp;
  52. std::getline (std::cin,sdp);
  53. std::cout << "Got answer" << sdp << std::endl;
  54. json j = json::parse(sdp);
  55. rtc::Description answer(j["sdp"].get<std::string>(), j["type"].get<std::string>());
  56. pc->setRemoteDescription(answer, answer);
  57. std::cout << "Press any key to exit." << std::endl;
  58. std::cin >> sdp;
  59. }