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