2 * Demo gstreamer app for negotiating and streaming a sendrecv webrtc stream
3 * with a browser JS app.
5 * Build by running: `make webrtc-sendrecv`, or build the gstreamer monorepo.
7 * Author: Nirbheek Chauhan <nirbheek@centricular.com>
10 #include <gst/sdp/sdp.h>
11 #include <gst/rtp/rtp.h>
13 #include <gst/webrtc/webrtc.h>
14 #include <gst/webrtc/nice/nice.h>
16 #include "custom_agent.h"
19 #include <libsoup/soup.h>
20 #include <json-glib/json-glib.h>
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,
38 PEER_CALL_NEGOTIATING = 4000,
45 #define GST_CAT_DEFAULT webrtc_sendrecv_debug
46 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
48 static GMainLoop *loop;
49 static GstElement *pipe1, *webrtc1, *audio_bin, *video_bin = NULL;
50 static GObject *send_channel, *receive_channel;
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;
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},
77 cleanup_and_quit_loop (const gchar * msg, enum AppState state)
80 gst_printerr ("%s\n", msg);
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, "");
90 g_clear_object (&ws_conn);
94 g_main_loop_quit (loop);
95 g_clear_pointer (&loop, g_main_loop_unref);
98 /* To allow usage as a GSourceFunc */
99 return G_SOURCE_REMOVE;
103 get_string_from_json_object (JsonObject * object)
106 JsonGenerator *generator;
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);
115 /* Release everything */
116 g_object_unref (generator);
117 json_node_free (root);
122 handle_media_stream (GstPad * pad, GstElement * pipe, const char *convert_name,
123 const char *sink_name)
126 GstElement *q, *conv, *resample, *sink;
127 GstPadLinkReturn ret;
129 gst_println ("Trying to handle stream with %s ! %s", convert_name, sink_name);
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);
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);
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);
157 qpad = gst_element_get_static_pad (q, "sink");
159 ret = gst_pad_link (pad, qpad);
160 g_assert_cmphex (ret, ==, GST_PAD_LINK_OK);
164 on_incoming_decodebin_stream (GstElement * decodebin, GstPad * pad,
170 if (!gst_pad_has_current_caps (pad)) {
171 gst_printerr ("Pad '%s' has no caps, can't do anything, ignoring\n",
176 caps = gst_pad_get_current_caps (pad);
177 name = gst_structure_get_name (gst_caps_get_structure (caps, 0));
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");
184 gst_printerr ("Unknown pad %s, ignoring", GST_PAD_NAME (pad));
189 on_incoming_stream (GstElement * webrtc, GstPad * pad, GstElement * pipe)
191 GstElement *decodebin;
194 if (GST_PAD_DIRECTION (pad) != GST_PAD_SRC)
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);
203 sinkpad = gst_element_get_static_pad (decodebin, "sink");
204 gst_pad_link (pad, sinkpad);
205 gst_object_unref (sinkpad);
209 send_ice_candidate_message (GstElement * webrtc G_GNUC_UNUSED, guint mlineindex,
210 gchar * candidate, gpointer user_data G_GNUC_UNUSED)
213 JsonObject *ice, *msg;
215 if (app_state < PEER_CALL_NEGOTIATING) {
216 cleanup_and_quit_loop ("Can't send ICE, not in call", APP_STATE_ERROR);
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);
228 soup_websocket_connection_send_text (ws_conn, text);
233 send_sdp_to_peer (GstWebRTCSessionDescription * desc)
236 JsonObject *msg, *sdp;
238 if (app_state < PEER_CALL_NEGOTIATING) {
239 cleanup_and_quit_loop ("Can't send SDP to peer, not in call",
244 text = gst_sdp_message_as_text (desc->sdp);
245 sdp = json_object_new ();
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");
254 g_assert_not_reached ();
257 json_object_set_string_member (sdp, "sdp", text);
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);
265 soup_websocket_connection_send_text (ws_conn, text);
269 /* Offer created by our pipeline, to be sent to the peer */
271 on_offer_created (GstPromise * promise, gpointer user_data)
273 GstWebRTCSessionDescription *offer = NULL;
274 const GstStructure *reply;
276 g_assert_cmphex (app_state, ==, PEER_CALL_NEGOTIATING);
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);
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);
289 /* Send offer to peer */
290 send_sdp_to_peer (offer);
291 gst_webrtc_session_description_free (offer);
295 on_negotiation_needed (GstElement * element, gpointer user_data)
297 gboolean create_offer = GPOINTER_TO_INT (user_data);
298 app_state = PEER_CALL_NEGOTIATING;
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);
310 data_channel_on_error (GObject * dc, gpointer user_data)
312 cleanup_and_quit_loop ("Data channel error", 0);
316 data_channel_on_open (GObject * dc, gpointer user_data)
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);
326 data_channel_on_close (GObject * dc, gpointer user_data)
328 cleanup_and_quit_loop ("Data channel closed", 0);
332 data_channel_on_message_string (GObject * dc, gchar * str, gpointer user_data)
334 gst_print ("Received data channel message: %s\n", str);
338 connect_data_channel_signals (GObject * data_channel)
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),
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);
351 on_data_channel (GstElement * webrtc, GObject * data_channel,
354 connect_data_channel_signals (data_channel);
355 receive_channel = data_channel;
359 on_ice_gathering_state_notify (GstElement * webrtcbin, GParamSpec * pspec,
362 GstWebRTCICEGatheringState ice_gather_state;
363 const gchar *new_state = "unknown";
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:
370 case GST_WEBRTC_ICE_GATHERING_STATE_GATHERING:
371 new_state = "gathering";
373 case GST_WEBRTC_ICE_GATHERING_STATE_COMPLETE:
374 new_state = "complete";
377 gst_print ("ICE gathering state changed to %s\n", new_state);
380 static gboolean webrtcbin_get_stats (GstElement * webrtcbin);
383 on_webrtcbin_stat (GQuark field_id, const GValue * value, gpointer unused)
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));
389 GST_FIXME ("unknown field \'%s\' value type: \'%s\'",
390 g_quark_to_string (field_id), g_type_name (G_VALUE_TYPE (value)));
397 on_webrtcbin_get_stats (GstPromise * promise, GstElement * webrtcbin)
399 const GstStructure *stats;
401 g_return_if_fail (gst_promise_wait (promise) == GST_PROMISE_RESULT_REPLIED);
403 stats = gst_promise_get_reply (promise);
404 gst_structure_foreach (stats, on_webrtcbin_stat, NULL);
406 g_timeout_add (100, (GSourceFunc) webrtcbin_get_stats, webrtcbin);
410 webrtcbin_get_stats (GstElement * webrtcbin)
415 gst_promise_new_with_change_func (
416 (GstPromiseChangeFunc) on_webrtcbin_get_stats, webrtcbin, NULL);
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);
422 return G_SOURCE_REMOVE;
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
432 start_pipeline (gboolean create_offer, guint opus_pt, guint vp8_pt)
434 char *audio_desc, *video_desc;
435 GstStateChangeReturn ret;
436 GstWebRTCICE *custom_agent;
437 GError *audio_error = NULL;
438 GError *video_error = NULL;
440 pipe1 = gst_pipeline_new ("webrtc-pipeline");
444 ("audiotestsrc is-live=true wave=red-noise ! audioconvert ! audioresample"
445 "! queue ! opusenc ! rtpopuspay name=audiopay pt=%u ! queue", opus_pt);
446 audio_bin = gst_parse_bin_from_description (audio_desc, TRUE, &audio_error);
449 gst_printerr ("Failed to parse audio_bin: %s\n", audio_error->message);
450 g_error_free (audio_error);
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.
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 pt=%u ! queue", vp8_pt);
465 video_bin = gst_parse_bin_from_description (video_desc, TRUE, &video_error);
468 gst_printerr ("Failed to parse video_bin: %s\n", video_error->message);
469 g_error_free (video_error);
474 custom_agent = GST_WEBRTC_ICE (customice_agent_new ("custom"));
475 webrtc1 = gst_element_factory_make_full ("webrtcbin", "name", "sendrecv",
476 "stun-server", STUN_SERVER, "ice-agent", custom_agent, NULL);
478 webrtc1 = gst_element_factory_make_full ("webrtcbin", "name", "sendrecv",
479 "stun-server", STUN_SERVER, NULL);
481 g_assert_nonnull (webrtc1);
482 gst_util_set_object_arg (G_OBJECT (webrtc1), "bundle-policy", "max-bundle");
484 gst_bin_add_many (GST_BIN (pipe1), audio_bin, video_bin, webrtc1, NULL);
486 if (!gst_element_link (audio_bin, webrtc1)) {
487 gst_printerr ("Failed to link audio_bin \n");
489 if (!gst_element_link (video_bin, webrtc1)) {
490 gst_printerr ("Failed to link video_bin \n");
494 /* XXX: this will fail when the remote offers twcc as the extension id
495 * cannot currently be negotiated when receiving an offer.
497 GST_FIXME ("Need to implement header extension negotiation when "
498 "reciving a remote offers");
500 GstElement *videopay, *audiopay;
501 GstRTPHeaderExtension *video_twcc, *audio_twcc;
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);
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);
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);
534 gst_element_set_state (pipe1, GST_STATE_READY);
536 g_signal_emit_by_name (webrtc1, "create-data-channel", "channel", NULL,
539 gst_print ("Created data channel\n");
540 connect_data_channel_signals (send_channel);
542 gst_print ("Could not create data channel, is usrsctp available?\n");
545 g_signal_connect (webrtc1, "on-data-channel", G_CALLBACK (on_data_channel),
547 /* Incoming streams will be exposed via this signal */
548 g_signal_connect (webrtc1, "pad-added", G_CALLBACK (on_incoming_stream),
550 /* Lifetime is the same as the pipeline itself */
551 gst_object_unref (webrtc1);
553 g_timeout_add (100, (GSourceFunc) webrtcbin_get_stats, webrtc1);
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)
564 g_clear_object (&pipe1);
575 if (soup_websocket_connection_get_state (ws_conn) !=
576 SOUP_WEBSOCKET_STATE_OPEN)
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);
591 register_with_server (void)
595 if (soup_websocket_connection_get_state (ws_conn) !=
596 SOUP_WEBSOCKET_STATE_OPEN)
602 id = g_random_int_range (10, 10000);
603 gst_print ("Registering id %i with server\n", id);
605 hello = g_strdup_printf ("HELLO %i", id);
607 gst_print ("Registering id %s with server\n", our_id);
609 hello = g_strdup_printf ("HELLO %s", our_id);
612 app_state = SERVER_REGISTERING;
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);
623 on_server_closed (SoupWebsocketConnection * conn G_GNUC_UNUSED,
624 gpointer user_data G_GNUC_UNUSED)
626 app_state = SERVER_CLOSED;
627 cleanup_and_quit_loop ("Server connection closed", 0);
630 /* Answer created by our pipeline, to be sent to the peer */
632 on_answer_created (GstPromise * promise, gpointer user_data)
634 GstWebRTCSessionDescription *answer = NULL;
635 const GstStructure *reply;
637 g_assert_cmphex (app_state, ==, PEER_CALL_NEGOTIATING);
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);
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);
650 /* Send answer to peer */
651 send_sdp_to_peer (answer);
652 gst_webrtc_session_description_free (answer);
656 on_offer_set (GstPromise * promise, gpointer user_data)
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);
664 on_offer_received (GstSDPMessage * sdp)
666 GstWebRTCSessionDescription *offer = NULL;
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;
675 gst_println ("Parsing offer to find payload types");
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++) {
685 const char *fmt, *encoding_name;
687 fmt = gst_sdp_media_get_format (media, j);
688 if (g_strcmp0 (fmt, "webrtc-datachannel") == 0)
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)
696 if (opus_pt == 0 && g_strcmp0 (encoding_name, "OPUS") == 0)
701 g_assert_cmpint (opus_pt, !=, 0);
702 g_assert_cmpint (vp8_pt, !=, 0);
704 gst_println ("Starting pipeline with opus pt: %u vp8 pt: %u", opus_pt,
707 if (!start_pipeline (FALSE, opus_pt, vp8_pt)) {
708 cleanup_and_quit_loop ("ERROR: failed to start pipeline",
713 offer = gst_webrtc_session_description_new (GST_WEBRTC_SDP_TYPE_OFFER, sdp);
714 g_assert_nonnull (offer);
716 /* Set remote description on our pipeline */
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);
721 gst_webrtc_session_description_free (offer);
724 /* One mega message handler for our asynchronous calling mechanism */
726 on_server_message (SoupWebsocketConnection * conn, SoupWebsocketDataType type,
727 GBytes * message, gpointer user_data)
732 case SOUP_WEBSOCKET_DATA_BINARY:
733 gst_printerr ("Received unknown binary message, ignoring\n");
735 case SOUP_WEBSOCKET_DATA_TEXT:{
737 const gchar *data = g_bytes_get_data (message, &size);
738 /* Convert to NULL-terminated string */
739 text = g_strndup (data, size);
743 g_assert_not_reached ();
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",
753 app_state = SERVER_REGISTERED;
754 gst_print ("Registered with server\n");
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);
762 gst_println ("Waiting for connection from peer (our-id: %s)", our_id);
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
767 if (app_state != PEER_CONNECTING) {
768 cleanup_and_quit_loop ("ERROR: Received SESSION_OK when not calling",
769 PEER_CONNECTION_ERROR);
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",
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");
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",
788 } else if (g_str_has_prefix (text, "ERROR")) {
791 case SERVER_CONNECTING:
792 app_state = SERVER_CONNECTION_ERROR;
794 case SERVER_REGISTERING:
795 app_state = SERVER_REGISTRATION_ERROR;
797 case PEER_CONNECTING:
798 app_state = PEER_CONNECTION_ERROR;
801 case PEER_CALL_NEGOTIATING:
802 app_state = PEER_CALL_ERROR;
805 app_state = APP_STATE_ERROR;
807 cleanup_and_quit_loop (text, 0);
809 /* Look for JSON messages containing SDP and ICE candidates */
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);
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);
826 object = json_node_get_object (root);
827 /* Check type of JSON message */
828 if (json_object_has_member (object, "sdp")) {
831 const gchar *text, *sdptype;
832 GstWebRTCSessionDescription *answer;
834 app_state = PEER_CALL_NEGOTIATING;
836 child = json_object_get_object_member (object, "sdp");
838 if (!json_object_has_member (child, "type")) {
839 cleanup_and_quit_loop ("ERROR: received SDP without 'type'",
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.
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);
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,
861 g_assert_nonnull (answer);
863 /* Set remote description on our pipeline */
865 GstPromise *promise = gst_promise_new ();
866 g_signal_emit_by_name (webrtc1, "set-remote-description", answer,
868 gst_promise_interrupt (promise);
869 gst_promise_unref (promise);
871 app_state = PEER_CALL_STARTED;
873 gst_print ("Received offer:\n%s\n", text);
874 on_offer_received (sdp);
877 } else if (json_object_has_member (object, "ice")) {
878 const gchar *candidate;
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");
885 /* Add ice candidate sent by remote peer */
886 g_signal_emit_by_name (webrtc1, "add-ice-candidate", sdpmlineindex,
889 gst_printerr ("Ignoring unknown JSON message:\n%s\n", text);
891 g_object_unref (parser);
899 on_server_connected (SoupSession * session, GAsyncResult * res,
902 GError *error = NULL;
904 ws_conn = soup_session_websocket_connect_finish (session, res, &error);
906 cleanup_and_quit_loop (error->message, SERVER_CONNECTION_ERROR);
907 g_error_free (error);
911 g_assert_nonnull (ws_conn);
913 app_state = SERVER_CONNECTED;
914 gst_print ("Connected to signalling server\n");
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);
919 /* Register with the server so it knows about us and can accept commands */
920 register_with_server ();
924 * Connect to the signalling server. This is the entrypoint for everything else.
927 connect_to_websocket_server_async (void)
930 SoupMessage *message;
931 SoupSession *session;
932 const char *https_aliases[] = { "wss", NULL };
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);
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);
944 message = soup_message_new (SOUP_METHOD_GET, server_url);
946 gst_print ("Connecting to server...\n");
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;
960 GstRegistry *registry;
961 const gchar *needed[] = { "opus", "vpx", "nice", "webrtc", "dtls", "srtp",
962 "rtpmanager", "videotestsrc", "audiotestsrc", NULL
965 registry = gst_registry_get ();
967 for (i = 0; i < g_strv_length ((gchar **) needed); i++) {
968 plugin = gst_registry_find_plugin (registry, needed[i]);
970 gst_print ("Required gstreamer plugin '%s' not found\n", needed[i]);
974 gst_object_unref (plugin);
980 main (int argc, char *argv[])
982 GOptionContext *context;
983 GError *error = NULL;
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);
994 GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "webrtc-sendrecv", 0,
995 "WebRTC Sending and Receiving example");
997 if (!check_plugins ()) {
1001 if (!peer_id && !our_id) {
1002 gst_printerr ("--peer-id or --our-id is a required argument\n");
1006 if (peer_id && our_id) {
1007 gst_printerr ("specify only --peer-id or --our-id\n");
1013 /* Disable ssl when running a localhost server, because
1014 * it's probably a test server with a self-signed certificate */
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)
1020 gst_uri_unref (uri);
1023 loop = g_main_loop_new (NULL, FALSE);
1025 connect_to_websocket_server_async ();
1027 g_main_loop_run (loop);
1030 g_main_loop_unref (loop);
1033 gst_element_set_state (GST_ELEMENT (pipe1), GST_STATE_NULL);
1034 gst_print ("Pipeline stopped\n");
1035 gst_object_unref (pipe1);