rtspsrc: Use a mutex for protecting against concurrent send/receives
[platform/upstream/gst-plugins-good.git] / gst / rtsp / gstrtspsrc.c
index bbcaecc..9ebccb3 100644 (file)
@@ -53,7 +53,7 @@
  * protocols can be controlled with the #GstRTSPSrc:protocols property.
  *
  * rtspsrc currently understands SDP as the format of the session description.
- * For each stream listed in the SDP a new rtp_stream%d pad will be created
+ * For each stream listed in the SDP a new rtp_stream\%d pad will be created
  * with caps derived from the SDP media description. This is a caps of mime type
  * "application/x-rtp" that can be connected to any available RTP depayloader
  * element.
@@ -73,8 +73,6 @@
  * ]| Establish a connection to an RTSP server and send the raw RTP packets to a
  * fakesink.
  * </refsect2>
- *
- * Last reviewed on 2006-08-18 (0.10.5)
  */
 
 #ifdef HAVE_CONFIG_H
@@ -92,7 +90,7 @@
 #include <gst/net/gstnet.h>
 #include <gst/sdp/gstsdpmessage.h>
 #include <gst/sdp/gstmikey.h>
-#include <gst/rtp/gstrtppayloads.h>
+#include <gst/rtp/rtp.h>
 
 #include "gst/gst-i18n-plugin.h"
 
@@ -125,6 +123,7 @@ enum
   SIGNAL_ON_SDP,
   SIGNAL_SELECT_STREAM,
   SIGNAL_NEW_MANAGER,
+  SIGNAL_REQUEST_RTCP_KEY,
   LAST_SIGNAL
 };
 
@@ -165,6 +164,37 @@ gst_rtsp_src_buffer_mode_get_type (void)
   return buffer_mode_type;
 }
 
+enum _GstRtspSrcNtpTimeSource
+{
+  NTP_TIME_SOURCE_NTP,
+  NTP_TIME_SOURCE_UNIX,
+  NTP_TIME_SOURCE_RUNNING_TIME,
+  NTP_TIME_SOURCE_CLOCK_TIME
+};
+
+#define GST_TYPE_RTSP_SRC_NTP_TIME_SOURCE (gst_rtsp_src_ntp_time_source_get_type())
+static GType
+gst_rtsp_src_ntp_time_source_get_type (void)
+{
+  static GType ntp_time_source_type = 0;
+  static const GEnumValue ntp_time_source_values[] = {
+    {NTP_TIME_SOURCE_NTP, "NTP time based on realtime clock", "ntp"},
+    {NTP_TIME_SOURCE_UNIX, "UNIX time based on realtime clock", "unix"},
+    {NTP_TIME_SOURCE_RUNNING_TIME,
+          "Running time based on pipeline clock",
+        "running-time"},
+    {NTP_TIME_SOURCE_CLOCK_TIME, "Pipeline clock time", "clock-time"},
+    {0, NULL, NULL},
+  };
+
+  if (!ntp_time_source_type) {
+    ntp_time_source_type =
+        g_enum_register_static ("GstRTSPSrcNtpTimeSource",
+        ntp_time_source_values);
+  }
+  return ntp_time_source_type;
+}
+
 #define DEFAULT_LOCATION         NULL
 #define DEFAULT_PROTOCOLS        GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
 #define DEFAULT_DEBUG            FALSE
@@ -192,6 +222,12 @@ gst_rtsp_src_buffer_mode_get_type (void)
 #define DEFAULT_USE_PIPELINE_CLOCK       FALSE
 #define DEFAULT_TLS_VALIDATION_FLAGS     G_TLS_CERTIFICATE_VALIDATE_ALL
 #define DEFAULT_TLS_DATABASE     NULL
+#define DEFAULT_TLS_INTERACTION     NULL
+#define DEFAULT_DO_RETRANSMISSION        TRUE
+#define DEFAULT_NTP_TIME_SOURCE  NTP_TIME_SOURCE_NTP
+#define DEFAULT_USER_AGENT       "GStreamer/" PACKAGE_VERSION
+#define DEFAULT_MAX_RTCP_RTP_TIME_DIFF 1000
+#define DEFAULT_RFC7273_SYNC         FALSE
 
 enum
 {
@@ -226,7 +262,12 @@ enum
   PROP_SDES,
   PROP_TLS_VALIDATION_FLAGS,
   PROP_TLS_DATABASE,
-  PROP_LAST
+  PROP_TLS_INTERACTION,
+  PROP_DO_RETRANSMISSION,
+  PROP_NTP_TIME_SOURCE,
+  PROP_USER_AGENT,
+  PROP_MAX_RTCP_RTP_TIME_DIFF,
+  PROP_RFC7273_SYNC
 };
 
 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
@@ -247,6 +288,14 @@ gst_rtsp_nat_method_get_type (void)
   return rtsp_nat_method_type;
 }
 
+#define RTSP_SRC_RESPONSE_ERROR(src, response_msg, err_cat, err_code, error_message) \
+  do { \
+    GST_ELEMENT_ERROR_WITH_DETAILS((src), err_cat, err_code, ("%s", error_message), \
+        ("%s (%d)", (response_msg)->type_data.response.reason, (response_msg)->type_data.response.code), \
+        ("rtsp-status-code", G_TYPE_UINT, (response_msg)->type_data.response.code, \
+         "rtsp-status-reason", G_TYPE_STRING, GST_STR_NULL((response_msg)->type_data.response.reason), NULL)); \
+  } while (0)
+
 static void gst_rtspsrc_finalize (GObject * object);
 
 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
@@ -259,14 +308,9 @@ static GstClock *gst_rtspsrc_provide_clock (GstElement * element);
 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
     gpointer iface_data);
 
-static void gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes,
-    GstCaps * caps);
-
 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
 
-static GstCaps *gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media);
-
 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
     GstStateChange transition);
 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
@@ -297,6 +341,8 @@ static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
     GstRTSPStream * stream, GstEvent * event);
 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
 static void gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush);
+static GstRTSPResult gst_rtsp_conninfo_close (GstRTSPSrc * src,
+    GstRTSPConnInfo * info, gboolean free);
 
 typedef struct
 {
@@ -305,13 +351,13 @@ typedef struct
 } PtMapItem;
 
 /* commands we send to out loop to notify it of events */
-#define CMD_OPEN       (1 << 0)
-#define CMD_PLAY       (1 << 1)
-#define CMD_PAUSE      (1 << 2)
-#define CMD_CLOSE      (1 << 3)
-#define CMD_WAIT       (1 << 4)
-#define CMD_RECONNECT  (1 << 5)
-#define CMD_LOOP       (1 << 6)
+#define CMD_OPEN       (1 << 0)
+#define CMD_PLAY       (1 << 1)
+#define CMD_PAUSE      (1 << 2)
+#define CMD_CLOSE      (1 << 3)
+#define CMD_WAIT       (1 << 4)
+#define CMD_RECONNECT  (1 << 5)
+#define CMD_LOOP       (1 << 6)
 
 /* mask for all commands */
 #define CMD_ALL         ((CMD_LOOP << 1) - 1)
@@ -331,6 +377,31 @@ static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 };
 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
 
