gstwebrtcbin.c 189 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 52 53 54

#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)))

/*
 * This webrtcbin implements the majority of the W3's peerconnection API and
 * implementation guide where possible. Generating offers, answers and setting
55 56
 * local and remote SDP's are all supported.  Both media descriptions and
 * descriptions involving data channels are supported.
57 58 59 60 61 62 63 64
 *
 * 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
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
 * 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.
80 81 82 83 84 85 86
 */

/*
 * TODO:
 * assert sending payload type matches the stream
 * reconfiguration (of anything)
 * LS groups
87
 * balanced bundle policy
88 89 90 91 92 93
 * setting custom DTLS certificates
 *
 * seperate session id's from mlineindex properly
 * how to deal with replacing a input/output track/stream
 */

94 95
static void _update_need_negotiation (GstWebRTCBin * webrtc);

96 97 98
#define GST_CAT_DEFAULT gst_webrtc_bin_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);

99 100 101 102 103
enum
{
  PROP_PAD_TRANSCEIVER = 1,
};

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
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;
}

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
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;
}

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
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;
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
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)
{
199 200
  GstWebRTCBinPad *pad = GST_WEBRTC_BIN_PAD (object);

201
  switch (prop_id) {
202 203 204
    case PROP_PAD_TRANSCEIVER:
      g_value_set_object (value, pad->trans);
      break;
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    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;

220 221 222 223
  if (pad->received_caps)
    gst_caps_unref (pad->received_caps);
  pad->received_caps = NULL;

224 225 226 227 228 229 230 231 232 233 234
  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;
235 236 237 238 239 240 241

  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));
242 243
}

244 245 246 247
static gboolean
gst_webrtcbin_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
{
  GstWebRTCBinPad *wpad = GST_WEBRTC_BIN_PAD (pad);
248 249
  GstWebRTCBin *webrtc = GST_WEBRTC_BIN (parent);
  gboolean check_negotiation = FALSE;
250 251 252 253 254

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

    gst_event_parse_caps (event, &caps);
255
    check_negotiation = (!wpad->received_caps
256 257 258
        || gst_caps_is_equal (wpad->received_caps, caps));
    gst_caps_replace (&wpad->received_caps, caps);

259 260 261 262 263 264 265 266 267 268 269
    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);
270 271 272 273 274
  }

  return gst_pad_event_default (pad, parent, event);
}

275 276 277 278 279 280 281 282 283 284 285 286
static void
gst_webrtc_bin_pad_init (GstWebRTCBinPad * pad)
{
}

static GstWebRTCBinPad *
gst_webrtc_bin_pad_new (const gchar * name, GstPadDirection direction)
{
  GstWebRTCBinPad *pad =
      g_object_new (gst_webrtc_bin_pad_get_type (), "name", name, "direction",
      direction, NULL);

287 288
  gst_pad_set_event_function (GST_PAD (pad), gst_webrtcbin_sink_event);

289 290 291 292 293 294 295 296 297 298 299 300
  if (!gst_ghost_pad_construct (GST_GHOST_PAD (pad))) {
    gst_object_unref (pad);
    return NULL;
  }

  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,
301
    G_ADD_PRIVATE (GstWebRTCBin)
302
    GST_DEBUG_CATEGORY_INIT (gst_webrtc_bin_debug, "webrtcbin", 0,
303 304
        "webrtcbin element");
    );
305

306 307 308
static GstPad *_connect_input_stream (GstWebRTCBin * webrtc,
    GstWebRTCBinPad * pad);

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
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"));

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,
329
  ON_NEW_TRANSCEIVER_SIGNAL,
330 331
  GET_STATS_SIGNAL,
  ADD_TRANSCEIVER_SIGNAL,
332
  GET_TRANSCEIVER_SIGNAL,
333
  GET_TRANSCEIVERS_SIGNAL,
334
  ADD_TURN_SERVER_SIGNAL,
335 336
  CREATE_DATA_CHANNEL_SIGNAL,
  ON_DATA_CHANNEL_SIGNAL,
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  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,
355
  PROP_BUNDLE_POLICY,
356
  PROP_ICE_TRANSPORT_POLICY,
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 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 438 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 484 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
};

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 =
        g_array_index (webrtc->priv->transceivers, GstWebRTCRTPTransceiver *,
        i);

    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++) {
    TransportStream *stream =
        g_array_index (webrtc->priv->transports, TransportStream *,
        i);

    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;
}

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
typedef gboolean (*FindDataChannelFunc) (GstWebRTCDataChannel * p1,
    gconstpointer data);

static GstWebRTCDataChannel *
_find_data_channel (GstWebRTCBin * webrtc, gconstpointer data,
    FindDataChannelFunc func)
{
  int i;

  for (i = 0; i < webrtc->priv->data_channels->len; i++) {
    GstWebRTCDataChannel *channel =
        g_array_index (webrtc->priv->data_channels, GstWebRTCDataChannel *,
        i);

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

  return NULL;
}

static gboolean
data_channel_match_for_id (GstWebRTCDataChannel * channel, gint * id)
{
  return channel->id == *id;
}

static GstWebRTCDataChannel *
_find_data_channel_for_id (GstWebRTCBin * webrtc, gint id)
{
  GstWebRTCDataChannel *channel;

  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;
}

577 578 579 580 581 582 583 584 585 586 587 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 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
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);

  PC_LOCK (webrtc);
  g_main_context_unref (webrtc->priv->main_context);
  webrtc->priv->main_context = NULL;
  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)
{
  PC_LOCK (webrtc);
  webrtc->priv->thread = g_thread_new ("gst-pc-ops",
      (GThreadFunc) _gst_pc_thread, webrtc);

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

static void
_stop_thread (GstWebRTCBin * webrtc)
{
  PC_LOCK (webrtc);
  webrtc->priv->is_closed = TRUE;
  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) {
    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);
  g_free (op);
}

void
gst_webrtc_bin_enqueue_task (GstWebRTCBin * webrtc, GstWebRTCBinFunc func,
    gpointer data, GDestroyNotify notify)
{
  GstWebRTCBinTask *op;
  GSource *source;

  g_return_if_fail (GST_IS_WEBRTC_BIN (webrtc));

  if (webrtc->priv->is_closed) {
    GST_DEBUG_OBJECT (webrtc, "Peerconnection is closed, aborting execution");
    if (notify)
      notify (data);
    return;
  }
  op = g_new0 (GstWebRTCBinTask, 1);
  op->webrtc = webrtc;
  op->op = func;
  op->data = data;
  op->notify = notify;

  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);
  g_source_attach (source, webrtc->priv->main_context);
  g_source_unref (source);
}

/* 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;
  gboolean all_closed = TRUE;
  int i;

  for (i = 0; i < webrtc->priv->transceivers->len; i++) {
    GstWebRTCRTPTransceiver *rtp_trans =
        g_array_index (webrtc->priv->transceivers, GstWebRTCRTPTransceiver *,
        i);
    WebRTCTransceiver *trans = WEBRTC_TRANSCEIVER (rtp_trans);
    TransportStream *stream = trans->stream;
    GstWebRTCICETransport *transport, *rtcp_transport;
    GstWebRTCICEConnectionState ice_state;
    gboolean rtcp_mux = FALSE;

    if (rtp_trans->stopped)
      continue;
    if (!rtp_trans->mid)
      continue;

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

808
    transport = webrtc_transceiver_get_dtls_transport (rtp_trans)->transport;
809 810 811 812 813 814 815

    /* get transport state */
    g_object_get (transport, "state", &ice_state, NULL);
    any_state |= (1 << ice_state);
    if (ice_state != STATE (CLOSED))
      all_closed = FALSE;

