gstwebrtcbin.c 212 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* GStreamer
 * Copyright (C) 2017 Matthew Waters <matthew@centricular.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "gstwebrtcbin.h"
#include "gstwebrtcstats.h"
#include "transportstream.h"
#include "transportreceivebin.h"
#include "utils.h"
#include "webrtcsdp.h"
#include "webrtctransceiver.h"
31
32
#include "webrtcdatachannel.h"
#include "sctptransport.h"
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define RANDOM_SESSION_ID \
    ((((((guint64) g_random_int()) << 32) | \
       (guint64) g_random_int ())) & \
    G_GUINT64_CONSTANT (0x7fffffffffffffff))

#define PC_GET_LOCK(w) (&w->priv->pc_lock)
#define PC_LOCK(w) (g_mutex_lock (PC_GET_LOCK(w)))
#define PC_UNLOCK(w) (g_mutex_unlock (PC_GET_LOCK(w)))

#define PC_GET_COND(w) (&w->priv->pc_cond)
#define PC_COND_WAIT(w) (g_cond_wait(PC_GET_COND(w), PC_GET_LOCK(w)))
#define PC_COND_BROADCAST(w) (g_cond_broadcast(PC_GET_COND(w)))
#define PC_COND_SIGNAL(w) (g_cond_signal(PC_GET_COND(w)))

52
53
54
55
#define ICE_GET_LOCK(w) (&w->priv->ice_lock)
#define ICE_LOCK(w) (g_mutex_lock (ICE_GET_LOCK(w)))
#define ICE_UNLOCK(w) (g_mutex_unlock (ICE_GET_LOCK(w)))

56
57
58
59

/* The extra time for the rtpstorage compared to the RTP jitterbuffer (in ms) */
#define RTPSTORAGE_EXTRA_TIME (50)

60
61
62
/*
 * This webrtcbin implements the majority of the W3's peerconnection API and
 * implementation guide where possible. Generating offers, answers and setting
63
64
 * local and remote SDP's are all supported.  Both media descriptions and
 * descriptions involving data channels are supported.
65
66
67
68
69
70
71
72
 *
 * Each input/output pad is equivalent to a Track in W3 parlance which are
 * added/removed from the bin.  The number of requested sink pads is the number
 * of streams that will be sent to the receiver and will be associated with a
 * GstWebRTCRTPTransceiver (very similar to W3 RTPTransceiver's).
 *
 * On the receiving side, RTPTransceiver's are created in response to setting
 * a remote description.  Output pads for the receiving streams in the set
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
 * description are also created when data is received.
 *
 * A TransportStream is created when needed in order to transport the data over
 * the necessary DTLS/ICE channel to the peer.  The exact configuration depends
 * on the negotiated SDP's between the peers based on the bundle and rtcp
 * configuration.  Some cases are outlined below for a simple single
 * audio/video/data session:
 *
 * - max-bundle (requires rtcp-muxing) uses a single transport for all
 *   media/data transported.  Renegotiation involves adding/removing the
 *   necessary streams to the existing transports.
 * - max-compat without rtcp-mux involves two TransportStream per media stream
 *   to transport the rtp and the rtcp packets and a single TransportStream for
 *   all data channels.  Each stream change involves modifying the associated
 *   TransportStream/s as necessary.
88
89
90
91
92
93
94
 */

/*
 * TODO:
 * assert sending payload type matches the stream
 * reconfiguration (of anything)
 * LS groups
95
 * balanced bundle policy
96
97
 * setting custom DTLS certificates
 *
98
 * separate session id's from mlineindex properly
99
100
101
 * how to deal with replacing a input/output track/stream
 */

102
103
static void _update_need_negotiation (GstWebRTCBin * webrtc);

104
105
106
#define GST_CAT_DEFAULT gst_webrtc_bin_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);

107
108
109
110
111
112
113
114
115
116
static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink_%u",
    GST_PAD_SINK,
    GST_PAD_REQUEST,
    GST_STATIC_CAPS ("application/x-rtp"));

static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src_%u",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS ("application/x-rtp"));