+#ifndef GST_DISABLE_GST_DEBUG
+static inline const char *
+cmd_to_string (guint cmd)
+{
+  switch (cmd) {
+    case CMD_OPEN:
+      return "OPEN";
+    case CMD_PLAY:
+      return "PLAY";
+    case CMD_PAUSE:
+      return "PAUSE";
+    case CMD_CLOSE:
+      return "CLOSE";
+    case CMD_WAIT:
+      return "WAIT";
+    case CMD_RECONNECT:
+      return "RECONNECT";
+    case CMD_LOOP:
+      return "LOOP";
+  }
+
+  return "unknown";
+}
+#endif
+
 static gboolean
 default_select_stream (GstRTSPSrc * src, guint id, GstCaps * caps)
 {
@@ -572,9 +643,10 @@ gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
 
   g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
       g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
-          "Use the pipeline running-time to set the NTP time in the RTCP SR messages",
+          "Use the pipeline running-time to set the NTP time in the RTCP SR messages"
+          "(DEPRECATED: Use ntp-time-source property)",
           DEFAULT_USE_PIPELINE_CLOCK,
-          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED));
 
   g_object_class_install_property (gobject_class, PROP_SDES,
       g_param_spec_boxed ("sdes", "SDES",
@@ -609,6 +681,74 @@ gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
 
   /**
+   * GstRTSPSrc::tls-interaction:
+   *
+   * A #GTlsInteraction object to be used when the connection or certificate
+   * database need to interact with the user. This will be used to prompt the
+   * user for passwords where necessary.
+   *
+   * Since: 1.6
+   */
+  g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
+      g_param_spec_object ("tls-interaction", "TLS interaction",
+          "A GTlsInteraction object to promt the user for password or certificate",
+          G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstRTSPSrc::do-retransmission:
+   *
+   * Attempt to ask the server to retransmit lost packets according to RFC4588.
+   *
+   * Note: currently only works with SSRC-multiplexed retransmission streams
+   *
+   * Since: 1.6
+   */
+  g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
+      g_param_spec_boolean ("do-retransmission", "Retransmission",
+          "Ask the server to retransmit lost packets",
+          DEFAULT_DO_RETRANSMISSION,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstRTSPSrc::ntp-time-source:
+   *
+   * allows to select the time source that should be used
+   * for the NTP time in RTCP packets
+   *
+   * Since: 1.6
+   */
+  g_object_class_install_property (gobject_class, PROP_NTP_TIME_SOURCE,
+      g_param_spec_enum ("ntp-time-source", "NTP Time Source",
+          "NTP time source for RTCP packets",
+          GST_TYPE_RTSP_SRC_NTP_TIME_SOURCE, DEFAULT_NTP_TIME_SOURCE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstRTSPSrc::user-agent:
+   *
+   * The string to set in the User-Agent header.
+   *
+   * Since: 1.6
+   */
+  g_object_class_install_property (gobject_class, PROP_USER_AGENT,
+      g_param_spec_string ("user-agent", "User Agent",
+          "The User-Agent string to send to the server",
+          DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_MAX_RTCP_RTP_TIME_DIFF,
+      g_param_spec_int ("max-rtcp-rtp-time-diff", "Max RTCP RTP Time Diff",
+          "Maximum amount of time in ms that the RTP time in RTCP SRs "
+          "is allowed to be ahead (-1 disabled)", -1, G_MAXINT,
+          DEFAULT_MAX_RTCP_RTP_TIME_DIFF,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_RFC7273_SYNC,
+      g_param_spec_boolean ("rfc7273-sync", "Sync on RFC7273 clock",
+          "Synchronize received streams to the RFC7273 clock "
+          "(requires clock and offset to be provided)", DEFAULT_RFC7273_SYNC,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
    * GstRTSPSrc::handle-request:
    * @rtspsrc: a #GstRTSPSrc
    * @request: a #GstRTSPMessage
@@ -685,12 +825,26 @@ gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP, 0, NULL, NULL,
       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
 
+  /**
+   * GstRTSPSrc::request-rtcp-key:
+   * @rtspsrc: a #GstRTSPSrc
+   * @num: the stream number
+   *
+   * Signal emited to get the crypto parameters relevant to the RTCP
+   * stream. User should provide the key and the RTCP encryption ciphers
+   * and authentication, and return them wrapped in a GstCaps.
+   *
+   * Since: 1.4
+   */
+  gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY] =
+      g_signal_new ("request-rtcp-key", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, GST_TYPE_CAPS, 1, G_TYPE_UINT);
+
   gstelement_class->send_event = gst_rtspsrc_send_event;
   gstelement_class->provide_clock = gst_rtspsrc_provide_clock;
   gstelement_class->change_state = gst_rtspsrc_change_state;
 
-  gst_element_class_add_pad_template (gstelement_class,
-      gst_static_pad_template_get (&rtptemplate));
+  gst_element_class_add_static_pad_template (gstelement_class, &rtptemplate);
 
   gst_element_class_set_static_metadata (gstelement_class,
       "RTSP packet receiver", "Source/Network",
@@ -736,6 +890,12 @@ gst_rtspsrc_init (GstRTSPSrc * src)
   src->sdes = NULL;
   src->tls_validation_flags = DEFAULT_TLS_VALIDATION_FLAGS;
   src->tls_database = DEFAULT_TLS_DATABASE;
+  src->tls_interaction = DEFAULT_TLS_INTERACTION;
+  src->do_retransmission = DEFAULT_DO_RETRANSMISSION;
+  src->ntp_time_source = DEFAULT_NTP_TIME_SOURCE;
+  src->user_agent = g_strdup (DEFAULT_USER_AGENT);
+  src->max_rtcp_rtp_time_diff = DEFAULT_MAX_RTCP_RTP_TIME_DIFF;
+  src->rfc7273_sync = DEFAULT_RFC7273_SYNC;
 
   /* get a list of all extensions */
   src->extensions = gst_rtsp_ext_list_get ();
@@ -754,6 +914,8 @@ gst_rtspsrc_init (GstRTSPSrc * src)
   src->state = GST_RTSP_STATE_INVALID;
 
   GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
+  gst_bin_set_suppressed_flags (GST_BIN (src),
+      GST_ELEMENT_FLAG_SOURCE | GST_ELEMENT_FLAG_SINK);
 }
 
 static void
@@ -770,6 +932,7 @@ gst_rtspsrc_finalize (GObject * object)
   g_free (rtspsrc->user_id);
   g_free (rtspsrc->user_pw);
   g_free (rtspsrc->multi_iface);
+  g_free (rtspsrc->user_agent);
 
   if (rtspsrc->sdp) {
     gst_sdp_message_free (rtspsrc->sdp);
@@ -784,6 +947,9 @@ gst_rtspsrc_finalize (GObject * object)
   if (rtspsrc->tls_database)
     g_object_unref (rtspsrc->tls_database);
 
+  if (rtspsrc->tls_interaction)
+    g_object_unref (rtspsrc->tls_interaction);
+
   /* free locks */
   g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
   g_rec_mutex_clear (&rtspsrc->state_rec_lock);
@@ -798,9 +964,9 @@ gst_rtspsrc_provide_clock (GstElement * element)
   GstClock *clock;
 
   if ((clock = src->provided_clock) != NULL)
-    gst_object_ref (clock);
+    return gst_object_ref (clock);
 
-  return clock;
+  return GST_ELEMENT_CLASS (parent_class)->provide_clock (element);
 }
 
 /* a proxy string of the format [user:passwd@]host[:port] */
@@ -925,26 +1091,22 @@ gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
       gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
       break;
     case PROP_PROXY_ID:
-      if (rtspsrc->prop_proxy_id)
-        g_free (rtspsrc->prop_proxy_id);
+      g_free (rtspsrc->prop_proxy_id);
       rtspsrc->prop_proxy_id = g_value_dup_string (value);
       break;
     case PROP_PROXY_PW:
-      if (rtspsrc->prop_proxy_pw)
-        g_free (rtspsrc->prop_proxy_pw);
+      g_free (rtspsrc->prop_proxy_pw);
       rtspsrc->prop_proxy_pw = g_value_dup_string (value);
       break;
     case PROP_RTP_BLOCKSIZE:
       rtspsrc->rtp_blocksize = g_value_get_uint (value);
       break;
     case PROP_USER_ID:
-      if (rtspsrc->user_id)
-        g_free (rtspsrc->user_id);
+      g_free (rtspsrc->user_id);
       rtspsrc->user_id = g_value_dup_string (value);
       break;
     case PROP_USER_PW:
-      if (rtspsrc->user_pw)
-        g_free (rtspsrc->user_pw);
+      g_free (rtspsrc->user_pw);
       rtspsrc->user_pw = g_value_dup_string (value);
       break;
     case PROP_BUFFER_MODE:
@@ -955,10 +1117,8 @@ gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
       const gchar *str;
 
       str = g_value_get_string (value);
-      if (str) {
-        sscanf (str, "%u-%u",
-            &rtspsrc->client_port_range.min, &rtspsrc->client_port_range.max);
-      } else {
+      if (sscanf (str, "%u-%u", &rtspsrc->client_port_range.min,
+              &rtspsrc->client_port_range.max) != 2) {
         rtspsrc->client_port_range.min = 0;
         rtspsrc->client_port_range.max = 0;
       }
@@ -1000,6 +1160,26 @@ gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
       g_clear_object (&rtspsrc->tls_database);
       rtspsrc->tls_database = g_value_dup_object (value);
       break;
+    case PROP_TLS_INTERACTION:
+      g_clear_object (&rtspsrc->tls_interaction);
+      rtspsrc->tls_interaction = g_value_dup_object (value);
+      break;
+    case PROP_DO_RETRANSMISSION:
+      rtspsrc->do_retransmission = g_value_get_boolean (value);
+      break;
+    case PROP_NTP_TIME_SOURCE:
+      rtspsrc->ntp_time_source = g_value_get_enum (value);
+      break;
+    case PROP_USER_AGENT:
+      g_free (rtspsrc->user_agent);
+      rtspsrc->user_agent = g_value_dup_string (value);
+      break;
+    case PROP_MAX_RTCP_RTP_TIME_DIFF:
+      rtspsrc->max_rtcp_rtp_time_diff = g_value_get_int (value);
+      break;
+    case PROP_RFC7273_SYNC:
+      rtspsrc->rfc7273_sync = g_value_get_boolean (value);
+      break;
     default:
       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
       break;
@@ -1034,7 +1214,7 @@ gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
     {
       guint64 timeout;
 
-      timeout = rtspsrc->tcp_timeout.tv_sec * G_USEC_PER_SEC +
+      timeout = ((guint64) rtspsrc->tcp_timeout.tv_sec) * G_USEC_PER_SEC +
           rtspsrc->tcp_timeout.tv_usec;
       g_value_set_uint64 (value, timeout);
       break;
@@ -1131,6 +1311,24 @@ gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
     case PROP_TLS_DATABASE:
       g_value_set_object (value, rtspsrc->tls_database);
       break;
+    case PROP_TLS_INTERACTION:
+      g_value_set_object (value, rtspsrc->tls_interaction);
+      break;
+    case PROP_DO_RETRANSMISSION:
+      g_value_set_boolean (value, rtspsrc->do_retransmission);
+      break;
+    case PROP_NTP_TIME_SOURCE:
+      g_value_set_enum (value, rtspsrc->ntp_time_source);
+      break;
+    case PROP_USER_AGENT:
+      g_value_set_string (value, rtspsrc->user_agent);
+      break;
+    case PROP_MAX_RTCP_RTP_TIME_DIFF:
+      g_value_set_int (value, rtspsrc->max_rtcp_rtp_time_diff);
+      break;
+    case PROP_RFC7273_SYNC:
+      g_value_set_boolean (value, rtspsrc->rfc7273_sync);
+      break;
     default:
       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
       break;
@@ -1149,7 +1347,10 @@ find_stream_by_id (GstRTSPStream * stream, gint * id)
 static gint
 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
 {
-  if (stream->channel[0] == *channel || stream->channel[1] == *channel)
+  /* ignore unconfigured channels here (e.g., those that
+   * were explicitly skipped during SETUP) */
+  if ((stream->channelpad[0] != NULL) &&
+      (stream->channel[0] == *channel || stream->channel[1] == *channel))
     return 0;
 
   return -1;
@@ -1310,6 +1511,7 @@ gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
 {
   guint i, len;
   const gchar *proto;
+  GstCaps *global_caps;
 
   /* get proto */
   proto = gst_sdp_media_get_proto (media);
@@ -1327,10 +1529,22 @@ gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
   else
     goto unknown_proto;
 
+  /* Parse global SDP attributes once */
+  global_caps = gst_caps_new_empty_simple ("application/x-unknown");
+  GST_DEBUG ("mapping sdp session level attributes to caps");
+  gst_sdp_message_attributes_to_caps (sdp, global_caps);
+  GST_DEBUG ("mapping sdp media level attributes to caps");
+  gst_sdp_media_attributes_to_caps (media, global_caps);
+
+  /* Keep a copy of the SDP key management */
+  gst_sdp_media_parse_keymgmt (media, &stream->mikey);
+  if (stream->mikey == NULL)
+    gst_sdp_message_parse_keymgmt (sdp, &stream->mikey);
+
   len = gst_sdp_media_formats_len (media);
   for (i = 0; i < len; i++) {
     gint pt;
-    GstCaps *caps;
+    GstCaps *caps, *outcaps;
     GstStructure *s;
     const gchar *enc;
     PtMapItem item;
@@ -1340,7 +1554,7 @@ gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
     GST_DEBUG_OBJECT (src, " looking at %d pt: %d", i, pt);
 
     /* convert caps */
-    caps = gst_rtspsrc_media_to_caps (pt, media);
+    caps = gst_sdp_media_get_caps_from_media (media, pt);
     if (caps == NULL) {
       GST_WARNING_OBJECT (src, " skipping pt %d without caps", pt);
       continue;
@@ -1353,19 +1567,23 @@ gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
       if (strcmp (enc, "X-ASF-PF") == 0)
         stream->container = TRUE;
     }
-    GST_DEBUG ("mapping sdp session level attributes to caps");
-    gst_rtspsrc_sdp_attributes_to_caps (sdp->attributes, caps);
-    GST_DEBUG ("mapping sdp media level attributes to caps");
-    gst_rtspsrc_sdp_attributes_to_caps (media->attributes, caps);
+
+    /* Merge in global caps */
+    /* Intersect will merge in missing fields to the current caps */
+    outcaps = gst_caps_intersect (caps, global_caps);
+    gst_caps_unref (caps);
 
     /* the first pt will be the default */
     if (stream->ptmap->len == 0)
       stream->default_pt = pt;
 
     item.pt = pt;
-    item.caps = caps;
+    item.caps = outcaps;
+
     g_array_append_val (stream->ptmap, item);
   }
+
+  gst_caps_unref (global_caps);
   return;
 
 no_proto:
@@ -1375,7 +1593,7 @@ no_proto:
   }
 unknown_proto:
   {
-    GST_ERROR_OBJECT (src, "unknown proto in media %s", proto);
+    GST_ERROR_OBJECT (src, "unknown proto in media: '%s'", proto);
     return;
   }
 }
@@ -1405,7 +1623,8 @@ clear_ptmap_item (PtMapItem * item)
 }
 
 static GstRTSPStream *
-gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
+gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx,
+    gint n_streams)
 {
   GstRTSPStream *stream;
   const gchar *control_url;
@@ -1429,8 +1648,10 @@ gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
   stream->discont = TRUE;
   stream->seqbase = -1;
   stream->timebase = -1;
+  stream->send_ssrc = g_random_int ();
   stream->profile = GST_RTSP_PROFILE_AVP;
   stream->ptmap = g_array_new (FALSE, FALSE, sizeof (PtMapItem));
+  stream->mikey = NULL;
   g_array_set_clear_func (stream->ptmap, (GDestroyNotify) clear_ptmap_item);
 
   /* collect bandwidth information for this steam. FIXME, configure in the RTP
@@ -1458,6 +1679,11 @@ gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
   GST_DEBUG_OBJECT (src, " container: %d", stream->container);
   GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
 
+  /* RFC 2326, C.3: missing control_url permitted in case of a single stream */
+  if (control_url == NULL && n_streams == 1) {
+    control_url = "";
+  }
+
   if (control_url != NULL) {
     stream->control_url = g_strdup (control_url);
     /* Build a fully qualified url using the content_base if any or by prefixing
@@ -1514,41 +1740,40 @@ gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
       gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
       gst_object_unref (stream->udpsrc[i]);
-      stream->udpsrc[i] = NULL;
     }
-    if (stream->channelpad[i]) {
+    if (stream->channelpad[i])
       gst_object_unref (stream->channelpad[i]);
-      stream->channelpad[i] = NULL;
-    }
+
     if (stream->udpsink[i]) {
       gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
       gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
       gst_object_unref (stream->udpsink[i]);
-      stream->udpsink[i] = NULL;
     }
   }
   if (stream->fakesrc) {
     gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
     gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
     gst_object_unref (stream->fakesrc);
-    stream->fakesrc = NULL;
   }
   if (stream->srcpad) {
     gst_pad_set_active (stream->srcpad, FALSE);
-    if (stream->added) {
+    if (stream->added)
       gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
-      stream->added = FALSE;
-    }
-    stream->srcpad = NULL;
   }
-  if (stream->rtcppad) {
+  if (stream->srtpenc)
+    gst_object_unref (stream->srtpenc);
+  if (stream->srtpdec)
+    gst_object_unref (stream->srtpdec);
+  if (stream->srtcpparams)
+    gst_caps_unref (stream->srtcpparams);
+  if (stream->mikey)
+    gst_mikey_message_unref (stream->mikey);
+  if (stream->rtcppad)
     gst_object_unref (stream->rtcppad);
-    stream->rtcppad = NULL;
-  }
-  if (stream->session) {
+  if (stream->session)
     g_object_unref (stream->session);
-    stream->session = NULL;
-  }
+  if (stream->rtx_pt_map)
+    gst_structure_free (stream->rtx_pt_map);
   g_free (stream);
 }
 
@@ -1594,420 +1819,15 @@ gst_rtspsrc_cleanup (GstRTSPSrc * src)
     gst_sdp_message_free (src->sdp);
     src->sdp = NULL;
   }
-  if (src->start_segment) {
-    gst_event_unref (src->start_segment);
-    src->start_segment = NULL;
-  }
+
+  src->need_segment = FALSE;
+
   if (src->provided_clock) {
     gst_object_unref (src->provided_clock);
     src->provided_clock = NULL;
   }
 }
 
-#define PARSE_INT(p, del, res)          \
-G_STMT_START {                          \
-  gchar *t = p;                         \
-  p = strstr (p, del);                  \
-  if (p == NULL)                        \
-    res = -1;                           \
-  else {                                \
-    *p = '\0';                          \
-    p++;                                \
-    res = atoi (t);                     \
-  }                                     \
-} G_STMT_END
-
-#define PARSE_STRING(p, del, res)       \
-G_STMT_START {                          \
-  gchar *t = p;                         \
-  p = strstr (p, del);                  \
-  if (p == NULL) {                      \
-    res = NULL;                         \
-    p = t;                              \
-  }                                     \
-  else {                                \
-    *p = '\0';                          \
-    p++;                                \
-    res = t;                            \
-  }                                     \
-} G_STMT_END
-
-#define SKIP_SPACES(p)                  \
-  while (*p && g_ascii_isspace (*p))    \
-    p++;
-
-/* rtpmap contains:
- *
- *  <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
- */
-static gboolean
-gst_rtspsrc_parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
-    gint * rate, gchar ** params)
-{
-  gchar *p, *t;
-
-  p = (gchar *) rtpmap;
-
-  PARSE_INT (p, " ", *payload);
-  if (*payload == -1)
-    return FALSE;
-
-  SKIP_SPACES (p);
-  if (*p == '\0')
-    return FALSE;
-
-  PARSE_STRING (p, "/", *name);
-  if (*name == NULL) {
-    GST_DEBUG ("no rate, name %s", p);
-    /* no rate, assume -1 then, this is not supposed to happen but RealMedia
-     * streams seem to omit the rate. */
-    *name = p;
-    *rate = -1;
-    return TRUE;
-  }
-
-  t = p;
-  p = strstr (p, "/");
-  if (p == NULL) {
-    *rate = atoi (t);
-    return TRUE;
-  }
-  *p = '\0';
-  p++;
-  *rate = atoi (t);
-
-  t = p;
-  if (*p == '\0')
-    return TRUE;
-  *params = t;
-
-  return TRUE;
-}
-
-static gboolean
-parse_keymgmt (const gchar * keymgmt, GstCaps * caps)
-{
-  gboolean res = FALSE;
-  gchar *p, *kmpid;
-  gsize size;
-  guchar *data;
-  GstMIKEYMessage *msg;
-  const GstMIKEYPayload *payload;
-  const gchar *srtp_cipher;
-  const gchar *srtp_auth;
-
-  p = (gchar *) keymgmt;
-
-  SKIP_SPACES (p);
-  if (*p == '\0')
-    return FALSE;
-
-  PARSE_STRING (p, " ", kmpid);
-  if (!g_str_equal (kmpid, "mikey"))
-    return FALSE;
-
-  data = g_base64_decode (p, &size);
-  if (data == NULL)
-    return FALSE;
-
-  msg = gst_mikey_message_new_from_data (data, size);
-  if (msg == NULL)
-    return FALSE;
-
-  srtp_cipher = "aes-128-icm";
-  srtp_auth = "hmac-sha1-80";
-
-  /* check the Security policy if any */
-  if ((payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_SP, 0))) {
-    GstMIKEYPayloadSP *p = (GstMIKEYPayloadSP *) payload;
-    guint len, i;
-
-    if (p->proto != GST_MIKEY_SEC_PROTO_SRTP)
-      goto done;
-
-    len = gst_mikey_payload_sp_get_n_params (payload);
-    for (i = 0; i < len; i++) {
-      const GstMIKEYPayloadSPParam *param =
-          gst_mikey_payload_sp_get_param (payload, i);
-
-      switch (param->type) {
-        case GST_MIKEY_SP_SRTP_ENC_ALG:
-          switch (param->val[0]) {
-            case 0:
-              srtp_cipher = "null";
-              break;
-            case 2:
-            case 1:
-              srtp_cipher = "aes-128-icm";
-              break;
-            default:
-              break;
-          }
-          break;
-        case GST_MIKEY_SP_SRTP_AUTH_ALG:
-          switch (param->val[0]) {
-            case 0:
-              srtp_auth = "null";
-              break;
-            case 2:
-            case 1:
-              srtp_auth = "hmac-sha1-80";
-              break;
-            default:
-              break;
-          }
-          break;
-        case GST_MIKEY_SP_SRTP_SRTP_ENC:
-          break;
-        case GST_MIKEY_SP_SRTP_SRTCP_ENC:
-          break;
-        default:
-          break;
-      }
-    }
-  }
-
-  if (!(payload = gst_mikey_message_find_payload (msg, GST_MIKEY_PT_KEMAC, 0)))
-    goto done;
-  else {
-    GstMIKEYPayloadKEMAC *p = (GstMIKEYPayloadKEMAC *) payload;
-    GstBuffer *buf;
-
-    if (p->enc_alg != GST_MIKEY_ENC_NULL || p->mac_alg != GST_MIKEY_MAC_NULL)
-      goto done;
-
-    buf =
-        gst_buffer_new_wrapped (g_memdup (p->enc_data, p->enc_len), p->enc_len);
-    gst_caps_set_simple (caps, "srtp-key", GST_TYPE_BUFFER, buf, NULL);
-  }
-
-  gst_caps_set_simple (caps,
-      "srtp-cipher", G_TYPE_STRING, srtp_cipher,
-      "srtp-auth", G_TYPE_STRING, srtp_auth,
-      "srtcp-cipher", G_TYPE_STRING, srtp_cipher,
-      "srtcp-auth", G_TYPE_STRING, srtp_auth, NULL);
-
-  res = TRUE;
-done:
-  gst_mikey_message_free (msg);
-
-  return res;
-}
-
-/*
- * Mapping SDP attributes to caps
- *
- * prepend 'a-' to IANA registered sdp attributes names
- * (ie: not prefixed with 'x-') in order to avoid
- * collision with gstreamer standard caps properties names
- */
-static void
-gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
-{
-  if (attributes->len > 0) {
-    GstStructure *s;
-    guint i;
-
-    s = gst_caps_get_structure (caps, 0);
-
-    for (i = 0; i < attributes->len; i++) {
-      GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
-      gchar *tofree, *key;
-
-      key = attr->key;
-
-      /* skip some of the attribute we already handle */
-      if (!strcmp (key, "fmtp"))
-        continue;
-      if (!strcmp (key, "rtpmap"))
-        continue;
-      if (!strcmp (key, "control"))
-        continue;
-      if (!strcmp (key, "range"))
-        continue;
-      if (g_str_equal (key, "key-mgmt")) {
-        parse_keymgmt (attr->value, caps);
-        continue;
-      }
-
-      /* string must be valid UTF8 */
-      if (!g_utf8_validate (attr->value, -1, NULL))
-        continue;
-
-      if (!g_str_has_prefix (key, "x-"))
-        tofree = key = g_strdup_printf ("a-%s", key);
-      else
-        tofree = NULL;
-
-      GST_DEBUG ("adding caps: %s=%s", key, attr->value);
-      gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
-      g_free (tofree);
-    }
-  }
-}
-
-static const gchar *
-rtsp_get_attribute_for_pt (const GstSDPMedia * media, const gchar * name,
-    gint pt)
-{
-  guint i;
-
-  for (i = 0;; i++) {
-    const gchar *attr;
-    gint val;
-
-    if ((attr = gst_sdp_media_get_attribute_val_n (media, name, i)) == NULL)
-      break;
-
-    if (sscanf (attr, "%d ", &val) != 1)
-      continue;
-
-    if (val == pt)
-      return attr;
-  }
-  return NULL;
-}
-
-/*
- *  Mapping of caps to and from SDP fields:
- *
- *   a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
- *   a=fmtp:<payload> <param>[=<value>];...
- */
-static GstCaps *
-gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media)
-{
-  GstCaps *caps;
-  const gchar *rtpmap;
-  const gchar *fmtp;
-  gchar *name = NULL;
-  gint rate = -1;
-  gchar *params = NULL;
-  gchar *tmp;
-  GstStructure *s;
-  gint payload = 0;
-  gboolean ret;
-
-  /* get and parse rtpmap */
-  rtpmap = rtsp_get_attribute_for_pt (media, "rtpmap", pt);
-
-  if (rtpmap) {
-    ret = gst_rtspsrc_parse_rtpmap (rtpmap, &payload, &name, &rate, &params);
-    if (!ret) {
-      g_warning ("error parsing rtpmap, ignoring");
-      rtpmap = NULL;
-    }
-  }
-  /* dynamic payloads need rtpmap or we fail */
-  if (rtpmap == NULL && pt >= 96)
-    goto no_rtpmap;
-
-  /* check if we have a rate, if not, we need to look up the rate from the
-   * default rates based on the payload types. */
-  if (rate == -1) {
-    const GstRTPPayloadInfo *info;
-
-    if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
-      /* dynamic types, use media and encoding_name */
-      tmp = g_ascii_strdown (media->media, -1);
-      info = gst_rtp_payload_info_for_name (tmp, name);
-      g_free (tmp);
-    } else {
-      /* static types, use payload type */
-      info = gst_rtp_payload_info_for_pt (pt);
-    }
-
-    if (info) {
-      if ((rate = info->clock_rate) == 0)
-        rate = -1;
-    }
-    /* we fail if we cannot find one */
-    if (rate == -1)
-      goto no_rate;
-  }
-
-  tmp = g_ascii_strdown (media->media, -1);
-  caps = gst_caps_new_simple ("application/x-unknown",
-      "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
-  g_free (tmp);
-  s = gst_caps_get_structure (caps, 0);
-
-  gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
-
-  /* encoding name must be upper case */
-  if (name != NULL) {
-    tmp = g_ascii_strup (name, -1);
-    gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
-    g_free (tmp);
-  }
-
-  /* params must be lower case */
-  if (params != NULL) {
-    tmp = g_ascii_strdown (params, -1);
-    gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
-    g_free (tmp);
-  }
-
-  /* parse optional fmtp: field */
-  if ((fmtp = rtsp_get_attribute_for_pt (media, "fmtp", pt))) {
-    gchar *p;
-    gint payload = 0;
-
-    p = (gchar *) fmtp;
-
-    /* p is now of the format <payload> <param>[=<value>];... */
-    PARSE_INT (p, " ", payload);
-    if (payload != -1 && payload == pt) {
-      gchar **pairs;
-      gint i;
-
-      /* <param>[=<value>] are separated with ';' */
-      pairs = g_strsplit (p, ";", 0);
-      for (i = 0; pairs[i]; i++) {
-        gchar *valpos;
-        const gchar *val, *key;
-
-        /* the key may not have a '=', the value can have other '='s */
-        valpos = strstr (pairs[i], "=");
-        if (valpos) {
-          /* we have a '=' and thus a value, remove the '=' with \0 */
-          *valpos = '\0';
-          /* value is everything between '=' and ';'. We split the pairs at ;
-           * boundaries so we can take the remainder of the value. Some servers
-           * put spaces around the value which we strip off here. Alternatively
-           * we could strip those spaces in the depayloaders should these spaces
-           * actually carry any meaning in the future. */
-          val = g_strstrip (valpos + 1);
-        } else {
-          /* simple <param>;.. is translated into <param>=1;... */
-          val = "1";
-        }
-        /* strip the key of spaces, convert key to lowercase but not the value. */
-        key = g_strstrip (pairs[i]);
-        if (strlen (key) > 1) {
-          tmp = g_ascii_strdown (key, -1);
-          gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
-          g_free (tmp);
-        }
-      }
-      g_strfreev (pairs);
-    }
-  }
-  return caps;
-
-  /* ERRORS */
-no_rtpmap:
-  {
-    g_warning ("rtpmap type not given for dynamic payload %d", pt);
-    return NULL;
-  }
-no_rate:
-  {
-    g_warning ("rate unknown for payload type %d", pt);
-    return NULL;
-  }
-}
-
 static gboolean
 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
     gint * rtpport, gint * rtcpport)
@@ -2232,29 +2052,35 @@ gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
 }
 
 static GstRTSPResult
-gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
+gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
     GstRTSPMessage * message, GTimeVal * timeout)
 {
   GstRTSPResult ret;
 
-  if (conn)
-    ret = gst_rtsp_connection_send (conn, message, timeout);
-  else
+  if (conninfo->connection) {
+    g_mutex_lock (&conninfo->send_lock);
+    ret = gst_rtsp_connection_send (conninfo->connection, message, timeout);
+    g_mutex_unlock (&conninfo->send_lock);
+  } else {
     ret = GST_RTSP_ERROR;
+  }
 
   return ret;
 }
 
 static GstRTSPResult
-gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
+gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
     GstRTSPMessage * message, GTimeVal * timeout)
 {
   GstRTSPResult ret;
 
-  if (conn)
-    ret = gst_rtsp_connection_receive (conn, message, timeout);
-  else
+  if (conninfo->connection) {
+    g_mutex_lock (&conninfo->send_lock);
+    ret = gst_rtsp_connection_receive (conninfo->connection, message, timeout);
+    g_mutex_unlock (&conninfo->send_lock);
+  } else {
     ret = GST_RTSP_ERROR;
+  }
 
   return ret;
 }
@@ -2278,22 +2104,16 @@ gst_rtspsrc_get_position (GstRTSPSrc * src)
         GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
             GST_TIME_ARGS (pos));
         src->last_pos = pos;
-        return;
+        goto out;
       }
     }
   }
 
   src->last_pos = 0;