816 817
    rtcp_transport =
        webrtc_transceiver_get_rtcp_dtls_transport (rtp_trans)->transport;
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902

    if (!rtcp_mux && rtcp_transport && transport != rtcp_transport) {
      g_object_get (rtcp_transport, "state", &ice_state, NULL);
      any_state |= (1 << ice_state);
      if (ice_state != STATE (CLOSED))
        all_closed = FALSE;
    }
  }

  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);
  }
  /* Any of the RTCIceTransport s are in the failed state. */
  if (any_state & (1 << STATE (FAILED))) {
    GST_TRACE_OBJECT (webrtc, "returning failed");
    return STATE (FAILED);
  }
  /* Any of the RTCIceTransport s are in the disconnected state and
   * none of them are in the failed state. */
  if (any_state & (1 << STATE (DISCONNECTED))) {
    GST_TRACE_OBJECT (webrtc, "returning disconnected");
    return STATE (DISCONNECTED);
  }
  /* Any of the RTCIceTransport's are in the checking state and none of them
   * are in the failed or disconnected state. */
  if (any_state & (1 << STATE (CHECKING))) {
    GST_TRACE_OBJECT (webrtc, "returning checking");
    return STATE (CHECKING);
  }
  /* Any of the RTCIceTransport s are in the new state and none of them are
   * in the checking, failed or disconnected state, or all RTCIceTransport's
   * are in the closed state. */
  if ((any_state & (1 << STATE (NEW))) || all_closed) {
    GST_TRACE_OBJECT (webrtc, "returning new");
    return STATE (NEW);
  }
  /* All RTCIceTransport s are in the connected, completed or closed state
   * and at least one of them is in the connected state. */
  if (any_state & (1 << STATE (CONNECTED) | 1 << STATE (COMPLETED) | 1 <<
          STATE (CLOSED)) && any_state & (1 << STATE (CONNECTED))) {
    GST_TRACE_OBJECT (webrtc, "returning connected");
    return STATE (CONNECTED);
  }
  /* All RTCIceTransport s are in the completed or closed state and at least
   * one of them is in the completed state. */
  if (any_state & (1 << STATE (COMPLETED) | 1 << STATE (CLOSED))
      && any_state & (1 << STATE (COMPLETED))) {
    GST_TRACE_OBJECT (webrtc, "returning connected");
    return STATE (CONNECTED);
  }

  GST_FIXME ("unspecified situation, returning new");
  return STATE (NEW);
#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 =
        g_array_index (webrtc->priv->transceivers, GstWebRTCRTPTransceiver *,
        i);
    WebRTCTransceiver *trans = WEBRTC_TRANSCEIVER (rtp_trans);
    TransportStream *stream = trans->stream;
    GstWebRTCICETransport *transport, *rtcp_transport;
    GstWebRTCICEGatheringState ice_state;
    gboolean rtcp_mux = FALSE;

    if (rtp_trans->stopped)
      continue;
    if (!rtp_trans->mid)
      continue;

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

903
    transport = webrtc_transceiver_get_dtls_transport (rtp_trans)->transport;
904 905 906 907 908 909 910

    /* get gathering state */
    g_object_get (transport, "gathering-state", &ice_state, NULL);
    any_state |= (1 << ice_state);
    if (ice_state != STATE (COMPLETE))
      all_completed = FALSE;

911 912
    rtcp_transport =
        webrtc_transceiver_get_rtcp_dtls_transport (rtp_trans)->transport;
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

    if (!rtcp_mux && rtcp_transport && rtcp_transport != transport) {
      g_object_get (rtcp_transport, "gathering-state", &ice_state, NULL);
      any_state |= (1 << ice_state);
      if (ice_state != STATE (COMPLETE))
        all_completed = FALSE;
    }
  }

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

  /* Any of the RTCIceTransport s are in the gathering state. */
  if (any_state & (1 << STATE (GATHERING))) {
    GST_TRACE_OBJECT (webrtc, "returning gathering");
    return STATE (GATHERING);
  }
  /* At least one RTCIceTransport exists, and all RTCIceTransport s are in
   * the completed gathering state. */
  if (all_completed) {
    GST_TRACE_OBJECT (webrtc, "returning complete");
    return STATE (COMPLETE);
  }

  /* Any of the RTCIceTransport s are in the new gathering state and none
   * of the transports are in the gathering state, or there are no transports. */
  GST_TRACE_OBJECT (webrtc, "returning new");
  return STATE (NEW);
#undef STATE
}

/* https://www.w3.org/TR/webrtc/#rtcpeerconnectionstate-enum */
static GstWebRTCPeerConnectionState
_collate_peer_connection_states (GstWebRTCBin * webrtc)
{
#define STATE(v) GST_WEBRTC_PEER_CONNECTION_STATE_ ## v
#define ICE_STATE(v) GST_WEBRTC_ICE_CONNECTION_STATE_ ## v
#define DTLS_STATE(v) GST_WEBRTC_DTLS_TRANSPORT_STATE_ ## v
  GstWebRTCICEConnectionState any_ice_state = 0;
  GstWebRTCDTLSTransportState any_dtls_state = 0;
  int i;

  for (i = 0; i < webrtc->priv->transceivers->len; i++) {
    GstWebRTCRTPTransceiver *rtp_trans =
        g_array_index (webrtc->priv->transceivers, GstWebRTCRTPTransceiver *,
        i);
    WebRTCTransceiver *trans = WEBRTC_TRANSCEIVER (rtp_trans);
    TransportStream *stream = trans->stream;
    GstWebRTCDTLSTransport *transport, *rtcp_transport;
    GstWebRTCICEGatheringState ice_state;
    GstWebRTCDTLSTransportState dtls_state;
    gboolean rtcp_mux = FALSE;

    if (rtp_trans->stopped)
      continue;
    if (!rtp_trans->mid)
      continue;

    g_object_get (stream, "rtcp-mux", &rtcp_mux, NULL);
971
    transport = webrtc_transceiver_get_dtls_transport (rtp_trans);
972 973 974 975 976 977 978

    /* get transport state */
    g_object_get (transport, "state", &dtls_state, NULL);
    any_dtls_state |= (1 << dtls_state);
    g_object_get (transport->transport, "state", &ice_state, NULL);
    any_ice_state |= (1 << ice_state);

979
    rtcp_transport = webrtc_transceiver_get_rtcp_dtls_transport (rtp_trans);
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

    if (!rtcp_mux && rtcp_transport && rtcp_transport != transport) {
      g_object_get (rtcp_transport, "state", &dtls_state, NULL);
      any_dtls_state |= (1 << dtls_state);
      g_object_get (rtcp_transport->transport, "state", &ice_state, NULL);
      any_ice_state |= (1 << ice_state);
    }
  }

  GST_TRACE_OBJECT (webrtc, "ICE connection state: 0x%x. DTLS connection "
      "state: 0x%x", any_ice_state, any_dtls_state);

  /* The RTCPeerConnection object's [[ isClosed]] slot is true.  */
  if (webrtc->priv->is_closed) {
    GST_TRACE_OBJECT (webrtc, "returning closed");
    return STATE (CLOSED);
  }

  /* Any of the RTCIceTransport s or RTCDtlsTransport s are in a failed state. */
  if (any_ice_state & (1 << ICE_STATE (FAILED))) {
    GST_TRACE_OBJECT (webrtc, "returning failed");
    return STATE (FAILED);
  }
  if (any_dtls_state & (1 << DTLS_STATE (FAILED))) {
    GST_TRACE_OBJECT (webrtc, "returning failed");
    return STATE (FAILED);
  }

  /* Any of the RTCIceTransport's or RTCDtlsTransport's are in the connecting
   * or checking state and none of them is in the failed state. */
  if (any_ice_state & (1 << ICE_STATE (CHECKING))) {
    GST_TRACE_OBJECT (webrtc, "returning connecting");
    return STATE (CONNECTING);
  }
  if (any_dtls_state & (1 << DTLS_STATE (CONNECTING))) {
    GST_TRACE_OBJECT (webrtc, "returning connecting");
    return STATE (CONNECTING);
  }

  /* Any of the RTCIceTransport's or RTCDtlsTransport's are in the disconnected
   * state and none of them are in the failed or connecting or checking state. */
  if (any_ice_state & (1 << ICE_STATE (DISCONNECTED))) {
    GST_TRACE_OBJECT (webrtc, "returning disconnected");
    return STATE (DISCONNECTED);
  }

  /* All RTCIceTransport's and RTCDtlsTransport's are in the connected,
   * completed or closed state and at least of them is in the connected or
   * completed state. */
  if (!(any_ice_state & ~(1 << ICE_STATE (CONNECTED) | 1 <<
              ICE_STATE (COMPLETED) | 1 << ICE_STATE (CLOSED)))
      && !(any_dtls_state & ~(1 << DTLS_STATE (CONNECTED) | 1 <<
              DTLS_STATE (CLOSED)))
      && (any_ice_state & (1 << ICE_STATE (CONNECTED) | 1 <<
              ICE_STATE (COMPLETED))
          || any_dtls_state & (1 << DTLS_STATE (CONNECTED)))) {
    GST_TRACE_OBJECT (webrtc, "returning connected");
    return STATE (CONNECTED);
  }

  /* Any of the RTCIceTransport's or RTCDtlsTransport's are in the new state
   * and none of the transports are in the connecting, checking, failed or
   * disconnected state, or all transports are in the closed state. */
  if (!(any_ice_state & ~(1 << ICE_STATE (CLOSED)))) {
    GST_TRACE_OBJECT (webrtc, "returning new");
    return STATE (NEW);
  }
  if ((any_ice_state & (1 << ICE_STATE (NEW))
          || any_dtls_state & (1 << DTLS_STATE (NEW)))
      && !(any_ice_state & (1 << ICE_STATE (CHECKING) | 1 << ICE_STATE (FAILED)
              | (1 << ICE_STATE (DISCONNECTED))))
      && !(any_dtls_state & (1 << DTLS_STATE (CONNECTING) | 1 <<
              DTLS_STATE (FAILED)))) {
    GST_TRACE_OBJECT (webrtc, "returning new");
    return STATE (NEW);
  }

  GST_FIXME_OBJECT (webrtc, "Undefined situation detected, returning new");
  return STATE (NEW);
#undef DTLS_STATE
#undef ICE_STATE
#undef STATE
}

