033ad4721bb2f67d3d097ccd211729f81f9358e7
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / ext / webrtc / webrtcdatachannel.c
1 /* GStreamer
2  * Copyright (C) 2018 Matthew Waters <matthew@centricular.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 /**
21  * SECTION:gstwebrtc-datachannel
22  * @short_description: RTCDataChannel object
23  * @title: GstWebRTCDataChannel
24  * @see_also: #GstWebRTCRTPTransceiver
25  *
26  * <http://w3c.github.io/webrtc-pc/#dom-rtcsctptransport>
27  */
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include "webrtcdatachannel.h"
34 #include <gst/app/gstappsink.h>
35 #include <gst/app/gstappsrc.h>
36 #include <gst/base/gstbytereader.h>
37 #include <gst/base/gstbytewriter.h>
38 #include <gst/sctp/sctpreceivemeta.h>
39 #include <gst/sctp/sctpsendmeta.h>
40
41 #include "gstwebrtcbin.h"
42 #include "utils.h"
43
44 #define GST_CAT_DEFAULT webrtc_data_channel_debug
45 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
46
47 #define webrtc_data_channel_parent_class parent_class
48 G_DEFINE_TYPE_WITH_CODE (WebRTCDataChannel, webrtc_data_channel,
49     GST_TYPE_WEBRTC_DATA_CHANNEL,
50     GST_DEBUG_CATEGORY_INIT (webrtc_data_channel_debug, "webrtcdatachannel", 0,
51         "webrtcdatachannel"););
52
53 G_LOCK_DEFINE_STATIC (outstanding_channels_lock);
54 static GList *outstanding_channels;
55
56 typedef enum
57 {
58   DATA_CHANNEL_PPID_WEBRTC_CONTROL = 50,
59   DATA_CHANNEL_PPID_WEBRTC_STRING = 51,
60   DATA_CHANNEL_PPID_WEBRTC_BINARY_PARTIAL = 52, /* deprecated */
61   DATA_CHANNEL_PPID_WEBRTC_BINARY = 53,
62   DATA_CHANNEL_PPID_WEBRTC_STRING_PARTIAL = 54, /* deprecated */
63   DATA_CHANNEL_PPID_WEBRTC_BINARY_EMPTY = 56,
64   DATA_CHANNEL_PPID_WEBRTC_STRING_EMPTY = 57,
65 } DataChannelPPID;
66
67 typedef enum
68 {
69   CHANNEL_TYPE_RELIABLE = 0x00,
70   CHANNEL_TYPE_RELIABLE_UNORDERED = 0x80,
71   CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT = 0x01,
72   CHANNEL_TYPE_PARTIAL_RELIABLE_REXMIT_UNORDERED = 0x81,
73   CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED = 0x02,
74   CHANNEL_TYPE_PARTIAL_RELIABLE_TIMED_UNORDERED = 0x82,
75 } DataChannelReliabilityType;
76
77 typedef enum
78 {
79   CHANNEL_MESSAGE_ACK = 0x02,
80   CHANNEL_MESSAGE_OPEN = 0x03,
81 } DataChannelMessage;
82
83 static guint16
84 priority_type_to_uint (GstWebRTCPriorityType pri)
85 {
86   switch (pri) {
87     case GST_WEBRTC_PRIORITY_TYPE_VERY_LOW:
88       return 64;
89     case GST_WEBRTC_PRIORITY_TYPE_LOW:
90       return 192;
91     case GST_WEBRTC_PRIORITY_TYPE_MEDIUM:
92       return 384;
93     case GST_WEBRTC_PRIORITY_TYPE_HIGH:
94       return 768;
95   }
96   g_assert_not_reached ();
97   return 0;
98 }
99
100 static GstWebRTCPriorityType
101 priority_uint_to_type (guint16 val)
102 {
103   if (val <= 128)
104     return GST_WEBRTC_PRIORITY_TYPE_VERY_LOW;
105   if (val <= 256)
106     return GST_WEBRTC_PRIORITY_TYPE_LOW;
107   if (val <= 512)
108     return GST_WEBRTC_PRIORITY_TYPE_MEDIUM;
109   return GST_WEBRTC_PRIORITY_TYPE_HIGH;
110 }
111
112 static GstBuffer *
113 construct_open_packet (WebRTCDataChannel * channel)
114 {
115   GstByteWriter w;
116   gsize label_len = strlen (channel->parent.label);
117   gsize proto_len = strlen (channel->parent.protocol);
118   gsize size = 12 + label_len + proto_len;
119   DataChannelReliabilityType reliability = 0;
120   guint32 reliability_param = 0;
121   guint16 priority;
122   GstBuffer *buf;
123
124 /*
125  *    0                   1                   2                   3
126  *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
127  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
128  *   |  Message Type |  Channel Type |            Priority           |
129  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
130  *   |                    Reliability Parameter                      |
131  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
132  *   |         Label Length          |       Protocol Length         |
133  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
134  *   \                                                               /
135  *   |                             Label                             |
136  *   /                                                               \
137  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
138  *   \                                                               /
139  *   |                            Protocol                           |
140  *   /                                                               \
141  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
142  */
143
144   gst_byte_writer_init_with_size (&w, size, FALSE);
145
146   if (!gst_byte_writer_put_uint8 (&w, (guint8) CHANNEL_MESSAGE_OPEN))
147     g_return_val_if_reached (NULL);
148
149   if (!channel->parent.ordered)
150     reliability |= 0x80;
151   if (channel->parent.max_retransmits != -1) {
152     reliability |= 0x01;
153     reliability_param = channel->parent.max_retransmits;
154   }
155   if (channel->parent.max_packet_lifetime != -1) {
156     reliability |= 0x02;
157     reliability_param = channel->parent.max_packet_lifetime;
158   }
159
160   priority = priority_type_to_uint (channel->parent.priority);
161
162   if (!gst_byte_writer_put_uint8 (&w, (guint8) reliability))
163     g_return_val_if_reached (NULL);
164   if (!gst_byte_writer_put_uint16_be (&w, (guint16) priority))
165     g_return_val_if_reached (NULL);
166   if (!gst_byte_writer_put_uint32_be (&w, (guint32) reliability_param))
167     g_return_val_if_reached (NULL);
168   if (!gst_byte_writer_put_uint16_be (&w, (guint16) label_len))
169     g_return_val_if_reached (NULL);
170   if (!gst_byte_writer_put_uint16_be (&w, (guint16) proto_len))
171     g_return_val_if_reached (NULL);
172   if (!gst_byte_writer_put_data (&w, (guint8 *) channel->parent.label,
173           label_len))
174     g_return_val_if_reached (NULL);
175   if (!gst_byte_writer_put_data (&w, (guint8 *) channel->parent.protocol,
176           proto_len))
177     g_return_val_if_reached (NULL);
178
179   buf = gst_byte_writer_reset_and_get_buffer (&w);
180
181   /* send reliable and ordered */
182   gst_sctp_buffer_add_send_meta (buf, DATA_CHANNEL_PPID_WEBRTC_CONTROL, TRUE,
183       GST_SCTP_SEND_META_PARTIAL_RELIABILITY_NONE, 0);
184
185   return buf;
186 }
187
188 static GstBuffer *
189 construct_ack_packet (WebRTCDataChannel * channel)
190 {
191   GstByteWriter w;
192   GstBuffer *buf;
193
194 /*
195  *   0                   1                   2                   3
196  *   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
197  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
198  *   |  Message Type |
199  *   +-+-+-+-+-+-+-+-+
200  */
201
202   gst_byte_writer_init_with_size (&w, 1, FALSE);
203
204   if (!gst_byte_writer_put_uint8 (&w, (guint8) CHANNEL_MESSAGE_ACK))
205     g_return_val_if_reached (NULL);
206
207   buf = gst_byte_writer_reset_and_get_buffer (&w);
208
209   /* send reliable and ordered */
210   gst_sctp_buffer_add_send_meta (buf, DATA_CHANNEL_PPID_WEBRTC_CONTROL, TRUE,
211       GST_SCTP_SEND_META_PARTIAL_RELIABILITY_NONE, 0);
212
213   return buf;
214 }
215
216 typedef void (*ChannelTask) (GstWebRTCDataChannel * channel,
217     gpointer user_data);
218
219 struct task
220 {
221   GstWebRTCDataChannel *channel;
222   ChannelTask func;
223   gpointer user_data;
224   GDestroyNotify notify;
225 };
226
227 static GstStructure *
228 _execute_task (GstWebRTCBin * webrtc, struct task *task)
229 {
230   if (task->func)
231     task->func (task->channel, task->user_data);
232
233   return NULL;
234 }
235
236 static void
237 _free_task (struct task *task)
238 {
239   gst_object_unref (task->channel);
240
241   if (task->notify)
242     task->notify (task->user_data);
243   g_free (task);
244 }
245
246 static void
247 _channel_enqueue_task (WebRTCDataChannel * channel, ChannelTask func,
248     gpointer user_data, GDestroyNotify notify)
249 {
250   struct task *task = g_new0 (struct task, 1);
251
252   task->channel = gst_object_ref (channel);
253   task->func = func;
254   task->user_data = user_data;
255   task->notify = notify;
256
257   gst_webrtc_bin_enqueue_task (channel->webrtcbin,
258       (GstWebRTCBinFunc) _execute_task, task, (GDestroyNotify) _free_task,
259       NULL);
260 }
261
262 static void
263 _channel_store_error (WebRTCDataChannel * channel, GError * error)
264 {
265   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
266   if (error) {
267     GST_WARNING_OBJECT (channel, "Error: %s",
268         error ? error->message : "Unknown");
269     if (!channel->stored_error)
270       channel->stored_error = error;
271     else
272       g_clear_error (&error);
273   }
274   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
275 }
276
277 static void
278 _emit_on_open (WebRTCDataChannel * channel, gpointer user_data)
279 {
280   gst_webrtc_data_channel_on_open (GST_WEBRTC_DATA_CHANNEL (channel));
281 }
282
283 static void
284 _transport_closed (WebRTCDataChannel * channel)
285 {
286   GError *error;
287   gboolean both_sides_closed;
288
289   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
290   error = channel->stored_error;
291   channel->stored_error = NULL;
292
293   both_sides_closed =
294       channel->peer_closed && channel->parent.buffered_amount <= 0;
295   if (both_sides_closed || error) {
296     channel->peer_closed = FALSE;
297   }
298   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
299
300   if (error) {
301     gst_webrtc_data_channel_on_error (GST_WEBRTC_DATA_CHANNEL (channel), error);
302     g_clear_error (&error);
303   }
304   if (both_sides_closed || error) {
305     gst_webrtc_data_channel_on_close (GST_WEBRTC_DATA_CHANNEL (channel));
306   }
307 }
308
309 static void
310 _close_sctp_stream (WebRTCDataChannel * channel, gpointer user_data)
311 {
312   GstPad *pad, *peer;
313
314   GST_INFO_OBJECT (channel, "Closing outgoing SCTP stream %i label \"%s\"",
315       channel->parent.id, channel->parent.label);
316
317   pad = gst_element_get_static_pad (channel->appsrc, "src");
318   peer = gst_pad_get_peer (pad);
319   gst_object_unref (pad);
320
321   if (peer) {
322     GstElement *sctpenc = gst_pad_get_parent_element (peer);
323
324     if (sctpenc) {
325       gst_element_release_request_pad (sctpenc, peer);
326       gst_object_unref (sctpenc);
327     }
328     gst_object_unref (peer);
329   }
330
331   _transport_closed (channel);
332 }
333
334 static void
335 _close_procedure (WebRTCDataChannel * channel, gpointer user_data)
336 {
337   /* https://www.w3.org/TR/webrtc/#data-transport-closing-procedure */
338   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
339   if (channel->parent.ready_state == GST_WEBRTC_DATA_CHANNEL_STATE_CLOSED) {
340     GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
341     return;
342   } else if (channel->parent.ready_state ==
343       GST_WEBRTC_DATA_CHANNEL_STATE_CLOSING) {
344     _channel_enqueue_task (channel, (ChannelTask) _transport_closed, NULL,
345         NULL);
346   } else if (channel->parent.ready_state == GST_WEBRTC_DATA_CHANNEL_STATE_OPEN) {
347 #ifdef TIZEN_FEATURE_WEBRTC_MODIFICATION
348     channel->parent.prev_ready_state = channel->parent.ready_state;
349 #endif
350     channel->parent.ready_state = GST_WEBRTC_DATA_CHANNEL_STATE_CLOSING;
351     GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
352     g_object_notify (G_OBJECT (channel), "ready-state");
353
354     GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
355     if (channel->parent.buffered_amount <= 0) {
356       _channel_enqueue_task (channel, (ChannelTask) _close_sctp_stream,
357           NULL, NULL);
358     }
359   }
360
361   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
362 }
363
364 static void
365 _on_sctp_stream_reset (WebRTCSCTPTransport * sctp, guint stream_id,
366     WebRTCDataChannel * channel)
367 {
368   if (channel->parent.id == stream_id) {
369     GST_INFO_OBJECT (channel,
370         "Received channel close for SCTP stream %i label \"%s\"",
371         channel->parent.id, channel->parent.label);
372
373     GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
374     channel->peer_closed = TRUE;
375     GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
376
377     _channel_enqueue_task (channel, (ChannelTask) _close_procedure,
378         GUINT_TO_POINTER (stream_id), NULL);
379   }
380 }
381
382 static void
383 webrtc_data_channel_close (GstWebRTCDataChannel * channel)
384 {
385   _close_procedure (WEBRTC_DATA_CHANNEL (channel), NULL);
386 }
387
388 static GstFlowReturn
389 _parse_control_packet (WebRTCDataChannel * channel, guint8 * data,
390     gsize size, GError ** error)
391 {
392   GstByteReader r;
393   guint8 message_type;
394   gchar *label = NULL;
395   gchar *proto = NULL;
396
397   if (!data)
398     g_return_val_if_reached (GST_FLOW_ERROR);
399   if (size < 1)
400     g_return_val_if_reached (GST_FLOW_ERROR);
401
402   gst_byte_reader_init (&r, data, size);
403
404   if (!gst_byte_reader_get_uint8 (&r, &message_type))
405     g_return_val_if_reached (GST_FLOW_ERROR);
406
407   if (message_type == CHANNEL_MESSAGE_ACK) {
408     /* all good */
409     GST_INFO_OBJECT (channel, "Received channel ack");
410     return GST_FLOW_OK;
411   } else if (message_type == CHANNEL_MESSAGE_OPEN) {
412     guint8 reliability;
413     guint32 reliability_param;
414     guint16 priority, label_len, proto_len;
415     const guint8 *src;
416     GstBuffer *buffer;
417     GstFlowReturn ret;
418
419     GST_INFO_OBJECT (channel, "Received channel open");
420
421     if (channel->parent.negotiated) {
422       g_set_error (error, GST_WEBRTC_ERROR,
423           GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
424           "Data channel was signalled as negotiated already");
425       g_return_val_if_reached (GST_FLOW_ERROR);
426     }
427
428     if (channel->opened)
429       return GST_FLOW_OK;
430
431     if (!gst_byte_reader_get_uint8 (&r, &reliability))
432       goto parse_error;
433     if (!gst_byte_reader_get_uint16_be (&r, &priority))
434       goto parse_error;
435     if (!gst_byte_reader_get_uint32_be (&r, &reliability_param))
436       goto parse_error;
437     if (!gst_byte_reader_get_uint16_be (&r, &label_len))
438       goto parse_error;
439     if (!gst_byte_reader_get_uint16_be (&r, &proto_len))
440       goto parse_error;
441
442     label = g_new0 (gchar, (gsize) label_len + 1);
443     proto = g_new0 (gchar, (gsize) proto_len + 1);
444
445     if (!gst_byte_reader_get_data (&r, label_len, &src))
446       goto parse_error;
447     memcpy (label, src, label_len);
448     label[label_len] = '\0';
449     if (!gst_byte_reader_get_data (&r, proto_len, &src))
450       goto parse_error;
451     memcpy (proto, src, proto_len);
452     proto[proto_len] = '\0';
453
454     g_free (channel->parent.label);
455     channel->parent.label = label;
456     g_free (channel->parent.protocol);
457     channel->parent.protocol = proto;
458     channel->parent.priority = priority_uint_to_type (priority);
459     channel->parent.ordered = !(reliability & 0x80);
460     if (reliability & 0x01) {
461       channel->parent.max_retransmits = reliability_param;
462       channel->parent.max_packet_lifetime = -1;
463     } else if (reliability & 0x02) {
464       channel->parent.max_retransmits = -1;
465       channel->parent.max_packet_lifetime = reliability_param;
466     } else {
467       channel->parent.max_retransmits = -1;
468       channel->parent.max_packet_lifetime = -1;
469     }
470     channel->opened = TRUE;
471
472     GST_INFO_OBJECT (channel, "Received channel open for SCTP stream %i "
473         "label \"%s\" protocol %s ordered %s", channel->parent.id,
474         channel->parent.label, channel->parent.protocol,
475         channel->parent.ordered ? "true" : "false");
476
477     _channel_enqueue_task (channel, (ChannelTask) _emit_on_open, NULL, NULL);
478
479     GST_INFO_OBJECT (channel, "Sending channel ack");
480     buffer = construct_ack_packet (channel);
481
482     GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
483     channel->parent.buffered_amount += gst_buffer_get_size (buffer);
484     GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
485
486     ret = gst_app_src_push_buffer (GST_APP_SRC (channel->appsrc), buffer);
487     if (ret != GST_FLOW_OK) {
488       g_set_error (error, GST_WEBRTC_ERROR,
489           GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE, "Could not send ack packet");
490       return ret;
491     }
492
493     return ret;
494   } else {
495     g_set_error (error, GST_WEBRTC_ERROR,
496         GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
497         "Unknown message type in control protocol");
498     return GST_FLOW_ERROR;
499   }
500
501 parse_error:
502   {
503     g_free (label);
504     g_free (proto);
505     g_set_error (error, GST_WEBRTC_ERROR,
506         GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE, "Failed to parse packet");
507     g_return_val_if_reached (GST_FLOW_ERROR);
508   }
509 }
510
511 static void
512 on_sink_eos (GstAppSink * sink, gpointer user_data)
513 {
514 }
515
516 struct map_info
517 {
518   GstBuffer *buffer;
519   GstMapInfo map_info;
520 };
521
522 static void
523 buffer_unmap_and_unref (struct map_info *info)
524 {
525   gst_buffer_unmap (info->buffer, &info->map_info);
526   gst_buffer_unref (info->buffer);
527   g_free (info);
528 }
529
530 static void
531 _emit_have_data (WebRTCDataChannel * channel, GBytes * data)
532 {
533   gst_webrtc_data_channel_on_message_data (GST_WEBRTC_DATA_CHANNEL (channel),
534       data);
535 }
536
537 static void
538 _emit_have_string (GstWebRTCDataChannel * channel, gchar * str)
539 {
540   gst_webrtc_data_channel_on_message_string (GST_WEBRTC_DATA_CHANNEL (channel),
541       str);
542 }
543
544 static GstFlowReturn
545 _data_channel_have_sample (WebRTCDataChannel * channel, GstSample * sample,
546     GError ** error)
547 {
548   GstSctpReceiveMeta *receive;
549   GstBuffer *buffer;
550   GstFlowReturn ret = GST_FLOW_OK;
551
552   GST_LOG_OBJECT (channel, "Received sample %" GST_PTR_FORMAT, sample);
553
554   g_return_val_if_fail (channel->sctp_transport != NULL, GST_FLOW_ERROR);
555
556   buffer = gst_sample_get_buffer (sample);
557   if (!buffer) {
558     g_set_error (error, GST_WEBRTC_ERROR,
559         GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE, "No buffer to handle");
560     return GST_FLOW_ERROR;
561   }
562   receive = gst_sctp_buffer_get_receive_meta (buffer);
563   if (!receive) {
564     g_set_error (error, GST_WEBRTC_ERROR,
565         GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
566         "No SCTP Receive meta on the buffer");
567     return GST_FLOW_ERROR;
568   }
569
570   switch (receive->ppid) {
571     case DATA_CHANNEL_PPID_WEBRTC_CONTROL:{
572       GstMapInfo info = GST_MAP_INFO_INIT;
573       if (!gst_buffer_map (buffer, &info, GST_MAP_READ)) {
574         g_set_error (error, GST_WEBRTC_ERROR,
575             GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
576             "Failed to map received buffer");
577         ret = GST_FLOW_ERROR;
578       } else {
579         ret = _parse_control_packet (channel, info.data, info.size, error);
580         gst_buffer_unmap (buffer, &info);
581       }
582       break;
583     }
584     case DATA_CHANNEL_PPID_WEBRTC_STRING:
585     case DATA_CHANNEL_PPID_WEBRTC_STRING_PARTIAL:{
586       GstMapInfo info = GST_MAP_INFO_INIT;
587       if (!gst_buffer_map (buffer, &info, GST_MAP_READ)) {
588         g_set_error (error, GST_WEBRTC_ERROR,
589             GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
590             "Failed to map received buffer");
591         ret = GST_FLOW_ERROR;
592       } else {
593         gchar *str = g_strndup ((gchar *) info.data, info.size);
594         _channel_enqueue_task (channel, (ChannelTask) _emit_have_string, str,
595             g_free);
596         gst_buffer_unmap (buffer, &info);
597       }
598       break;
599     }
600     case DATA_CHANNEL_PPID_WEBRTC_BINARY:
601     case DATA_CHANNEL_PPID_WEBRTC_BINARY_PARTIAL:{
602       struct map_info *info = g_new0 (struct map_info, 1);
603       if (!gst_buffer_map (buffer, &info->map_info, GST_MAP_READ)) {
604         g_set_error (error, GST_WEBRTC_ERROR,
605             GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
606             "Failed to map received buffer");
607         ret = GST_FLOW_ERROR;
608       } else {
609         GBytes *data = g_bytes_new_with_free_func (info->map_info.data,
610             info->map_info.size, (GDestroyNotify) buffer_unmap_and_unref, info);
611         info->buffer = gst_buffer_ref (buffer);
612         _channel_enqueue_task (channel, (ChannelTask) _emit_have_data, data,
613             (GDestroyNotify) g_bytes_unref);
614       }
615       break;
616     }
617     case DATA_CHANNEL_PPID_WEBRTC_BINARY_EMPTY:
618       _channel_enqueue_task (channel, (ChannelTask) _emit_have_data, NULL,
619           NULL);
620       break;
621     case DATA_CHANNEL_PPID_WEBRTC_STRING_EMPTY:
622       _channel_enqueue_task (channel, (ChannelTask) _emit_have_string, NULL,
623           NULL);
624       break;
625     default:
626       g_set_error (error, GST_WEBRTC_ERROR,
627           GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
628           "Unknown SCTP PPID %u received", receive->ppid);
629       ret = GST_FLOW_ERROR;
630       break;
631   }
632
633   return ret;
634 }
635
636 static GstFlowReturn
637 on_sink_preroll (GstAppSink * sink, gpointer user_data)
638 {
639   WebRTCDataChannel *channel = user_data;
640   GstSample *sample = gst_app_sink_pull_preroll (sink);
641   GstFlowReturn ret;
642
643   if (sample) {
644     /* This sample also seems to be provided by the sample callback
645        ret = _data_channel_have_sample (channel, sample); */
646     ret = GST_FLOW_OK;
647     gst_sample_unref (sample);
648   } else if (gst_app_sink_is_eos (sink)) {
649     ret = GST_FLOW_EOS;
650   } else {
651     ret = GST_FLOW_ERROR;
652   }
653
654   if (ret != GST_FLOW_OK) {
655     _channel_enqueue_task (channel, (ChannelTask) _close_procedure, NULL, NULL);
656   }
657
658   return ret;
659 }
660
661 static GstFlowReturn
662 on_sink_sample (GstAppSink * sink, gpointer user_data)
663 {
664   WebRTCDataChannel *channel = user_data;
665   GstSample *sample = gst_app_sink_pull_sample (sink);
666   GstFlowReturn ret;
667   GError *error = NULL;
668
669   if (sample) {
670     ret = _data_channel_have_sample (channel, sample, &error);
671     gst_sample_unref (sample);
672   } else if (gst_app_sink_is_eos (sink)) {
673     ret = GST_FLOW_EOS;
674   } else {
675     ret = GST_FLOW_ERROR;
676   }
677
678   if (error)
679     _channel_store_error (channel, error);
680
681   if (ret != GST_FLOW_OK) {
682     _channel_enqueue_task (channel, (ChannelTask) _close_procedure, NULL, NULL);
683   }
684
685   return ret;
686 }
687
688 static GstAppSinkCallbacks sink_callbacks = {
689   on_sink_eos,
690   on_sink_preroll,
691   on_sink_sample,
692 };
693
694 void
695 webrtc_data_channel_start_negotiation (WebRTCDataChannel * channel)
696 {
697   GstBuffer *buffer;
698
699   g_return_if_fail (!channel->parent.negotiated);
700   g_return_if_fail (channel->parent.id != -1);
701   g_return_if_fail (channel->sctp_transport != NULL);
702
703   buffer = construct_open_packet (channel);
704
705   GST_INFO_OBJECT (channel, "Sending channel open for SCTP stream %i "
706       "label \"%s\" protocol %s ordered %s", channel->parent.id,
707       channel->parent.label, channel->parent.protocol,
708       channel->parent.ordered ? "true" : "false");
709
710   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
711   channel->parent.buffered_amount += gst_buffer_get_size (buffer);
712   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
713   g_object_notify (G_OBJECT (&channel->parent), "buffered-amount");
714
715   if (gst_app_src_push_buffer (GST_APP_SRC (channel->appsrc),
716           buffer) == GST_FLOW_OK) {
717     channel->opened = TRUE;
718 #ifdef TIZEN_FEATURE_WEBRTC_MODIFICATION
719     channel->webrtcbin->priv->data_channels_opened++;
720 #endif
721     _channel_enqueue_task (channel, (ChannelTask) _emit_on_open, NULL, NULL);
722   } else {
723     GError *error = NULL;
724     g_set_error (&error, GST_WEBRTC_ERROR,
725         GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
726         "Failed to send DCEP open packet");
727     _channel_store_error (channel, error);
728     _channel_enqueue_task (channel, (ChannelTask) _close_procedure, NULL, NULL);
729   }
730 }
731
732 static void
733 _get_sctp_reliability (WebRTCDataChannel * channel,
734     GstSctpSendMetaPartiallyReliability * reliability, guint * rel_param)
735 {
736   if (channel->parent.max_retransmits != -1) {
737     *reliability = GST_SCTP_SEND_META_PARTIAL_RELIABILITY_RTX;
738     *rel_param = channel->parent.max_retransmits;
739   } else if (channel->parent.max_packet_lifetime != -1) {
740     *reliability = GST_SCTP_SEND_META_PARTIAL_RELIABILITY_TTL;
741     *rel_param = channel->parent.max_packet_lifetime;
742   } else {
743     *reliability = GST_SCTP_SEND_META_PARTIAL_RELIABILITY_NONE;
744     *rel_param = 0;
745   }
746 }
747
748 static gboolean
749 _is_within_max_message_size (WebRTCDataChannel * channel, gsize size)
750 {
751   return size <= channel->sctp_transport->max_message_size;
752 }
753
754 static void
755 webrtc_data_channel_send_data (GstWebRTCDataChannel * base_channel,
756     GBytes * bytes)
757 {
758   WebRTCDataChannel *channel = WEBRTC_DATA_CHANNEL (base_channel);
759   GstSctpSendMetaPartiallyReliability reliability;
760   guint rel_param;
761   guint32 ppid;
762   GstBuffer *buffer;
763   GstFlowReturn ret;
764
765   if (!bytes) {
766     buffer = gst_buffer_new ();
767     ppid = DATA_CHANNEL_PPID_WEBRTC_BINARY_EMPTY;
768   } else {
769     gsize size;
770     guint8 *data;
771
772     data = (guint8 *) g_bytes_get_data (bytes, &size);
773     g_return_if_fail (data != NULL);
774     if (!_is_within_max_message_size (channel, size)) {
775       GError *error = NULL;
776       g_set_error (&error, GST_WEBRTC_ERROR,
777           GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
778           "Requested to send data that is too large");
779       _channel_store_error (channel, error);
780       _channel_enqueue_task (channel, (ChannelTask) _close_procedure, NULL,
781           NULL);
782       return;
783     }
784
785     buffer = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, data, size,
786         0, size, g_bytes_ref (bytes), (GDestroyNotify) g_bytes_unref);
787     ppid = DATA_CHANNEL_PPID_WEBRTC_BINARY;
788   }
789
790   _get_sctp_reliability (channel, &reliability, &rel_param);
791   gst_sctp_buffer_add_send_meta (buffer, ppid, channel->parent.ordered,
792       reliability, rel_param);
793
794   GST_LOG_OBJECT (channel, "Sending data using buffer %" GST_PTR_FORMAT,
795       buffer);
796
797   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
798   channel->parent.buffered_amount += gst_buffer_get_size (buffer);
799   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
800   g_object_notify (G_OBJECT (&channel->parent), "buffered-amount");
801
802   ret = gst_app_src_push_buffer (GST_APP_SRC (channel->appsrc), buffer);
803
804   if (ret != GST_FLOW_OK) {
805     GError *error = NULL;
806     g_set_error (&error, GST_WEBRTC_ERROR,
807         GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE, "Failed to send data");
808     _channel_store_error (channel, error);
809     _channel_enqueue_task (channel, (ChannelTask) _close_procedure, NULL, NULL);
810   }
811 }
812
813 static void
814 webrtc_data_channel_send_string (GstWebRTCDataChannel * base_channel,
815     const gchar * str)
816 {
817   WebRTCDataChannel *channel = WEBRTC_DATA_CHANNEL (base_channel);
818   GstSctpSendMetaPartiallyReliability reliability;
819   guint rel_param;
820   guint32 ppid;
821   GstBuffer *buffer;
822   GstFlowReturn ret;
823
824   if (!channel->parent.negotiated)
825     g_return_if_fail (channel->opened);
826   g_return_if_fail (channel->sctp_transport != NULL);
827
828   if (!str) {
829     buffer = gst_buffer_new ();
830     ppid = DATA_CHANNEL_PPID_WEBRTC_STRING_EMPTY;
831   } else {
832     gsize size = strlen (str);
833     gchar *str_copy;
834
835     if (!_is_within_max_message_size (channel, size)) {
836       GError *error = NULL;
837       g_set_error (&error, GST_WEBRTC_ERROR,
838           GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE,
839           "Requested to send a string that is too large");
840       _channel_store_error (channel, error);
841       _channel_enqueue_task (channel, (ChannelTask) _close_procedure, NULL,
842           NULL);
843       return;
844     }
845
846     str_copy = g_strdup (str);
847     buffer =
848         gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, str_copy,
849         size, 0, size, str_copy, g_free);
850     ppid = DATA_CHANNEL_PPID_WEBRTC_STRING;
851   }
852
853   _get_sctp_reliability (channel, &reliability, &rel_param);
854   gst_sctp_buffer_add_send_meta (buffer, ppid, channel->parent.ordered,
855       reliability, rel_param);
856
857   GST_TRACE_OBJECT (channel, "Sending string using buffer %" GST_PTR_FORMAT,
858       buffer);
859
860   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
861   channel->parent.buffered_amount += gst_buffer_get_size (buffer);
862   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
863   g_object_notify (G_OBJECT (&channel->parent), "buffered-amount");
864
865   ret = gst_app_src_push_buffer (GST_APP_SRC (channel->appsrc), buffer);
866
867   if (ret != GST_FLOW_OK) {
868     GError *error = NULL;
869     g_set_error (&error, GST_WEBRTC_ERROR,
870         GST_WEBRTC_ERROR_DATA_CHANNEL_FAILURE, "Failed to send string");
871     _channel_store_error (channel, error);
872     _channel_enqueue_task (channel, (ChannelTask) _close_procedure, NULL, NULL);
873   }
874 }
875
876 static void
877 _on_sctp_notify_state_unlocked (GObject * sctp_transport,
878     WebRTCDataChannel * channel)
879 {
880   GstWebRTCSCTPTransportState state;
881
882   g_object_get (sctp_transport, "state", &state, NULL);
883   if (state == GST_WEBRTC_SCTP_TRANSPORT_STATE_CONNECTED) {
884     if (channel->parent.negotiated)
885       _channel_enqueue_task (channel, (ChannelTask) _emit_on_open, NULL, NULL);
886   }
887 }
888
889 static WebRTCDataChannel *
890 ensure_channel_alive (WebRTCDataChannel * channel)
891 {
892   /* ghetto impl of, does the channel still exist?.
893    * Needed because g_signal_handler_disconnect*() will not disconnect any
894    * running functions and _finalize() implementation can complete and
895    * invalidate channel */
896   G_LOCK (outstanding_channels_lock);
897   if (g_list_find (outstanding_channels, channel)) {
898     g_object_ref (channel);
899   } else {
900     G_UNLOCK (outstanding_channels_lock);
901     return NULL;
902   }
903   G_UNLOCK (outstanding_channels_lock);
904
905   return channel;
906 }
907
908 static void
909 _on_sctp_notify_state (GObject * sctp_transport, GParamSpec * pspec,
910     WebRTCDataChannel * channel)
911 {
912   if (!(channel = ensure_channel_alive (channel)))
913     return;
914
915   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
916   _on_sctp_notify_state_unlocked (sctp_transport, channel);
917   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
918
919   g_object_unref (channel);
920 }
921
922 static void
923 _emit_low_threshold (WebRTCDataChannel * channel, gpointer user_data)
924 {
925   gst_webrtc_data_channel_on_buffered_amount_low (GST_WEBRTC_DATA_CHANNEL
926       (channel));
927 }
928
929 static GstPadProbeReturn
930 on_appsrc_data (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
931 {
932   WebRTCDataChannel *channel = user_data;
933   guint64 prev_amount;
934   guint64 size = 0;
935
936   if (GST_PAD_PROBE_INFO_TYPE (info) & (GST_PAD_PROBE_TYPE_BUFFER)) {
937     GstBuffer *buffer = GST_PAD_PROBE_INFO_BUFFER (info);
938     size = gst_buffer_get_size (buffer);
939   } else if (GST_PAD_PROBE_INFO_TYPE (info) & GST_PAD_PROBE_TYPE_BUFFER_LIST) {
940     GstBufferList *list = GST_PAD_PROBE_INFO_BUFFER_LIST (info);
941     size = gst_buffer_list_calculate_size (list);
942   }
943
944   if (size > 0) {
945     GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
946     prev_amount = channel->parent.buffered_amount;
947     channel->parent.buffered_amount -= size;
948     GST_TRACE_OBJECT (channel, "checking low-threshold: prev %"
949         G_GUINT64_FORMAT " low-threshold %" G_GUINT64_FORMAT " buffered %"
950         G_GUINT64_FORMAT, prev_amount,
951         channel->parent.buffered_amount_low_threshold,
952         channel->parent.buffered_amount);
953     if (prev_amount >= channel->parent.buffered_amount_low_threshold
954         && channel->parent.buffered_amount <
955         channel->parent.buffered_amount_low_threshold) {
956       _channel_enqueue_task (channel, (ChannelTask) _emit_low_threshold, NULL,
957           NULL);
958     }
959
960     if (channel->parent.ready_state == GST_WEBRTC_DATA_CHANNEL_STATE_CLOSING
961         && channel->parent.buffered_amount <= 0) {
962       _channel_enqueue_task (channel, (ChannelTask) _close_sctp_stream, NULL,
963           NULL);
964     }
965     GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
966     g_object_notify (G_OBJECT (&channel->parent), "buffered-amount");
967   }
968
969   return GST_PAD_PROBE_OK;
970 }
971
972 static void
973 gst_webrtc_data_channel_constructed (GObject * object)
974 {
975   WebRTCDataChannel *channel = WEBRTC_DATA_CHANNEL (object);
976   GstPad *pad;
977   GstCaps *caps;
978
979   caps = gst_caps_new_any ();
980
981   channel->appsrc = gst_element_factory_make ("appsrc", NULL);
982   gst_object_ref_sink (channel->appsrc);
983   pad = gst_element_get_static_pad (channel->appsrc, "src");
984
985   channel->src_probe = gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_DATA_BOTH,
986       (GstPadProbeCallback) on_appsrc_data, channel, NULL);
987
988   channel->appsink = gst_element_factory_make ("appsink", NULL);
989   gst_object_ref_sink (channel->appsink);
990   g_object_set (channel->appsink, "sync", FALSE, "async", FALSE, "caps", caps,
991       NULL);
992   gst_app_sink_set_callbacks (GST_APP_SINK (channel->appsink), &sink_callbacks,
993       channel, NULL);
994
995   gst_object_unref (pad);
996   gst_caps_unref (caps);
997 }
998
999 static void
1000 gst_webrtc_data_channel_dispose (GObject * object)
1001 {
1002   G_LOCK (outstanding_channels_lock);
1003   outstanding_channels = g_list_remove (outstanding_channels, object);
1004   G_UNLOCK (outstanding_channels_lock);
1005
1006   G_OBJECT_CLASS (parent_class)->dispose (object);
1007 }
1008
1009 static void
1010 gst_webrtc_data_channel_finalize (GObject * object)
1011 {
1012   WebRTCDataChannel *channel = WEBRTC_DATA_CHANNEL (object);
1013
1014   if (channel->src_probe) {
1015     GstPad *pad = gst_element_get_static_pad (channel->appsrc, "src");
1016     gst_pad_remove_probe (pad, channel->src_probe);
1017     gst_object_unref (pad);
1018     channel->src_probe = 0;
1019   }
1020
1021   if (channel->sctp_transport)
1022     g_signal_handlers_disconnect_by_data (channel->sctp_transport, channel);
1023   g_clear_object (&channel->sctp_transport);
1024
1025   g_clear_object (&channel->appsrc);
1026   g_clear_object (&channel->appsink);
1027
1028   G_OBJECT_CLASS (parent_class)->finalize (object);
1029 }
1030
1031 static void
1032 webrtc_data_channel_class_init (WebRTCDataChannelClass * klass)
1033 {
1034   GObjectClass *gobject_class = (GObjectClass *) klass;
1035   GstWebRTCDataChannelClass *channel_class =
1036       (GstWebRTCDataChannelClass *) klass;
1037
1038   gobject_class->constructed = gst_webrtc_data_channel_constructed;
1039   gobject_class->dispose = gst_webrtc_data_channel_dispose;
1040   gobject_class->finalize = gst_webrtc_data_channel_finalize;
1041
1042   channel_class->send_data = webrtc_data_channel_send_data;
1043   channel_class->send_string = webrtc_data_channel_send_string;
1044   channel_class->close = webrtc_data_channel_close;
1045 }
1046
1047 static void
1048 webrtc_data_channel_init (WebRTCDataChannel * channel)
1049 {
1050   G_LOCK (outstanding_channels_lock);
1051   outstanding_channels = g_list_prepend (outstanding_channels, channel);
1052   G_UNLOCK (outstanding_channels_lock);
1053 }
1054
1055 static void
1056 _data_channel_set_sctp_transport (WebRTCDataChannel * channel,
1057     WebRTCSCTPTransport * sctp)
1058 {
1059   g_return_if_fail (GST_IS_WEBRTC_DATA_CHANNEL (channel));
1060   g_return_if_fail (GST_IS_WEBRTC_SCTP_TRANSPORT (sctp));
1061
1062   GST_WEBRTC_DATA_CHANNEL_LOCK (channel);
1063   if (channel->sctp_transport)
1064     g_signal_handlers_disconnect_by_data (channel->sctp_transport, channel);
1065   GST_TRACE ("%p set sctp %p", channel, sctp);
1066
1067   gst_object_replace ((GstObject **) & channel->sctp_transport,
1068       GST_OBJECT (sctp));
1069
1070   if (sctp) {
1071     g_signal_connect (sctp, "stream-reset", G_CALLBACK (_on_sctp_stream_reset),
1072         channel);
1073     g_signal_connect (sctp, "notify::state", G_CALLBACK (_on_sctp_notify_state),
1074         channel);
1075   }
1076   GST_WEBRTC_DATA_CHANNEL_UNLOCK (channel);
1077 }
1078
1079 void
1080 webrtc_data_channel_link_to_sctp (WebRTCDataChannel * channel,
1081     WebRTCSCTPTransport * sctp_transport)
1082 {
1083   if (sctp_transport && !channel->sctp_transport) {
1084     gint id;
1085
1086     g_object_get (channel, "id", &id, NULL);
1087
1088     if (sctp_transport->association_established && id != -1) {
1089       gchar *pad_name;
1090
1091       _data_channel_set_sctp_transport (channel, sctp_transport);
1092       pad_name = g_strdup_printf ("sink_%u", id);
1093       if (!gst_element_link_pads (channel->appsrc, "src",
1094               channel->sctp_transport->sctpenc, pad_name))
1095         g_warn_if_reached ();
1096       g_free (pad_name);
1097
1098       _on_sctp_notify_state_unlocked (G_OBJECT (sctp_transport), channel);
1099     }
1100   }
1101 }