-}
 
-static gboolean
-gst_rtspsrc_do_seek (GstRTSPSrc * src, GstSegment * segment)
-{
-  src->state = GST_RTSP_STATE_SEEKING;
-  /* PLAY will add the range header now. */
-  src->need_range = TRUE;
+out:
 
-  return TRUE;
+  gst_query_unref (query);
 }
 
 static gboolean
@@ -2375,9 +2195,8 @@ gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
   if ((stop = seeksegment.stop) == -1)
     stop = seeksegment.duration;
 
-  playing = (src->state == GST_RTSP_STATE_PLAYING);
-
   /* if we were playing, pause first */
+  playing = (src->state == GST_RTSP_STATE_PLAYING);
   if (playing) {
     /* obtain current position in case seek fails */
     gst_rtspsrc_get_position (src);
@@ -2385,11 +2204,10 @@ gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
   }
   src->skip = skip;
 
-  gst_rtspsrc_do_seek (src, &seeksegment);
+  src->state = GST_RTSP_STATE_SEEKING;
 
-  /* and continue playing */
-  if (playing)
-    gst_rtspsrc_play (src, &seeksegment, FALSE);
+  /* PLAY will add the range header now. */
+  src->need_range = TRUE;
 
   /* prepare for streaming again */
   if (flush) {
@@ -2419,6 +2237,15 @@ gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
     stream->discont = TRUE;
   }
 