static void
_update_ice_gathering_state_task (GstWebRTCBin * webrtc, gpointer data)
{
  GstWebRTCICEGatheringState old_state = webrtc->ice_gathering_state;
  GstWebRTCICEGatheringState new_state;

  new_state = _collate_ice_gathering_states (webrtc);

  if (new_state != webrtc->ice_gathering_state) {
    gchar *old_s, *new_s;

    old_s = _enum_value_to_string (GST_TYPE_WEBRTC_ICE_GATHERING_STATE,
        old_state);
    new_s = _enum_value_to_string (GST_TYPE_WEBRTC_ICE_GATHERING_STATE,
        new_state);
    GST_INFO_OBJECT (webrtc, "ICE gathering state change from %s(%u) to %s(%u)",
        old_s, old_state, new_s, new_state);
    g_free (old_s);
    g_free (new_s);

    webrtc->ice_gathering_state = new_state;
    PC_UNLOCK (webrtc);
    g_object_notify (G_OBJECT (webrtc), "ice-gathering-state");
    PC_LOCK (webrtc);
  }
}

static void
_update_ice_gathering_state (GstWebRTCBin * webrtc)
{
  gst_webrtc_bin_enqueue_task (webrtc, _update_ice_gathering_state_task, NULL,
      NULL);
}

static void
_update_ice_connection_state_task (GstWebRTCBin * webrtc, gpointer data)
{
  GstWebRTCICEConnectionState old_state = webrtc->ice_connection_state;
  GstWebRTCICEConnectionState new_state;

  new_state = _collate_ice_connection_states (webrtc);

  if (new_state != old_state) {
    gchar *old_s, *new_s;

    old_s = _enum_value_to_string (GST_TYPE_WEBRTC_ICE_CONNECTION_STATE,
        old_state);
    new_s = _enum_value_to_string (GST_TYPE_WEBRTC_ICE_CONNECTION_STATE,
        new_state);
    GST_INFO_OBJECT (webrtc,
        "ICE connection state change from %s(%u) to %s(%u)", old_s, old_state,
        new_s, new_state);
    g_free (old_s);
    g_free (new_s);

    webrtc->ice_connection_state = new_state;
    PC_UNLOCK (webrtc);
    g_object_notify (G_OBJECT (webrtc), "ice-connection-state");
    PC_LOCK (webrtc);
  }
}

static void
_update_ice_connection_state (GstWebRTCBin * webrtc)
{
  gst_webrtc_bin_enqueue_task (webrtc, _update_ice_connection_state_task, NULL,
      NULL);
}

static void
_update_peer_connection_state_task (GstWebRTCBin * webrtc, gpointer data)
{
  GstWebRTCPeerConnectionState old_state = webrtc->peer_connection_state;
  GstWebRTCPeerConnectionState new_state;

  new_state = _collate_peer_connection_states (webrtc);

  if (new_state != old_state) {
    gchar *old_s, *new_s;

    old_s = _enum_value_to_string (GST_TYPE_WEBRTC_PEER_CONNECTION_STATE,
        old_state);
    new_s = _enum_value_to_string (GST_TYPE_WEBRTC_PEER_CONNECTION_STATE,
        new_state);
    GST_INFO_OBJECT (webrtc,
        "Peer connection state change from %s(%u) to %s(%u)", old_s, old_state,
        new_s, new_state);
    g_free (old_s);
    g_free (new_s);

    webrtc->peer_connection_state = new_state;
    PC_UNLOCK (webrtc);
    g_object_notify (G_OBJECT (webrtc), "connection-state");
    PC_LOCK (webrtc);
  }
}

static void
_update_peer_connection_state (GstWebRTCBin * webrtc)
{
  gst_webrtc_bin_enqueue_task (webrtc, _update_peer_connection_state_task,
      NULL, NULL);
}

1168 1169 1170 1171 1172 1173 1174 1175 1176
static gboolean
_all_sinks_have_caps (GstWebRTCBin * webrtc)
{
  GList *l;
  gboolean res = FALSE;

  GST_OBJECT_LOCK (webrtc);
  l = GST_ELEMENT (webrtc)->pads;
  for (; l; l = g_list_next (l)) {
1177 1178
    GstWebRTCBinPad *wpad;

1179 1180
    if (!GST_IS_WEBRTC_BIN_PAD (l->data))
      continue;
1181 1182 1183 1184

    wpad = GST_WEBRTC_BIN_PAD (l->data);
    if (GST_PAD_DIRECTION (l->data) == GST_PAD_SINK && !wpad->received_caps
        && (!wpad->trans || !wpad->trans->stopped)) {
1185
      goto done;
1186
    }
1187 1188 1189 1190
  }

  l = webrtc->priv->pending_pads;
  for (; l; l = g_list_next (l)) {
1191
    if (!GST_IS_WEBRTC_BIN_PAD (l->data)) {
1192
      goto done;
1193
    }
1194 1195 1196 1197 1198 1199 1200 1201 1202
  }

  res = TRUE;

done:
  GST_OBJECT_UNLOCK (webrtc);
  return res;
}

1203 1204 1205 1206 1207 1208 1209 1210
/* http://w3c.github.io/webrtc-pc/#dfn-check-if-negotiation-is-needed */
static gboolean
_check_if_negotiation_is_needed (GstWebRTCBin * webrtc)
{
  int i;

  GST_LOG_OBJECT (webrtc, "checking if negotiation is needed");

1211 1212 1213 1214 1215 1216 1217 1218
  /* We can't negotiate until we have received caps on all our sink pads,
   * as we will need the ssrcs in our offer / answer */
  if (!_all_sinks_have_caps (webrtc)) {
    GST_LOG_OBJECT (webrtc,
        "no negotiation possible until caps have been received on all sink pads");
    return FALSE;
  }

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
  /* If any implementation-specific negotiation is required, as described at
   * the start of this section, return "true".
   * FIXME */
  /* FIXME: emit when input caps/format changes? */

  if (!webrtc->current_local_description) {
    GST_LOG_OBJECT (webrtc, "no local description set");
    return TRUE;
  }

  if (!webrtc->current_remote_description) {
    GST_LOG_OBJECT (webrtc, "no remote description set");
    return TRUE;
  }

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
  /* If connection has created any RTCDataChannel's, and no m= section has
   * been negotiated yet for data, return "true". */
  if (webrtc->priv->data_channels->len > 0) {
    if (_message_get_datachannel_index (webrtc->current_local_description->
            sdp) >= G_MAXUINT) {
      GST_LOG_OBJECT (webrtc,
          "no data channel media section and have %u " "transports",
          webrtc->priv->data_channels->len);
      return TRUE;
    }
  }

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
  for (i = 0; i < webrtc->priv->transceivers->len; i++) {
    GstWebRTCRTPTransceiver *trans;

    trans =
        g_array_index (webrtc->priv->transceivers, GstWebRTCRTPTransceiver *,
        i);

    if (trans->stopped) {
      /* FIXME: If t is stopped and is associated with an m= section according to
       * [JSEP] (section 3.4.1.), but the associated m= section is not yet
       * rejected in connection's currentLocalDescription or
       * currentRemoteDescription , return "true". */
      GST_FIXME_OBJECT (webrtc,
          "check if the transceiver is rejected in descriptions");
    } else {
      const GstSDPMedia *media;
      GstWebRTCRTPTransceiverDirection local_dir, remote_dir;

1264
      if (trans->mline == -1 || trans->mid == NULL) {
1265 1266
        GST_LOG_OBJECT (webrtc, "unassociated transceiver %i %" GST_PTR_FORMAT
            " mid %s", i, trans, trans->mid);
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
        return TRUE;
      }
      /* internal inconsistency */
      g_assert (trans->mline <
          gst_sdp_message_medias_len (webrtc->current_local_description->sdp));
      g_assert (trans->mline <
          gst_sdp_message_medias_len (webrtc->current_remote_description->sdp));

      /* FIXME: msid handling
       * If t's direction is "sendrecv" or "sendonly", and the associated m=
       * section in connection's currentLocalDescription doesn't contain an
       * "a=msid" line, return "true". */

      media =
          gst_sdp_message_get_media (webrtc->current_local_description->sdp,
          trans->mline);
      local_dir = _get_direction_from_media (media);

      media =
          gst_sdp_message_get_media (webrtc->current_remote_description->sdp,
          trans->mline);
      remote_dir = _get_direction_from_media (media);

      if (webrtc->current_local_description->type == GST_WEBRTC_SDP_TYPE_OFFER) {
        /* If connection's currentLocalDescription if of type "offer", and
         * the direction of the associated m= section in neither the offer
         * nor answer matches t's direction, return "true". */

        if (local_dir != trans->direction && remote_dir != trans->direction) {
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
          gchar *local_str, *remote_str, *dir_str;

          local_str =
              _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
              local_dir);
          remote_str =
              _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
              remote_dir);
          dir_str =
              _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
              trans->direction);

          GST_LOG_OBJECT (webrtc, "transceiver direction (%s) doesn't match "
              "description (local %s remote %s)", dir_str, local_str,
              remote_str);

          g_free (dir_str);
          g_free (local_str);
          g_free (remote_str);

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
          return TRUE;
        }
      } else if (webrtc->current_local_description->type ==
          GST_WEBRTC_SDP_TYPE_ANSWER) {
        GstWebRTCRTPTransceiverDirection intersect_dir;

        /* If connection's currentLocalDescription if of type "answer", and
         * the direction of the associated m= section in the answer does not
         * match t's direction intersected with the offered direction (as
         * described in [JSEP] (section 5.3.1.)), return "true". */

        /* remote is the offer, local is the answer */
        intersect_dir = _intersect_answer_directions (remote_dir, local_dir);

        if (intersect_dir != trans->direction) {
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
          gchar *local_str, *remote_str, *inter_str, *dir_str;

          local_str =
              _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
              local_dir);
          remote_str =
              _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
              remote_dir);
          dir_str =
              _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
              trans->direction);
          inter_str =
              _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
              intersect_dir);

          GST_LOG_OBJECT (webrtc, "transceiver direction (%s) doesn't match "
              "description intersected direction %s (local %s remote %s)",
              dir_str, local_str, inter_str, remote_str);

          g_free (dir_str);
          g_free (local_str);
          g_free (remote_str);
          g_free (inter_str);

