b51a345361c137721e8e8d23a367f61eafb16f11
[platform/upstream/gstreamer.git] / subprojects / gst-examples / webrtc / sendrecv / gst / webrtc-sendrecv.c
1 /*
2  * Demo gstreamer app for negotiating and streaming a sendrecv webrtc stream
3  * with a browser JS app.
4  *
5  * Build by running: `make webrtc-sendrecv`, or build the gstreamer monorepo.
6  *
7  * Author: Nirbheek Chauhan <nirbheek@centricular.com>
8  */
9 #include <gst/gst.h>
10 #include <gst/sdp/sdp.h>
11 #include <gst/rtp/rtp.h>
12
13 #define GST_USE_UNSTABLE_API
14 #include <gst/webrtc/webrtc.h>
15
16 /* For signalling */
17 #include <libsoup/soup.h>
18 #include <json-glib/json-glib.h>
19
20 #include <string.h>
21
22 enum AppState
23 {
24   APP_STATE_UNKNOWN = 0,
25   APP_STATE_ERROR = 1,          /* generic error */
26   SERVER_CONNECTING = 1000,
27   SERVER_CONNECTION_ERROR,
28   SERVER_CONNECTED,             /* Ready to register */
29   SERVER_REGISTERING = 2000,
30   SERVER_REGISTRATION_ERROR,
31   SERVER_REGISTERED,            /* Ready to call a peer */
32   SERVER_CLOSED,                /* server connection closed by us or the server */
33   PEER_CONNECTING = 3000,
34   PEER_CONNECTION_ERROR,
35   PEER_CONNECTED,
36   PEER_CALL_NEGOTIATING = 4000,
37   PEER_CALL_STARTED,
38   PEER_CALL_STOPPING,
39   PEER_CALL_STOPPED,
40   PEER_CALL_ERROR,
41 };
42
43 #define GST_CAT_DEFAULT webrtc_sendrecv_debug
44 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
45
46 static GMainLoop *loop;
47 static GstElement *pipe1, *webrtc1 = NULL;
48 static GObject *send_channel, *receive_channel;
49
50 static SoupWebsocketConnection *ws_conn = NULL;
51 static enum AppState app_state = 0;
52 static gchar *peer_id = NULL;
53 static gchar *our_id = NULL;
54 static const gchar *server_url = "wss://webrtc.nirbheek.in:8443";
55 static gboolean disable_ssl = FALSE;
56 static gboolean remote_is_offerer = FALSE;
57
58 static GOptionEntry entries[] = {
59   {"peer-id", 0, 0, G_OPTION_ARG_STRING, &peer_id,
60       "String ID of the peer to connect to", "ID"},
61   {"our-id", 0, 0, G_OPTION_ARG_STRING, &our_id,
62       "String ID that the peer can use to connect to us", "ID"},
63   {"server", 0, 0, G_OPTION_ARG_STRING, &server_url,
64       "Signalling server to connect to", "URL"},
65   {"disable-ssl", 0, 0, G_OPTION_ARG_NONE, &disable_ssl, "Disable ssl", NULL},
66   {"remote-offerer", 0, 0, G_OPTION_ARG_NONE, &remote_is_offerer,
67       "Request that the peer generate the offer and we'll answer", NULL},
68   {NULL},
69 };
70
71 static gboolean
72 cleanup_and_quit_loop (const gchar * msg, enum AppState state)
73 {
74   if (msg)
75     gst_printerr ("%s\n", msg);
76   if (state > 0)
77     app_state = state;
78
79   if (ws_conn) {
80     if (soup_websocket_connection_get_state (ws_conn) ==
81         SOUP_WEBSOCKET_STATE_OPEN)
82       /* This will call us again */
83       soup_websocket_connection_close (ws_conn, 1000, "");
84     else
85       g_clear_object (&ws_conn);
86   }
87
88   if (loop) {
89     g_main_loop_quit (loop);
90     g_clear_pointer (&loop, g_main_loop_unref);
91   }
92
93   /* To allow usage as a GSourceFunc */
94   return G_SOURCE_REMOVE;
95 }
96
97 static gchar *
98 get_string_from_json_object (JsonObject * object)
99 {
100   JsonNode *root;
101   JsonGenerator *generator;
102   gchar *text;
103
104   /* Make it the root node */
105   root = json_node_init_object (json_node_alloc (), object);
106   generator = json_generator_new ();
107   json_generator_set_root (generator, root);
108   text = json_generator_to_data (generator, NULL);
109
110   /* Release everything */
111   g_object_unref (generator);
112   json_node_free (root);
113   return text;
114 }
115
116 static void
117 handle_media_stream (GstPad * pad, GstElement * pipe, const char *convert_name,
118     const char *sink_name)
119 {
120   GstPad *qpad;
121   GstElement *q, *conv, *resample, *sink;
122   GstPadLinkReturn ret;
123
124   gst_println ("Trying to handle stream with %s ! %s", convert_name, sink_name);
125
126   q = gst_element_factory_make ("queue", NULL);
127   g_assert_nonnull (q);
128   conv = gst_element_factory_make (convert_name, NULL);
129   g_assert_nonnull (conv);
130   sink = gst_element_factory_make (sink_name, NULL);
131   g_assert_nonnull (sink);
132
133   if (g_strcmp0 (convert_name, "audioconvert") == 0) {
134     /* Might also need to resample, so add it just in case.
135      * Will be a no-op if it's not required. */
136     resample = gst_element_factory_make ("audioresample", NULL);
137     g_assert_nonnull (resample);
138     gst_bin_add_many (GST_BIN (pipe), q, conv, resample, sink, NULL);
139     gst_element_sync_state_with_parent (q);
140     gst_element_sync_state_with_parent (conv);
141     gst_element_sync_state_with_parent (resample);
142     gst_element_sync_state_with_parent (sink);
143     gst_element_link_many (q, conv, resample, sink, NULL);
144   } else {
145     gst_bin_add_many (GST_BIN (pipe), q, conv, sink, NULL);
146     gst_element_sync_state_with_parent (q);
147     gst_element_sync_state_with_parent (conv);
148     gst_element_sync_state_with_parent (sink);
149     gst_element_link_many (q, conv, sink, NULL);
150   }
151
152   qpad = gst_element_get_static_pad (q, "sink");
153
154   ret = gst_pad_link (pad, qpad);
155   g_assert_cmphex (ret, ==, GST_PAD_LINK_OK);
156 }
157
158 static void
159 on_incoming_decodebin_stream (GstElement * decodebin, GstPad * pad,
160     GstElement * pipe)
161 {
162   GstCaps *caps;
163   const gchar *name;
164
165   if (!gst_pad_has_current_caps (pad)) {
166     gst_printerr ("Pad '%s' has no caps, can't do anything, ignoring\n",
167         GST_PAD_NAME (pad));
168     return;
169   }
170
171   caps = gst_pad_get_current_caps (pad);
172   name = gst_structure_get_name (gst_caps_get_structure (caps, 0));
173
174   if (g_str_has_prefix (name, "video")) {
175     handle_media_stream (pad, pipe, "videoconvert", "autovideosink");
176   } else if (g_str_has_prefix (name, "audio")) {
177     handle_media_stream (pad, pipe, "audioconvert", "autoaudiosink");
178   } else {
179     gst_printerr ("Unknown pad %s, ignoring", GST_PAD_NAME (pad));
180   }
181 }
182
183 static void
184 on_incoming_stream (GstElement * webrtc, GstPad * pad, GstElement * pipe)
185 {
186   GstElement *decodebin;
187   GstPad *sinkpad;
188
189   if (GST_PAD_DIRECTION (pad) != GST_PAD_SRC)
190     return;
191
192   decodebin = gst_element_factory_make ("decodebin", NULL);
193   g_signal_connect (decodebin, "pad-added",
194       G_CALLBACK (on_incoming_decodebin_stream), pipe);
195   gst_bin_add (GST_BIN (pipe), decodebin);
196   gst_element_sync_state_with_parent (decodebin);
197
198   sinkpad = gst_element_get_static_pad (decodebin, "sink");
199   gst_pad_link (pad, sinkpad);
200   gst_object_unref (sinkpad);
201 }
202
203 static void
204 send_ice_candidate_message (GstElement * webrtc G_GNUC_UNUSED, guint mlineindex,
205     gchar * candidate, gpointer user_data G_GNUC_UNUSED)
206 {
207   gchar *text;
208   JsonObject *ice, *msg;
209
210   if (app_state < PEER_CALL_NEGOTIATING) {
211     cleanup_and_quit_loop ("Can't send ICE, not in call", APP_STATE_ERROR);
212     return;
213   }
214
215   ice = json_object_new ();
216   json_object_set_string_member (ice, "candidate", candidate);
217   json_object_set_int_member (ice, "sdpMLineIndex", mlineindex);
218   msg = json_object_new ();
219   json_object_set_object_member (msg, "ice", ice);
220   text = get_string_from_json_object (msg);
221   json_object_unref (msg);
222
223   soup_websocket_connection_send_text (ws_conn, text);
224   g_free (text);
225 }
226
227 static void
228 send_sdp_to_peer (GstWebRTCSessionDescription * desc)
229 {
230   gchar *text;
231   JsonObject *msg, *sdp;
232
233   if (app_state < PEER_CALL_NEGOTIATING) {
234     cleanup_and_quit_loop ("Can't send SDP to peer, not in call",
235         APP_STATE_ERROR);
236     return;
237   }
238
239   text = gst_sdp_message_as_text (desc->sdp);
240   sdp = json_object_new ();
241
242   if (desc->type == GST_WEBRTC_SDP_TYPE_OFFER) {
243     gst_print ("Sending offer:\n%s\n", text);
244     json_object_set_string_member (sdp, "type", "offer");
245   } else if (desc->type == GST_WEBRTC_SDP_TYPE_ANSWER) {
246     gst_print ("Sending answer:\n%s\n", text);
247     json_object_set_string_member (sdp, "type", "answer");
248   } else {
249     g_assert_not_reached ();
250   }
251
252   json_object_set_string_member (sdp, "sdp", text);
253   g_free (text);
254
255   msg = json_object_new ();
256   json_object_set_object_member (msg, "sdp", sdp);
257   text = get_string_from_json_object (msg);
258   json_object_unref (msg);
259
260   soup_websocket_connection_send_text (ws_conn, text);
261   g_free (text);
262 }
263
264 /* Offer created by our pipeline, to be sent to the peer */
265 static void
266 on_offer_created (GstPromise * promise, gpointer user_data)
267 {
268   GstWebRTCSessionDescription *offer = NULL;
269   const GstStructure *reply;
270
271   g_assert_cmphex (app_state, ==, PEER_CALL_NEGOTIATING);
272
273   g_assert_cmphex (gst_promise_wait (promise), ==, GST_PROMISE_RESULT_REPLIED);
274   reply = gst_promise_get_reply (promise);
275   gst_structure_get (reply, "offer",
276       GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &offer, NULL);
277   gst_promise_unref (promise);
278
279   promise = gst_promise_new ();
280   g_signal_emit_by_name (webrtc1, "set-local-description", offer, promise);
281   gst_promise_interrupt (promise);
282   gst_promise_unref (promise);
283
284   /* Send offer to peer */
285   send_sdp_to_peer (offer);
286   gst_webrtc_session_description_free (offer);
287 }
288
289 static void
290 on_negotiation_needed (GstElement * element, gpointer user_data)
291 {
292   gboolean create_offer = GPOINTER_TO_INT (user_data);
293   app_state = PEER_CALL_NEGOTIATING;
294
295   if (remote_is_offerer) {
296     soup_websocket_connection_send_text (ws_conn, "OFFER_REQUEST");
297   } else if (create_offer) {
298     GstPromise *promise =
299         gst_promise_new_with_change_func (on_offer_created, NULL, NULL);
300     g_signal_emit_by_name (webrtc1, "create-offer", NULL, promise);
301   }
302 }
303
304 #define STUN_SERVER " stun-server=stun://stun.l.google.com:19302 "
305 #define RTP_CAPS_OPUS "application/x-rtp,media=audio,encoding-name=OPUS,payload="
306 #define RTP_CAPS_VP8 "application/x-rtp,media=video,encoding-name=VP8,payload="
307
308 static void
309 data_channel_on_error (GObject * dc, gpointer user_data)
310 {
311   cleanup_and_quit_loop ("Data channel error", 0);
312 }
313
314 static void
315 data_channel_on_open (GObject * dc, gpointer user_data)
316 {
317   GBytes *bytes = g_bytes_new ("data", strlen ("data"));
318   gst_print ("data channel opened\n");
319   g_signal_emit_by_name (dc, "send-string", "Hi! from GStreamer");
320   g_signal_emit_by_name (dc, "send-data", bytes);
321   g_bytes_unref (bytes);
322 }
323
324 static void
325 data_channel_on_close (GObject * dc, gpointer user_data)
326 {
327   cleanup_and_quit_loop ("Data channel closed", 0);
328 }
329
330 static void
331 data_channel_on_message_string (GObject * dc, gchar * str, gpointer user_data)
332 {
333   gst_print ("Received data channel message: %s\n", str);
334 }
335
336 static void
337 connect_data_channel_signals (GObject * data_channel)
338 {
339   g_signal_connect (data_channel, "on-error",
340       G_CALLBACK (data_channel_on_error), NULL);
341   g_signal_connect (data_channel, "on-open", G_CALLBACK (data_channel_on_open),
342       NULL);
343   g_signal_connect (data_channel, "on-close",
344       G_CALLBACK (data_channel_on_close), NULL);
345   g_signal_connect (data_channel, "on-message-string",
346       G_CALLBACK (data_channel_on_message_string), NULL);
347 }
348
349 static void
350 on_data_channel (GstElement * webrtc, GObject * data_channel,
351     gpointer user_data)
352 {
353   connect_data_channel_signals (data_channel);
354   receive_channel = data_channel;
355 }
356
357 static void
358 on_ice_gathering_state_notify (GstElement * webrtcbin, GParamSpec * pspec,
359     gpointer user_data)
360 {
361   GstWebRTCICEGatheringState ice_gather_state;
362   const gchar *new_state = "unknown";
363
364   g_object_get (webrtcbin, "ice-gathering-state", &ice_gather_state, NULL);
365   switch (ice_gather_state) {
366     case GST_WEBRTC_ICE_GATHERING_STATE_NEW:
367       new_state = "new";
368       break;
369     case GST_WEBRTC_ICE_GATHERING_STATE_GATHERING:
370       new_state = "gathering";
371       break;
372     case GST_WEBRTC_ICE_GATHERING_STATE_COMPLETE:
373       new_state = "complete";
374       break;
375   }
376   gst_print ("ICE gathering state changed to %s\n", new_state);
377 }
378
379 static gboolean webrtcbin_get_stats (GstElement * webrtcbin);
380
381 static gboolean
382 on_webrtcbin_stat (GQuark field_id, const GValue * value, gpointer unused)
383 {
384   if (GST_VALUE_HOLDS_STRUCTURE (value)) {
385     GST_DEBUG ("stat: \'%s\': %" GST_PTR_FORMAT, g_quark_to_string (field_id),
386         gst_value_get_structure (value));
387   } else {
388     GST_FIXME ("unknown field \'%s\' value type: \'%s\'",
389         g_quark_to_string (field_id), g_type_name (G_VALUE_TYPE (value)));
390   }
391
392   return TRUE;
393 }
394
395 static void
396 on_webrtcbin_get_stats (GstPromise * promise, GstElement * webrtcbin)
397 {
398   const GstStructure *stats;
399
400   g_return_if_fail (gst_promise_wait (promise) == GST_PROMISE_RESULT_REPLIED);
401
402   stats = gst_promise_get_reply (promise);
403   gst_structure_foreach (stats, on_webrtcbin_stat, NULL);
404
405   g_timeout_add (100, (GSourceFunc) webrtcbin_get_stats, webrtcbin);
406 }
407
408 static gboolean
409 webrtcbin_get_stats (GstElement * webrtcbin)
410 {
411   GstPromise *promise;
412
413   promise =
414       gst_promise_new_with_change_func (
415       (GstPromiseChangeFunc) on_webrtcbin_get_stats, webrtcbin, NULL);
416
417   GST_TRACE ("emitting get-stats on %" GST_PTR_FORMAT, webrtcbin);
418   g_signal_emit_by_name (webrtcbin, "get-stats", NULL, promise);
419   gst_promise_unref (promise);
420
421   return G_SOURCE_REMOVE;
422 }
423
424 #define RTP_TWCC_URI "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"
425
426 static gboolean
427 start_pipeline (gboolean create_offer)
428 {
429   GstStateChangeReturn ret;
430   GError *error = NULL;
431
432   pipe1 =
433       gst_parse_launch ("webrtcbin bundle-policy=max-bundle name=sendrecv "
434       STUN_SERVER
435       "videotestsrc is-live=true pattern=ball ! videoconvert ! queue ! "
436       /* increase the default keyframe distance, browsers have really long
437        * periods between keyframes and rely on PLI events on packet loss to
438        * fix corrupted video.
439        */
440       "vp8enc deadline=1 keyframe-max-dist=2000 ! "
441       /* picture-id-mode=15-bit seems to make TWCC stats behave better, and
442        * fixes stuttery video playback in Chrome */
443       "rtpvp8pay name=videopay picture-id-mode=15-bit ! "
444       "queue ! " RTP_CAPS_VP8 "96 ! sendrecv. "
445       "audiotestsrc is-live=true wave=red-noise ! audioconvert ! audioresample ! queue ! opusenc ! rtpopuspay name=audiopay ! "
446       "queue ! " RTP_CAPS_OPUS "97 ! sendrecv. ", &error);
447
448   if (error) {
449     gst_printerr ("Failed to parse launch: %s\n", error->message);
450     g_error_free (error);
451     goto err;
452   }
453
454   webrtc1 = gst_bin_get_by_name (GST_BIN (pipe1), "sendrecv");
455   g_assert_nonnull (webrtc1);
456
457   if (remote_is_offerer) {
458     /* XXX: this will fail when the remote offers twcc as the extension id
459      * cannot currently be negotiated when receiving an offer.
460      */
461     GST_FIXME ("Need to implement header extension negotiation when "
462         "reciving a remote offers");
463   } else {
464     GstElement *videopay, *audiopay;
465     GstRTPHeaderExtension *video_twcc, *audio_twcc;
466
467     videopay = gst_bin_get_by_name (GST_BIN (pipe1), "videopay");
468     g_assert_nonnull (videopay);
469     video_twcc = gst_rtp_header_extension_create_from_uri (RTP_TWCC_URI);
470     g_assert_nonnull (video_twcc);
471     gst_rtp_header_extension_set_id (video_twcc, 1);
472     g_signal_emit_by_name (videopay, "add-extension", video_twcc);
473     g_clear_object (&video_twcc);
474     g_clear_object (&videopay);
475
476     audiopay = gst_bin_get_by_name (GST_BIN (pipe1), "audiopay");
477     g_assert_nonnull (audiopay);
478     audio_twcc = gst_rtp_header_extension_create_from_uri (RTP_TWCC_URI);
479     g_assert_nonnull (audio_twcc);
480     gst_rtp_header_extension_set_id (audio_twcc, 1);
481     g_signal_emit_by_name (audiopay, "add-extension", audio_twcc);
482     g_clear_object (&audio_twcc);
483     g_clear_object (&audiopay);
484   }
485
486   /* This is the gstwebrtc entry point where we create the offer and so on. It
487    * will be called when the pipeline goes to PLAYING. */
488   g_signal_connect (webrtc1, "on-negotiation-needed",
489       G_CALLBACK (on_negotiation_needed), GINT_TO_POINTER (create_offer));
490   /* We need to transmit this ICE candidate to the browser via the websockets
491    * signalling server. Incoming ice candidates from the browser need to be
492    * added by us too, see on_server_message() */
493   g_signal_connect (webrtc1, "on-ice-candidate",
494       G_CALLBACK (send_ice_candidate_message), NULL);
495   g_signal_connect (webrtc1, "notify::ice-gathering-state",
496       G_CALLBACK (on_ice_gathering_state_notify), NULL);
497
498   gst_element_set_state (pipe1, GST_STATE_READY);
499
500   g_signal_emit_by_name (webrtc1, "create-data-channel", "channel", NULL,
501       &send_channel);
502   if (send_channel) {
503     gst_print ("Created data channel\n");
504     connect_data_channel_signals (send_channel);
505   } else {
506     gst_print ("Could not create data channel, is usrsctp available?\n");
507   }
508
509   g_signal_connect (webrtc1, "on-data-channel", G_CALLBACK (on_data_channel),
510       NULL);
511   /* Incoming streams will be exposed via this signal */
512   g_signal_connect (webrtc1, "pad-added", G_CALLBACK (on_incoming_stream),
513       pipe1);
514   /* Lifetime is the same as the pipeline itself */
515   gst_object_unref (webrtc1);
516
517   g_timeout_add (100, (GSourceFunc) webrtcbin_get_stats, webrtc1);
518
519   gst_print ("Starting pipeline\n");
520   ret = gst_element_set_state (GST_ELEMENT (pipe1), GST_STATE_PLAYING);
521   if (ret == GST_STATE_CHANGE_FAILURE)
522     goto err;
523
524   return TRUE;
525
526 err:
527   if (pipe1)
528     g_clear_object (&pipe1);
529   if (webrtc1)
530     webrtc1 = NULL;
531   return FALSE;
532 }
533
534 static gboolean
535 setup_call (void)
536 {
537   gchar *msg;
538
539   if (soup_websocket_connection_get_state (ws_conn) !=
540       SOUP_WEBSOCKET_STATE_OPEN)
541     return FALSE;
542
543   if (!peer_id)
544     return FALSE;
545
546   gst_print ("Setting up signalling server call with %s\n", peer_id);
547   app_state = PEER_CONNECTING;
548   msg = g_strdup_printf ("SESSION %s", peer_id);
549   soup_websocket_connection_send_text (ws_conn, msg);
550   g_free (msg);
551   return TRUE;
552 }
553
554 static gboolean
555 register_with_server (void)
556 {
557   gchar *hello;
558
559   if (soup_websocket_connection_get_state (ws_conn) !=
560       SOUP_WEBSOCKET_STATE_OPEN)
561     return FALSE;
562
563   if (!our_id) {
564     gint32 id;
565
566     id = g_random_int_range (10, 10000);
567     gst_print ("Registering id %i with server\n", id);
568
569     hello = g_strdup_printf ("HELLO %i", id);
570   } else {
571     gst_print ("Registering id %s with server\n", our_id);
572
573     hello = g_strdup_printf ("HELLO %s", our_id);
574   }
575
576   app_state = SERVER_REGISTERING;
577
578   /* Register with the server with a random integer id. Reply will be received
579    * by on_server_message() */
580   soup_websocket_connection_send_text (ws_conn, hello);
581   g_free (hello);
582
583   return TRUE;
584 }
585
586 static void
587 on_server_closed (SoupWebsocketConnection * conn G_GNUC_UNUSED,
588     gpointer user_data G_GNUC_UNUSED)
589 {
590   app_state = SERVER_CLOSED;
591   cleanup_and_quit_loop ("Server connection closed", 0);
592 }
593
594 /* Answer created by our pipeline, to be sent to the peer */
595 static void
596 on_answer_created (GstPromise * promise, gpointer user_data)
597 {
598   GstWebRTCSessionDescription *answer = NULL;
599   const GstStructure *reply;
600
601   g_assert_cmphex (app_state, ==, PEER_CALL_NEGOTIATING);
602
603   g_assert_cmphex (gst_promise_wait (promise), ==, GST_PROMISE_RESULT_REPLIED);
604   reply = gst_promise_get_reply (promise);
605   gst_structure_get (reply, "answer",
606       GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &answer, NULL);
607   gst_promise_unref (promise);
608
609   promise = gst_promise_new ();
610   g_signal_emit_by_name (webrtc1, "set-local-description", answer, promise);
611   gst_promise_interrupt (promise);
612   gst_promise_unref (promise);
613
614   /* Send answer to peer */
615   send_sdp_to_peer (answer);
616   gst_webrtc_session_description_free (answer);
617 }
618
619 static void
620 on_offer_set (GstPromise * promise, gpointer user_data)
621 {
622   gst_promise_unref (promise);
623   promise = gst_promise_new_with_change_func (on_answer_created, NULL, NULL);
624   g_signal_emit_by_name (webrtc1, "create-answer", NULL, promise);
625 }
626
627 static void
628 on_offer_received (GstSDPMessage * sdp)
629 {
630   GstWebRTCSessionDescription *offer = NULL;
631   GstPromise *promise;
632
633   offer = gst_webrtc_session_description_new (GST_WEBRTC_SDP_TYPE_OFFER, sdp);
634   g_assert_nonnull (offer);
635
636   /* Set remote description on our pipeline */
637   {
638     promise = gst_promise_new_with_change_func (on_offer_set, NULL, NULL);
639     g_signal_emit_by_name (webrtc1, "set-remote-description", offer, promise);
640   }
641   gst_webrtc_session_description_free (offer);
642 }
643
644 /* One mega message handler for our asynchronous calling mechanism */
645 static void
646 on_server_message (SoupWebsocketConnection * conn, SoupWebsocketDataType type,
647     GBytes * message, gpointer user_data)
648 {
649   gchar *text;
650
651   switch (type) {
652     case SOUP_WEBSOCKET_DATA_BINARY:
653       gst_printerr ("Received unknown binary message, ignoring\n");
654       return;
655     case SOUP_WEBSOCKET_DATA_TEXT:{
656       gsize size;
657       const gchar *data = g_bytes_get_data (message, &size);
658       /* Convert to NULL-terminated string */
659       text = g_strndup (data, size);
660       break;
661     }
662     default:
663       g_assert_not_reached ();
664   }
665
666   if (g_strcmp0 (text, "HELLO") == 0) {
667     /* Server has accepted our registration, we are ready to send commands */
668     if (app_state != SERVER_REGISTERING) {
669       cleanup_and_quit_loop ("ERROR: Received HELLO when not registering",
670           APP_STATE_ERROR);
671       goto out;
672     }
673     app_state = SERVER_REGISTERED;
674     gst_print ("Registered with server\n");
675     if (!our_id) {
676       /* Ask signalling server to connect us with a specific peer */
677       if (!setup_call ()) {
678         cleanup_and_quit_loop ("ERROR: Failed to setup call", PEER_CALL_ERROR);
679         goto out;
680       }
681     } else {
682       gst_println ("Waiting for connection from peer (our-id: %s)", our_id);
683     }
684   } else if (g_strcmp0 (text, "SESSION_OK") == 0) {
685     /* The call initiated by us has been setup by the server; now we can start
686      * negotiation */
687     if (app_state != PEER_CONNECTING) {
688       cleanup_and_quit_loop ("ERROR: Received SESSION_OK when not calling",
689           PEER_CONNECTION_ERROR);
690       goto out;
691     }
692
693     app_state = PEER_CONNECTED;
694     /* Start negotiation (exchange SDP and ICE candidates) */
695     if (!start_pipeline (TRUE))
696       cleanup_and_quit_loop ("ERROR: failed to start pipeline",
697           PEER_CALL_ERROR);
698   } else if (g_strcmp0 (text, "OFFER_REQUEST") == 0) {
699     if (app_state != SERVER_REGISTERED) {
700       gst_printerr ("Received OFFER_REQUEST at a strange time, ignoring\n");
701       goto out;
702     }
703     gst_print ("Received OFFER_REQUEST, sending offer\n");
704     /* Peer wants us to start negotiation (exchange SDP and ICE candidates) */
705     if (!start_pipeline (TRUE))
706       cleanup_and_quit_loop ("ERROR: failed to start pipeline",
707           PEER_CALL_ERROR);
708   } else if (g_str_has_prefix (text, "ERROR")) {
709     /* Handle errors */
710     switch (app_state) {
711       case SERVER_CONNECTING:
712         app_state = SERVER_CONNECTION_ERROR;
713         break;
714       case SERVER_REGISTERING:
715         app_state = SERVER_REGISTRATION_ERROR;
716         break;
717       case PEER_CONNECTING:
718         app_state = PEER_CONNECTION_ERROR;
719         break;
720       case PEER_CONNECTED:
721       case PEER_CALL_NEGOTIATING:
722         app_state = PEER_CALL_ERROR;
723         break;
724       default:
725         app_state = APP_STATE_ERROR;
726     }
727     cleanup_and_quit_loop (text, 0);
728   } else {
729     /* Look for JSON messages containing SDP and ICE candidates */
730     JsonNode *root;
731     JsonObject *object, *child;
732     JsonParser *parser = json_parser_new ();
733     if (!json_parser_load_from_data (parser, text, -1, NULL)) {
734       gst_printerr ("Unknown message '%s', ignoring\n", text);
735       g_object_unref (parser);
736       goto out;
737     }
738
739     root = json_parser_get_root (parser);
740     if (!JSON_NODE_HOLDS_OBJECT (root)) {
741       gst_printerr ("Unknown json message '%s', ignoring\n", text);
742       g_object_unref (parser);
743       goto out;
744     }
745
746     /* If peer connection wasn't made yet and we are expecting peer will
747      * connect to us, launch pipeline at this moment */
748     if (!webrtc1 && our_id) {
749       if (!start_pipeline (FALSE)) {
750         cleanup_and_quit_loop ("ERROR: failed to start pipeline",
751             PEER_CALL_ERROR);
752       }
753
754       app_state = PEER_CALL_NEGOTIATING;
755     }
756
757     object = json_node_get_object (root);
758     /* Check type of JSON message */
759     if (json_object_has_member (object, "sdp")) {
760       int ret;
761       GstSDPMessage *sdp;
762       const gchar *text, *sdptype;
763       GstWebRTCSessionDescription *answer;
764
765       g_assert_cmphex (app_state, ==, PEER_CALL_NEGOTIATING);
766
767       child = json_object_get_object_member (object, "sdp");
768
769       if (!json_object_has_member (child, "type")) {
770         cleanup_and_quit_loop ("ERROR: received SDP without 'type'",
771             PEER_CALL_ERROR);
772         goto out;
773       }
774
775       sdptype = json_object_get_string_member (child, "type");
776       /* In this example, we create the offer and receive one answer by default,
777        * but it's possible to comment out the offer creation and wait for an offer
778        * instead, so we handle either here.
779        *
780        * See tests/examples/webrtcbidirectional.c in gst-plugins-bad for another
781        * example how to handle offers from peers and reply with answers using webrtcbin. */
782       text = json_object_get_string_member (child, "sdp");
783       ret = gst_sdp_message_new (&sdp);
784       g_assert_cmphex (ret, ==, GST_SDP_OK);
785       ret = gst_sdp_message_parse_buffer ((guint8 *) text, strlen (text), sdp);
786       g_assert_cmphex (ret, ==, GST_SDP_OK);
787
788       if (g_str_equal (sdptype, "answer")) {
789         gst_print ("Received answer:\n%s\n", text);
790         answer = gst_webrtc_session_description_new (GST_WEBRTC_SDP_TYPE_ANSWER,
791             sdp);
792         g_assert_nonnull (answer);
793
794         /* Set remote description on our pipeline */
795         {
796           GstPromise *promise = gst_promise_new ();
797           g_signal_emit_by_name (webrtc1, "set-remote-description", answer,
798               promise);
799           gst_promise_interrupt (promise);
800           gst_promise_unref (promise);
801         }
802         app_state = PEER_CALL_STARTED;
803       } else {
804         gst_print ("Received offer:\n%s\n", text);
805         on_offer_received (sdp);
806       }
807
808     } else if (json_object_has_member (object, "ice")) {
809       const gchar *candidate;
810       gint sdpmlineindex;
811
812       child = json_object_get_object_member (object, "ice");
813       candidate = json_object_get_string_member (child, "candidate");
814       sdpmlineindex = json_object_get_int_member (child, "sdpMLineIndex");
815
816       /* Add ice candidate sent by remote peer */
817       g_signal_emit_by_name (webrtc1, "add-ice-candidate", sdpmlineindex,
818           candidate);
819     } else {
820       gst_printerr ("Ignoring unknown JSON message:\n%s\n", text);
821     }
822     g_object_unref (parser);
823   }
824
825 out:
826   g_free (text);
827 }
828
829 static void
830 on_server_connected (SoupSession * session, GAsyncResult * res,
831     SoupMessage * msg)
832 {
833   GError *error = NULL;
834
835   ws_conn = soup_session_websocket_connect_finish (session, res, &error);
836   if (error) {
837     cleanup_and_quit_loop (error->message, SERVER_CONNECTION_ERROR);
838     g_error_free (error);
839     return;
840   }
841
842   g_assert_nonnull (ws_conn);
843
844   app_state = SERVER_CONNECTED;
845   gst_print ("Connected to signalling server\n");
846
847   g_signal_connect (ws_conn, "closed", G_CALLBACK (on_server_closed), NULL);
848   g_signal_connect (ws_conn, "message", G_CALLBACK (on_server_message), NULL);
849
850   /* Register with the server so it knows about us and can accept commands */
851   register_with_server ();
852 }
853
854 /*
855  * Connect to the signalling server. This is the entrypoint for everything else.
856  */
857 static void
858 connect_to_websocket_server_async (void)
859 {
860   SoupLogger *logger;
861   SoupMessage *message;
862   SoupSession *session;
863   const char *https_aliases[] = { "wss", NULL };
864
865   session =
866       soup_session_new_with_options (SOUP_SESSION_SSL_STRICT, !disable_ssl,
867       SOUP_SESSION_SSL_USE_SYSTEM_CA_FILE, TRUE,
868       //SOUP_SESSION_SSL_CA_FILE, "/etc/ssl/certs/ca-bundle.crt",
869       SOUP_SESSION_HTTPS_ALIASES, https_aliases, NULL);
870
871   logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, -1);
872   soup_session_add_feature (session, SOUP_SESSION_FEATURE (logger));
873   g_object_unref (logger);
874
875   message = soup_message_new (SOUP_METHOD_GET, server_url);
876
877   gst_print ("Connecting to server...\n");
878
879   /* Once connected, we will register */
880   soup_session_websocket_connect_async (session, message, NULL, NULL, NULL,
881       (GAsyncReadyCallback) on_server_connected, message);
882   app_state = SERVER_CONNECTING;
883 }
884
885 static gboolean
886 check_plugins (void)
887 {
888   int i;
889   gboolean ret;
890   GstPlugin *plugin;
891   GstRegistry *registry;
892   const gchar *needed[] = { "opus", "vpx", "nice", "webrtc", "dtls", "srtp",
893     "rtpmanager", "videotestsrc", "audiotestsrc", NULL
894   };
895
896   registry = gst_registry_get ();
897   ret = TRUE;
898   for (i = 0; i < g_strv_length ((gchar **) needed); i++) {
899     plugin = gst_registry_find_plugin (registry, needed[i]);
900     if (!plugin) {
901       gst_print ("Required gstreamer plugin '%s' not found\n", needed[i]);
902       ret = FALSE;
903       continue;
904     }
905     gst_object_unref (plugin);
906   }
907   return ret;
908 }
909
910 int
911 main (int argc, char *argv[])
912 {
913   GOptionContext *context;
914   GError *error = NULL;
915   int ret_code = -1;
916
917   context = g_option_context_new ("- gstreamer webrtc sendrecv demo");
918   g_option_context_add_main_entries (context, entries, NULL);
919   g_option_context_add_group (context, gst_init_get_option_group ());
920   if (!g_option_context_parse (context, &argc, &argv, &error)) {
921     gst_printerr ("Error initializing: %s\n", error->message);
922     return -1;
923   }
924
925   GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "webrtc-sendrecv", 0,
926       "WebRTC Sending and Receiving example");
927
928   if (!check_plugins ()) {
929     goto out;
930   }
931
932   if (!peer_id && !our_id) {
933     gst_printerr ("--peer-id or --our-id is a required argument\n");
934     goto out;
935   }
936
937   if (peer_id && our_id) {
938     gst_printerr ("specify only --peer-id or --our-id\n");
939     goto out;
940   }
941
942   ret_code = 0;
943
944   /* Disable ssl when running a localhost server, because
945    * it's probably a test server with a self-signed certificate */
946   {
947     GstUri *uri = gst_uri_from_string (server_url);
948     if (g_strcmp0 ("localhost", gst_uri_get_host (uri)) == 0 ||
949         g_strcmp0 ("127.0.0.1", gst_uri_get_host (uri)) == 0)
950       disable_ssl = TRUE;
951     gst_uri_unref (uri);
952   }
953
954   loop = g_main_loop_new (NULL, FALSE);
955
956   connect_to_websocket_server_async ();
957
958   g_main_loop_run (loop);
959
960   if (loop)
961     g_main_loop_unref (loop);
962
963   if (pipe1) {
964     gst_element_set_state (GST_ELEMENT (pipe1), GST_STATE_NULL);
965     gst_print ("Pipeline stopped\n");
966     gst_object_unref (pipe1);
967   }
968
969 out:
970   g_free (peer_id);
971   g_free (our_id);
972
973   return ret_code;
974 }