+  /* and continue playing if needed */
+  GST_OBJECT_LOCK (src);
+  playing = (GST_STATE_PENDING (src) == GST_STATE_VOID_PENDING
+      && GST_STATE (src) == GST_STATE_PLAYING)
+      || (GST_STATE_PENDING (src) == GST_STATE_PLAYING);
+  GST_OBJECT_UNLOCK (src);
+  if (playing)
+    gst_rtspsrc_play (src, &seeksegment, FALSE);
+
   GST_RTSP_STREAM_UNLOCK (src);
 
   return TRUE;
@@ -2593,9 +2420,8 @@ gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
         seekable = seekable && src->seekable && src->segment.duration &&
             GST_CLOCK_TIME_IS_VALID (src->segment.duration);
 
-        /* FIXME ?? should we have 0 and segment.duration here; see demuxers */
-        gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
-            src->segment.start, src->segment.stop);
+        gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0,
+            src->segment.duration);
         res = TRUE;
       }
       break;
@@ -2641,7 +2467,7 @@ gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
   guint size;
   GstRTSPResult ret;
   GstRTSPMessage message = { 0 };
-  GstRTSPConnection *conn;
+  GstRTSPConnInfo *conninfo;
 
   stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
   src = stream->parent;
@@ -2656,12 +2482,12 @@ gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
   gst_rtsp_message_take_body (&message, data, size);
 
   if (stream->conninfo.connection)
-    conn = stream->conninfo.connection;
+    conninfo = &stream->conninfo;
   else
-    conn = src->conninfo.connection;
+    conninfo = &src->conninfo;
 
   GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
-  ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
+  ret = gst_rtspsrc_connection_send (src, conninfo, &message, NULL);
   GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
 
   /* and steal it away again because we will free it when unreffing the
@@ -2945,44 +2771,259 @@ set_manager_buffer_mode (GstRTSPSrc * src)
       gst_object_unref (clock);
   }
 
-  GST_DEBUG_OBJECT (src, "auto buffering mode");
-  if (src->use_buffering) {
-    GST_DEBUG_OBJECT (src, "selected buffer");
-    g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
-  } else {
-    GST_DEBUG_OBJECT (src, "selected slave");
-    g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
-  }
+  GST_DEBUG_OBJECT (src, "auto buffering mode");
+  if (src->use_buffering) {
+    GST_DEBUG_OBJECT (src, "selected buffer");
+    g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
+  } else {
+    GST_DEBUG_OBJECT (src, "selected slave");
+    g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
+  }
+}
+
+static GstCaps *
+request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
+{
+  guint i;
+  GstCaps *caps;
+  GstMIKEYMessage *msg = stream->mikey;
+
+  GST_DEBUG ("request key SSRC %u", ssrc);
+
+  caps = gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
+  caps = gst_caps_make_writable (caps);
+
+  /* parse crypto sessions and look for the SSRC rollover counter */
+  msg = stream->mikey;
+  for (i = 0; msg && i < gst_mikey_message_get_n_cs (msg); i++) {
+    const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
+
+    if (ssrc == map->ssrc) {
+      gst_caps_set_simple (caps, "roc", G_TYPE_UINT, map->roc, NULL);
+      break;
+    }
+  }
+
+  return caps;
+}
+
+static GstElement *
+request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
+{
+  GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
+  if (stream->id != session)
+    return NULL;
+
+  if (stream->profile != GST_RTSP_PROFILE_SAVP &&
+      stream->profile != GST_RTSP_PROFILE_SAVPF)
+    return NULL;
+
+  if (stream->srtpdec == NULL) {
+    gchar *name;
+
+    name = g_strdup_printf ("srtpdec_%u", session);
+    stream->srtpdec = gst_element_factory_make ("srtpdec", name);
+    g_free (name);
+
+    if (stream->srtpdec == NULL) {
+      GST_ELEMENT_ERROR (stream->parent, CORE, MISSING_PLUGIN, (NULL),
+          ("no srtpdec element present!"));
+      return NULL;
+    }
+    g_signal_connect (stream->srtpdec, "request-key",
+        (GCallback) request_key, stream);
+  }
+  return gst_object_ref (stream->srtpdec);
+}
+
+static GstElement *
+request_rtcp_encoder (GstElement * rtpbin, guint session,
+    GstRTSPStream * stream)
+{
+  gchar *name;
+  GstPad *pad;
+
+  GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
+  if (stream->id != session)
+    return NULL;
+
+  if (stream->profile != GST_RTSP_PROFILE_SAVP &&
+      stream->profile != GST_RTSP_PROFILE_SAVPF)
+    return NULL;
+
+  if (stream->srtpenc == NULL) {
+    GstStructure *s;
+
+    name = g_strdup_printf ("srtpenc_%u", session);
+    stream->srtpenc = gst_element_factory_make ("srtpenc", name);
+    g_free (name);
+
+    if (stream->srtpenc == NULL) {
+      GST_ELEMENT_ERROR (stream->parent, CORE, MISSING_PLUGIN, (NULL),
+          ("no srtpenc element present!"));
+      return NULL;
+    }
+
+    /* get RTCP crypto parameters from caps */
+    s = gst_caps_get_structure (stream->srtcpparams, 0);
+    if (s) {
+      GstBuffer *buf;
+      const gchar *str;
+      GType ciphertype, authtype;
+      GValue rtcp_cipher = G_VALUE_INIT, rtcp_auth = G_VALUE_INIT;
+
+      ciphertype = g_type_from_name ("GstSrtpCipherType");
+      authtype = g_type_from_name ("GstSrtpAuthType");
+      g_value_init (&rtcp_cipher, ciphertype);
+      g_value_init (&rtcp_auth, authtype);
+
+      str = gst_structure_get_string (s, "srtcp-cipher");
+      gst_value_deserialize (&rtcp_cipher, str);
+      str = gst_structure_get_string (s, "srtcp-auth");
+      gst_value_deserialize (&rtcp_auth, str);
+      gst_structure_get (s, "srtp-key", GST_TYPE_BUFFER, &buf, NULL);
+
+      g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-cipher",
+          &rtcp_cipher);
+      g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-auth",
+          &rtcp_auth);
+      g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-cipher",
+          &rtcp_cipher);
+      g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-auth",
+          &rtcp_auth);
+      g_object_set (stream->srtpenc, "key", buf, NULL);
+
+      g_value_unset (&rtcp_cipher);
+      g_value_unset (&rtcp_auth);
+      gst_buffer_unref (buf);
+    }
+  }
+  name = g_strdup_printf ("rtcp_sink_%d", session);
+  pad = gst_element_get_request_pad (stream->srtpenc, name);
+  g_free (name);
+  gst_object_unref (pad);
+
+  return gst_object_ref (stream->srtpenc);
 }
 
-static GstCaps *
-request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
+static GstElement *
+request_aux_receiver (GstElement * rtpbin, guint sessid, GstRTSPSrc * src)
 {
-  GST_DEBUG ("request key %u", ssrc);
-  return gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
+  GstElement *rtx, *bin;
+  GstPad *pad;
+  gchar *name;
+  GstRTSPStream *stream;
+
+  stream = find_stream (src, &sessid, (gpointer) find_stream_by_id);
+  if (!stream) {
+    GST_WARNING_OBJECT (src, "Stream %u not found", sessid);
+    return NULL;
+  }
+
+  GST_INFO_OBJECT (src, "creating retransmision receiver for session %u "
+      "with map %" GST_PTR_FORMAT, sessid, stream->rtx_pt_map);
+  bin = gst_bin_new (NULL);
+  rtx = gst_element_factory_make ("rtprtxreceive", NULL);
+  g_object_set (rtx, "payload-type-map", stream->rtx_pt_map, NULL);
+  gst_bin_add (GST_BIN (bin), rtx);
+
+  pad = gst_element_get_static_pad (rtx, "src");
+  name = g_strdup_printf ("src_%u", sessid);
+  gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
+  g_free (name);
+  gst_object_unref (pad);
+
+  pad = gst_element_get_static_pad (rtx, "sink");
+  name = g_strdup_printf ("sink_%u", sessid);
+  gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
+  g_free (name);
+  gst_object_unref (pad);
+
+  return bin;
 }
 