1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
          return TRUE;
        }
      }
    }
  }

  GST_LOG_OBJECT (webrtc, "no negotiation needed");
  return FALSE;
}

static void
_check_need_negotiation_task (GstWebRTCBin * webrtc, gpointer unused)
{
  if (webrtc->priv->need_negotiation) {
    GST_TRACE_OBJECT (webrtc, "emitting on-negotiation-needed");
    PC_UNLOCK (webrtc);
    g_signal_emit (webrtc, gst_webrtc_bin_signals[ON_NEGOTIATION_NEEDED_SIGNAL],
        0);
    PC_LOCK (webrtc);
  }
}

/* http://w3c.github.io/webrtc-pc/#dfn-update-the-negotiation-needed-flag */
static void
_update_need_negotiation (GstWebRTCBin * webrtc)
{
  /* If connection's [[isClosed]] slot is true, abort these steps. */
  if (webrtc->priv->is_closed)
    return;
  /* If connection's signaling state is not "stable", abort these steps. */
  if (webrtc->signaling_state != GST_WEBRTC_SIGNALING_STATE_STABLE)
    return;

  /* If the result of checking if negotiation is needed is "false", clear the
   * negotiation-needed flag by setting connection's [[ needNegotiation]] slot
   * to false, and abort these steps. */
  if (!_check_if_negotiation_is_needed (webrtc)) {
    webrtc->priv->need_negotiation = FALSE;
    return;
  }
  /* If connection's [[needNegotiation]] slot is already true, abort these steps. */
  if (webrtc->priv->need_negotiation)
    return;
  /* Set connection's [[needNegotiation]] slot to true. */
  webrtc->priv->need_negotiation = TRUE;
  /* Queue a task to check connection's [[ needNegotiation]] slot and, if still
   * true, fire a simple event named negotiationneeded at connection. */
  gst_webrtc_bin_enqueue_task (webrtc, _check_need_negotiation_task, NULL,
      NULL);
}

static GstCaps *
1407 1408 1409
_find_codec_preferences (GstWebRTCBin * webrtc,
    GstWebRTCRTPTransceiver * rtp_trans, GstPadDirection direction,
    guint media_idx)
1410
{
1411
  WebRTCTransceiver *trans = (WebRTCTransceiver *) rtp_trans;
1412 1413 1414 1415 1416
  GstCaps *ret = NULL;

  GST_LOG_OBJECT (webrtc, "retreiving codec preferences from %" GST_PTR_FORMAT,
      trans);

1417
  if (rtp_trans && rtp_trans->codec_preferences) {
1418
    GST_LOG_OBJECT (webrtc, "Using codec preferences: %" GST_PTR_FORMAT,
1419 1420
        rtp_trans->codec_preferences);
    ret = gst_caps_ref (rtp_trans->codec_preferences);
1421
  } else {
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
    GstWebRTCBinPad *pad = NULL;

    /* try to find a pad */
    if (!trans
        || !(pad = _find_pad_for_transceiver (webrtc, direction, rtp_trans)))
      pad = _find_pad_for_mline (webrtc, direction, media_idx);

    if (!pad) {
      if (trans && trans->last_configured_caps)
        ret = gst_caps_ref (trans->last_configured_caps);
    } else {
1433 1434 1435 1436 1437
      GstCaps *caps = NULL;

      if (pad->received_caps) {
        caps = gst_caps_ref (pad->received_caps);
      } else if ((caps = gst_pad_get_current_caps (GST_PAD (pad)))) {
1438 1439 1440 1441 1442 1443 1444
        GST_LOG_OBJECT (webrtc, "Using current pad caps: %" GST_PTR_FORMAT,
            caps);
      } else {
        if ((caps = gst_pad_peer_query_caps (GST_PAD (pad), NULL)))
          GST_LOG_OBJECT (webrtc, "Using peer query caps: %" GST_PTR_FORMAT,
              caps);
      }
1445 1446 1447 1448
      if (caps) {
        if (trans)
          gst_caps_replace (&trans->last_configured_caps, caps);

1449
        ret = caps;
1450 1451
      }

1452 1453 1454 1455
      gst_object_unref (pad);
    }
  }

1456 1457 1458
  if (!ret)
    GST_DEBUG_OBJECT (trans, "Could not find caps for mline %u", media_idx);

1459 1460 1461 1462
  return ret;
}

static GstCaps *
1463 1464
_add_supported_attributes_to_caps (GstWebRTCBin * webrtc,
    WebRTCTransceiver * trans, const GstCaps * caps)
1465 1466
{
  GstCaps *ret;
1467
  guint i;
1468 1469 1470 1471 1472 1473

  ret = gst_caps_make_writable (caps);

  for (i = 0; i < gst_caps_get_size (ret); i++) {
    GstStructure *s = gst_caps_get_structure (ret, i);

1474 1475 1476 1477
    if (trans->do_nack)
      if (!gst_structure_has_field (s, "rtcp-fb-nack"))
        gst_structure_set (s, "rtcp-fb-nack", G_TYPE_BOOLEAN, TRUE, NULL);

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    if (!gst_structure_has_field (s, "rtcp-fb-nack-pli"))
      gst_structure_set (s, "rtcp-fb-nack-pli", G_TYPE_BOOLEAN, TRUE, NULL);
    /* FIXME: is this needed? */
    /*if (!gst_structure_has_field (s, "rtcp-fb-transport-cc"))
       gst_structure_set (s, "rtcp-fb-nack-pli", G_TYPE_BOOLEAN, TRUE, NULL); */

    /* FIXME: codec-specific paramters? */
  }

  return ret;
}

static void
_on_ice_transport_notify_state (GstWebRTCICETransport * transport,
    GParamSpec * pspec, GstWebRTCBin * webrtc)
{
  _update_ice_connection_state (webrtc);
  _update_peer_connection_state (webrtc);
}

static void
_on_ice_transport_notify_gathering_state (GstWebRTCICETransport * transport,
    GParamSpec * pspec, GstWebRTCBin * webrtc)
{
  _update_ice_gathering_state (webrtc);
}

static void
_on_dtls_transport_notify_state (GstWebRTCDTLSTransport * transport,
    GParamSpec * pspec, GstWebRTCBin * webrtc)
{
  _update_peer_connection_state (webrtc);
}

static WebRTCTransceiver *
1513 1514
_create_webrtc_transceiver (GstWebRTCBin * webrtc,
    GstWebRTCRTPTransceiverDirection direction, guint mline)
1515 1516 1517 1518 1519 1520
{
  WebRTCTransceiver *trans;
  GstWebRTCRTPTransceiver *rtp_trans;
  GstWebRTCRTPSender *sender;
  GstWebRTCRTPReceiver *receiver;

1521
  sender = gst_webrtc_rtp_sender_new ();
1522 1523 1524
  receiver = gst_webrtc_rtp_receiver_new ();
  trans = webrtc_transceiver_new (webrtc, sender, receiver);
  rtp_trans = GST_WEBRTC_RTP_TRANSCEIVER (trans);
1525 1526
  rtp_trans->direction = direction;
  rtp_trans->mline = mline;
1527 1528 1529 1530 1531 1532

  g_array_append_val (webrtc->priv->transceivers, trans);

  gst_object_unref (sender);
  gst_object_unref (receiver);

1533 1534 1535
  g_signal_emit (webrtc, gst_webrtc_bin_signals[ON_NEW_TRANSCEIVER_SIGNAL],
      0, trans);

1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
  return trans;
}

