blob: 2289df3bd9171137a88935031c7f9c58fbcdc67f [file] [log] [blame]
Tyler Chatowb3850c12020-02-26 20:55:48 -08001#define GST_USE_UNSTABLE_API
2#define GST_DISABLE_REGISTRY 1
3
4#include <glib-unix.h>
5#include <glib.h>
6#include <gst/app/app.h>
7#include <gst/gst.h>
8#include <gst/sdp/sdp.h>
9#include <gst/webrtc/icetransport.h>
10#include <gst/webrtc/webrtc.h>
11#include <sys/stat.h>
12#include <sys/types.h>
13
14#include <map>
15#include <thread>
16
17#include "absl/strings/str_format.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070018#include "flatbuffers/flatbuffers.h"
19#include "gflags/gflags.h"
20#include "glog/logging.h"
21
Tyler Chatowb3850c12020-02-26 20:55:48 -080022#include "aos/events/glib_main_loop.h"
23#include "aos/events/shm_event_loop.h"
24#include "aos/init.h"
25#include "aos/network/web_proxy_generated.h"
26#include "aos/seasocks/seasocks_logger.h"
Tyler Chatowb3850c12020-02-26 20:55:48 -080027#include "frc971/vision/vision_generated.h"
Tyler Chatowb3850c12020-02-26 20:55:48 -080028#include "internal/Embedded.h"
29#include "seasocks/Server.h"
30#include "seasocks/StringUtil.h"
31#include "seasocks/WebSocket.h"
32
milind-ub0773e92023-02-05 15:57:43 -080033DEFINE_string(config, "aos_config.json",
Tyler Chatowb3850c12020-02-26 20:55:48 -080034 "Name of the config file to replay using.");
Tyler Chatow39b6a322022-04-15 00:03:58 -070035DEFINE_string(device, "/dev/video0",
36 "Camera fd. Ignored if reading from channel");
Tyler Chatowb3850c12020-02-26 20:55:48 -080037DEFINE_string(data_dir, "image_streamer_www",
38 "Directory to serve data files from");
Austin Schuhf5dbe2c2024-04-06 16:10:24 -070039DEFINE_bool(publish_images, true,
40 "If true, publish images read from v4l2 to /camera.");
Tyler Chatowb3850c12020-02-26 20:55:48 -080041DEFINE_int32(width, 400, "Image width");
42DEFINE_int32(height, 300, "Image height");
43DEFINE_int32(framerate, 25, "Framerate (FPS)");
44DEFINE_int32(brightness, 50, "Camera brightness");
45DEFINE_int32(exposure, 300, "Manual exposure");
46DEFINE_int32(bitrate, 500000, "H264 encode bitrate");
milind-ub0773e92023-02-05 15:57:43 -080047DEFINE_int32(streaming_port, 1180, "Port to stream images on with seasocks");
Tyler Chatowb3850c12020-02-26 20:55:48 -080048DEFINE_int32(min_port, 5800, "Min rtp port");
49DEFINE_int32(max_port, 5810, "Max rtp port");
Tyler Chatow39b6a322022-04-15 00:03:58 -070050DEFINE_string(listen_on, "",
51 "Channel on which to receive frames from. Used in place of "
52 "internal V4L2 reader. Note: width and height MUST match the "
53 "expected size of channel images.");
Tyler Chatowb3850c12020-02-26 20:55:48 -080054
55class Connection;
56
57using aos::web_proxy::Payload;
58using aos::web_proxy::SdpType;
59using aos::web_proxy::WebSocketIce;
60using aos::web_proxy::WebSocketMessage;
61using aos::web_proxy::WebSocketSdp;
62
Tyler Chatow39b6a322022-04-15 00:03:58 -070063class GstSampleSource {
64 public:
65 GstSampleSource() = default;
66
67 virtual ~GstSampleSource() = default;
68
69 private:
70 GstSampleSource(const GstSampleSource &) = delete;
71};
72
73class V4L2Source : public GstSampleSource {
74 public:
75 V4L2Source(std::function<void(GstSample *)> callback)
76 : callback_(std::move(callback)) {
77 GError *error = NULL;
78
79 // Create pipeline to read from camera, pack into rtp stream, and dump
80 // stream to callback. v4l2 device should already be configured with correct
81 // bitrate from v4l2-ctl. do-timestamp marks the time the frame was taken to
82 // track when it should be dropped under latency.
83
84 // With the Pi's hardware encoder, we can encode and package the stream once
85 // and the clients will jump in at any point unsynchronized. With the stream
86 // from x264enc this doesn't seem to work. For now, just reencode for each
87 // client since we don't expect more than 1 or 2.
88
Austin Schuhf5dbe2c2024-04-06 16:10:24 -070089 std::string exposure;
90 if (FLAGS_exposure > 0) {
91 exposure = absl::StrFormat(",auto_exposure=1,exposure_time_absolute=%d",
92 FLAGS_exposure);
93 }
94
Tyler Chatow39b6a322022-04-15 00:03:58 -070095 pipeline_ = gst_parse_launch(
96 absl::StrFormat("v4l2src device=%s do-timestamp=true "
Austin Schuhf5dbe2c2024-04-06 16:10:24 -070097 "extra-controls=\"c,brightness=%d%s\" ! "
Tyler Chatow39b6a322022-04-15 00:03:58 -070098 "video/x-raw,width=%d,height=%d,framerate=%d/"
99 "1,format=YUY2 ! appsink "
100 "name=appsink "
101 "emit-signals=true sync=false async=false "
102 "caps=video/x-raw,format=YUY2",
Austin Schuhf5dbe2c2024-04-06 16:10:24 -0700103 FLAGS_device, FLAGS_brightness, exposure, FLAGS_width,
104 FLAGS_height, FLAGS_framerate)
Tyler Chatow39b6a322022-04-15 00:03:58 -0700105 .c_str(),
106 &error);
107
108 if (error != NULL) {
109 LOG(FATAL) << "Could not create v4l2 pipeline: " << error->message;
110 }
111
112 appsink_ = gst_bin_get_by_name(GST_BIN(pipeline_), "appsink");
113 if (appsink_ == NULL) {
114 LOG(FATAL) << "Could not get appsink";
115 }
116
117 g_signal_connect(appsink_, "new-sample",
118 G_CALLBACK(V4L2Source::OnSampleCallback),
119 static_cast<gpointer>(this));
120
121 gst_element_set_state(pipeline_, GST_STATE_PLAYING);
122 }
123
124 ~V4L2Source() {
125 if (pipeline_ != NULL) {
126 gst_element_set_state(GST_ELEMENT(pipeline_), GST_STATE_NULL);
127 gst_object_unref(GST_OBJECT(pipeline_));
128 gst_object_unref(GST_OBJECT(appsink_));
129 }
130 }
131
132 private:
133 static GstFlowReturn OnSampleCallback(GstElement *, gpointer user_data) {
134 static_cast<V4L2Source *>(user_data)->OnSample();
135 return GST_FLOW_OK;
136 }
137
138 void OnSample() {
139 GstSample *sample = gst_app_sink_pull_sample(GST_APP_SINK(appsink_));
140 if (sample == NULL) {
141 LOG(WARNING) << "Received null sample";
142 return;
143 }
144 callback_(sample);
145 gst_sample_unref(sample);
146 }
147
148 GstElement *pipeline_;
149 GstElement *appsink_;
150
151 std::function<void(GstSample *)> callback_;
152};
153
154class ChannelSource : public GstSampleSource {
155 public:
156 ChannelSource(aos::ShmEventLoop *event_loop,
157 std::function<void(GstSample *)> callback)
158 : callback_(std::move(callback)) {
159 event_loop->MakeWatcher(
160 FLAGS_listen_on,
161 [this](const frc971::vision::CameraImage &image) { OnImage(image); });
162 }
163
164 private:
165 void OnImage(const frc971::vision::CameraImage &image) {
166 if (!image.has_rows() || !image.has_cols() || !image.has_data()) {
167 VLOG(2) << "Skipping CameraImage with no data";
168 return;
169 }
170 CHECK_EQ(image.rows(), FLAGS_height);
171 CHECK_EQ(image.cols(), FLAGS_width);
172
173 GBytes *bytes = g_bytes_new(image.data()->data(), image.data()->size());
174 GstBuffer *buffer = gst_buffer_new_wrapped_bytes(bytes);
175
176 GST_BUFFER_PTS(buffer) = image.monotonic_timestamp_ns();
177
178 GstCaps *caps = CHECK_NOTNULL(gst_caps_new_simple(
179 "video/x-raw", "width", G_TYPE_INT, image.cols(), "height", G_TYPE_INT,
180 image.rows(), "format", G_TYPE_STRING, "YUY2", nullptr));
181
182 GstSample *sample = gst_sample_new(buffer, caps, nullptr, nullptr);
183
184 callback_(sample);
185
186 gst_sample_unref(sample);
187 gst_caps_unref(caps);
188 gst_buffer_unref(buffer);
189 g_bytes_unref(bytes);
190 }
191
192 std::function<void(GstSample *)> callback_;
193};
194
Tyler Chatowb3850c12020-02-26 20:55:48 -0800195// Basic class that handles receiving new websocket connections. Creates a new
196// Connection to manage the rest of the negotiation and data passing. When the
197// websocket closes, it deletes the Connection.
198class WebsocketHandler : public ::seasocks::WebSocket::Handler {
199 public:
200 WebsocketHandler(aos::ShmEventLoop *event_loop, ::seasocks::Server *server);
Tyler Chatow39b6a322022-04-15 00:03:58 -0700201 ~WebsocketHandler() override = default;
Tyler Chatowb3850c12020-02-26 20:55:48 -0800202
203 void onConnect(::seasocks::WebSocket *sock) override;
204 void onData(::seasocks::WebSocket *sock, const uint8_t *data,
205 size_t size) override;
206 void onDisconnect(::seasocks::WebSocket *sock) override;
207
208 private:
Tyler Chatow39b6a322022-04-15 00:03:58 -0700209 void OnSample(GstSample *sample);
Tyler Chatowb3850c12020-02-26 20:55:48 -0800210
211 std::map<::seasocks::WebSocket *, std::unique_ptr<Connection>> connections_;
212 ::seasocks::Server *server_;
Tyler Chatow39b6a322022-04-15 00:03:58 -0700213 std::unique_ptr<GstSampleSource> source_;
Tyler Chatowb3850c12020-02-26 20:55:48 -0800214
215 aos::Sender<frc971::vision::CameraImage> sender_;
216};
217
218// Seasocks requires that sends happen on the correct thread. This class takes a
219// detached buffer to send on a specific websocket connection and sends it when
220// seasocks is ready.
221class UpdateData : public ::seasocks::Server::Runnable {
222 public:
223 UpdateData(::seasocks::WebSocket *websocket,
224 flatbuffers::DetachedBuffer &&buffer)
225 : sock_(websocket), buffer_(std::move(buffer)) {}
226 ~UpdateData() override = default;
227 UpdateData(const UpdateData &) = delete;
228 UpdateData &operator=(const UpdateData &) = delete;
229
230 void run() override { sock_->send(buffer_.data(), buffer_.size()); }
231
232 private:
233 ::seasocks::WebSocket *sock_;
234 const flatbuffers::DetachedBuffer buffer_;
235};
236
237class Connection {
238 public:
239 Connection(::seasocks::WebSocket *sock, ::seasocks::Server *server);
240
241 ~Connection();
242
243 void HandleWebSocketData(const uint8_t *data, size_t size);
244
245 void OnSample(GstSample *sample);
246
247 private:
248 static void OnOfferCreatedCallback(GstPromise *promise, gpointer user_data) {
249 static_cast<Connection *>(user_data)->OnOfferCreated(promise);
250 }
251
252 static void OnNegotiationNeededCallback(GstElement *, gpointer user_data) {
253 static_cast<Connection *>(user_data)->OnNegotiationNeeded();
254 }
255
256 static void OnIceCandidateCallback(GstElement *, guint mline_index,
257 gchar *candidate, gpointer user_data) {
258 static_cast<Connection *>(user_data)->OnIceCandidate(mline_index,
259 candidate);
260 }
261
262 void OnOfferCreated(GstPromise *promise);
263 void OnNegotiationNeeded();
264 void OnIceCandidate(guint mline_index, gchar *candidate);
265
266 ::seasocks::WebSocket *sock_;
267 ::seasocks::Server *server_;
268
269 GstElement *pipeline_;
270 GstElement *webrtcbin_;
271 GstElement *appsrc_;
272
273 bool first_sample_ = true;
274};
275
276WebsocketHandler::WebsocketHandler(aos::ShmEventLoop *event_loop,
277 ::seasocks::Server *server)
Tyler Chatow39b6a322022-04-15 00:03:58 -0700278 : server_(server) {
279 if (FLAGS_listen_on.empty()) {
Austin Schuhf5dbe2c2024-04-06 16:10:24 -0700280 if (FLAGS_publish_images) {
281 sender_ = event_loop->MakeSender<frc971::vision::CameraImage>("/camera");
282 }
Tyler Chatow39b6a322022-04-15 00:03:58 -0700283 source_ =
284 std::make_unique<V4L2Source>([this](auto sample) { OnSample(sample); });
285 } else {
286 source_ = std::make_unique<ChannelSource>(
287 event_loop, [this](auto sample) { OnSample(sample); });
Tyler Chatowb3850c12020-02-26 20:55:48 -0800288 }
289}
290
291void WebsocketHandler::onConnect(::seasocks::WebSocket *sock) {
292 std::unique_ptr<Connection> conn =
293 std::make_unique<Connection>(sock, server_);
294 connections_.insert({sock, std::move(conn)});
295}
296
297void WebsocketHandler::onData(::seasocks::WebSocket *sock, const uint8_t *data,
298 size_t size) {
299 connections_[sock]->HandleWebSocketData(data, size);
300}
301
Tyler Chatow39b6a322022-04-15 00:03:58 -0700302void WebsocketHandler::OnSample(GstSample *sample) {
Tyler Chatowb3850c12020-02-26 20:55:48 -0800303 for (auto iter = connections_.begin(); iter != connections_.end(); ++iter) {
304 iter->second->OnSample(sample);
305 }
306
Tyler Chatow39b6a322022-04-15 00:03:58 -0700307 if (sender_.valid()) {
Tyler Chatowb3850c12020-02-26 20:55:48 -0800308 const GstCaps *caps = CHECK_NOTNULL(gst_sample_get_caps(sample));
309 CHECK_GT(gst_caps_get_size(caps), 0U);
310 const GstStructure *str = gst_caps_get_structure(caps, 0);
311
312 gint width;
313 gint height;
314
315 CHECK(gst_structure_get_int(str, "width", &width));
316 CHECK(gst_structure_get_int(str, "height", &height));
317
318 GstBuffer *buffer = CHECK_NOTNULL(gst_sample_get_buffer(sample));
319
320 const gsize size = gst_buffer_get_size(buffer);
321
322 auto builder = sender_.MakeBuilder();
323
324 uint8_t *image_data;
325 auto image_offset =
326 builder.fbb()->CreateUninitializedVector(size, &image_data);
327 gst_buffer_extract(buffer, 0, image_data, size);
328
329 auto image_builder = builder.MakeBuilder<frc971::vision::CameraImage>();
330 image_builder.add_rows(height);
331 image_builder.add_cols(width);
332 image_builder.add_data(image_offset);
333
334 builder.CheckOk(builder.Send(image_builder.Finish()));
335 }
Tyler Chatowb3850c12020-02-26 20:55:48 -0800336}
337
338void WebsocketHandler::onDisconnect(::seasocks::WebSocket *sock) {
339 connections_.erase(sock);
340}
341
342Connection::Connection(::seasocks::WebSocket *sock, ::seasocks::Server *server)
343 : sock_(sock), server_(server) {
344 GError *error = NULL;
345
346 // Build pipeline to read data from application into pipeline, place in
347 // webrtcbin group, and stream.
348
349 pipeline_ = gst_parse_launch(
350 // aggregate-mode should be zero-latency but this drops the stream on
351 // bitrate spikes for some reason - probably the weak CPU on the pi.
352 absl::StrFormat(
353 "webrtcbin name=webrtcbin appsrc "
354 "name=appsrc block=false "
355 "is-live=true "
356 "format=3 max-buffers=0 leaky-type=2 "
357 "caps=video/x-raw,width=%d,height=%d,format=YUY2 ! videoconvert ! "
358 "x264enc bitrate=%d speed-preset=ultrafast "
359 "tune=zerolatency key-int-max=15 sliced-threads=true ! "
360 "video/x-h264,profile=constrained-baseline ! h264parse ! "
361 "rtph264pay "
362 "config-interval=-1 name=payloader aggregate-mode=none ! "
363 "application/"
364 "x-rtp,media=video,encoding-name=H264,payload=96,clock-rate=90000 !"
365 "webrtcbin. ",
366 FLAGS_width, FLAGS_height, FLAGS_bitrate / 1000)
367 .c_str(),
368 &error);
369
370 if (error != NULL) {
371 LOG(FATAL) << "Could not create WebRTC pipeline: " << error->message;
372 }
373
374 webrtcbin_ = gst_bin_get_by_name(GST_BIN(pipeline_), "webrtcbin");
375 if (webrtcbin_ == NULL) {
376 LOG(FATAL) << "Could not initialize webrtcbin";
377 }
378
379 appsrc_ = gst_bin_get_by_name(GST_BIN(pipeline_), "appsrc");
380 if (appsrc_ == NULL) {
381 LOG(FATAL) << "Could not initialize appsrc";
382 }
383
384 {
385 GArray *transceivers;
386 g_signal_emit_by_name(webrtcbin_, "get-transceivers", &transceivers);
387 if (transceivers == NULL || transceivers->len <= 0) {
388 LOG(FATAL) << "Could not initialize transceivers";
389 }
390
391 GstWebRTCRTPTransceiver *trans =
392 g_array_index(transceivers, GstWebRTCRTPTransceiver *, 0);
393 g_object_set(trans, "direction",
394 GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_SENDONLY, nullptr);
395
396 g_array_unref(transceivers);
397 }
398
399 {
400 GstObject *ice = nullptr;
401 g_object_get(G_OBJECT(webrtcbin_), "ice-agent", &ice, nullptr);
402 CHECK_NOTNULL(ice);
403
404 g_object_set(ice, "min-rtp-port", FLAGS_min_port, "max-rtp-port",
405 FLAGS_max_port, nullptr);
406
407 // We don't need upnp on a local network.
408 {
409 GstObject *nice = nullptr;
410 g_object_get(ice, "agent", &nice, nullptr);
411 CHECK_NOTNULL(nice);
412
413 g_object_set(nice, "upnp", false, nullptr);
414 g_object_unref(nice);
415 }
416
417 gst_object_unref(ice);
418 }
419
420 g_signal_connect(webrtcbin_, "on-negotiation-needed",
421 G_CALLBACK(Connection::OnNegotiationNeededCallback),
422 static_cast<gpointer>(this));
423
424 g_signal_connect(webrtcbin_, "on-ice-candidate",
425 G_CALLBACK(Connection::OnIceCandidateCallback),
426 static_cast<gpointer>(this));
427
428 gst_element_set_state(pipeline_, GST_STATE_READY);
429 gst_element_set_state(pipeline_, GST_STATE_PLAYING);
430}
431
432Connection::~Connection() {
433 if (pipeline_ != NULL) {
434 gst_element_set_state(pipeline_, GST_STATE_NULL);
435
436 gst_object_unref(GST_OBJECT(webrtcbin_));
437 gst_object_unref(GST_OBJECT(pipeline_));
438 gst_object_unref(GST_OBJECT(appsrc_));
439 }
440}
441
442void Connection::OnSample(GstSample *sample) {
443 GstFlowReturn response =
444 gst_app_src_push_sample(GST_APP_SRC(appsrc_), sample);
445 if (response != GST_FLOW_OK) {
446 LOG(WARNING) << "Sample pushed, did not receive OK";
447 }
448
449 // Since the stream is already running (the camera turns on with
450 // image_streamer) we need to tell the new appsrc where
451 // we are starting in the stream so it can catch up immediately.
452 if (first_sample_) {
453 GstPad *src = gst_element_get_static_pad(appsrc_, "src");
454 if (src == NULL) {
455 return;
456 }
457
458 GstSegment *segment = gst_sample_get_segment(sample);
459 GstBuffer *buffer = gst_sample_get_buffer(sample);
460
461 guint64 offset = gst_segment_to_running_time(segment, GST_FORMAT_TIME,
462 GST_BUFFER_PTS(buffer));
463 LOG(INFO) << "Fixing offset " << offset;
464 gst_pad_set_offset(src, -offset);
465
466 gst_object_unref(GST_OBJECT(src));
467 first_sample_ = false;
468 }
469}
470
471void Connection::OnOfferCreated(GstPromise *promise) {
472 LOG(INFO) << "OnOfferCreated";
473
474 GstWebRTCSessionDescription *offer = NULL;
475 gst_structure_get(gst_promise_get_reply(promise), "offer",
476 GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &offer, NULL);
477 gst_promise_unref(promise);
478
479 {
480 std::unique_ptr<GstPromise, decltype(&gst_promise_unref)>
481 local_desc_promise(gst_promise_new(), &gst_promise_unref);
482 g_signal_emit_by_name(webrtcbin_, "set-local-description", offer,
483 local_desc_promise.get());
484 gst_promise_interrupt(local_desc_promise.get());
485 }
486
487 GstSDPMessage *sdp_msg = offer->sdp;
488 std::string sdp_str(gst_sdp_message_as_text(sdp_msg));
489
490 LOG(INFO) << "Negotiation offer created:\n" << sdp_str;
491
492 flatbuffers::FlatBufferBuilder fbb(512);
493 flatbuffers::Offset<WebSocketSdp> sdp_fb =
494 CreateWebSocketSdpDirect(fbb, SdpType::OFFER, sdp_str.c_str());
495 flatbuffers::Offset<WebSocketMessage> answer_message =
496 CreateWebSocketMessage(fbb, Payload::WebSocketSdp, sdp_fb.Union());
497 fbb.Finish(answer_message);
498
499 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
500}
501
502void Connection::OnNegotiationNeeded() {
503 LOG(INFO) << "OnNegotiationNeeded";
504
505 GstPromise *promise;
506 promise = gst_promise_new_with_change_func(Connection::OnOfferCreatedCallback,
507 static_cast<gpointer>(this), NULL);
508 g_signal_emit_by_name(G_OBJECT(webrtcbin_), "create-offer", NULL, promise);
509}
510
511void Connection::OnIceCandidate(guint mline_index, gchar *candidate) {
512 LOG(INFO) << "OnIceCandidate";
513
514 flatbuffers::FlatBufferBuilder fbb(512);
515
Austin Schuhf5dbe2c2024-04-06 16:10:24 -0700516 flatbuffers::Offset<flatbuffers::String> sdp_mid_offset =
517 fbb.CreateString("video0");
518 flatbuffers::Offset<flatbuffers::String> candidate_offset =
519 fbb.CreateString(static_cast<char *>(candidate));
520
Tyler Chatowb3850c12020-02-26 20:55:48 -0800521 auto ice_fb_builder = WebSocketIce::Builder(fbb);
522 ice_fb_builder.add_sdp_m_line_index(mline_index);
Austin Schuhf5dbe2c2024-04-06 16:10:24 -0700523 ice_fb_builder.add_sdp_mid(sdp_mid_offset);
524 ice_fb_builder.add_candidate(candidate_offset);
Tyler Chatowb3850c12020-02-26 20:55:48 -0800525 flatbuffers::Offset<WebSocketIce> ice_fb = ice_fb_builder.Finish();
526
527 flatbuffers::Offset<WebSocketMessage> ice_message =
528 CreateWebSocketMessage(fbb, Payload::WebSocketIce, ice_fb.Union());
529 fbb.Finish(ice_message);
530
531 server_->execute(std::make_shared<UpdateData>(sock_, fbb.Release()));
532
533 g_signal_emit_by_name(webrtcbin_, "add-ice-candidate", mline_index,
534 candidate);
535}
536
537void Connection::HandleWebSocketData(const uint8_t *data, size_t /* size*/) {
538 LOG(INFO) << "HandleWebSocketData";
539
540 const WebSocketMessage *message =
541 flatbuffers::GetRoot<WebSocketMessage>(data);
542
543 switch (message->payload_type()) {
544 case Payload::WebSocketSdp: {
545 const WebSocketSdp *offer = message->payload_as_WebSocketSdp();
546 if (offer->type() != SdpType::ANSWER) {
547 LOG(WARNING) << "Expected SDP message type \"answer\"";
548 break;
549 }
550 const flatbuffers::String *sdp_string = offer->payload();
551
552 LOG(INFO) << "Received SDP:\n" << sdp_string->c_str();
553
554 GstSDPMessage *sdp;
555 GstSDPResult status = gst_sdp_message_new(&sdp);
556 if (status != GST_SDP_OK) {
557 LOG(WARNING) << "Could not create SDP message";
558 break;
559 }
560
561 status = gst_sdp_message_parse_buffer((const guint8 *)sdp_string->c_str(),
562 sdp_string->size(), sdp);
563
564 if (status != GST_SDP_OK) {
565 LOG(WARNING) << "Could not parse SDP string";
566 break;
567 }
568
569 std::unique_ptr<GstWebRTCSessionDescription,
570 decltype(&gst_webrtc_session_description_free)>
571 answer(gst_webrtc_session_description_new(GST_WEBRTC_SDP_TYPE_ANSWER,
572 sdp),
573 &gst_webrtc_session_description_free);
574 std::unique_ptr<GstPromise, decltype(&gst_promise_unref)> promise(
575 gst_promise_new(), &gst_promise_unref);
576 g_signal_emit_by_name(webrtcbin_, "set-remote-description", answer.get(),
577 promise.get());
578 gst_promise_interrupt(promise.get());
579
580 break;
581 }
582 case Payload::WebSocketIce: {
583 const WebSocketIce *ice = message->payload_as_WebSocketIce();
584 if (!ice->has_candidate() || ice->candidate()->size() == 0) {
585 LOG(WARNING) << "Received ICE message without candidate";
586 break;
587 }
588
589 const gchar *candidate =
590 static_cast<const gchar *>(ice->candidate()->c_str());
591 guint mline_index = ice->sdp_m_line_index();
592
593 LOG(INFO) << "Received ICE candidate with mline index " << mline_index
594 << "; candidate: " << candidate;
595
596 g_signal_emit_by_name(webrtcbin_, "add-ice-candidate", mline_index,
597 candidate);
598
599 break;
600 }
601 default:
602 break;
603 }
604}
605
Tyler Chatowb3850c12020-02-26 20:55:48 -0800606int main(int argc, char **argv) {
607 aos::InitGoogle(&argc, &argv);
608
609 findEmbeddedContent("");
610
611 std::string openssl_env = "OPENSSL_CONF=\"\"";
612 putenv(const_cast<char *>(openssl_env.c_str()));
613
Tyler Chatowb3850c12020-02-26 20:55:48 -0800614 gst_init(&argc, &argv);
Tyler Chatowb3850c12020-02-26 20:55:48 -0800615
616 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
617 aos::configuration::ReadConfig(FLAGS_config);
618 aos::ShmEventLoop event_loop(&config.message());
619
620 {
621 aos::GlibMainLoop main_loop(&event_loop);
622
623 seasocks::Server server(::std::shared_ptr<seasocks::Logger>(
624 new ::aos::seasocks::SeasocksLogger(seasocks::Logger::Level::Info)));
625
626 LOG(INFO) << "Serving from " << FLAGS_data_dir;
627
628 auto websocket_handler =
629 std::make_shared<WebsocketHandler>(&event_loop, &server);
630 server.addWebSocketHandler("/ws", websocket_handler);
631
milind-ub0773e92023-02-05 15:57:43 -0800632 server.startListening(FLAGS_streaming_port);
Tyler Chatowb3850c12020-02-26 20:55:48 -0800633 server.setStaticPath(FLAGS_data_dir.c_str());
634
635 aos::internal::EPoll *epoll = event_loop.epoll();
636
637 epoll->OnReadable(server.fd(), [&server] {
638 CHECK(::seasocks::Server::PollResult::Continue == server.poll(0));
639 });
640
641 event_loop.Run();
642
643 epoll->DeleteFd(server.fd());
644 server.terminate();
645 }
646
647 gst_deinit();
648
649 return 0;
650}