-static GstElement *
-request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
+static void
+add_retransmission (GstRTSPSrc * src, GstRTSPTransport * transport)
 {
-  if (stream->id != session)
-    return NULL;
+  GList *walk;
+  guint signal_id;
+  gboolean do_retransmission = FALSE;
 
-  if (stream->profile != GST_RTSP_PROFILE_SAVP &&
-      stream->profile != GST_RTSP_PROFILE_SAVPF)
-    return NULL;
+  if (transport->trans != GST_RTSP_TRANS_RTP)
+    return;
+  if (transport->profile != GST_RTSP_PROFILE_AVPF &&
+      transport->profile != GST_RTSP_PROFILE_SAVPF)
+    return;
 
-  if (stream->srtpdec == NULL) {
-    gchar *name;
+  signal_id = g_signal_lookup ("request-aux-receiver",
+      G_OBJECT_TYPE (src->manager));
+  /* there's already something connected */
+  if (g_signal_handler_find (src->manager, G_SIGNAL_MATCH_ID, signal_id, 0,
+          NULL, NULL, NULL) != 0) {
+    GST_DEBUG_OBJECT (src, "Not adding RTX AUX element as "
+        "\"request-aux-receiver\" signal is "
+        "already used by the application");
+    return;
+  }
 
-    name = g_strdup_printf ("srtpdec_%u", session);
-    stream->srtpdec = gst_element_factory_make ("srtpdec", name);
-    g_free (name);
+  /* build the retransmission payload type map */
+  for (walk = src->streams; walk; walk = g_list_next (walk)) {
+    GstRTSPStream *stream = (GstRTSPStream *) walk->data;
+    gboolean do_retransmission_stream = FALSE;
+    int i;
+
+    if (stream->rtx_pt_map)
+      gst_structure_free (stream->rtx_pt_map);
+    stream->rtx_pt_map = gst_structure_new_empty ("application/x-rtp-pt-map");
+
+    for (i = 0; i < stream->ptmap->len; i++) {
+      PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
+      GstStructure *s = gst_caps_get_structure (item->caps, 0);
+      const gchar *encoding;
+
+      /* we only care about RTX streams */
+      if ((encoding = gst_structure_get_string (s, "encoding-name"))
+          && g_strcmp0 (encoding, "RTX") == 0) {
+        const gchar *stream_pt_s;
+        gint rtx_pt;
+
+        if (gst_structure_get_int (s, "payload", &rtx_pt)
+            && (stream_pt_s = gst_structure_get_string (s, "apt"))) {
+
+          if (rtx_pt != 0) {
+            gst_structure_set (stream->rtx_pt_map, stream_pt_s, G_TYPE_UINT,
+                rtx_pt, NULL);
+            do_retransmission_stream = TRUE;
+          }
+        }
+      }
+    }
 
-    g_signal_connect (stream->srtpdec, "request-key",
-        (GCallback) request_key, stream);
+    if (do_retransmission_stream) {
+      GST_DEBUG_OBJECT (src, "built retransmission payload map for stream "
+          "id %i: %" GST_PTR_FORMAT, stream->id, stream->rtx_pt_map);
+      do_retransmission = TRUE;
+    } else {
+      GST_DEBUG_OBJECT (src, "no retransmission payload map for stream "
+          "id %i", stream->id);
+      gst_structure_free (stream->rtx_pt_map);
+      stream->rtx_pt_map = NULL;
+    }
+  }
+
+  if (do_retransmission) {
+    GST_DEBUG_OBJECT (src, "Enabling retransmissions");
+
+    g_object_set (src->manager, "do-retransmission", TRUE, NULL);
+
+    /* enable RFC4588 retransmission handling by setting rtprtxreceive
+     * as the "aux" element of rtpbin */
+    g_signal_connect (src->manager, "request-aux-receiver",
+        (GCallback) request_aux_receiver, src);
+  } else {
+    GST_DEBUG_OBJECT (src,
+        "Not enabling retransmissions as no stream had a retransmission payload map");
   }
-  return gst_object_ref (stream->srtpdec);
 }
 
 /* try to get and configure a manager */
@@ -3033,9 +3074,19 @@ gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
         g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
       }
 
-      if (g_object_class_find_property (klass, "use-pipeline-clock")) {
-        g_object_set (src->manager, "use-pipeline-clock",
-            src->use_pipeline_clock, NULL);
+      if (g_object_class_find_property (klass, "rfc7273-sync")) {
+        g_object_set (src->manager, "rfc7273-sync", src->rfc7273_sync, NULL);
+      }
+
+      if (src->use_pipeline_clock) {
+        if (g_object_class_find_property (klass, "use-pipeline-clock")) {
+          g_object_set (src->manager, "use-pipeline-clock", TRUE, NULL);
+        }
+      } else {
+        if (g_object_class_find_property (klass, "ntp-time-source")) {
+          g_object_set (src->manager, "ntp-time-source", src->ntp_time_source,
+              NULL);
+        }
       }
 
       if (src->sdes && g_object_class_find_property (klass, "sdes")) {
@@ -3047,6 +3098,11 @@ gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
             NULL);
       }
 
+      if (g_object_class_find_property (klass, "max-rtcp-rtp-time-diff")) {
+        g_object_set (src->manager, "max-rtcp-rtp-time-diff",
+            src->max_rtcp_rtp_time_diff, NULL);
+      }
+
       /* buffer mode pauses are handled by adding offsets to buffer times,
        * but some depayloaders may have a hard time syncing output times
        * with such input times, e.g. container ones, most notably ASF */
@@ -3056,7 +3112,7 @@ gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
        * so slaving in jitterbuffer does not make much sense
        * (and might mess things up due to bursts) */
       if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
-          src->segment.duration && !stream->container) {
+          src->segment.duration && stream->container) {
         src->use_buffering = TRUE;
       } else {
         src->use_buffering = FALSE;
@@ -3079,11 +3135,16 @@ gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
 
       g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_NEW_MANAGER], 0,
           src->manager);
+
+      if (src->do_retransmission)
+        add_retransmission (src, transport);
     }
     g_signal_connect (src->manager, "request-rtp-decoder",
         (GCallback) request_rtp_decoder, stream);
     g_signal_connect (src->manager, "request-rtcp-decoder",
         (GCallback) request_rtp_decoder, stream);
+    g_signal_connect (src->manager, "request-rtcp-encoder",
+        (GCallback) request_rtcp_encoder, stream);
 
     /* we stream directly to the manager, get some pads. Each RTSP stream goes
      * into a separate RTP session. */
@@ -3102,6 +3163,8 @@ gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
           &rtpsession);
       if (rtpsession) {
+        GstRTPProfile rtp_profile;
+
         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
 
         stream->session = rtpsession;
@@ -3123,8 +3186,28 @@ gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
               NULL);
         }
 
+        switch (stream->profile) {
+          case GST_RTSP_PROFILE_AVPF:
+            rtp_profile = GST_RTP_PROFILE_AVPF;
+            break;
+          case GST_RTSP_PROFILE_SAVP:
+            rtp_profile = GST_RTP_PROFILE_SAVP;
+            break;
+          case GST_RTSP_PROFILE_SAVPF:
+            rtp_profile = GST_RTP_PROFILE_SAVPF;
+            break;
+          case GST_RTSP_PROFILE_AVP:
+          default:
+            rtp_profile = GST_RTP_PROFILE_AVP;
+            break;
+        }
+
+        g_object_set (rtpsession, "rtp-profile", rtp_profile, NULL);
+
         g_object_set (rtpsession, "probation", src->probation, NULL);
 
+        g_object_set (rtpsession, "internal-ssrc", stream->send_ssrc, NULL);
+
         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
             stream);
         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
@@ -3452,7 +3535,8 @@ gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
      * configure all the streams to let the application autoplug decoders. */
     stream->blockid =
         gst_pad_add_probe (stream->blockedpad,
-        GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, pad_blocked, src, NULL);
+        GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
+        GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocked, src, NULL);
 
     if (stream->channelpad[0]) {
       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
@@ -3550,6 +3634,9 @@ gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
        * so that NAT firewalls will open a hole for us */
       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
+      if (!socket)
+        goto no_socket;
+
       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
       /* configure socket and make sure udpsink does not close it when shutting
        * down, it belongs to udpsrc after all. */
@@ -3567,9 +3654,6 @@ gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
 
-    /* we don't want to consider this a sink */
-    GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
-
     /* keep everything locked */
     gst_element_set_locked_state (stream->udpsink[0], TRUE);
     gst_element_set_locked_state (stream->fakesrc, TRUE);
@@ -3605,6 +3689,9 @@ gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
        * because some servers check the port number of where it sends RTCP to identify
        * the RTCP packets it receives */
       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
+      if (!socket)
+        goto no_socket;
+
       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
       /* configure socket and make sure udpsink does not close it when shutting
        * down, it belongs to udpsrc after all. */
@@ -3613,9 +3700,6 @@ gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
       g_object_unref (socket);
     }
 
-    /* we don't want to consider this a sink */
-    GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
-
     /* we keep this playing always */
     gst_element_set_locked_state (stream->udpsink[1], TRUE);
     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
@@ -3642,17 +3726,22 @@ gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
   /* ERRORS */
 no_destination:
   {
-    GST_DEBUG_OBJECT (src, "no destination address specified");
+    GST_ERROR_OBJECT (src, "no destination address specified");
     return FALSE;
   }
 no_sink_element:
   {
-    GST_DEBUG_OBJECT (src, "no UDP sink element found");
+    GST_ERROR_OBJECT (src, "no UDP sink element found");
     return FALSE;
   }
 no_fakesrc_element:
   {
-    GST_DEBUG_OBJECT (src, "no fakesrc element found");
+    GST_ERROR_OBJECT (src, "no fakesrc element found");
+    return FALSE;
+  }
+no_socket:
+  {
+    GST_ERROR_OBJECT (src, "failed to create socket");
     return FALSE;
   }
 }
@@ -3897,8 +3986,10 @@ gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
       GST_DEBUG_OBJECT (src, "stream %p, pt %d, caps %" GST_PTR_FORMAT, stream,
           item->pt, caps);
 
-      if (item->pt == stream->default_pt && stream->udpsrc[0]) {
-        g_object_set (stream->udpsrc[0], "caps", caps, NULL);
+      if (item->pt == stream->default_pt) {
+        if (stream->udpsrc[0])
+          g_object_set (stream->udpsrc[0], "caps", caps, NULL);
+        stream->need_caps = TRUE;
       }
     }
   }
@@ -4002,65 +4093,94 @@ gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
     gboolean async)
 {
   GstRTSPResult res;
+  GstRTSPMessage response;
+  gboolean retry = FALSE;
+  memset (&response, 0, sizeof (response));
+  gst_rtsp_message_init (&response);
+  do {
+    if (info->connection == NULL) {
+      if (info->url == NULL) {
+        GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
+        if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
+          goto parse_error;
+      }
+      /* create connection */
+      GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
+      if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
+        goto could_not_create;
 
-  if (info->connection == NULL) {
-    if (info->url == NULL) {
-      GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
-      if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
-        goto parse_error;
-    }
-
-    /* create connection */
-    GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
-    if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
-      goto could_not_create;
+      if (retry) {
+        gst_rtspsrc_setup_auth (src, &response);
+      }
 
-    if (info->url_str)
       g_free (info->url_str);
-    info->url_str = gst_rtsp_url_get_request_uri (info->url);
+      info->url_str = gst_rtsp_url_get_request_uri (info->url);
+
+      GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
+
+      if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
+        if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
+                src->tls_validation_flags))
+          GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
 
-    GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
+        if (src->tls_database)
+          gst_rtsp_connection_set_tls_database (info->connection,
+              src->tls_database);
 
-    if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
-      if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
-              src->tls_validation_flags))
-        GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
+        if (src->tls_interaction)
+          gst_rtsp_connection_set_tls_interaction (info->connection,
+              src->tls_interaction);
+      }
+
+      if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
+        gst_rtsp_connection_set_tunneled (info->connection, TRUE);
 
-      if (src->tls_database)
-        gst_rtsp_connection_set_tls_database (info->connection,
-            src->tls_database);
+      if (src->proxy_host) {
+        GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
+            src->proxy_port);
+        gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
+            src->proxy_port);
+      }
     }
 
-    if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
-      gst_rtsp_connection_set_tunneled (info->connection, TRUE);
+    if (!info->connected) {
+      /* connect */
+      if (async)
+        GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
+            ("Connecting to %s", info->location));
+      GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
+      res = gst_rtsp_connection_connect_with_response (info->connection,
+          src->ptcp_timeout, &response);
+
+      if (response.type == GST_RTSP_MESSAGE_HTTP_RESPONSE &&
+          response.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
+        gst_rtsp_conninfo_close (src, info, TRUE);
+        if (!retry)
+          retry = TRUE;
+        else
+          retry = FALSE;        // we should not retry more than once
+      } else {
+        retry = FALSE;
+      }
 