static TransportStream *
_create_transport_channel (GstWebRTCBin * webrtc, guint session_id)
{
  GstWebRTCDTLSTransport *transport;
  TransportStream *ret;

  /* FIXME: how to parametrize the sender and the receiver */
  ret = transport_stream_new (webrtc, session_id);
  transport = ret->transport;

  g_signal_connect (G_OBJECT (transport->transport), "notify::state",
      G_CALLBACK (_on_ice_transport_notify_state), webrtc);
  g_signal_connect (G_OBJECT (transport->transport),
      "notify::gathering-state",
      G_CALLBACK (_on_ice_transport_notify_gathering_state), webrtc);
  g_signal_connect (G_OBJECT (transport), "notify::state",
      G_CALLBACK (_on_dtls_transport_notify_state), webrtc);

  if ((transport = ret->rtcp_transport)) {
    g_signal_connect (G_OBJECT (transport->transport),
        "notify::state", G_CALLBACK (_on_ice_transport_notify_state), webrtc);
    g_signal_connect (G_OBJECT (transport->transport),
        "notify::gathering-state",
        G_CALLBACK (_on_ice_transport_notify_gathering_state), webrtc);
    g_signal_connect (G_OBJECT (transport), "notify::state",
        G_CALLBACK (_on_dtls_transport_notify_state), webrtc);
  }

1567 1568 1569 1570 1571 1572 1573
  GST_TRACE_OBJECT (webrtc,
      "Create transport %" GST_PTR_FORMAT " for session %u", ret, session_id);

  return ret;
}

static TransportStream *
1574
_get_or_create_rtp_transport_channel (GstWebRTCBin * webrtc, guint session_id)
1575
{
1576
  TransportStream *ret;
1577 1578
  gchar *pad_name;

1579
  ret = _find_transport_for_session (webrtc, session_id);
1580

1581 1582 1583 1584 1585
  if (!ret) {
    ret = _create_transport_channel (webrtc, session_id);
    gst_bin_add (GST_BIN (webrtc), GST_ELEMENT (ret->send_bin));
    gst_bin_add (GST_BIN (webrtc), GST_ELEMENT (ret->receive_bin));
    g_array_append_val (webrtc->priv->transports, ret);
1586

1587 1588 1589 1590 1591
    pad_name = g_strdup_printf ("recv_rtcp_sink_%u", ret->session_id);
    if (!gst_element_link_pads (GST_ELEMENT (ret->receive_bin), "rtcp_src",
            GST_ELEMENT (webrtc->rtpbin), pad_name))
      g_warn_if_reached ();
    g_free (pad_name);
1592

1593 1594 1595 1596 1597 1598
    pad_name = g_strdup_printf ("send_rtcp_src_%u", ret->session_id);
    if (!gst_element_link_pads (GST_ELEMENT (webrtc->rtpbin), pad_name,
            GST_ELEMENT (ret->send_bin), "rtcp_sink"))
      g_warn_if_reached ();
    g_free (pad_name);
  }
1599 1600 1601 1602 1603 1604 1605

  gst_element_sync_state_with_parent (GST_ELEMENT (ret->send_bin));
  gst_element_sync_state_with_parent (GST_ELEMENT (ret->receive_bin));

  return ret;
}

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
/* this is called from the webrtc thread with the pc lock held */
static void
_on_data_channel_ready_state (GstWebRTCDataChannel * channel,
    GParamSpec * pspec, GstWebRTCBin * webrtc)
{
  GstWebRTCDataChannelState ready_state;
  guint i;

  g_object_get (channel, "ready-state", &ready_state, NULL);

  if (ready_state == GST_WEBRTC_DATA_CHANNEL_STATE_OPEN) {
    gboolean found = FALSE;

    for (i = 0; i < webrtc->priv->pending_data_channels->len; i++) {
      GstWebRTCDataChannel *c;

      c = g_array_index (webrtc->priv->pending_data_channels,
          GstWebRTCDataChannel *, i);
      if (c == channel) {
        found = TRUE;
        g_array_remove_index (webrtc->priv->pending_data_channels, i);
        break;
      }
    }
    if (found == FALSE) {
      GST_FIXME_OBJECT (webrtc, "Received open for unknown data channel");
      return;
    }

    g_array_append_val (webrtc->priv->data_channels, channel);

    g_signal_emit (webrtc, gst_webrtc_bin_signals[ON_DATA_CHANNEL_SIGNAL], 0,
        gst_object_ref (channel));
  }
}

static void
_on_sctpdec_pad_added (GstElement * sctpdec, GstPad * pad,
    GstWebRTCBin * webrtc)
{
  GstWebRTCDataChannel *channel;
  guint stream_id;
  GstPad *sink_pad;

  if (sscanf (GST_PAD_NAME (pad), "src_%u", &stream_id) != 1)
    return;

  PC_LOCK (webrtc);
  channel = _find_data_channel_for_id (webrtc, stream_id);
  if (!channel) {
    channel = g_object_new (GST_TYPE_WEBRTC_DATA_CHANNEL, NULL);
    channel->id = stream_id;
    channel->webrtcbin = webrtc;

    gst_bin_add (GST_BIN (webrtc), channel->appsrc);
    gst_bin_add (GST_BIN (webrtc), channel->appsink);

    gst_element_sync_state_with_parent (channel->appsrc);
    gst_element_sync_state_with_parent (channel->appsink);

1666 1667
    gst_webrtc_data_channel_link_to_sctp (channel,
        webrtc->priv->sctp_transport);
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703

    g_array_append_val (webrtc->priv->pending_data_channels, channel);
  }

  g_signal_connect (channel, "notify::ready-state",
      G_CALLBACK (_on_data_channel_ready_state), webrtc);

  sink_pad = gst_element_get_static_pad (channel->appsink, "sink");
  if (gst_pad_link (pad, sink_pad) != GST_PAD_LINK_OK)
    GST_WARNING_OBJECT (channel, "Failed to link sctp pad %s with channel %"
        GST_PTR_FORMAT, GST_PAD_NAME (pad), channel);
  gst_object_unref (sink_pad);
  PC_UNLOCK (webrtc);
}

static void
_on_sctp_state_notify (GstWebRTCSCTPTransport * sctp, GParamSpec * pspec,
    GstWebRTCBin * webrtc)
{
  GstWebRTCSCTPTransportState state;

  g_object_get (sctp, "state", &state, NULL);

  if (state == GST_WEBRTC_SCTP_TRANSPORT_STATE_CONNECTED) {
    int i;

    PC_LOCK (webrtc);
    GST_DEBUG_OBJECT (webrtc, "SCTP association established");

    for (i = 0; i < webrtc->priv->data_channels->len; i++) {
      GstWebRTCDataChannel *channel;

      channel =
          g_array_index (webrtc->priv->data_channels, GstWebRTCDataChannel *,
          i);

1704 1705
      gst_webrtc_data_channel_link_to_sctp (channel,
          webrtc->priv->sctp_transport);
1706 1707 1708 1709 1710 1711 1712 1713 1714

      if (!channel->negotiated && !channel->opened)
        gst_webrtc_data_channel_start_negotiation (channel);
    }
    PC_UNLOCK (webrtc);
  }
}