117
118
119
120
121
enum
{
  PROP_PAD_TRANSCEIVER = 1,
};

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
static gboolean
_have_nice_elements (GstWebRTCBin * webrtc)
{
  GstPluginFeature *feature;

  feature = gst_registry_lookup_feature (gst_registry_get (), "nicesrc");
  if (feature) {
    gst_object_unref (feature);
  } else {
    GST_ELEMENT_ERROR (webrtc, CORE, MISSING_PLUGIN, NULL,
        ("%s", "libnice elements are not available"));
    return FALSE;
  }

  feature = gst_registry_lookup_feature (gst_registry_get (), "nicesink");
  if (feature) {
    gst_object_unref (feature);
  } else {
    GST_ELEMENT_ERROR (webrtc, CORE, MISSING_PLUGIN, NULL,
        ("%s", "libnice elements are not available"));
    return FALSE;
  }

  return TRUE;
}

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
static gboolean
_have_sctp_elements (GstWebRTCBin * webrtc)
{
  GstPluginFeature *feature;

  feature = gst_registry_lookup_feature (gst_registry_get (), "sctpdec");
  if (feature) {
    gst_object_unref (feature);
  } else {
    GST_ELEMENT_ERROR (webrtc, CORE, MISSING_PLUGIN, NULL,
        ("%s", "sctp elements are not available"));
    return FALSE;
  }

  feature = gst_registry_lookup_feature (gst_registry_get (), "sctpenc");
  if (feature) {
    gst_object_unref (feature);
  } else {
    GST_ELEMENT_ERROR (webrtc, CORE, MISSING_PLUGIN, NULL,
        ("%s", "sctp elements are not available"));
    return FALSE;
  }

  return TRUE;
}

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
static gboolean
_have_dtls_elements (GstWebRTCBin * webrtc)
{
  GstPluginFeature *feature;

  feature = gst_registry_lookup_feature (gst_registry_get (), "dtlsdec");
  if (feature) {
    gst_object_unref (feature);
  } else {
    GST_ELEMENT_ERROR (webrtc, CORE, MISSING_PLUGIN, NULL,
        ("%s", "dtls elements are not available"));
    return FALSE;
  }

  feature = gst_registry_lookup_feature (gst_registry_get (), "dtlsenc");
  if (feature) {
    gst_object_unref (feature);
  } else {
    GST_ELEMENT_ERROR (webrtc, CORE, MISSING_PLUGIN, NULL,
        ("%s", "dtls elements are not available"));
    return FALSE;
  }

  return TRUE;
}

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
G_DEFINE_TYPE (GstWebRTCBinPad, gst_webrtc_bin_pad, GST_TYPE_GHOST_PAD);