-    if (src->proxy_host) {
-      GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
-          src->proxy_port);
-      gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
-          src->proxy_port);
+      if (res == GST_RTSP_OK)
+        info->connected = TRUE;
+      else if (!retry)
+        goto could_not_connect;
     }
-  }
+  } while (!info->connected && retry);
 
-  if (!info->connected) {
-    /* connect */
-    if (async)
-      GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
-          ("Connecting to %s", info->location));
-    GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
-    if ((res =
-            gst_rtsp_connection_connect (info->connection,
-                src->ptcp_timeout)) < 0)
-      goto could_not_connect;
+  g_mutex_init (&info->send_lock);
+  g_mutex_init (&info->recv_lock);
 
-    info->connected = TRUE;
-  }
+  gst_rtsp_message_unset (&response);
   return GST_RTSP_OK;
 
   /* ERRORS */
 parse_error:
   {
     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
+    gst_rtsp_message_unset (&response);
     return res;
   }
 could_not_create:
@@ -4068,6 +4188,7 @@ could_not_create:
     gchar *str = gst_rtsp_strresult (res);
     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
     g_free (str);
+    gst_rtsp_message_unset (&response);
     return res;
   }
 could_not_connect:
@@ -4075,6 +4196,7 @@ could_not_connect:
     gchar *str = gst_rtsp_strresult (res);
     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
     g_free (str);
+    gst_rtsp_message_unset (&response);
     return res;
   }
 }
@@ -4094,6 +4216,10 @@ gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
     GST_DEBUG_OBJECT (src, "freeing connection...");
     gst_rtsp_connection_free (info->connection);
     info->connection = NULL;
+    info->flushing = FALSE;
+
+    g_mutex_clear (&info->send_lock);
+    g_mutex_clear (&info->recv_lock);
   }
   GST_RTSP_STATE_UNLOCK (src);
   return GST_RTSP_OK;
@@ -4135,9 +4261,26 @@ gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
   GST_RTSP_STATE_UNLOCK (src);
 }
 
+static GstRTSPResult
+gst_rtspsrc_init_request (GstRTSPSrc * src, GstRTSPMessage * msg,
+    GstRTSPMethod method, const gchar * uri)
+{
+  GstRTSPResult res;
+
+  res = gst_rtsp_message_init_request (msg, method, uri);
+  if (res < 0)
+    return res;
+
+  /* set user-agent */
+  if (src->user_agent)
+    gst_rtsp_message_add_header (msg, GST_RTSP_HDR_USER_AGENT, src->user_agent);
+
+  return res;
+}
+
 /* FIXME, handle server request, reply with OK, for now */
 static GstRTSPResult
-gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
+gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
     GstRTSPMessage * request)
 {
   GstRTSPMessage response = { 0 };
@@ -4166,7 +4309,7 @@ gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
     if (src->debug)
       gst_rtsp_message_dump (&response);
 
-    res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
+    res = gst_rtspsrc_connection_send (src, conninfo, &response, NULL);
     if (res < 0)
       goto send_error;
 
@@ -4211,16 +4354,14 @@ gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
   if (control == NULL)
     goto no_control;
 
-  res = gst_rtsp_message_init_request (&request, method, control);
+  res = gst_rtspsrc_init_request (src, &request, method, control);
   if (res < 0)
     goto send_error;
 
   if (src->debug)
     gst_rtsp_message_dump (&request);
 
-  res =
-      gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
-      NULL);
+  res = gst_rtspsrc_connection_send (src, &src->conninfo, &request, NULL);
   if (res < 0)
     goto send_error;
 
@@ -4258,7 +4399,6 @@ gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
   guint size;
   GstBuffer *buf;
   gboolean is_rtcp;
-  GstEvent *event;
 
   channel = message->type_data.data.channel;
 
@@ -4323,6 +4463,7 @@ gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
 
     for (streams = src->streams; streams; streams = g_list_next (streams)) {
       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
+      GstCaps *caps;
 
       stream_id =
           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
@@ -4331,15 +4472,50 @@ gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
 
       g_free (stream_id);
       gst_rtspsrc_stream_push_event (src, ostream, event);
+
+      if ((caps = stream_get_caps_for_pt (ostream, ostream->default_pt))) {
+        /* only streams that have a connection to the outside world */
+        if (ostream->setup) {
+          if (ostream->udpsrc[0]) {
+            gst_element_send_event (ostream->udpsrc[0],
+                gst_event_new_caps (caps));
+          } else if (ostream->channelpad[0]) {
+            if (GST_PAD_IS_SRC (ostream->channelpad[0]))
+              gst_pad_push_event (ostream->channelpad[0],
+                  gst_event_new_caps (caps));
+            else
+              gst_pad_send_event (ostream->channelpad[0],
+                  gst_event_new_caps (caps));
+          }
+          ostream->need_caps = FALSE;
+
+          if (ostream->profile == GST_RTSP_PROFILE_SAVP ||
+              ostream->profile == GST_RTSP_PROFILE_SAVPF)
+            caps = gst_caps_new_empty_simple ("application/x-srtcp");
+          else
+            caps = gst_caps_new_empty_simple ("application/x-rtcp");
+
+          if (ostream->udpsrc[1]) {
+            gst_element_send_event (ostream->udpsrc[1],
+                gst_event_new_caps (caps));
+          } else if (ostream->channelpad[1]) {
+            if (GST_PAD_IS_SRC (ostream->channelpad[1]))
+              gst_pad_push_event (ostream->channelpad[1],
+                  gst_event_new_caps (caps));
+            else
+              gst_pad_send_event (ostream->channelpad[1],
+                  gst_event_new_caps (caps));
+          }
+
+          gst_caps_unref (caps);
+        }
+      }
     }
     g_checksum_free (cs);
 
     gst_rtspsrc_activate_streams (src);
     src->need_activate = FALSE;
-  }
-  if ((event = src->start_segment) != NULL) {
-    src->start_segment = NULL;
-    gst_rtspsrc_push_event (src, event);
+    src->need_segment = TRUE;
   }
 
   if (src->base_time == -1) {
@@ -4366,6 +4542,37 @@ gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
     GST_OBJECT_UNLOCK (src);
   }
 
+  /* If needed send a new segment, don't forget we are live and buffer are
+   * timestamped with running time */
+  if (src->need_segment) {
+    GstSegment segment;
+    src->need_segment = FALSE;
+    gst_segment_init (&segment, GST_FORMAT_TIME);
+    gst_rtspsrc_push_event (src, gst_event_new_segment (&segment));
+  }
+
+  if (stream->need_caps) {
+    GstCaps *caps;
+
+    if ((caps = stream_get_caps_for_pt (stream, stream->default_pt))) {
+      /* only streams that have a connection to the outside world */
+      if (stream->setup) {
+        /* Only need to update the TCP caps here, UDP is already handled */
+        if (stream->channelpad[0]) {
+          if (GST_PAD_IS_SRC (stream->channelpad[0]))
+            gst_pad_push_event (stream->channelpad[0],
+                gst_event_new_caps (caps));
+          else
+            gst_pad_send_event (stream->channelpad[0],
+                gst_event_new_caps (caps));
+        }
+        stream->need_caps = FALSE;
+      }
+    }
+
+    stream->need_caps = FALSE;
+  }
+
   if (stream->discont && !is_rtcp) {
     /* mark first RTP buffer as discont */
     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
@@ -4435,7 +4642,7 @@ gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
     /* protect the connection with the connection lock so that we can see when
      * we are finished doing server communication */
     res =
-        gst_rtspsrc_connection_receive (src, src->conninfo.connection,
+        gst_rtspsrc_connection_receive (src, &src->conninfo,
         &message, src->ptcp_timeout);
 
     switch (res) {
@@ -4461,9 +4668,7 @@ gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
     switch (message.type) {
       case GST_RTSP_MESSAGE_REQUEST:
         /* server sends us a request message, handle it */
-        res =
-            gst_rtspsrc_handle_request (src, src->conninfo.connection,
-            &message);
+        res = gst_rtspsrc_handle_request (src, &src->conninfo, &message);
         if (res == GST_RTSP_EEOF)
           goto server_eof;
         else if (res < 0)
@@ -4554,7 +4759,7 @@ gst_rtspsrc_loop_udp (GstRTSPSrc * src)
     /* we should continue reading the TCP socket because the server might
      * send us requests. When the session timeout expires, we need to send a
      * keep-alive request to keep the session open. */
-    res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
+    res = gst_rtspsrc_connection_receive (src, &src->conninfo,
         &message, &tv_timeout);
 
     switch (res) {
@@ -4594,9 +4799,7 @@ gst_rtspsrc_loop_udp (GstRTSPSrc * src)
     switch (message.type) {
       case GST_RTSP_MESSAGE_REQUEST:
         /* server sends us a request message, handle it */
-        res =
-            gst_rtspsrc_handle_request (src, src->conninfo.connection,
-            &message);
+        res = gst_rtspsrc_handle_request (src, &src->conninfo, &message);
         if (res == GST_RTSP_EEOF)
           goto server_eof;
         else if (res < 0)
@@ -4723,8 +4926,8 @@ gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
    * that nothing happened. It's most likely a firewall thing. */
   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
       ("Could not receive any UDP packets for %.4f seconds, maybe your "
-          "firewall is blocking it. Retrying using a TCP connection.",
-          gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
+          "firewall is blocking it. Retrying using a tcp connection.",
+          gst_guint64_to_gdouble (src->udp_timeout) / 1000000.0));
 
   /* open new connection using tcp */
   if (gst_rtspsrc_open (src, async) < 0)
@@ -4745,7 +4948,7 @@ no_protocols:
     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
         ("Could not receive any UDP packets for %.4f seconds, maybe your "
             "firewall is blocking it. No other protocols to try.",
-            gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
+            gst_guint64_to_gdouble (src->udp_timeout) / 1000000.0));
     return GST_RTSP_ERROR;
   }
 open_failed:
@@ -4864,30 +5067,38 @@ gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
   /* start new request */
   gst_rtspsrc_loop_start_cmd (src, cmd);
 
-  GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
+  GST_DEBUG_OBJECT (src, "sending cmd %s", cmd_to_string (cmd));
 
   GST_OBJECT_LOCK (src);
   old = src->pending_cmd;
   if (old == CMD_RECONNECT) {
     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
     cmd = CMD_RECONNECT;
-  }
-  if (old != CMD_WAIT) {
+  } else if (old == CMD_CLOSE) {
+    /* our CMD_CLOSE might have interrutped CMD_LOOP. gst_rtspsrc_loop
+     * will send a CMD_WAIT which would cancel our pending CMD_CLOSE (if
+     * still pending). We just avoid it here by making sure CMD_CLOSE is
+     * still the pending command. */
+    GST_DEBUG_OBJECT (src, "ignore, we were closing");
+    cmd = CMD_CLOSE;
+  } else if (old != CMD_WAIT) {
     src->pending_cmd = CMD_WAIT;
     GST_OBJECT_UNLOCK (src);
     /* cancel previous request */
-    GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
+    GST_DEBUG_OBJECT (src, "cancel previous request %s", cmd_to_string (old));
     gst_rtspsrc_loop_cancel_cmd (src, old);
     GST_OBJECT_LOCK (src);
   }
   src->pending_cmd = cmd;
   /* interrupt if allowed */
   if (src->busy_cmd & mask) {
-    GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
+    GST_DEBUG_OBJECT (src, "connection flush busy %s",
+        cmd_to_string (src->busy_cmd));
     gst_rtspsrc_connection_flush (src, TRUE);
     flushed = TRUE;
   } else {
-    GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
+    GST_DEBUG_OBJECT (src, "not interrupting busy cmd %s",
+        cmd_to_string (src->busy_cmd));
   }
   if (src->task)
     gst_task_start (src->task);
@@ -4942,9 +5153,7 @@ pause:
     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
       /* for fatal errors we post an error message, post the error before the
        * EOS so the app knows about the error first. */
-      GST_ELEMENT_ERROR (src, STREAM, FAILED,
-          ("Internal data flow error."),
-          ("streaming task paused, reason %s (%d)", reason, ret));
+      GST_ELEMENT_FLOW_ERROR (src, ret);
       gst_rtspsrc_push_event (src, gst_event_new_eos ());
     }
     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
@@ -4975,132 +5184,6 @@ gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
 }
 #endif
 
-static const gchar *
-gst_rtspsrc_skip_lws (const gchar * s)
-{
-  while (g_ascii_isspace (*s))
-    s++;
-  return s;
-}
-
-static const gchar *
-gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
-{
-  while (s > start && g_ascii_isspace (*(s - 1)))
-    s--;
-  return s;
-}
-
-static const gchar *
-gst_rtspsrc_skip_commas (const gchar * s)
-{
-  /* The grammar allows for multiple commas */
-  while (g_ascii_isspace (*s) || *s == ',')
-    s++;
-  return s;
-}
-
-static const gchar *
-gst_rtspsrc_skip_item (const gchar * s)
-{
-  gboolean quoted = FALSE;
-  const gchar *start = s;
-
-  /* A list item ends at the last non-whitespace character
-   * before a comma which is not inside a quoted-string. Or at
-   * the end of the string.
-   */
-  while (*s) {
-    if (*s == '"')
-      quoted = !quoted;
-    else if (quoted) {
-      if (*s == '\\' && *(s + 1))
-        s++;
-    } else {
-      if (*s == ',')
-        break;
-    }
-    s++;
-  }
-
-  return gst_rtspsrc_unskip_lws (s, start);
-}
-
-static void
-gst_rtsp_decode_quoted_string (gchar * quoted_string)
-{
-  gchar *src, *dst;
-
-  src = quoted_string + 1;
-  dst = quoted_string;
-  while (*src && *src != '"') {
-    if (*src == '\\' && *(src + 1))
-      src++;
-    *dst++ = *src++;
-  }
-  *dst = '\0';
-}
-
-/* Extract the authentication tokens that the server provided for each method
- * into an array of structures and give those to the connection object.
- */
-static void
-gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
-    const gchar * header, gboolean * stale)
-{
-  GSList *list = NULL, *iter;
-  const gchar *end;
-  gchar *item, *eq, *name_end, *value;
-
-  g_return_if_fail (stale != NULL);
-
-  gst_rtsp_connection_clear_auth_params (conn);
-  *stale = FALSE;
-
-  /* Parse a header whose content is described by RFC2616 as
-   * "#something", where "something" does not itself contain commas,
-   * except as part of quoted-strings, into a list of allocated strings.
-   */
-  header = gst_rtspsrc_skip_commas (header);
-  while (*header) {
-    end = gst_rtspsrc_skip_item (header);
-    list = g_slist_prepend (list, g_strndup (header, end - header));
-    header = gst_rtspsrc_skip_commas (end);
-  }
-  if (!list)
-    return;
-
-  list = g_slist_reverse (list);
-  for (iter = list; iter; iter = iter->next) {
-    item = iter->data;
-
-    eq = strchr (item, '=');
-    if (eq) {
-      name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
-      if (name_end == item) {
-        /* That's no good... */
-        g_free (item);
-        continue;
-      }
-
-      *name_end = '\0';
-
-      value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
-      if (*value == '"')
-        gst_rtsp_decode_quoted_string (value);
-    } else
-      value = NULL;
-
-    if (item && (strcmp (item, "stale") == 0) &&
-        value && (strcmp (value, "TRUE") == 0))
-      *stale = TRUE;
-    gst_rtsp_connection_set_auth_param (conn, item, value);
-    g_free (item);
-  }
-
-  g_slist_free (list);
-}
-
 /* Parse a WWW-Authenticate Response header and determine the
  * available authentication methods
  *
@@ -5110,24 +5193,47 @@ gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
  * At the moment, for Basic auth, we just do a minimal check and don't
  * even parse out the realm */
 static void
-gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
-    GstRTSPConnection * conn, gboolean * stale)
+gst_rtspsrc_parse_auth_hdr (GstRTSPMessage * response,
+    GstRTSPAuthMethod * methods, GstRTSPConnection * conn, gboolean * stale)
 {
-  gchar *start;
+  GstRTSPAuthCredential **credentials, **credential;
 
-  g_return_if_fail (hdr != NULL);
+  g_return_if_fail (response != NULL);
   g_return_if_fail (methods != NULL);
   g_return_if_fail (stale != NULL);
 
-  /* Skip whitespace at the start of the string */
-  for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
+  credentials =
+      gst_rtsp_message_parse_auth_credentials (response,
+      GST_RTSP_HDR_WWW_AUTHENTICATE);
+  if (!credentials)
+    return;
+
+  credential = credentials;
+  while (*credential) {
+    if ((*credential)->scheme == GST_RTSP_AUTH_BASIC) {
+      *methods |= GST_RTSP_AUTH_BASIC;
+    } else if ((*credential)->scheme == GST_RTSP_AUTH_DIGEST) {
+      GstRTSPAuthParam **param = (*credential)->params;
+
+      *methods |= GST_RTSP_AUTH_DIGEST;
+
+      gst_rtsp_connection_clear_auth_params (conn);
+      *stale = FALSE;
+
+      while (*param) {
+        if (strcmp ((*param)->name, "stale") == 0
+            && g_ascii_strcasecmp ((*param)->value, "TRUE") == 0)
+          *stale = TRUE;
+        gst_rtsp_connection_set_auth_param (conn, (*param)->name,
+            (*param)->value);
+        param++;
+      }
+    }
 
-  if (g_ascii_strncasecmp (start, "basic", 5) == 0)
-    *methods |= GST_RTSP_AUTH_BASIC;
-  else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
-    *methods |= GST_RTSP_AUTH_DIGEST;
-    gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
+    credential++;
   }
+
+  gst_rtsp_auth_credentials_free (credentials);
 }
 
 /**
@@ -5154,16 +5260,12 @@ gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
   GstRTSPResult auth_result;
   GstRTSPUrl *url;
   GstRTSPConnection *conn;
-  gchar *hdr;
   gboolean stale = FALSE;
 
   conn = src->conninfo.connection;
 
   /* Identify the available auth methods and see if any are supported */
-  if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
-          &hdr, 0) == GST_RTSP_OK) {
-    gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
-  }
+  gst_rtspsrc_parse_auth_hdr (response, &avail_methods, conn, &stale);
 
   if (avail_methods == GST_RTSP_AUTH_NONE)
     goto no_auth_available;
@@ -5239,7 +5341,7 @@ no_user_pass:
 }
 
 static GstRTSPResult
-gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
+gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
     GstRTSPMessage * request, GstRTSPMessage * response,
     GstRTSPStatusCode * code)
 {
@@ -5257,14 +5359,16 @@ again:
   if (src->debug)
     gst_rtsp_message_dump (request);
 
-  res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
+  res = gst_rtspsrc_connection_send (src, conninfo, request, src->ptcp_timeout);
   if (res < 0)
     goto send_error;
 
-  gst_rtsp_connection_reset_timeout (conn);
+  gst_rtsp_connection_reset_timeout (conninfo->connection);
 
 next:
-  res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
+  res =
+      gst_rtspsrc_connection_receive (src, conninfo, response,
+      src->ptcp_timeout);
   if (res < 0)
     goto receive_error;
 
@@ -5273,7 +5377,7 @@ next:
 
   switch (response->type) {
     case GST_RTSP_MESSAGE_REQUEST:
-      res = gst_rtspsrc_handle_request (src, conn, response);
+      res = gst_rtspsrc_handle_request (src, conninfo, response);
       if (res == GST_RTSP_EEOF)
         goto server_eof;
       else if (res < 0)
@@ -5401,7 +5505,7 @@ server_eof:
  * Returns: #GST_RTSP_OK if the processing was successful.
  */
 static GstRTSPResult
-gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
+gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnInfo * conninfo,
     GstRTSPMessage * request, GstRTSPMessage * response,
     GstRTSPStatusCode * code)
 {
@@ -5423,11 +5527,13 @@ gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
     method = request->type_data.request.method;
 
     if ((res =
-            gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
+            gst_rtspsrc_try_send (src, conninfo, request, response,
+                &int_code)) < 0)
       goto error;
 
     switch (int_code) {
       case GST_RTSP_STS_UNAUTHORIZED:
+      case GST_RTSP_STS_NOT_FOUND:
         if (gst_rtspsrc_setup_auth (src, response)) {
           /* Try the request/response again after configuring the auth info
            * and loop again */
@@ -5460,8 +5566,12 @@ error_response:
 
     switch (response->type_data.response.code) {
       case GST_RTSP_STS_NOT_FOUND:
-        GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
-                response->type_data.response.reason));
+        RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_FOUND,
+            "Not found");
+        break;
+      case GST_RTSP_STS_UNAUTHORIZED:
+        RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, NOT_AUTHORIZED,
+            "Unauthorized");
         break;
       case GST_RTSP_STS_MOVED_PERMANENTLY:
       case GST_RTSP_STS_MOVE_TEMPORARILY:
@@ -5493,7 +5603,6 @@ error_response:
           src->conninfo.url->transports = transports;
 
         src->need_redirect = TRUE;
-        src->state = GST_RTSP_STATE_INIT;
         res = GST_RTSP_OK;
         break;
       }
@@ -5506,9 +5615,8 @@ error_response:
         res = GST_RTSP_OK;
         break;
       default:
-        GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
-            ("Got error response: %d (%s).", response->type_data.response.code,
-                response->type_data.response.reason));
+        RTSP_SRC_RESPONSE_ERROR (src, response, RESOURCE, READ,
+            "Unhandled error");
         break;
     }
     /* if we return ERROR we should unset the response ourselves */
@@ -5523,8 +5631,7 @@ static GstRTSPResult
 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
     GstRTSPMessage * response, GstRTSPSrc * src)
 {
-  return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
-      NULL);
+  return gst_rtspsrc_send (src, &src->conninfo, request, response, NULL);
 }
 
 
@@ -5598,7 +5705,7 @@ no_setup:
 
 /* masks to be kept in sync with the hardcoded protocol order of preference
  * in code below */
-static guint protocol_masks[] = {
+static const guint protocol_masks[] = {
   GST_RTSP_LOWER_TRANS_UDP,
   GST_RTSP_LOWER_TRANS_UDP_MCAST,
   GST_RTSP_LOWER_TRANS_TCP,
@@ -5771,6 +5878,76 @@ failed:
   }
 }
 