static TransportStream *
1715
_get_or_create_data_channel_transports (GstWebRTCBin * webrtc, guint session_id)
1716 1717
{
  if (!webrtc->priv->data_channel_transport) {
1718
    TransportStream *stream;
1719 1720 1721
    GstWebRTCSCTPTransport *sctp_transport;
    int i;

1722 1723 1724 1725 1726 1727 1728 1729 1730
    stream = _find_transport_for_session (webrtc, session_id);

    if (!stream) {
      stream = _create_transport_channel (webrtc, session_id);
      gst_bin_add (GST_BIN (webrtc), GST_ELEMENT (stream->send_bin));
      gst_bin_add (GST_BIN (webrtc), GST_ELEMENT (stream->receive_bin));
      g_array_append_val (webrtc->priv->transports, stream);
    }

1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
    webrtc->priv->data_channel_transport = stream;

    g_object_set (stream, "rtcp-mux", TRUE, NULL);

    if (!(sctp_transport = webrtc->priv->sctp_transport)) {
      sctp_transport = gst_webrtc_sctp_transport_new ();
      sctp_transport->transport =
          g_object_ref (webrtc->priv->data_channel_transport->transport);
      sctp_transport->webrtcbin = webrtc;

      gst_bin_add (GST_BIN (webrtc), sctp_transport->sctpdec);
      gst_bin_add (GST_BIN (webrtc), sctp_transport->sctpenc);
    }

    g_signal_connect (sctp_transport->sctpdec, "pad-added",
        G_CALLBACK (_on_sctpdec_pad_added), webrtc);
    g_signal_connect (sctp_transport, "notify::state",
        G_CALLBACK (_on_sctp_state_notify), webrtc);

    if (!gst_element_link_pads (GST_ELEMENT (stream->receive_bin), "data_src",
            GST_ELEMENT (sctp_transport->sctpdec), "sink"))
      g_warn_if_reached ();

    if (!gst_element_link_pads (GST_ELEMENT (sctp_transport->sctpenc), "src",
            GST_ELEMENT (stream->send_bin), "data_sink"))
      g_warn_if_reached ();

    for (i = 0; i < webrtc->priv->data_channels->len; i++) {
      GstWebRTCDataChannel *channel;

      channel =
          g_array_index (webrtc->priv->data_channels, GstWebRTCDataChannel *,
          i);

1765 1766
      gst_webrtc_data_channel_link_to_sctp (channel,
          webrtc->priv->sctp_transport);
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    }

    gst_element_sync_state_with_parent (GST_ELEMENT (stream->send_bin));
    gst_element_sync_state_with_parent (GST_ELEMENT (stream->receive_bin));

    if (!webrtc->priv->sctp_transport) {
      gst_element_sync_state_with_parent (GST_ELEMENT
          (sctp_transport->sctpdec));
      gst_element_sync_state_with_parent (GST_ELEMENT
          (sctp_transport->sctpenc));
    }

    webrtc->priv->sctp_transport = sctp_transport;
  }

  return webrtc->priv->data_channel_transport;
}

static TransportStream *
1786
_get_or_create_transport_stream (GstWebRTCBin * webrtc, guint session_id,
1787 1788 1789
    gboolean is_datachannel)
{
  if (is_datachannel)
1790
    return _get_or_create_data_channel_transports (webrtc, session_id);
1791
  else
1792
    return _get_or_create_rtp_transport_channel (webrtc, session_id);
1793 1794
}

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
static guint
g_array_find_uint (GArray * array, guint val)
{
  guint i;

  for (i = 0; i < array->len; i++) {
    if (g_array_index (array, guint, i) == val)
      return i;
  }

  return G_MAXUINT;
}

static gboolean
_pick_available_pt (GArray * reserved_pts, guint * i)
{
  gboolean ret = FALSE;

  for (*i = 96; *i <= 127; (*i)++) {
    if (g_array_find_uint (reserved_pts, *i) == G_MAXUINT) {
      g_array_append_val (reserved_pts, *i);
      ret = TRUE;
      break;
    }
  }

  return ret;
}

static gboolean
_pick_fec_payload_types (GstWebRTCBin * webrtc, WebRTCTransceiver * trans,
    GArray * reserved_pts, gint clockrate, gint * rtx_target_pt,
    GstSDPMedia * media)
{
  gboolean ret = TRUE;

  if (trans->fec_type == GST_WEBRTC_FEC_TYPE_NONE)
    goto done;

  if (trans->fec_type == GST_WEBRTC_FEC_TYPE_ULP_RED && clockrate != -1) {
    guint pt;
    gchar *str;

    if (!(ret = _pick_available_pt (reserved_pts, &pt)))
      goto done;

    /* https://tools.ietf.org/html/rfc5109#section-14.1 */

    str = g_strdup_printf ("%u", pt);
    gst_sdp_media_add_format (media, str);
    g_free (str);
    str = g_strdup_printf ("%u red/%d", pt, clockrate);
    gst_sdp_media_add_attribute (media, "rtpmap", str);
    g_free (str);

    *rtx_target_pt = pt;

    if (!(ret = _pick_available_pt (reserved_pts, &pt)))
      goto done;

    str = g_strdup_printf ("%u", pt);
    gst_sdp_media_add_format (media, str);
    g_free (str);
    str = g_strdup_printf ("%u ulpfec/%d", pt, clockrate);
    gst_sdp_media_add_attribute (media, "rtpmap", str);
    g_free (str);
  }

done:
  return ret;
}

static gboolean
_pick_rtx_payload_types (GstWebRTCBin * webrtc, WebRTCTransceiver * trans,
    GArray * reserved_pts, gint clockrate, gint target_pt, guint target_ssrc,
    GstSDPMedia * media)
{
  gboolean ret = TRUE;

  if (trans->local_rtx_ssrc_map)
    gst_structure_free (trans->local_rtx_ssrc_map);

  trans->local_rtx_ssrc_map =
      gst_structure_new_empty ("application/x-rtp-ssrc-map");

  if (trans->do_nack) {
    guint pt;
    gchar *str;

    if (!(ret = _pick_available_pt (reserved_pts, &pt)))
      goto done;

    /* https://tools.ietf.org/html/rfc4588#section-8.6 */

    str = g_strdup_printf ("%u", target_ssrc);
    gst_structure_set (trans->local_rtx_ssrc_map, str, G_TYPE_UINT,
        g_random_int (), NULL);
Jan Schmidt's avatar
Jan Schmidt committed
1892
    g_free (str);
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005

    str = g_strdup_printf ("%u", pt);
    gst_sdp_media_add_format (media, str);
    g_free (str);

    str = g_strdup_printf ("%u rtx/%d", pt, clockrate);
    gst_sdp_media_add_attribute (media, "rtpmap", str);
    g_free (str);

    str = g_strdup_printf ("%u apt=%d", pt, target_pt);
    gst_sdp_media_add_attribute (media, "fmtp", str);
    g_free (str);
  }

done:
  return ret;
}

/* https://tools.ietf.org/html/rfc5576#section-4.2 */
static gboolean
_media_add_rtx_ssrc_group (GQuark field_id, const GValue * value,
    GstSDPMedia * media)
{
  gchar *str;

  str =
      g_strdup_printf ("FID %s %u", g_quark_to_string (field_id),
      g_value_get_uint (value));
  gst_sdp_media_add_attribute (media, "ssrc-group", str);

  g_free (str);

  return TRUE;
}

typedef struct
{
  GstSDPMedia *media;
  GstWebRTCBin *webrtc;
  WebRTCTransceiver *trans;
} RtxSsrcData;

static gboolean
_media_add_rtx_ssrc (GQuark field_id, const GValue * value, RtxSsrcData * data)
{
  gchar *str;
  GstStructure *sdes;
  const gchar *cname;

  g_object_get (data->webrtc->rtpbin, "sdes", &sdes, NULL);
  /* http://www.freesoft.org/CIE/RFC/1889/24.htm */
  cname = gst_structure_get_string (sdes, "cname");

  /* https://tools.ietf.org/html/draft-ietf-mmusic-msid-16 */
  str =
      g_strdup_printf ("%u msid:%s %s", g_value_get_uint (value),
      cname, GST_OBJECT_NAME (data->trans));
  gst_sdp_media_add_attribute (data->media, "ssrc", str);
  g_free (str);

  str = g_strdup_printf ("%u cname:%s", g_value_get_uint (value), cname);
  gst_sdp_media_add_attribute (data->media, "ssrc", str);
  g_free (str);

  gst_structure_free (sdes);

  return TRUE;
}

static void
_media_add_ssrcs (GstSDPMedia * media, GstCaps * caps, GstWebRTCBin * webrtc,
    WebRTCTransceiver * trans)
{
  guint i;
  RtxSsrcData data = { media, webrtc, trans };
  const gchar *cname;
  GstStructure *sdes;

  g_object_get (webrtc->rtpbin, "sdes", &sdes, NULL);
  /* http://www.freesoft.org/CIE/RFC/1889/24.htm */
  cname = gst_structure_get_string (sdes, "cname");

  if (trans->local_rtx_ssrc_map)
    gst_structure_foreach (trans->local_rtx_ssrc_map,
        (GstStructureForeachFunc) _media_add_rtx_ssrc_group, media);

  for (i = 0; i < gst_caps_get_size (caps); i++) {
    const GstStructure *s = gst_caps_get_structure (caps, i);
    guint ssrc;

    if (gst_structure_get_uint (s, "ssrc", &ssrc)) {
      gchar *str;

      /* https://tools.ietf.org/html/draft-ietf-mmusic-msid-16 */
      str =
          g_strdup_printf ("%u msid:%s %s", ssrc, cname,
          GST_OBJECT_NAME (trans));
      gst_sdp_media_add_attribute (media, "ssrc", str);
      g_free (str);

      str = g_strdup_printf ("%u cname:%s", ssrc, cname);
      gst_sdp_media_add_attribute (media, "ssrc", str);
      g_free (str);
    }
  }

  gst_structure_free (sdes);

  if (trans->local_rtx_ssrc_map)
    gst_structure_foreach (trans->local_rtx_ssrc_map,
        (GstStructureForeachFunc) _media_add_rtx_ssrc, &data);
}