static void
gst_webrtc_bin_pad_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  switch (prop_id) {
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_webrtc_bin_pad_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
217
218
  GstWebRTCBinPad *pad = GST_WEBRTC_BIN_PAD (object);

219
  switch (prop_id) {
220
221
222
    case PROP_PAD_TRANSCEIVER:
      g_value_set_object (value, pad->trans);
      break;
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_webrtc_bin_pad_finalize (GObject * object)
{
  GstWebRTCBinPad *pad = GST_WEBRTC_BIN_PAD (object);

  if (pad->trans)
    gst_object_unref (pad->trans);
  pad->trans = NULL;

238
239
240
241
  if (pad->received_caps)
    gst_caps_unref (pad->received_caps);
  pad->received_caps = NULL;

242
243
244
245
246
247
248
249
250
251
252
  G_OBJECT_CLASS (gst_webrtc_bin_pad_parent_class)->finalize (object);
}

static void
gst_webrtc_bin_pad_class_init (GstWebRTCBinPadClass * klass)
{
  GObjectClass *gobject_class = (GObjectClass *) klass;

  gobject_class->get_property = gst_webrtc_bin_pad_get_property;
  gobject_class->set_property = gst_webrtc_bin_pad_set_property;
  gobject_class->finalize = gst_webrtc_bin_pad_finalize;
253
254
255
256
257
258
259

  g_object_class_install_property (gobject_class,
      PROP_PAD_TRANSCEIVER,
      g_param_spec_object ("transceiver", "Transceiver",
          "Transceiver associated with this pad",
          GST_TYPE_WEBRTC_RTP_TRANSCEIVER,
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
260
261
}

262
263
264
265
static gboolean
gst_webrtcbin_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
{
  GstWebRTCBinPad *wpad = GST_WEBRTC_BIN_PAD (pad);
266
267
  GstWebRTCBin *webrtc = GST_WEBRTC_BIN (parent);
  gboolean check_negotiation = FALSE;
268
269
270
271
272

  if (GST_EVENT_TYPE (event) == GST_EVENT_CAPS) {
    GstCaps *caps;

    gst_event_parse_caps (event, &caps);
273
    check_negotiation = (!wpad->received_caps
274
275
276
        || gst_caps_is_equal (wpad->received_caps, caps));
    gst_caps_replace (&wpad->received_caps, caps);

277
278
279
280
281
282
283
284
285
286
287
    GST_DEBUG_OBJECT (parent,
        "On %" GST_PTR_FORMAT " checking negotiation? %u, caps %"
        GST_PTR_FORMAT, pad, check_negotiation, caps);
  } else if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
    check_negotiation = TRUE;
  }

  if (check_negotiation) {
    PC_LOCK (webrtc);
    _update_need_negotiation (webrtc);
    PC_UNLOCK (webrtc);
288
289
290
291
292
  }

  return gst_pad_event_default (pad, parent, event);
}

293
294
295
296
297
298
299
300
static void
gst_webrtc_bin_pad_init (GstWebRTCBinPad * pad)
{
}

static GstWebRTCBinPad *
gst_webrtc_bin_pad_new (const gchar * name, GstPadDirection direction)
{
301
302
303
304
305
306
307
308
309
310
311
  GstWebRTCBinPad *pad;
  GstPadTemplate *template;

  if (direction == GST_PAD_SINK)
    template = gst_static_pad_template_get (&sink_template);
  else if (direction == GST_PAD_SRC)
    template = gst_static_pad_template_get (&src_template);
  else
    g_assert_not_reached ();

  pad =
312
      g_object_new (gst_webrtc_bin_pad_get_type (), "name", name, "direction",
313
314
      direction, "template", template, NULL);
  gst_object_unref (template);
315

316
317
  gst_pad_set_event_function (GST_PAD (pad), gst_webrtcbin_sink_event);

318
319
320
321
322
323
324
  GST_DEBUG_OBJECT (pad, "new visible pad with direction %s",
      direction == GST_PAD_SRC ? "src" : "sink");
  return pad;
}

#define gst_webrtc_bin_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstWebRTCBin, gst_webrtc_bin, GST_TYPE_BIN,
325
    G_ADD_PRIVATE (GstWebRTCBin)
326
    GST_DEBUG_CATEGORY_INIT (gst_webrtc_bin_debug, "webrtcbin", 0,
327
        "webrtcbin element"););
328

329
330
331
static GstPad *_connect_input_stream (GstWebRTCBin * webrtc,
    GstWebRTCBinPad * pad);

332
333
334
335
336
337
338
339
340
341
enum
{
  SIGNAL_0,
  CREATE_OFFER_SIGNAL,
  CREATE_ANSWER_SIGNAL,
  SET_LOCAL_DESCRIPTION_SIGNAL,
  SET_REMOTE_DESCRIPTION_SIGNAL,
  ADD_ICE_CANDIDATE_SIGNAL,
  ON_NEGOTIATION_NEEDED_SIGNAL,
  ON_ICE_CANDIDATE_SIGNAL,
342
  ON_NEW_TRANSCEIVER_SIGNAL,
343
344
  GET_STATS_SIGNAL,
  ADD_TRANSCEIVER_SIGNAL,
345
  GET_TRANSCEIVER_SIGNAL,
346
  GET_TRANSCEIVERS_SIGNAL,
347
  ADD_TURN_SERVER_SIGNAL,
348
349
  CREATE_DATA_CHANNEL_SIGNAL,
  ON_DATA_CHANNEL_SIGNAL,
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
  LAST_SIGNAL,
};

enum
{
  PROP_0,
  PROP_CONNECTION_STATE,
  PROP_SIGNALING_STATE,
  PROP_ICE_GATHERING_STATE,
  PROP_ICE_CONNECTION_STATE,
  PROP_LOCAL_DESCRIPTION,
  PROP_CURRENT_LOCAL_DESCRIPTION,
  PROP_PENDING_LOCAL_DESCRIPTION,
  PROP_REMOTE_DESCRIPTION,
  PROP_CURRENT_REMOTE_DESCRIPTION,
  PROP_PENDING_REMOTE_DESCRIPTION,
  PROP_STUN_SERVER,
  PROP_TURN_SERVER,
368
  PROP_BUNDLE_POLICY,
369
  PROP_ICE_TRANSPORT_POLICY,
370
  PROP_ICE_AGENT,
371
  PROP_LATENCY
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
};

static guint gst_webrtc_bin_signals[LAST_SIGNAL] = { 0 };

typedef struct
{
  guint session_id;
  GstWebRTCICEStream *stream;
} IceStreamItem;

/* FIXME: locking? */
GstWebRTCICEStream *
_find_ice_stream_for_session (GstWebRTCBin * webrtc, guint session_id)
{
  int i;

  for (i = 0; i < webrtc->priv->ice_stream_map->len; i++) {
    IceStreamItem *item =
        &g_array_index (webrtc->priv->ice_stream_map, IceStreamItem, i);

    if (item->session_id == session_id) {
      GST_TRACE_OBJECT (webrtc, "Found ice stream id %" GST_PTR_FORMAT " for "
          "session %u", item->stream, session_id);
      return item->stream;
    }
  }

  GST_TRACE_OBJECT (webrtc, "No ice stream available for session %u",
      session_id);
  return NULL;
}

void
_add_ice_stream_item (GstWebRTCBin * webrtc, guint session_id,
    GstWebRTCICEStream * stream)
{
  IceStreamItem item = { session_id, stream };

  GST_TRACE_OBJECT (webrtc, "adding ice stream %" GST_PTR_FORMAT " for "
      "session %u", stream, session_id);
  g_array_append_val (webrtc->priv->ice_stream_map, item);
}

typedef struct
{
  guint session_id;
  gchar *mid;
} SessionMidItem;

static void
clear_session_mid_item (SessionMidItem * item)
{
  g_free (item->mid);
}

typedef gboolean (*FindTransceiverFunc) (GstWebRTCRTPTransceiver * p1,
    gconstpointer data);

static GstWebRTCRTPTransceiver *
_find_transceiver (GstWebRTCBin * webrtc, gconstpointer data,
    FindTransceiverFunc func)
{
  int i;

  for (i = 0; i < webrtc->priv->transceivers->len; i++) {
    GstWebRTCRTPTransceiver *transceiver =
438
        g_ptr_array_index (webrtc->priv->transceivers, i);
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

    if (func (transceiver, data))
      return transceiver;
  }

  return NULL;
}

static gboolean
match_for_mid (GstWebRTCRTPTransceiver * trans, const gchar * mid)
{
  return g_strcmp0 (trans->mid, mid) == 0;
}

static gboolean
transceiver_match_for_mline (GstWebRTCRTPTransceiver * trans, guint * mline)
{
  return trans->mline == *mline;
}

static GstWebRTCRTPTransceiver *
_find_transceiver_for_mline (GstWebRTCBin * webrtc, guint mlineindex)
{
  GstWebRTCRTPTransceiver *trans;

  trans = _find_transceiver (webrtc, &mlineindex,
      (FindTransceiverFunc) transceiver_match_for_mline);

  GST_TRACE_OBJECT (webrtc,
      "Found transceiver %" GST_PTR_FORMAT " for mlineindex %u", trans,
      mlineindex);

  return trans;
}

typedef gboolean (*FindTransportFunc) (TransportStream * p1,
    gconstpointer data);

static TransportStream *
_find_transport (GstWebRTCBin * webrtc, gconstpointer data,
    FindTransportFunc func)
{
  int i;

  for (i = 0; i < webrtc->priv->transports->len; i++) {
484
    TransportStream *stream = g_ptr_array_index (webrtc->priv->transports, i);
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547

    if (func (stream, data))
      return stream;
  }

  return NULL;
}

static gboolean
match_stream_for_session (TransportStream * trans, guint * session)
{
  return trans->session_id == *session;
}

static TransportStream *
_find_transport_for_session (GstWebRTCBin * webrtc, guint session_id)
{
  TransportStream *stream;

  stream = _find_transport (webrtc, &session_id,
      (FindTransportFunc) match_stream_for_session);

  GST_TRACE_OBJECT (webrtc,
      "Found transport %" GST_PTR_FORMAT " for session %u", stream, session_id);

  return stream;
}

typedef gboolean (*FindPadFunc) (GstWebRTCBinPad * p1, gconstpointer data);

static GstWebRTCBinPad *
_find_pad (GstWebRTCBin * webrtc, gconstpointer data, FindPadFunc func)
{
  GstElement *element = GST_ELEMENT (webrtc);
  GList *l;

  GST_OBJECT_LOCK (webrtc);
  l = element->pads;
  for (; l; l = g_list_next (l)) {
    if (!GST_IS_WEBRTC_BIN_PAD (l->data))
      continue;
    if (func (l->data, data)) {
      gst_object_ref (l->data);
      GST_OBJECT_UNLOCK (webrtc);
      return l->data;
    }
  }

  l = webrtc->priv->pending_pads;
  for (; l; l = g_list_next (l)) {
    if (!GST_IS_WEBRTC_BIN_PAD (l->data))
      continue;
    if (func (l->data, data)) {
      gst_object_ref (l->data);
      GST_OBJECT_UNLOCK (webrtc);
      return l->data;
    }
  }
  GST_OBJECT_UNLOCK (webrtc);

  return NULL;
}

548
typedef gboolean (*FindDataChannelFunc) (WebRTCDataChannel * p1,
549
550
    gconstpointer data);

551
static WebRTCDataChannel *
552
553
554
555
556
557
_find_data_channel (GstWebRTCBin * webrtc, gconstpointer data,
    FindDataChannelFunc func)
{
  int i;

  for (i = 0; i < webrtc->priv->data_channels->len; i++) {
558
    WebRTCDataChannel *channel =
559
        g_ptr_array_index (webrtc->priv->data_channels, i);
560
561
562
563
564
565
566
567
568

    if (func (channel, data))
      return channel;
  }

  return NULL;
}

static gboolean
569
data_channel_match_for_id (WebRTCDataChannel * channel, gint * id)
570
{
571
  return channel->parent.id == *id;
572
573
}

574
static WebRTCDataChannel *
575
576
_find_data_channel_for_id (GstWebRTCBin * webrtc, gint id)
{
577
  WebRTCDataChannel *channel;
578
579
580
581
582
583
584
585
586
587

  channel = _find_data_channel (webrtc, &id,
      (FindDataChannelFunc) data_channel_match_for_id);

  GST_TRACE_OBJECT (webrtc,
      "Found data channel %" GST_PTR_FORMAT " for id %i", channel, id);

  return channel;
}

588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
static void
_add_pad_to_list (GstWebRTCBin * webrtc, GstWebRTCBinPad * pad)
{
  GST_OBJECT_LOCK (webrtc);
  webrtc->priv->pending_pads = g_list_prepend (webrtc->priv->pending_pads, pad);
  GST_OBJECT_UNLOCK (webrtc);
}

static void
_remove_pending_pad (GstWebRTCBin * webrtc, GstWebRTCBinPad * pad)
{
  GST_OBJECT_LOCK (webrtc);
  webrtc->priv->pending_pads = g_list_remove (webrtc->priv->pending_pads, pad);
  GST_OBJECT_UNLOCK (webrtc);
}

static void
_add_pad (GstWebRTCBin * webrtc, GstWebRTCBinPad * pad)
{
  _remove_pending_pad (webrtc, pad);

  if (webrtc->priv->running)
    gst_pad_set_active (GST_PAD (pad), TRUE);
  gst_element_add_pad (GST_ELEMENT (webrtc), GST_PAD (pad));
}

static void
_remove_pad (GstWebRTCBin * webrtc, GstWebRTCBinPad * pad)
{
  _remove_pending_pad (webrtc, pad);

  gst_element_remove_pad (GST_ELEMENT (webrtc), GST_PAD (pad));
}

typedef struct
{
  GstPadDirection direction;
  guint mlineindex;
} MLineMatch;

static gboolean
pad_match_for_mline (GstWebRTCBinPad * pad, const MLineMatch * match)
{
  return GST_PAD_DIRECTION (pad) == match->direction
      && pad->mlineindex == match->mlineindex;
}

static GstWebRTCBinPad *
_find_pad_for_mline (GstWebRTCBin * webrtc, GstPadDirection direction,
    guint mlineindex)
{
  MLineMatch m = { direction, mlineindex };

  return _find_pad (webrtc, &m, (FindPadFunc) pad_match_for_mline);
}

typedef struct
{
  GstPadDirection direction;
  GstWebRTCRTPTransceiver *trans;
} TransMatch;

static gboolean
pad_match_for_transceiver (GstWebRTCBinPad * pad, TransMatch * m)
{
  return GST_PAD_DIRECTION (pad) == m->direction && pad->trans == m->trans;
}

static GstWebRTCBinPad *
_find_pad_for_transceiver (GstWebRTCBin * webrtc, GstPadDirection direction,
    GstWebRTCRTPTransceiver * trans)
{
  TransMatch m = { direction, trans };

  return _find_pad (webrtc, &m, (FindPadFunc) pad_match_for_transceiver);
}

#if 0
static gboolean
match_for_ssrc (GstWebRTCBinPad * pad, guint * ssrc)
{
  return pad->ssrc == *ssrc;
}

static gboolean
match_for_pad (GstWebRTCBinPad * pad, GstWebRTCBinPad * other)
{
  return pad == other;
}
#endif

static gboolean
_unlock_pc_thread (GMutex * lock)
{
  g_mutex_unlock (lock);
  return G_SOURCE_REMOVE;
}

static gpointer
_gst_pc_thread (GstWebRTCBin * webrtc)
{
  PC_LOCK (webrtc);
  webrtc->priv->main_context = g_main_context_new ();
  webrtc->priv->loop = g_main_loop_new (webrtc->priv->main_context, FALSE);

  PC_COND_BROADCAST (webrtc);
  g_main_context_invoke (webrtc->priv->main_context,
      (GSourceFunc) _unlock_pc_thread, PC_GET_LOCK (webrtc));

  /* Having the thread be the thread default GMainContext will break the
   * required queue-like ordering (from W3's peerconnection spec) of re-entrant
   * tasks */
  g_main_loop_run (webrtc->priv->loop);

Jan Schmidt's avatar
Jan Schmidt committed
702
  GST_OBJECT_LOCK (webrtc);
703
704
  g_main_context_unref (webrtc->priv->main_context);
  webrtc->priv->main_context = NULL;
Jan Schmidt's avatar
Jan Schmidt committed
705
706
707
  GST_OBJECT_UNLOCK (webrtc);

  PC_LOCK (webrtc);
708
709
710
711
712
713
714
715
716
717
718
  g_main_loop_unref (webrtc->priv->loop);
  webrtc->priv->loop = NULL;
  PC_COND_BROADCAST (webrtc);
  PC_UNLOCK (webrtc);

  return NULL;
}

static void
_start_thread (GstWebRTCBin * webrtc)
{
719
720
  gchar *name;

721
  PC_LOCK (webrtc);
722
723
724
725
  name = g_strdup_printf ("%s:pc", GST_OBJECT_NAME (webrtc));
  webrtc->priv->thread = g_thread_new (name, (GThreadFunc) _gst_pc_thread,
      webrtc);
  g_free (name);
726
727
728
729
730
731
732
733
734
735

  while (!webrtc->priv->loop)
    PC_COND_WAIT (webrtc);
  webrtc->priv->is_closed = FALSE;
  PC_UNLOCK (webrtc);
}

static void
_stop_thread (GstWebRTCBin * webrtc)
{
Jan Schmidt's avatar
Jan Schmidt committed
736
  GST_OBJECT_LOCK (webrtc);
737
  webrtc->priv->is_closed = TRUE;
Jan Schmidt's avatar
Jan Schmidt committed
738
739
740
  GST_OBJECT_UNLOCK (webrtc);

  PC_LOCK (webrtc);
741
742
743
744
745
746
747
748
749
750
751
752
753
  g_main_loop_quit (webrtc->priv->loop);
  while (webrtc->priv->loop)
    PC_COND_WAIT (webrtc);
  PC_UNLOCK (webrtc);

  g_thread_unref (webrtc->priv->thread);
}

static gboolean
_execute_op (GstWebRTCBinTask * op)
{
  PC_LOCK (op->webrtc);
  if (op->webrtc->priv->is_closed) {
754
755
756
757
758
759
760
761
762
763
764
765
    if (op->promise) {
      GError *error =
          g_error_new (GST_WEBRTC_BIN_ERROR, GST_WEBRTC_BIN_ERROR_CLOSED,
          "webrtcbin is closed. aborting execution.");
      GstStructure *s =
          gst_structure_new ("application/x-gstwebrtcbin-promise-error",
          "error", G_TYPE_ERROR, error, NULL);

      gst_promise_reply (op->promise, s);

      g_clear_error (&error);
    }
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
    GST_DEBUG_OBJECT (op->webrtc,
        "Peerconnection is closed, aborting execution");
    goto out;
  }

  op->op (op->webrtc, op->data);

out:
  PC_UNLOCK (op->webrtc);
  return G_SOURCE_REMOVE;
}

static void
_free_op (GstWebRTCBinTask * op)
{
  if (op->notify)
    op->notify (op->data);
783
784
  if (op->promise)
    gst_promise_unref (op->promise);
785
786
787
  g_free (op);
}

788
789
790
791
792
793
794
/*
 * @promise is for correctly signalling the failure case to the caller when
 * the user supplies it.  Without passing it in, the promise would never
 * be replied to in the case that @webrtc becomes closed between the idle
 * source addition and the the execution of the idle source.
 */
gboolean
795
gst_webrtc_bin_enqueue_task (GstWebRTCBin * webrtc, GstWebRTCBinFunc func,
796
    gpointer data, GDestroyNotify notify, GstPromise * promise)
797
798
{
  GstWebRTCBinTask *op;
Jan Schmidt's avatar
Jan Schmidt committed
799
  GMainContext *ctx;
800
801
  GSource *source;

802
  g_return_val_if_fail (GST_IS_WEBRTC_BIN (webrtc), FALSE);
803

Jan Schmidt's avatar
Jan Schmidt committed
804
  GST_OBJECT_LOCK (webrtc);
805
  if (webrtc->priv->is_closed) {
Jan Schmidt's avatar
Jan Schmidt committed
806
    GST_OBJECT_UNLOCK (webrtc);
807
808
809
    GST_DEBUG_OBJECT (webrtc, "Peerconnection is closed, aborting execution");
    if (notify)
      notify (data);
810
    return FALSE;
811
  }
Jan Schmidt's avatar
Jan Schmidt committed
812
813
814
  ctx = g_main_context_ref (webrtc->priv->main_context);
  GST_OBJECT_UNLOCK (webrtc);

815
816
817
818
819
  op = g_new0 (GstWebRTCBinTask, 1);
  op->webrtc = webrtc;
  op->op = func;
  op->data = data;
  op->notify = notify;
820
821
  if (promise)
    op->promise = gst_promise_ref (promise);
822
823
824
825
826

  source = g_idle_source_new ();
  g_source_set_priority (source, G_PRIORITY_DEFAULT);
  g_source_set_callback (source, (GSourceFunc) _execute_op, op,
      (GDestroyNotify) _free_op);
Jan Schmidt's avatar
Jan Schmidt committed
827
  g_source_attach (source, ctx);
828
  g_source_unref (source);
Jan Schmidt's avatar
Jan Schmidt committed
829
  g_main_context_unref (ctx);
830
831

  return TRUE;
832
833
834
835
836
837
838
839
}

/* https://www.w3.org/TR/webrtc/#dom-rtciceconnectionstate */
static GstWebRTCICEConnectionState
_collate_ice_connection_states (GstWebRTCBin * webrtc)
{
#define STATE(val) GST_WEBRTC_ICE_CONNECTION_STATE_ ## val
  GstWebRTCICEConnectionState any_state = 0;
840
841
842
  gboolean all_new_or_closed = TRUE;
  gboolean all_completed_or_closed = TRUE;
  gboolean all_connected_completed_or_closed = TRUE;
843
844
845
846
  int i;

  for (i = 0; i < webrtc->priv->transceivers->len; i++) {
    GstWebRTCRTPTransceiver *rtp_trans =
847
        g_ptr_array_index (webrtc->priv->transceivers, i);
848
849
850
851
852
853
    WebRTCTransceiver *trans = WEBRTC_TRANSCEIVER (rtp_trans);
    TransportStream *stream = trans->stream;
    GstWebRTCICETransport *transport, *rtcp_transport;
    GstWebRTCICEConnectionState ice_state;
    gboolean rtcp_mux = FALSE;

854
855
    if (rtp_trans->stopped) {
      GST_TRACE_OBJECT (webrtc, "transceiver %p stopped", rtp_trans);
856
      continue;
857
858
859
860
    }

    if (!rtp_trans->mid) {
      GST_TRACE_OBJECT (webrtc, "transceiver %p has no mid", rtp_trans);
861
      continue;
862
    }
863
864
865

    g_object_get (stream, "rtcp-mux", &rtcp_mux, NULL);

866
    transport = webrtc_transceiver_get_dtls_transport (rtp_trans)->transport;
867
868
869

    /* get transport state */
    g_object_get (transport, "state", &ice_state, NULL);
870
871
    GST_TRACE_OBJECT (webrtc, "transceiver %p state 0x%x", rtp_trans,
        ice_state);
872
    any_state |= (1 << ice_state);
873
874
875
876
877
878
879
880

    if (ice_state != STATE (NEW) && ice_state != STATE (CLOSED))
      all_new_or_closed = FALSE;
    if (ice_state != STATE (COMPLETED) && ice_state != STATE (CLOSED))
      all_completed_or_closed = FALSE;
    if (ice_state != STATE (CONNECTED) && ice_state != STATE (COMPLETED)
        && ice_state != STATE (CLOSED))
      all_connected_completed_or_closed = FALSE;
881

882
883
    rtcp_transport =
        webrtc_transceiver_get_rtcp_dtls_transport (rtp_trans)->transport;
884
885
886

    if (!rtcp_mux && rtcp_transport && transport != rtcp_transport) {
      g_object_get (rtcp_transport, "state", &ice_state, NULL);
887
888
      GST_TRACE_OBJECT (webrtc, "transceiver %p RTCP state 0x%x", rtp_trans,
          ice_state);
889
      any_state |= (1 << ice_state);
890
891
892
893
894
895
896
897

      if (ice_state != STATE (NEW) && ice_state != STATE (CLOSED))
        all_new_or_closed = FALSE;
      if (ice_state != STATE (COMPLETED) && ice_state != STATE (CLOSED))
        all_completed_or_closed = FALSE;
      if (ice_state != STATE (CONNECTED) && ice_state != STATE (COMPLETED)
          && ice_state != STATE (CLOSED))
        all_connected_completed_or_closed = FALSE;
898
899
900
901
902
903
904
905
906
    }
  }

  GST_TRACE_OBJECT (webrtc, "ICE connection state: 0x%x", any_state);

  if (webrtc->priv->is_closed) {
    GST_TRACE_OBJECT (webrtc, "returning closed");
    return STATE (CLOSED);
  }
907
  /* Any of the RTCIceTransports are in the failed state. */
908
909
910
911
  if (any_state & (1 << STATE (FAILED))) {
    GST_TRACE_OBJECT (webrtc, "returning failed");
    return STATE (FAILED);
  }
912
  /* Any of the RTCIceTransports are in the disconnected state. */
913
914
915
916
  if (any_state & (1 << STATE (DISCONNECTED))) {
    GST_TRACE_OBJECT (webrtc, "returning disconnected");
    return STATE (DISCONNECTED);
  }
917
918
919
  /* All of the RTCIceTransports are in the new or closed state, or there are
   * no transports. */
  if (all_new_or_closed || webrtc->priv->transceivers->len == 0) {
920
921
922
    GST_TRACE_OBJECT (webrtc, "returning new");
    return STATE (NEW);
  }
923
924
925
926
927
928
929
930
931
  /* Any of the RTCIceTransports are in the checking or new state. */
  if ((any_state & (1 << STATE (CHECKING))) || (any_state & (1 << STATE (NEW)))) {
    GST_TRACE_OBJECT (webrtc, "returning checking");
    return STATE (CHECKING);
  }
  /* All RTCIceTransports are in the completed or closed state. */
  if (all_completed_or_closed) {
    GST_TRACE_OBJECT (webrtc, "returning completed");
    return STATE (COMPLETED);
932
  }
933
934
  /* All RTCIceTransports are in the connected, completed or closed state. */
  if (all_connected_completed_or_closed) {
935
936
937
938
    GST_TRACE_OBJECT (webrtc, "returning connected");
    return STATE (CONNECTED);
  }

939
940
  GST_FIXME ("unspecified situation, returning old state");
  return webrtc->ice_connection_state;
941
942
943
944
945
946
947
948
949
950
951
952
953
954
#undef STATE
}

/* https://www.w3.org/TR/webrtc/#dom-rtcicegatheringstate */
static GstWebRTCICEGatheringState
_collate_ice_gathering_states (GstWebRTCBin * webrtc)
{
#define STATE(val) GST_WEBRTC_ICE_GATHERING_STATE_ ## val
  GstWebRTCICEGatheringState any_state = 0;
  gboolean all_completed = webrtc->priv->transceivers->len > 0;
  int i;

  for (i = 0; i < webrtc->priv->transceivers->len; i++) {
    GstWebRTCRTPTransceiver *rtp_trans =
955
        g_ptr_array_index (webrtc->priv->transceivers, i);
956
957
    WebRTCTransceiver *trans = WEBRTC_TRANSCEIVER (rtp_trans);
    TransportStream *stream = trans->stream;
958
    GstWebRTCDTLSTransport *dtls_transport;
959
960
961
962
    GstWebRTCICETransport *transport, *rtcp_transport;
    GstWebRTCICEGatheringState ice_state;
    gboolean rtcp_mux = FALSE;

963
964
965
    if (rtp_trans->stopped || stream == NULL) {
      GST_TRACE_OBJECT (webrtc, "transceiver %p stopped or unassociated",
          rtp_trans);
966
      continue;
967
968
    }

969
970
    /* We only have a mid in the transceiver after we got the SDP answer,
     * which is usually long after gathering has finished */
971
972
973
    if (!rtp_trans->mid) {
      GST_TRACE_OBJECT (webrtc, "transceiver %p has no mid", rtp_trans);
    }
974
975
976

    g_object_get (stream, "rtcp-mux", &rtcp_mux, NULL);

977
978
979
980
981
982
983
    dtls_transport = webrtc_transceiver_get_dtls_transport (rtp_trans);
    if (dtls_transport == NULL) {
      GST_WARNING ("Transceiver %p has no DTLS transport", rtp_trans);
      continue;
    }

    transport = dtls_transport->transport;
984
985
986

    /* get gathering state */
    g_object_get (transport, "gathering-state", &ice_state, NULL);
987
988
    GST_TRACE_OBJECT (webrtc, "transceiver %p gathering state: 0x%x", rtp_trans,
        ice_state);
989
990
991
992
    any_state |= (1 << ice_state);
    if (ice_state != STATE (COMPLETE))
      all_completed = FALSE;

993
994
995
996
997
998
    dtls_transport = webrtc_transceiver_get_rtcp_dtls_transport (rtp_trans);
    if (dtls_transport == NULL) {
      GST_WARNING ("Transceiver %p has no DTLS RTCP transport", rtp_trans);
      continue;
    }
    rtcp_transport = dtls_transport->transport;
999
1000

    if (!rtcp_mux && rtcp_transport && rtcp_transport != transport) {