+static GstCaps *
+signal_get_srtcp_params (GstRTSPSrc * src, GstRTSPStream * stream)
+{
+  GstCaps *caps = NULL;
+
+  g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
+      stream->id, &caps);
+
+  if (caps != NULL)
+    GST_DEBUG_OBJECT (src, "SRTP parameters received");
+
+  return caps;
+}
+
+static GstCaps *
+default_srtcp_params (void)
+{
+  guint i;
+  GstCaps *caps;
+  GstBuffer *buf;
+  guint8 *key_data;
+#define KEY_SIZE 30
+  guint data_size = GST_ROUND_UP_4 (KEY_SIZE);
+
+  /* create a random key */
+  key_data = g_malloc (data_size);
+  for (i = 0; i < data_size; i += 4)
+    GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
+
+  buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
+
+  caps = gst_caps_new_simple ("application/x-srtcp",
+      "srtp-key", GST_TYPE_BUFFER, buf,
+      "srtp-cipher", G_TYPE_STRING, "aes-128-icm",
+      "srtp-auth", G_TYPE_STRING, "hmac-sha1-80",
+      "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
+      "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
+
+  gst_buffer_unref (buf);
+
+  return caps;
+}
+
+static gchar *
+gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
+{
+  gchar *base64, *result = NULL;
+  GstMIKEYMessage *mikey_msg;
+
+  stream->srtcpparams = signal_get_srtcp_params (src, stream);
+  if (stream->srtcpparams == NULL)
+    stream->srtcpparams = default_srtcp_params ();
+
+  mikey_msg = gst_mikey_message_new_from_caps (stream->srtcpparams);
+  if (mikey_msg) {
+    /* add policy '0' for our SSRC */
+    gst_mikey_message_add_cs_srtp (mikey_msg, 0, stream->send_ssrc, 0);
+
+    base64 = gst_mikey_message_base64_encode (mikey_msg);
+    gst_mikey_message_unref (mikey_msg);
+
+    if (base64) {
+      result = gst_sdp_make_keymgmt (stream->conninfo.location, base64);
+      g_free (base64);
+    }
+  }
+
+  return result;
+}
+
 /* Perform the SETUP request for all the streams.
  *
  * We ask the server for a specific transport, which initially includes all the
@@ -5823,7 +6000,7 @@ gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
     goto no_streams;
 
   for (walk = src->streams; walk; walk = g_list_next (walk)) {
-    GstRTSPConnection *conn;
+    GstRTSPConnInfo *conninfo;
     gchar *transports;
     gint retry = 0;
     guint mask = 0;
@@ -5888,9 +6065,9 @@ gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
         continue;
       }
-      conn = stream->conninfo.connection;
+      conninfo = &stream->conninfo;
     } else {
-      conn = src->conninfo.connection;
+      conninfo = &src->conninfo;
     }
     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
         stream->conninfo.location);
@@ -5938,7 +6115,7 @@ gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
 
     /* create SETUP request */
     res =
-        gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
+        gst_rtspsrc_init_request (src, &request, GST_RTSP_SETUP,
         stream->conninfo.location);
     if (res < 0) {
       g_free (transports);
@@ -5948,6 +6125,13 @@ gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
     /* select transport */
     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
 
+    /* set up keys */
+    if (stream->profile == GST_RTSP_PROFILE_SAVP ||
+        stream->profile == GST_RTSP_PROFILE_SAVPF) {
+      hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
+      gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
+    }
+
     /* if the user wants a non default RTP packet size we add the blocksize
      * parameter */
     if (src->rtp_blocksize > 0) {
@@ -5960,7 +6144,8 @@ gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
               stream->id));
 
     /* handle the code ourselves */
-    if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
+    res = gst_rtspsrc_send (src, conninfo, &request, &response, &code);
+    if (res < 0)
       goto send_error;
 
     switch (code) {
@@ -6054,7 +6239,7 @@ gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
           break;
       }
 
-      if (!stream->container || (!src->interleaved && !retry)) {
+      if (!src->interleaved || !retry) {
         /* now configure the stream with the selected transport */
         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
           GST_DEBUG_OBJECT (src,
@@ -6414,7 +6599,7 @@ gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
   /* create streams */
   n_streams = gst_sdp_message_medias_len (sdp);
   for (i = 0; i < n_streams; i++) {
-    gst_rtspsrc_create_stream (src, sdp, i);
+    gst_rtspsrc_create_stream (src, sdp, i, n_streams);
   }
 
   src->state = GST_RTSP_STATE_INIT;
@@ -6467,7 +6652,7 @@ restart:
   /* create OPTIONS */
   GST_DEBUG_OBJECT (src, "create options...");
   res =
-      gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
+      gst_rtspsrc_init_request (src, &request, GST_RTSP_OPTIONS,
       src->conninfo.url_str);
   if (res < 0)
     goto create_request_failed;
@@ -6479,7 +6664,7 @@ restart:
     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
 
   if ((res =
-          gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
+          gst_rtspsrc_send (src, &src->conninfo, &request, &response,
               NULL)) < 0)
     goto send_error;
 
@@ -6490,7 +6675,7 @@ restart:
   /* create DESCRIBE */
   GST_DEBUG_OBJECT (src, "create describe...");
   res =
-      gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
+      gst_rtspsrc_init_request (src, &request, GST_RTSP_DESCRIBE,
       src->conninfo.url_str);
   if (res < 0)
     goto create_request_failed;
@@ -6506,11 +6691,11 @@ restart:
     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
 
   if ((res =
-          gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
+          gst_rtspsrc_send (src, &src->conninfo, &request, &response,
               NULL)) < 0)
     goto send_error;
 
-  /* we only perform redirect for the describe, currently */
+  /* we only perform redirect for describe and play, currently */
   if (src->need_redirect) {
     /* close connection, we don't have to send a TEARDOWN yet, ignore the
      * result. */
@@ -6524,7 +6709,7 @@ restart:
   }
 
   /* it could be that the DESCRIBE method was not implemented */
-  if (!src->methods & GST_RTSP_DESCRIBE)
+  if (!(src->methods & GST_RTSP_DESCRIBE))
     goto no_describe;
 
   /* check if reply is SDP */
@@ -6533,8 +6718,24 @@ restart:
   /* could not be set but since the request returned OK, we assume it
    * was SDP, else check it. */
   if (respcont) {
-    if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
+    const gchar *props = strchr (respcont, ';');
+
+    if (props) {
+      gchar *mimetype = g_strndup (respcont, props - respcont);
+
+      mimetype = g_strstrip (mimetype);
+      if (g_ascii_strcasecmp (mimetype, "application/sdp") != 0) {
+        g_free (mimetype);
+        goto wrong_content_type;
+      }
+
+      /* TODO: Check for charset property and do conversions of all messages if
+       * needed. Some servers actually send that property */
+
+      g_free (mimetype);
+    } else if (g_ascii_strcasecmp (respcont, "application/sdp") != 0) {
       goto wrong_content_type;
+    }
   }
 
   /* get message body and parse as SDP */
@@ -6706,16 +6907,14 @@ gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
 
     /* do TEARDOWN */
     res =
-        gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
+        gst_rtspsrc_init_request (src, &request, GST_RTSP_TEARDOWN, setup_url);
     if (res < 0)
       goto create_request_failed;
 
     if (async)
       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
 
-    if ((res =
-            gst_rtspsrc_send (src, info->connection, &request, &response,
-                NULL)) < 0)
+    if ((res = gst_rtspsrc_send (src, info, &request, &response, NULL)) < 0)
       goto send_error;
 
     /* FIXME, parse result? */
@@ -6937,7 +7136,10 @@ clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
     item->caps = gst_caps_make_writable (item->caps);
     s = gst_caps_get_structure (item->caps, 0);
     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
+    if (item->pt == stream->default_pt && stream->udpsrc[0])
+      g_object_set (stream->udpsrc[0], "caps", item->caps, NULL);
   }
+  stream->need_caps = TRUE;
 }
 
 static GstRTSPResult
@@ -6977,6 +7179,7 @@ gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
 
   GST_DEBUG_OBJECT (src, "PLAY...");
 
+restart:
   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
     goto open_failed;
 
@@ -6997,15 +7200,13 @@ gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
   if (src->manager)
     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
 
-  gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
-
   /* construct a control url */
   control = get_aggregate_control (src);
 
   for (walk = src->streams; walk; walk = g_list_next (walk)) {
     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
     const gchar *setup_url;
-    GstRTSPConnection *conn;
+    GstRTSPConnInfo *conninfo;
 
     /* try aggregate control first but do non-aggregate control otherwise */
     if (control)
@@ -7014,15 +7215,15 @@ gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
       continue;
 
     if (src->conninfo.connection) {
-      conn = src->conninfo.connection;
+      conninfo = &src->conninfo;
     } else if (stream->conninfo.connection) {
-      conn = stream->conninfo.connection;
+      conninfo = &stream->conninfo;
     } else {
       continue;
     }
 
     /* do play */
-    res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
+    res = gst_rtspsrc_init_request (src, &request, GST_RTSP_PLAY, setup_url);
     if (res < 0)
       goto create_request_failed;
 
@@ -7032,9 +7233,7 @@ gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
 
       /* store the newsegment event so it can be sent from the streaming thread. */
-      if (src->start_segment)
-        gst_event_unref (src->start_segment);
-      src->start_segment = gst_event_new_segment (&src->segment);
+      src->need_segment = TRUE;
     }
 
     if (segment->rate != 1.0) {
@@ -7050,9 +7249,21 @@ gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
     if (async)
       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
 
-    if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
+    if ((res = gst_rtspsrc_send (src, conninfo, &request, &response, NULL)) < 0)
       goto send_error;
 
+    if (src->need_redirect) {
+      GST_DEBUG_OBJECT (src,
+          "redirect: tearing down and restarting with new url");
+      /* teardown and restart with new url */
+      gst_rtspsrc_close (src, TRUE, FALSE);
+      /* reset protocols to force re-negotiation with redirected url */
+      src->cur_protocols = src->protocols;
+      gst_rtsp_message_unset (&request);
+      gst_rtsp_message_unset (&response);
+      goto restart;
+    }
+
     /* seek may have silently failed as it is not supported */
     if (!(src->methods & GST_RTSP_PLAY)) {
       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
@@ -7120,6 +7331,11 @@ gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
    * the manager object when we set a new Range header (we did a seek) */
   gst_rtspsrc_configure_caps (src, segment, src->need_range);
 
+  /* set to PLAYING after we have configured the caps, otherwise we
+   * might end up calling request_key (with SRTP) while caps are still
+   * being configured. */
+  gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
+
   /* set again when needed */
   src->need_range = FALSE;
 
@@ -7211,7 +7427,7 @@ gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
    * aggregate control */
   for (walk = src->streams; walk; walk = g_list_next (walk)) {
     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
-    GstRTSPConnection *conn;
+    GstRTSPConnInfo *conninfo;
     const gchar *setup_url;
 
     /* try aggregate control first but do non-aggregate control otherwise */
@@ -7221,9 +7437,9 @@ gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
       continue;
 
     if (src->conninfo.connection) {
-      conn = src->conninfo.connection;
+      conninfo = &src->conninfo;
     } else if (stream->conninfo.connection) {
-      conn = stream->conninfo.connection;
+      conninfo = &stream->conninfo;
     } else {
       continue;
     }
@@ -7233,11 +7449,11 @@ gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
           ("Sending PAUSE request"));
 
     if ((res =
-            gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
+            gst_rtspsrc_init_request (src, &request, GST_RTSP_PAUSE,
                 setup_url)) < 0)
       goto create_request_failed;
 
-    if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
+    if ((res = gst_rtspsrc_send (src, conninfo, &request, &response, NULL)) < 0)
       goto send_error;
 
     gst_rtsp_message_unset (&request);
@@ -7394,7 +7610,7 @@ gst_rtspsrc_thread (GstRTSPSrc * src)
     src->pending_cmd = CMD_LOOP;
   else
     src->pending_cmd = CMD_WAIT;
-  GST_DEBUG_OBJECT (src, "got command %d", cmd);
+  GST_DEBUG_OBJECT (src, "got command %s", cmd_to_string (cmd));
 
   /* we got the message command, so ensure communication is possible again */
   gst_rtspsrc_connection_flush (src, FALSE);
@@ -7561,7 +7777,7 @@ gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
       ret = GST_STATE_CHANGE_NO_PREROLL;
       break;
     case GST_STATE_CHANGE_PAUSED_TO_READY:
-      gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
+      gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_ALL);
       ret = GST_STATE_CHANGE_SUCCESS;
       break;
     case GST_STATE_CHANGE_READY_TO_NULL:
@@ -7569,6 +7785,16 @@ gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
       ret = GST_STATE_CHANGE_SUCCESS;
       break;
     default:
+      /* Otherwise it's success, we don't want to return spurious
+       * NO_PREROLL or ASYNC from internal elements as we care for
+       * state changes ourselves here
+       *
+       * This is to catch PAUSED->PAUSED and PLAYING->PLAYING transitions.
+       */
+      if (GST_STATE_TRANSITION_NEXT (transition) == GST_STATE_PAUSED)
+        ret = GST_STATE_CHANGE_NO_PREROLL;
+      else
+        ret = GST_STATE_CHANGE_SUCCESS;
       break;
   }
 
@@ -7634,6 +7860,7 @@ gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
 {
   GstRTSPSrc *src;
   GstRTSPResult res;
+  GstSDPResult sres;
   GstRTSPUrl *newurl = NULL;
   GstSDPMessage *sdp = NULL;
 
@@ -7644,11 +7871,13 @@ gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
     goto was_ok;
 
   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
-    if ((res = gst_sdp_message_new (&sdp) < 0))
+    sres = gst_sdp_message_new (&sdp);
+    if (sres < 0)
       goto sdp_failed;
 
     GST_DEBUG_OBJECT (src, "parsing SDP message");
-    if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
+    sres = gst_sdp_message_parse_uri (uri, sdp);
+    if (sres < 0)
       goto invalid_sdp;
   } else {
     /* try to parse */
@@ -7689,14 +7918,14 @@ was_ok:
   }
 sdp_failed:
   {
-    GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
+    GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", sres);
     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
         "Could not create SDP");
     return FALSE;
   }
 invalid_sdp:
   {
-    GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
+    GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", sres,
         GST_STR_NULL (uri));
     gst_sdp_message_free (sdp);
     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,