2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
static void
_add_fingerprint_to_media (GstWebRTCDTLSTransport * transport,
    GstSDPMedia * media)
{
  gchar *cert, *fingerprint, *val;

  g_object_get (transport, "certificate", &cert, NULL);

  fingerprint =
      _generate_fingerprint_from_certificate (cert, G_CHECKSUM_SHA256);
  g_free (cert);
  val =
      g_strdup_printf ("%s %s",
      _g_checksum_to_webrtc_string (G_CHECKSUM_SHA256), fingerprint);
  g_free (fingerprint);

  gst_sdp_media_add_attribute (media, "fingerprint", val);
  g_free (val);
}

2026 2027 2028
/* based off https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-18#section-5.2.1 */
static gboolean
sdp_media_from_transceiver (GstWebRTCBin * webrtc, GstSDPMedia * media,
2029
    GstWebRTCRTPTransceiver * trans, GstWebRTCSDPType type, guint media_idx,
2030 2031
    GString * bundled_mids, guint bundle_idx, gchar * bundle_ufrag,
    gchar * bundle_pwd, GArray * reserved_pts)
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
{
  /* TODO:
   * rtp header extensions
   * ice attributes
   * rtx
   * fec
   * msid-semantics
   * msid
   * dtls fingerprints
   * multiple dtls fingerprints https://tools.ietf.org/html/draft-ietf-mmusic-4572-update-05
   */
2043
  GstSDPMessage *last_offer = _get_latest_self_generated_sdp (webrtc);
2044 2045
  gchar *direction, *sdp_mid, *ufrag, *pwd;
  gboolean bundle_only;
2046 2047 2048 2049 2050 2051 2052
  GstCaps *caps;
  int i;

  if (trans->direction == GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_NONE
      || trans->direction == GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_INACTIVE)
    return FALSE;

2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
  g_assert (trans->mline == -1 || trans->mline == media_idx);

  bundle_only = bundled_mids && bundle_idx != media_idx
      && webrtc->bundle_policy == GST_WEBRTC_BUNDLE_POLICY_MAX_BUNDLE;

  /* mandated by JSEP */
  gst_sdp_media_add_attribute (media, "setup", "actpass");

  /* FIXME: deal with ICE restarts */
  if (last_offer && trans->mline != -1 && trans->mid) {
    ufrag = g_strdup (_media_get_ice_ufrag (last_offer, trans->mline));
    pwd = g_strdup (_media_get_ice_pwd (last_offer, trans->mline));
    GST_DEBUG_OBJECT (trans, "%u Using previous ice parameters", media_idx);
  } else {
    GST_DEBUG_OBJECT (trans,
        "%u Generating new ice parameters mline %i, mid %s", media_idx,
        trans->mline, trans->mid);
    if (webrtc->bundle_policy == GST_WEBRTC_BUNDLE_POLICY_NONE) {
      _generate_ice_credentials (&ufrag, &pwd);
    } else {
      g_assert (bundle_ufrag && bundle_pwd);
      ufrag = g_strdup (bundle_ufrag);
      pwd = g_strdup (bundle_pwd);
    }
  }

  gst_sdp_media_add_attribute (media, "ice-ufrag", ufrag);
  gst_sdp_media_add_attribute (media, "ice-pwd", pwd);
  g_free (ufrag);
  g_free (pwd);

  gst_sdp_media_set_port_info (media, bundle_only || trans->stopped ? 0 : 9, 0);
2085 2086 2087
  gst_sdp_media_set_proto (media, "UDP/TLS/RTP/SAVPF");
  gst_sdp_media_add_connection (media, "IN", "IP4", "0.0.0.0", 0, 0);

2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
  if (bundle_only) {
    gst_sdp_media_add_attribute (media, "bundle-only", NULL);
  }

  /* FIXME: negotiate this */
  /* FIXME: when bundle_only, these should not be added:
   * https://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-52#section-7.1.3
   * However, this causes incompatibilities with current versions
   * of the major browsers */
  gst_sdp_media_add_attribute (media, "rtcp-mux", "");
  gst_sdp_media_add_attribute (media, "rtcp-rsize", NULL);

2100 2101 2102 2103 2104 2105 2106 2107
  direction =
      _enum_value_to_string (GST_TYPE_WEBRTC_RTP_TRANSCEIVER_DIRECTION,
      trans->direction);
  gst_sdp_media_add_attribute (media, direction, "");
  g_free (direction);

  if (type == GST_WEBRTC_SDP_TYPE_OFFER) {
    caps = _find_codec_preferences (webrtc, trans, GST_PAD_SINK, media_idx);
2108 2109 2110
    caps =
        _add_supported_attributes_to_caps (webrtc, WEBRTC_TRANSCEIVER (trans),
        caps);
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
  } else {
    g_assert_not_reached ();
  }

  if (!caps || gst_caps_is_empty (caps) || gst_caps_is_any (caps)) {
    GST_WARNING_OBJECT (webrtc, "no caps available for transceiver, skipping");
    if (caps)
      gst_caps_unref (caps);
    return FALSE;
  }

  for (i = 0; i < gst_caps_get_size (caps); i++) {
    GstCaps *format = gst_caps_new_empty ();
    const GstStructure *s = gst_caps_get_structure (caps, i);

    gst_caps_append_structure (format, gst_structure_copy (s));

    GST_DEBUG_OBJECT (webrtc, "Adding %u-th caps %" GST_PTR_FORMAT
        " to %u-th media", i, format, media_idx);

    /* this only looks at the first structure so we loop over the given caps
     * and add each structure inside it piecemeal */
    gst_sdp_media_set_media_from_caps (format, media);

    gst_caps_unref (format);
  }

2138 2139 2140 2141 2142
  if (type == GST_WEBRTC_SDP_TYPE_OFFER) {
    const GstStructure *s = gst_caps_get_structure (caps, 0);
    gint clockrate = -1;
    gint rtx_target_pt;
    gint original_rtx_target_pt;        /* Workaround chrome bug: https://bugs.chromium.org/p/webrtc/issues/detail?id=6196 */
2143
    guint rtx_target_ssrc = -1;
2144

2145 2146
    if (gst_structure_get_int (s, "payload", &rtx_target_pt) &&
        webrtc->bundle_policy == GST_WEBRTC_BUNDLE_POLICY_NONE)
2147 2148 2149 2150
      g_array_append_val (reserved_pts, rtx_target_pt);

    original_rtx_target_pt = rtx_target_pt;

2151 2152 2153 2154 2155 2156
    if (!gst_structure_get_int (s, "clock-rate", &clockrate))
      GST_WARNING_OBJECT (webrtc,
          "Caps %" GST_PTR_FORMAT " are missing clock-rate", caps);
    if (!gst_structure_get_uint (s, "ssrc", &rtx_target_ssrc))
      GST_WARNING_OBJECT (webrtc, "Caps %" GST_PTR_FORMAT " are missing ssrc",
          caps);
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168

    _pick_fec_payload_types (webrtc, WEBRTC_TRANSCEIVER (trans), reserved_pts,
        clockrate, &rtx_target_pt, media);
    _pick_rtx_payload_types (webrtc, WEBRTC_TRANSCEIVER (trans), reserved_pts,
        clockrate, rtx_target_pt, rtx_target_ssrc, media);
    if (original_rtx_target_pt != rtx_target_pt)
      _pick_rtx_payload_types (webrtc, WEBRTC_TRANSCEIVER (trans), reserved_pts,
          clockrate, original_rtx_target_pt, rtx_target_ssrc, media);
  }

  _media_add_ssrcs (media, caps, webrtc, WEBRTC_TRANSCEIVER (trans));

2169
  /* Some identifier; we also add the media name to it so it's identifiable */
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
  if (trans->mid) {
    gst_sdp_media_add_attribute (media, "mid", trans->mid);
  } else {
    sdp_mid = g_strdup_printf ("%s%u", gst_sdp_media_get_media (media),
        webrtc->priv->media_counter++);
    gst_sdp_media_add_attribute (media, "mid", sdp_mid);
    g_free (sdp_mid);
  }

  /* TODO:
   * - add a=candidate lines for gathered candidates
   */
2182 2183 2184 2185

  if (trans->sender) {
    if (!trans->sender->transport) {
      TransportStream *item;
2186 2187 2188 2189 2190

      item =
          _get_or_create_transport_stream (webrtc,
          bundled_mids ? bundle_idx : media_idx, FALSE);

2191 2192 2193
      webrtc_transceiver_set_transport (WEBRTC_TRANSCEIVER (trans), item);
    }

2194
    _add_fingerprint_to_media (trans->sender->transport, media);
2195 2196
  }

2197 2198 2199 2200 2201 2202 2203
  if (bundled_mids) {
    const gchar *mid = gst_sdp_media_get_attribute_val (media, "mid");

    g_assert (mid);
    g_string_append_printf (bundled_mids, " %s", mid);
  }

2204 2205 2206 2207 2208
  gst_caps_unref (caps);

  return TRUE;
}

2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
static void
gather_pad_pt (GstWebRTCBinPad * pad, GArray * reserved_pts)
{
  if (pad->received_caps) {
    GstStructure *s = gst_caps_get_structure (pad->received_caps, 0);
    gint pt;

    if (gst_structure_get_int (s, "payload", &pt)) {
      g_array_append_val (reserved_pts, pt);
    }
  }
}

static GArray *
gather_reserved_pts (GstWebRTCBin * webrtc)
{
  GstElement *element = GST_ELEMENT (webrtc);
  GArray *reserved_pts = g_array_new (FALSE, FALSE, sizeof (guint));

  GST_OBJECT_LOCK (webrtc);
  g_list_foreach (element->sinkpads, (GFunc) gather_pad_pt, reserved_pts);
  g_list_foreach (webrtc->priv->pending_pads, (GFunc) gather_pad_pt,
      reserved_pts);
  GST_OBJECT_UNLOCK (webrtc);

  return reserved_pts;
}

2237 2238 2239 2240 2241
static gboolean
_add_data_channel_offer (GstWebRTCBin * webrtc, GstSDPMessage * msg,
    GstSDPMedia * media, GString * bundled_mids, guint bundle_idx,
    gchar * bundle_ufrag, gchar * bundle_pwd)
{
2242
  GstSDPMessage *last_offer = _get_latest_self_generated_sdp (webrtc);
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
  gchar *ufrag, *pwd, *sdp_mid;
  gboolean bundle_only = bundled_mids
      && webrtc->bundle_policy == GST_WEBRTC_BUNDLE_POLICY_MAX_BUNDLE
      && gst_sdp_message_medias_len (msg) != bundle_idx;
  guint last_data_index = G_MAXUINT;

  /* add data channel support */
  if (webrtc->priv->data_channels->len == 0)
    return FALSE;

  if (last_offer) {
    last_data_index = _message_get_datachannel_index (last_offer);
    if (last_data_index < G_MAXUINT) {
      g_assert (last_data_index < gst_sdp_message_medias_len (last_offer));
      /* XXX: is this always true when recycling transceivers?
       * i.e. do we always put the data channel in the same mline */
      g_assert (last_data_index == gst_sdp_message_medias_len (msg));
    }
  }

  /* mandated by JSEP */
  gst_sdp_media_add_attribute (media, "setup", "actpass");

  /* FIXME: only needed when restarting ICE */
  if (last_offer && last_data_index < G_MAXUINT) {
    ufrag = g_strdup (_media_get_ice_ufrag (last_offer, last_data_index));
    pwd = g_strdup (_media_get_ice_pwd (last_offer, last_data_index));
  } else {
    if (webrtc->bundle_policy == GST_WEBRTC_BUNDLE_POLICY_NONE) {
      _generate_ice_credentials (&ufrag, &pwd);
    } else {
      ufrag = g_strdup (bundle_ufrag);
      pwd = g_strdup (bundle_pwd);
    }
  }
  gst_sdp_media_add_attribute (media, "ice-ufrag", ufrag);
  gst_sdp_media_add_attribute (media, "ice-pwd", pwd);
  g_free (ufrag);
  g_free (pwd);

  gst_sdp_media_set_media (media, "application");
  gst_sdp_media_set_port_info (media, bundle_only ? 0 : 9, 0);
  gst_sdp_media_set_proto (media, "UDP/DTLS/SCTP");
  gst_sdp_media_add_connection (media, "IN", "IP4", "0.0.0.0", 0, 0);
  gst_sdp_media_add_format (media, "webrtc-datachannel");

  if (bundle_idx != gst_sdp_message_medias_len (msg))
    gst_sdp_media_add_attribute (media, "bundle-only", NULL);

  if (last_offer && last_data_index < G_MAXUINT) {
    const GstSDPMedia *last_data_media;
    const gchar *mid;

    last_data_media = gst_sdp_message_get_media (last_offer, last_data_index);
    mid = gst_sdp_media_get_attribute_val (last_data_media, "mid");

    gst_sdp_media_add_attribute (media, "mid", mid);
  } else {
    sdp_mid = g_strdup_printf ("%s%u", gst_sdp_media_get_media (media),
        webrtc->priv->media_counter++);
    gst_sdp_media_add_attribute (media, "mid", sdp_mid);
    g_free (sdp_mid);
  }

  if (bundled_mids) {
    const gchar *mid = gst_sdp_media_get_attribute_val (media, "mid");

    g_assert (mid);
    g_string_append_printf (bundled_mids, " %s", mid);
  }

  /* FIXME: negotiate this properly */
  gst_sdp_media_add_attribute (media, "sctp-port", "5000");

  _get_or_create_data_channel_transports (webrtc,
      bundled_mids ? 0 : webrtc->priv->transceivers->len);
  _add_fingerprint_to_media (webrtc->priv->sctp_transport->transport, media);

  return TRUE;
}

2324
/* TODO: use the options argument */
2325 2326 2327 2328
static GstSDPMessage *
_create_offer_task (GstWebRTCBin * webrtc, const GstStructure * options)
{
  GstSDPMessage *ret;
2329 2330 2331
  GString *bundled_mids = NULL;
  gchar *bundle_ufrag = NULL;
  gchar *bundle_pwd = NULL;
2332
  GArray *reserved_pts = NULL;
2333
  GstSDPMessage *last_offer = _get_latest_self_generated_sdp (webrtc);
2334 2335 2336
  GList *seen_transceivers = NULL;
  guint media_idx = 0;
  int i;
2337 2338 2339 2340 2341

  gst_sdp_message_new (&ret);

  gst_sdp_message_set_version (ret, "0");
  {
2342 2343 2344 2345 2346 2347 2348 2349 2350
    gchar *v, *sess_id;
    v = g_strdup_printf ("%u", webrtc->priv->offer_count++);
    if (last_offer) {
      const GstSDPOrigin *origin = gst_sdp_message_get_origin (last_offer);
      sess_id = g_strdup (origin->sess_id);
    } else {
      sess_id = g_strdup_printf ("%" G_GUINT64_FORMAT, RANDOM_SESSION_ID);
    }
    gst_sdp_message_set_origin (ret, "-", sess_id, v, "IN", "IP4", "0.0.0.0");
2351
    g_free (sess_id);
2352
    g_free (v);
2353 2354 2355 2356 2357
  }
  gst_sdp_message_set_session_name (ret, "-");
  gst_sdp_message_add_time (ret, "0", "0", NULL);
  gst_sdp_message_add_attribute (ret, "ice-options", "trickle");

2358 2359 2360 2361 2362 2363 2364
  if (webrtc->bundle_policy == GST_WEBRTC_BUNDLE_POLICY_MAX_BUNDLE) {
    bundled_mids = g_string_new ("BUNDLE");
  } else if (webrtc->bundle_policy == GST_WEBRTC_BUNDLE_POLICY_MAX_COMPAT) {
    bundled_mids = g_string_new ("BUNDLE");
  }

  if (webrtc->bundle_policy != GST_WEBRTC_BUNDLE_POLICY_NONE) {
2365 2366 2367
    GStrv last_bundle = NULL;
    guint bundle_media_index;

2368
    reserved_pts = gather_reserved_pts (webrtc);
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
    if (last_offer && _parse_bundle (last_offer, &last_bundle) && last_bundle
        && last_bundle && last_bundle[0]
        && _get_bundle_index (last_offer, last_bundle, &bundle_media_index)) {
      bundle_ufrag =
          g_strdup (_media_get_ice_ufrag (last_offer, bundle_media_index));
      bundle_pwd =
          g_strdup (_media_get_ice_pwd (last_offer, bundle_media_index));
    } else {
      _generate_ice_credentials (&bundle_ufrag, &bundle_pwd);
    }

    g_strfreev (last_bundle);
2381 2382
  }

2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
  /* FIXME: recycle transceivers */

  /* Fill up the renegotiated streams first */
  if (last_offer) {
    for (i = 0; i < gst_sdp_message_medias_len (last_offer); i++) {
      GstWebRTCRTPTransceiver *trans = NULL;
      const GstSDPMedia *last_media;

      last_media = gst_sdp_message_get_media (last_offer, i);

      if (g_strcmp0 (gst_sdp_media_get_media (last_media), "audio") == 0
          || g_strcmp0 (gst_sdp_media_get_media (last_media), "video") == 0) {
        const gchar *last_mid;
        int j;
        last_mid = gst_sdp_media_get_attribute_val (last_media, "mid");

        for (j = 0; j < webrtc->priv->transceivers->len