rtspsrc: make all srtp encoder properties explicit
[platform/upstream/gst-plugins-good.git] / gst / rtsp / gstrtspsrc.c
1 /* GStreamer
2  * Copyright (C) <2005,2006> Wim Taymans <wim at fluendo dot com>
3  *               <2006> Lutz Mueller <lutz at topfrose dot de>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20 /*
21  * Unless otherwise indicated, Source Code is licensed under MIT license.
22  * See further explanation attached in License Statement (distributed in the file
23  * LICENSE).
24  *
25  * Permission is hereby granted, free of charge, to any person obtaining a copy of
26  * this software and associated documentation files (the "Software"), to deal in
27  * the Software without restriction, including without limitation the rights to
28  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
29  * of the Software, and to permit persons to whom the Software is furnished to do
30  * so, subject to the following conditions:
31  *
32  * The above copyright notice and this permission notice shall be included in all
33  * copies or substantial portions of the Software.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
41  * SOFTWARE.
42  */
43 /**
44  * SECTION:element-rtspsrc
45  *
46  * Makes a connection to an RTSP server and read the data.
47  * rtspsrc strictly follows RFC 2326 and therefore does not (yet) support
48  * RealMedia/Quicktime/Microsoft extensions.
49  *
50  * RTSP supports transport over TCP or UDP in unicast or multicast mode. By
51  * default rtspsrc will negotiate a connection in the following order:
52  * UDP unicast/UDP multicast/TCP. The order cannot be changed but the allowed
53  * protocols can be controlled with the #GstRTSPSrc:protocols property.
54  *
55  * rtspsrc currently understands SDP as the format of the session description.
56  * For each stream listed in the SDP a new rtp_stream\%d pad will be created
57  * with caps derived from the SDP media description. This is a caps of mime type
58  * "application/x-rtp" that can be connected to any available RTP depayloader
59  * element.
60  *
61  * rtspsrc will internally instantiate an RTP session manager element
62  * that will handle the RTCP messages to and from the server, jitter removal,
63  * packet reordering along with providing a clock for the pipeline.
64  * This feature is implemented using the gstrtpbin element.
65  *
66  * rtspsrc acts like a live source and will therefore only generate data in the
67  * PLAYING state.
68  *
69  * <refsect2>
70  * <title>Example launch line</title>
71  * |[
72  * gst-launch-1.0 rtspsrc location=rtsp://some.server/url ! fakesink
73  * ]| Establish a connection to an RTSP server and send the raw RTP packets to a
74  * fakesink.
75  * </refsect2>
76  */
77
78 #ifdef HAVE_CONFIG_H
79 #include "config.h"
80 #endif
81
82 #ifdef HAVE_UNISTD_H
83 #include <unistd.h>
84 #endif /* HAVE_UNISTD_H */
85 #include <stdlib.h>
86 #include <string.h>
87 #include <stdio.h>
88 #include <stdarg.h>
89
90 #include <gst/net/gstnet.h>
91 #include <gst/sdp/gstsdpmessage.h>
92 #include <gst/sdp/gstmikey.h>
93 #include <gst/rtp/rtp.h>
94
95 #include "gst/gst-i18n-plugin.h"
96
97 #include "gstrtspsrc.h"
98
99 GST_DEBUG_CATEGORY_STATIC (rtspsrc_debug);
100 #define GST_CAT_DEFAULT (rtspsrc_debug)
101
102 static GstStaticPadTemplate rtptemplate = GST_STATIC_PAD_TEMPLATE ("stream_%u",
103     GST_PAD_SRC,
104     GST_PAD_SOMETIMES,
105     GST_STATIC_CAPS ("application/x-rtp; application/x-rdt"));
106
107 /* templates used internally */
108 static GstStaticPadTemplate anysrctemplate =
109 GST_STATIC_PAD_TEMPLATE ("internalsrc_%u",
110     GST_PAD_SRC,
111     GST_PAD_SOMETIMES,
112     GST_STATIC_CAPS_ANY);
113
114 static GstStaticPadTemplate anysinktemplate =
115 GST_STATIC_PAD_TEMPLATE ("internalsink_%u",
116     GST_PAD_SINK,
117     GST_PAD_SOMETIMES,
118     GST_STATIC_CAPS_ANY);
119
120 enum
121 {
122   SIGNAL_HANDLE_REQUEST,
123   SIGNAL_ON_SDP,
124   SIGNAL_SELECT_STREAM,
125   SIGNAL_NEW_MANAGER,
126   SIGNAL_REQUEST_RTCP_KEY,
127   LAST_SIGNAL
128 };
129
130 enum _GstRtspSrcRtcpSyncMode
131 {
132   RTCP_SYNC_ALWAYS,
133   RTCP_SYNC_INITIAL,
134   RTCP_SYNC_RTP
135 };
136
137 enum _GstRtspSrcBufferMode
138 {
139   BUFFER_MODE_NONE,
140   BUFFER_MODE_SLAVE,
141   BUFFER_MODE_BUFFER,
142   BUFFER_MODE_AUTO,
143   BUFFER_MODE_SYNCED
144 };
145
146 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
147 static GType
148 gst_rtsp_src_buffer_mode_get_type (void)
149 {
150   static GType buffer_mode_type = 0;
151   static const GEnumValue buffer_modes[] = {
152     {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
153     {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
154     {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
155     {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
156     {BUFFER_MODE_SYNCED, "Synchronized sender and receiver clocks", "synced"},
157     {0, NULL, NULL},
158   };
159
160   if (!buffer_mode_type) {
161     buffer_mode_type =
162         g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
163   }
164   return buffer_mode_type;
165 }
166
167 enum _GstRtspSrcNtpTimeSource
168 {
169   NTP_TIME_SOURCE_NTP,
170   NTP_TIME_SOURCE_UNIX,
171   NTP_TIME_SOURCE_RUNNING_TIME,
172   NTP_TIME_SOURCE_CLOCK_TIME
173 };
174
175 #define GST_TYPE_RTSP_SRC_NTP_TIME_SOURCE (gst_rtsp_src_ntp_time_source_get_type())
176 static GType
177 gst_rtsp_src_ntp_time_source_get_type (void)
178 {
179   static GType ntp_time_source_type = 0;
180   static const GEnumValue ntp_time_source_values[] = {
181     {NTP_TIME_SOURCE_NTP, "NTP time based on realtime clock", "ntp"},
182     {NTP_TIME_SOURCE_UNIX, "UNIX time based on realtime clock", "unix"},
183     {NTP_TIME_SOURCE_RUNNING_TIME,
184           "Running time based on pipeline clock",
185         "running-time"},
186     {NTP_TIME_SOURCE_CLOCK_TIME, "Pipeline clock time", "clock-time"},
187     {0, NULL, NULL},
188   };
189
190   if (!ntp_time_source_type) {
191     ntp_time_source_type =
192         g_enum_register_static ("GstRTSPSrcNtpTimeSource",
193         ntp_time_source_values);
194   }
195   return ntp_time_source_type;
196 }
197
198 #define DEFAULT_LOCATION         NULL
199 #define DEFAULT_PROTOCOLS        GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
200 #define DEFAULT_DEBUG            FALSE
201 #define DEFAULT_RETRY            20
202 #define DEFAULT_TIMEOUT          5000000
203 #define DEFAULT_UDP_BUFFER_SIZE  0x80000
204 #define DEFAULT_TCP_TIMEOUT      20000000
205 #define DEFAULT_LATENCY_MS       2000
206 #define DEFAULT_DROP_ON_LATENCY  FALSE
207 #define DEFAULT_CONNECTION_SPEED 0
208 #define DEFAULT_NAT_METHOD       GST_RTSP_NAT_DUMMY
209 #define DEFAULT_DO_RTCP          TRUE
210 #define DEFAULT_DO_RTSP_KEEP_ALIVE       TRUE
211 #define DEFAULT_PROXY            NULL
212 #define DEFAULT_RTP_BLOCKSIZE    0
213 #define DEFAULT_USER_ID          NULL
214 #define DEFAULT_USER_PW          NULL
215 #define DEFAULT_BUFFER_MODE      BUFFER_MODE_AUTO
216 #define DEFAULT_PORT_RANGE       NULL
217 #define DEFAULT_SHORT_HEADER     FALSE
218 #define DEFAULT_PROBATION        2
219 #define DEFAULT_UDP_RECONNECT    TRUE
220 #define DEFAULT_MULTICAST_IFACE  NULL
221 #define DEFAULT_NTP_SYNC         FALSE
222 #define DEFAULT_USE_PIPELINE_CLOCK       FALSE
223 #define DEFAULT_TLS_VALIDATION_FLAGS     G_TLS_CERTIFICATE_VALIDATE_ALL
224 #define DEFAULT_TLS_DATABASE     NULL
225 #define DEFAULT_TLS_INTERACTION     NULL
226 #define DEFAULT_DO_RETRANSMISSION        TRUE
227 #define DEFAULT_NTP_TIME_SOURCE  NTP_TIME_SOURCE_NTP
228 #define DEFAULT_USER_AGENT       "GStreamer/" PACKAGE_VERSION
229 #define DEFAULT_MAX_RTCP_RTP_TIME_DIFF 1000
230 #define DEFAULT_RFC7273_SYNC         FALSE
231
232 enum
233 {
234   PROP_0,
235   PROP_LOCATION,
236   PROP_PROTOCOLS,
237   PROP_DEBUG,
238   PROP_RETRY,
239   PROP_TIMEOUT,
240   PROP_TCP_TIMEOUT,
241   PROP_LATENCY,
242   PROP_DROP_ON_LATENCY,
243   PROP_CONNECTION_SPEED,
244   PROP_NAT_METHOD,
245   PROP_DO_RTCP,
246   PROP_DO_RTSP_KEEP_ALIVE,
247   PROP_PROXY,
248   PROP_PROXY_ID,
249   PROP_PROXY_PW,
250   PROP_RTP_BLOCKSIZE,
251   PROP_USER_ID,
252   PROP_USER_PW,
253   PROP_BUFFER_MODE,
254   PROP_PORT_RANGE,
255   PROP_UDP_BUFFER_SIZE,
256   PROP_SHORT_HEADER,
257   PROP_PROBATION,
258   PROP_UDP_RECONNECT,
259   PROP_MULTICAST_IFACE,
260   PROP_NTP_SYNC,
261   PROP_USE_PIPELINE_CLOCK,
262   PROP_SDES,
263   PROP_TLS_VALIDATION_FLAGS,
264   PROP_TLS_DATABASE,
265   PROP_TLS_INTERACTION,
266   PROP_DO_RETRANSMISSION,
267   PROP_NTP_TIME_SOURCE,
268   PROP_USER_AGENT,
269   PROP_MAX_RTCP_RTP_TIME_DIFF,
270   PROP_RFC7273_SYNC
271 };
272
273 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
274 static GType
275 gst_rtsp_nat_method_get_type (void)
276 {
277   static GType rtsp_nat_method_type = 0;
278   static const GEnumValue rtsp_nat_method[] = {
279     {GST_RTSP_NAT_NONE, "None", "none"},
280     {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
281     {0, NULL, NULL},
282   };
283
284   if (!rtsp_nat_method_type) {
285     rtsp_nat_method_type =
286         g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
287   }
288   return rtsp_nat_method_type;
289 }
290
291 static void gst_rtspsrc_finalize (GObject * object);
292
293 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
294     const GValue * value, GParamSpec * pspec);
295 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
296     GValue * value, GParamSpec * pspec);
297
298 static GstClock *gst_rtspsrc_provide_clock (GstElement * element);
299
300 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
301     gpointer iface_data);
302
303 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
304 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
305
306 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
307     GstStateChange transition);
308 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
309 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
310
311 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
312     GstRTSPMessage * response);
313
314 static gboolean gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd,
315     gint mask);
316 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
317     GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
318
319 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
320 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
321     gboolean async);
322 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async);
323 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
324     gboolean only_close);
325
326 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
327     const gchar * uri, GError ** error);
328 static gchar *gst_rtspsrc_uri_get_uri (GstURIHandler * handler);
329
330 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
331 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
332 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
333     GstRTSPStream * stream, GstEvent * event);
334 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
335 static void gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush);
336 static GstRTSPResult gst_rtsp_conninfo_close (GstRTSPSrc * src,
337     GstRTSPConnInfo * info, gboolean free);
338
339 typedef struct
340 {
341   guint8 pt;
342   GstCaps *caps;
343 } PtMapItem;
344
345 /* commands we send to out loop to notify it of events */
346 #define CMD_OPEN        (1 << 0)
347 #define CMD_PLAY        (1 << 1)
348 #define CMD_PAUSE       (1 << 2)
349 #define CMD_CLOSE       (1 << 3)
350 #define CMD_WAIT        (1 << 4)
351 #define CMD_RECONNECT   (1 << 5)
352 #define CMD_LOOP        (1 << 6)
353
354 /* mask for all commands */
355 #define CMD_ALL         ((CMD_LOOP << 1) - 1)
356
357 #define GST_ELEMENT_PROGRESS(el, type, code, text)      \
358 G_STMT_START {                                          \
359   gchar *__txt = _gst_element_error_printf text;        \
360   gst_element_post_message (GST_ELEMENT_CAST (el),      \
361       gst_message_new_progress (GST_OBJECT_CAST (el),   \
362           GST_PROGRESS_TYPE_ ##type, code, __txt));     \
363   g_free (__txt);                                       \
364 } G_STMT_END
365
366 static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 };
367
368 #define gst_rtspsrc_parent_class parent_class
369 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
370     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
371
372 #ifndef GST_DISABLE_GST_DEBUG
373 static inline const char *
374 cmd_to_string (guint cmd)
375 {
376   switch (cmd) {
377     case CMD_OPEN:
378       return "OPEN";
379     case CMD_PLAY:
380       return "PLAY";
381     case CMD_PAUSE:
382       return "PAUSE";
383     case CMD_CLOSE:
384       return "CLOSE";
385     case CMD_WAIT:
386       return "WAIT";
387     case CMD_RECONNECT:
388       return "RECONNECT";
389     case CMD_LOOP:
390       return "LOOP";
391   }
392
393   return "unknown";
394 }
395 #endif
396
397 static gboolean
398 default_select_stream (GstRTSPSrc * src, guint id, GstCaps * caps)
399 {
400   GST_DEBUG_OBJECT (src, "default handler");
401   return TRUE;
402 }
403
404 static gboolean
405 select_stream_accum (GSignalInvocationHint * ihint,
406     GValue * return_accu, const GValue * handler_return, gpointer data)
407 {
408   gboolean myboolean;
409
410   myboolean = g_value_get_boolean (handler_return);
411   GST_DEBUG ("accum %d", myboolean);
412   g_value_set_boolean (return_accu, myboolean);
413
414   /* stop emission if FALSE */
415   return myboolean;
416 }
417
418 static void
419 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
420 {
421   GObjectClass *gobject_class;
422   GstElementClass *gstelement_class;
423   GstBinClass *gstbin_class;
424
425   gobject_class = (GObjectClass *) klass;
426   gstelement_class = (GstElementClass *) klass;
427   gstbin_class = (GstBinClass *) klass;
428
429   GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
430
431   gobject_class->set_property = gst_rtspsrc_set_property;
432   gobject_class->get_property = gst_rtspsrc_get_property;
433
434   gobject_class->finalize = gst_rtspsrc_finalize;
435
436   g_object_class_install_property (gobject_class, PROP_LOCATION,
437       g_param_spec_string ("location", "RTSP Location",
438           "Location of the RTSP url to read",
439           DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
440
441   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
442       g_param_spec_flags ("protocols", "Protocols",
443           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
444           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
445
446   g_object_class_install_property (gobject_class, PROP_DEBUG,
447       g_param_spec_boolean ("debug", "Debug",
448           "Dump request and response messages to stdout",
449           DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
450
451   g_object_class_install_property (gobject_class, PROP_RETRY,
452       g_param_spec_uint ("retry", "Retry",
453           "Max number of retries when allocating RTP ports.",
454           0, G_MAXUINT16, DEFAULT_RETRY,
455           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
456
457   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
458       g_param_spec_uint64 ("timeout", "Timeout",
459           "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
460           0, G_MAXUINT64, DEFAULT_TIMEOUT,
461           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
462
463   g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
464       g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
465           "Fail after timeout microseconds on TCP connections (0 = disabled)",
466           0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
467           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
468
469   g_object_class_install_property (gobject_class, PROP_LATENCY,
470       g_param_spec_uint ("latency", "Buffer latency in ms",
471           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
472           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
473
474   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
475       g_param_spec_boolean ("drop-on-latency",
476           "Drop buffers when maximum latency is reached",
477           "Tells the jitterbuffer to never exceed the given latency in size",
478           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
479
480   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
481       g_param_spec_uint64 ("connection-speed", "Connection Speed",
482           "Network connection speed in kbps (0 = unknown)",
483           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
484           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
485
486   g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
487       g_param_spec_enum ("nat-method", "NAT Method",
488           "Method to use for traversing firewalls and NAT",
489           GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
490           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
491
492   /**
493    * GstRTSPSrc:do-rtcp:
494    *
495    * Enable RTCP support. Some old server don't like RTCP and then this property
496    * needs to be set to FALSE.
497    */
498   g_object_class_install_property (gobject_class, PROP_DO_RTCP,
499       g_param_spec_boolean ("do-rtcp", "Do RTCP",
500           "Send RTCP packets, disable for old incompatible server.",
501           DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
502
503   /**
504    * GstRTSPSrc:do-rtsp-keep-alive:
505    *
506    * Enable RTSP keep alive support. Some old server don't like RTSP
507    * keep alive and then this property needs to be set to FALSE.
508    */
509   g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
510       g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
511           "Send RTSP keep alive packets, disable for old incompatible server.",
512           DEFAULT_DO_RTSP_KEEP_ALIVE,
513           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
514
515   /**
516    * GstRTSPSrc:proxy:
517    *
518    * Set the proxy parameters. This has to be a string of the format
519    * [http://][user:passwd@]host[:port].
520    */
521   g_object_class_install_property (gobject_class, PROP_PROXY,
522       g_param_spec_string ("proxy", "Proxy",
523           "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
524           DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
525   /**
526    * GstRTSPSrc:proxy-id:
527    *
528    * Sets the proxy URI user id for authentication. If the URI set via the
529    * "proxy" property contains a user-id already, that will take precedence.
530    *
531    * Since: 1.2
532    */
533   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
534       g_param_spec_string ("proxy-id", "proxy-id",
535           "HTTP proxy URI user id for authentication", "",
536           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
537   /**
538    * GstRTSPSrc:proxy-pw:
539    *
540    * Sets the proxy URI password for authentication. If the URI set via the
541    * "proxy" property contains a password already, that will take precedence.
542    *
543    * Since: 1.2
544    */
545   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
546       g_param_spec_string ("proxy-pw", "proxy-pw",
547           "HTTP proxy URI user password for authentication", "",
548           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
549
550   /**
551    * GstRTSPSrc:rtp-blocksize:
552    *
553    * RTP package size to suggest to server.
554    */
555   g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
556       g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
557           "RTP package size to suggest to server (0 = disabled)",
558           0, 65536, DEFAULT_RTP_BLOCKSIZE,
559           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
560
561   g_object_class_install_property (gobject_class,
562       PROP_USER_ID,
563       g_param_spec_string ("user-id", "user-id",
564           "RTSP location URI user id for authentication", DEFAULT_USER_ID,
565           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
566   g_object_class_install_property (gobject_class, PROP_USER_PW,
567       g_param_spec_string ("user-pw", "user-pw",
568           "RTSP location URI user password for authentication", DEFAULT_USER_PW,
569           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
570
571   /**
572    * GstRTSPSrc:buffer-mode:
573    *
574    * Control the buffering and timestamping mode used by the jitterbuffer.
575    */
576   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
577       g_param_spec_enum ("buffer-mode", "Buffer Mode",
578           "Control the buffering algorithm in use",
579           GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
580           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
581
582   /**
583    * GstRTSPSrc:port-range:
584    *
585    * Configure the client port numbers that can be used to recieve RTP and
586    * RTCP.
587    */
588   g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
589       g_param_spec_string ("port-range", "Port range",
590           "Client port range that can be used to receive RTP and RTCP data, "
591           "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
592           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
593
594   /**
595    * GstRTSPSrc:udp-buffer-size:
596    *
597    * Size of the kernel UDP receive buffer in bytes.
598    */
599   g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
600       g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
601           "Size of the kernel UDP receive buffer in bytes, 0=default",
602           0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
603           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
604
605   /**
606    * GstRTSPSrc:short-header:
607    *
608    * Only send the basic RTSP headers for broken encoders.
609    */
610   g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
611       g_param_spec_boolean ("short-header", "Short Header",
612           "Only send the basic RTSP headers for broken encoders",
613           DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
614
615   g_object_class_install_property (gobject_class, PROP_PROBATION,
616       g_param_spec_uint ("probation", "Number of probations",
617           "Consecutive packet sequence numbers to accept the source",
618           0, G_MAXUINT, DEFAULT_PROBATION,
619           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
620
621   g_object_class_install_property (gobject_class, PROP_UDP_RECONNECT,
622       g_param_spec_boolean ("udp-reconnect", "Reconnect to the server",
623           "Reconnect to the server if RTSP connection is closed when doing UDP",
624           DEFAULT_UDP_RECONNECT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
625
626   g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
627       g_param_spec_string ("multicast-iface", "Multicast Interface",
628           "The network interface on which to join the multicast group",
629           DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
630
631   g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
632       g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
633           "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
634           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
635
636   g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
637       g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
638           "Use the pipeline running-time to set the NTP time in the RTCP SR messages"
639           "(DEPRECATED: Use ntp-time-source property)",
640           DEFAULT_USE_PIPELINE_CLOCK,
641           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED));
642
643   g_object_class_install_property (gobject_class, PROP_SDES,
644       g_param_spec_boxed ("sdes", "SDES",
645           "The SDES items of this session",
646           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
647
648   /**
649    * GstRTSPSrc::tls-validation-flags:
650    *
651    * TLS certificate validation flags used to validate server
652    * certificate.
653    *
654    * Since: 1.2.1
655    */
656   g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
657       g_param_spec_flags ("tls-validation-flags", "TLS validation flags",
658           "TLS certificate validation flags used to validate the server certificate",
659           G_TYPE_TLS_CERTIFICATE_FLAGS, DEFAULT_TLS_VALIDATION_FLAGS,
660           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
661
662   /**
663    * GstRTSPSrc::tls-database:
664    *
665    * TLS database with anchor certificate authorities used to validate
666    * the server certificate.
667    *
668    * Since: 1.4
669    */
670   g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
671       g_param_spec_object ("tls-database", "TLS database",
672           "TLS database with anchor certificate authorities used to validate the server certificate",
673           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
674
675   /**
676    * GstRTSPSrc::tls-interaction:
677    *
678    * A #GTlsInteraction object to be used when the connection or certificate
679    * database need to interact with the user. This will be used to prompt the
680    * user for passwords where necessary.
681    *
682    * Since: 1.6
683    */
684   g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
685       g_param_spec_object ("tls-interaction", "TLS interaction",
686           "A GTlsInteraction object to promt the user for password or certificate",
687           G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
688
689   /**
690    * GstRTSPSrc::do-retransmission:
691    *
692    * Attempt to ask the server to retransmit lost packets according to RFC4588.
693    *
694    * Note: currently only works with SSRC-multiplexed retransmission streams
695    *
696    * Since: 1.6
697    */
698   g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
699       g_param_spec_boolean ("do-retransmission", "Retransmission",
700           "Ask the server to retransmit lost packets",
701           DEFAULT_DO_RETRANSMISSION,
702           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
703
704   /**
705    * GstRTSPSrc::ntp-time-source:
706    *
707    * allows to select the time source that should be used
708    * for the NTP time in RTCP packets
709    *
710    * Since: 1.6
711    */
712   g_object_class_install_property (gobject_class, PROP_NTP_TIME_SOURCE,
713       g_param_spec_enum ("ntp-time-source", "NTP Time Source",
714           "NTP time source for RTCP packets",
715           GST_TYPE_RTSP_SRC_NTP_TIME_SOURCE, DEFAULT_NTP_TIME_SOURCE,
716           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
717
718   /**
719    * GstRTSPSrc::user-agent:
720    *
721    * The string to set in the User-Agent header.
722    *
723    * Since: 1.6
724    */
725   g_object_class_install_property (gobject_class, PROP_USER_AGENT,
726       g_param_spec_string ("user-agent", "User Agent",
727           "The User-Agent string to send to the server",
728           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
729
730   g_object_class_install_property (gobject_class, PROP_MAX_RTCP_RTP_TIME_DIFF,
731       g_param_spec_int ("max-rtcp-rtp-time-diff", "Max RTCP RTP Time Diff",
732           "Maximum amount of time in ms that the RTP time in RTCP SRs "
733           "is allowed to be ahead (-1 disabled)", -1, G_MAXINT,
734           DEFAULT_MAX_RTCP_RTP_TIME_DIFF,
735           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
736
737   g_object_class_install_property (gobject_class, PROP_RFC7273_SYNC,
738       g_param_spec_boolean ("rfc7273-sync", "Sync on RFC7273 clock",
739           "Synchronize received streams to the RFC7273 clock "
740           "(requires clock and offset to be provided)", DEFAULT_RFC7273_SYNC,
741           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
742
743   /**
744    * GstRTSPSrc::handle-request:
745    * @rtspsrc: a #GstRTSPSrc
746    * @request: a #GstRTSPMessage
747    * @response: a #GstRTSPMessage
748    *
749    * Handle a server request in @request and prepare @response.
750    *
751    * This signal is called from the streaming thread, you should therefore not
752    * do any state changes on @rtspsrc because this might deadlock. If you want
753    * to modify the state as a result of this signal, post a
754    * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
755    * in some other way.
756    *
757    * Since: 1.2
758    */
759   gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST] =
760       g_signal_new ("handle-request", G_TYPE_FROM_CLASS (klass), 0,
761       0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
762       G_TYPE_POINTER, G_TYPE_POINTER);
763
764   /**
765    * GstRTSPSrc::on-sdp:
766    * @rtspsrc: a #GstRTSPSrc
767    * @sdp: a #GstSDPMessage
768    *
769    * Emited when the client has retrieved the SDP and before it configures the
770    * streams in the SDP. @sdp can be inspected and modified.
771    *
772    * This signal is called from the streaming thread, you should therefore not
773    * do any state changes on @rtspsrc because this might deadlock. If you want
774    * to modify the state as a result of this signal, post a
775    * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
776    * in some other way.
777    *
778    * Since: 1.2
779    */
780   gst_rtspsrc_signals[SIGNAL_ON_SDP] =
781       g_signal_new ("on-sdp", G_TYPE_FROM_CLASS (klass), 0,
782       0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
783       GST_TYPE_SDP_MESSAGE | G_SIGNAL_TYPE_STATIC_SCOPE);
784
785   /**
786    * GstRTSPSrc::select-stream:
787    * @rtspsrc: a #GstRTSPSrc
788    * @num: the stream number
789    * @caps: the stream caps
790    *
791    * Emited before the client decides to configure the stream @num with
792    * @caps.
793    *
794    * Returns: %TRUE when the stream should be selected, %FALSE when the stream
795    * is to be ignored.
796    *
797    * Since: 1.2
798    */
799   gst_rtspsrc_signals[SIGNAL_SELECT_STREAM] =
800       g_signal_new_class_handler ("select-stream", G_TYPE_FROM_CLASS (klass),
801       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP,
802       (GCallback) default_select_stream, select_stream_accum, NULL,
803       g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_UINT,
804       GST_TYPE_CAPS);
805   /**
806    * GstRTSPSrc::new-manager:
807    * @rtspsrc: a #GstRTSPSrc
808    * @manager: a #GstElement
809    *
810    * Emited after a new manager (like rtpbin) was created and the default
811    * properties were configured.
812    *
813    * Since: 1.4
814    */
815   gst_rtspsrc_signals[SIGNAL_NEW_MANAGER] =
816       g_signal_new_class_handler ("new-manager", G_TYPE_FROM_CLASS (klass),
817       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP, 0, NULL, NULL,
818       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
819
820   /**
821    * GstRTSPSrc::request-rtcp-key:
822    * @rtspsrc: a #GstRTSPSrc
823    * @num: the stream number
824    *
825    * Signal emited to get the crypto parameters relevant to the RTCP
826    * stream. User should provide the key and the RTCP encryption ciphers
827    * and authentication, and return them wrapped in a GstCaps.
828    *
829    * Since: 1.4
830    */
831   gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY] =
832       g_signal_new ("request-rtcp-key", G_TYPE_FROM_CLASS (klass),
833       G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, GST_TYPE_CAPS, 1, G_TYPE_UINT);
834
835   gstelement_class->send_event = gst_rtspsrc_send_event;
836   gstelement_class->provide_clock = gst_rtspsrc_provide_clock;
837   gstelement_class->change_state = gst_rtspsrc_change_state;
838
839   gst_element_class_add_static_pad_template (gstelement_class, &rtptemplate);
840
841   gst_element_class_set_static_metadata (gstelement_class,
842       "RTSP packet receiver", "Source/Network",
843       "Receive data over the network via RTSP (RFC 2326)",
844       "Wim Taymans <wim@fluendo.com>, "
845       "Thijs Vermeir <thijs.vermeir@barco.com>, "
846       "Lutz Mueller <lutz@topfrose.de>");
847
848   gstbin_class->handle_message = gst_rtspsrc_handle_message;
849
850   gst_rtsp_ext_list_init ();
851 }
852
853 static void
854 gst_rtspsrc_init (GstRTSPSrc * src)
855 {
856   src->conninfo.location = g_strdup (DEFAULT_LOCATION);
857   src->protocols = DEFAULT_PROTOCOLS;
858   src->debug = DEFAULT_DEBUG;
859   src->retry = DEFAULT_RETRY;
860   src->udp_timeout = DEFAULT_TIMEOUT;
861   gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
862   src->latency = DEFAULT_LATENCY_MS;
863   src->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
864   src->connection_speed = DEFAULT_CONNECTION_SPEED;
865   src->nat_method = DEFAULT_NAT_METHOD;
866   src->do_rtcp = DEFAULT_DO_RTCP;
867   src->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
868   gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
869   src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
870   src->user_id = g_strdup (DEFAULT_USER_ID);
871   src->user_pw = g_strdup (DEFAULT_USER_PW);
872   src->buffer_mode = DEFAULT_BUFFER_MODE;
873   src->client_port_range.min = 0;
874   src->client_port_range.max = 0;
875   src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
876   src->short_header = DEFAULT_SHORT_HEADER;
877   src->probation = DEFAULT_PROBATION;
878   src->udp_reconnect = DEFAULT_UDP_RECONNECT;
879   src->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
880   src->ntp_sync = DEFAULT_NTP_SYNC;
881   src->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
882   src->sdes = NULL;
883   src->tls_validation_flags = DEFAULT_TLS_VALIDATION_FLAGS;
884   src->tls_database = DEFAULT_TLS_DATABASE;
885   src->tls_interaction = DEFAULT_TLS_INTERACTION;
886   src->do_retransmission = DEFAULT_DO_RETRANSMISSION;
887   src->ntp_time_source = DEFAULT_NTP_TIME_SOURCE;
888   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
889   src->max_rtcp_rtp_time_diff = DEFAULT_MAX_RTCP_RTP_TIME_DIFF;
890   src->rfc7273_sync = DEFAULT_RFC7273_SYNC;
891
892   /* get a list of all extensions */
893   src->extensions = gst_rtsp_ext_list_get ();
894
895   /* connect to send signal */
896   gst_rtsp_ext_list_connect (src->extensions, "send",
897       (GCallback) gst_rtspsrc_send_cb, src);
898
899   /* protects the streaming thread in interleaved mode or the polling
900    * thread in UDP mode. */
901   g_rec_mutex_init (&src->stream_rec_lock);
902
903   /* protects our state changes from multiple invocations */
904   g_rec_mutex_init (&src->state_rec_lock);
905
906   src->state = GST_RTSP_STATE_INVALID;
907
908   GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
909 }
910
911 static void
912 gst_rtspsrc_finalize (GObject * object)
913 {
914   GstRTSPSrc *rtspsrc;
915
916   rtspsrc = GST_RTSPSRC (object);
917
918   gst_rtsp_ext_list_free (rtspsrc->extensions);
919   g_free (rtspsrc->conninfo.location);
920   gst_rtsp_url_free (rtspsrc->conninfo.url);
921   g_free (rtspsrc->conninfo.url_str);
922   g_free (rtspsrc->user_id);
923   g_free (rtspsrc->user_pw);
924   g_free (rtspsrc->multi_iface);
925   g_free (rtspsrc->user_agent);
926
927   if (rtspsrc->sdp) {
928     gst_sdp_message_free (rtspsrc->sdp);
929     rtspsrc->sdp = NULL;
930   }
931   if (rtspsrc->provided_clock)
932     gst_object_unref (rtspsrc->provided_clock);
933
934   if (rtspsrc->sdes)
935     gst_structure_free (rtspsrc->sdes);
936
937   if (rtspsrc->tls_database)
938     g_object_unref (rtspsrc->tls_database);
939
940   if (rtspsrc->tls_interaction)
941     g_object_unref (rtspsrc->tls_interaction);
942
943   /* free locks */
944   g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
945   g_rec_mutex_clear (&rtspsrc->state_rec_lock);
946
947   G_OBJECT_CLASS (parent_class)->finalize (object);
948 }
949
950 static GstClock *
951 gst_rtspsrc_provide_clock (GstElement * element)
952 {
953   GstRTSPSrc *src = GST_RTSPSRC (element);
954   GstClock *clock;
955
956   if ((clock = src->provided_clock) != NULL)
957     gst_object_ref (clock);
958
959   return clock;
960 }
961
962 /* a proxy string of the format [user:passwd@]host[:port] */
963 static gboolean
964 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
965 {
966   gchar *p, *at, *col;
967
968   g_free (rtsp->proxy_user);
969   rtsp->proxy_user = NULL;
970   g_free (rtsp->proxy_passwd);
971   rtsp->proxy_passwd = NULL;
972   g_free (rtsp->proxy_host);
973   rtsp->proxy_host = NULL;
974   rtsp->proxy_port = 0;
975
976   p = (gchar *) proxy;
977
978   if (p == NULL)
979     return TRUE;
980
981   /* we allow http:// in front but ignore it */
982   if (g_str_has_prefix (p, "http://"))
983     p += 7;
984
985   at = strchr (p, '@');
986   if (at) {
987     /* look for user:passwd */
988     col = strchr (proxy, ':');
989     if (col == NULL || col > at)
990       return FALSE;
991
992     rtsp->proxy_user = g_strndup (p, col - p);
993     col++;
994     rtsp->proxy_passwd = g_strndup (col, at - col);
995
996     /* move to host */
997     p = at + 1;
998   } else {
999     if (rtsp->prop_proxy_id != NULL && *rtsp->prop_proxy_id != '\0')
1000       rtsp->proxy_user = g_strdup (rtsp->prop_proxy_id);
1001     if (rtsp->prop_proxy_pw != NULL && *rtsp->prop_proxy_pw != '\0')
1002       rtsp->proxy_passwd = g_strdup (rtsp->prop_proxy_pw);
1003     if (rtsp->proxy_user != NULL || rtsp->proxy_passwd != NULL) {
1004       GST_LOG_OBJECT (rtsp, "set proxy user/pw from properties: %s:%s",
1005           GST_STR_NULL (rtsp->proxy_user), GST_STR_NULL (rtsp->proxy_passwd));
1006     }
1007   }
1008   col = strchr (p, ':');
1009
1010   if (col) {
1011     /* everything before the colon is the hostname */
1012     rtsp->proxy_host = g_strndup (p, col - p);
1013     p = col + 1;
1014     rtsp->proxy_port = strtoul (p, (char **) &p, 10);
1015   } else {
1016     rtsp->proxy_host = g_strdup (p);
1017     rtsp->proxy_port = 8080;
1018   }
1019   return TRUE;
1020 }
1021
1022 static void
1023 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
1024 {
1025   rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
1026   rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
1027
1028   if (timeout != 0)
1029     rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
1030   else
1031     rtspsrc->ptcp_timeout = NULL;
1032 }
1033
1034 static void
1035 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
1036     GParamSpec * pspec)
1037 {
1038   GstRTSPSrc *rtspsrc;
1039
1040   rtspsrc = GST_RTSPSRC (object);
1041
1042   switch (prop_id) {
1043     case PROP_LOCATION:
1044       gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
1045           g_value_get_string (value), NULL);
1046       break;
1047     case PROP_PROTOCOLS:
1048       rtspsrc->protocols = g_value_get_flags (value);
1049       break;
1050     case PROP_DEBUG:
1051       rtspsrc->debug = g_value_get_boolean (value);
1052       break;
1053     case PROP_RETRY:
1054       rtspsrc->retry = g_value_get_uint (value);
1055       break;
1056     case PROP_TIMEOUT:
1057       rtspsrc->udp_timeout = g_value_get_uint64 (value);
1058       break;
1059     case PROP_TCP_TIMEOUT:
1060       gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
1061       break;
1062     case PROP_LATENCY:
1063       rtspsrc->latency = g_value_get_uint (value);
1064       break;
1065     case PROP_DROP_ON_LATENCY:
1066       rtspsrc->drop_on_latency = g_value_get_boolean (value);
1067       break;
1068     case PROP_CONNECTION_SPEED:
1069       rtspsrc->connection_speed = g_value_get_uint64 (value);
1070       break;
1071     case PROP_NAT_METHOD:
1072       rtspsrc->nat_method = g_value_get_enum (value);
1073       break;
1074     case PROP_DO_RTCP:
1075       rtspsrc->do_rtcp = g_value_get_boolean (value);
1076       break;
1077     case PROP_DO_RTSP_KEEP_ALIVE:
1078       rtspsrc->do_rtsp_keep_alive = g_value_get_boolean (value);
1079       break;
1080     case PROP_PROXY:
1081       gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
1082       break;
1083     case PROP_PROXY_ID:
1084       g_free (rtspsrc->prop_proxy_id);
1085       rtspsrc->prop_proxy_id = g_value_dup_string (value);
1086       break;
1087     case PROP_PROXY_PW:
1088       g_free (rtspsrc->prop_proxy_pw);
1089       rtspsrc->prop_proxy_pw = g_value_dup_string (value);
1090       break;
1091     case PROP_RTP_BLOCKSIZE:
1092       rtspsrc->rtp_blocksize = g_value_get_uint (value);
1093       break;
1094     case PROP_USER_ID:
1095       g_free (rtspsrc->user_id);
1096       rtspsrc->user_id = g_value_dup_string (value);
1097       break;
1098     case PROP_USER_PW:
1099       g_free (rtspsrc->user_pw);
1100       rtspsrc->user_pw = g_value_dup_string (value);
1101       break;
1102     case PROP_BUFFER_MODE:
1103       rtspsrc->buffer_mode = g_value_get_enum (value);
1104       break;
1105     case PROP_PORT_RANGE:
1106     {
1107       const gchar *str;
1108
1109       str = g_value_get_string (value);
1110       if (sscanf (str, "%u-%u", &rtspsrc->client_port_range.min,
1111               &rtspsrc->client_port_range.max) != 2) {
1112         rtspsrc->client_port_range.min = 0;
1113         rtspsrc->client_port_range.max = 0;
1114       }
1115       break;
1116     }
1117     case PROP_UDP_BUFFER_SIZE:
1118       rtspsrc->udp_buffer_size = g_value_get_int (value);
1119       break;
1120     case PROP_SHORT_HEADER:
1121       rtspsrc->short_header = g_value_get_boolean (value);
1122       break;
1123     case PROP_PROBATION:
1124       rtspsrc->probation = g_value_get_uint (value);
1125       break;
1126     case PROP_UDP_RECONNECT:
1127       rtspsrc->udp_reconnect = g_value_get_boolean (value);
1128       break;
1129     case PROP_MULTICAST_IFACE:
1130       g_free (rtspsrc->multi_iface);
1131
1132       if (g_value_get_string (value) == NULL)
1133         rtspsrc->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
1134       else
1135         rtspsrc->multi_iface = g_value_dup_string (value);
1136       break;
1137     case PROP_NTP_SYNC:
1138       rtspsrc->ntp_sync = g_value_get_boolean (value);
1139       break;
1140     case PROP_USE_PIPELINE_CLOCK:
1141       rtspsrc->use_pipeline_clock = g_value_get_boolean (value);
1142       break;
1143     case PROP_SDES:
1144       rtspsrc->sdes = g_value_dup_boxed (value);
1145       break;
1146     case PROP_TLS_VALIDATION_FLAGS:
1147       rtspsrc->tls_validation_flags = g_value_get_flags (value);
1148       break;
1149     case PROP_TLS_DATABASE:
1150       g_clear_object (&rtspsrc->tls_database);
1151       rtspsrc->tls_database = g_value_dup_object (value);
1152       break;
1153     case PROP_TLS_INTERACTION:
1154       g_clear_object (&rtspsrc->tls_interaction);
1155       rtspsrc->tls_interaction = g_value_dup_object (value);
1156       break;
1157     case PROP_DO_RETRANSMISSION:
1158       rtspsrc->do_retransmission = g_value_get_boolean (value);
1159       break;
1160     case PROP_NTP_TIME_SOURCE:
1161       rtspsrc->ntp_time_source = g_value_get_enum (value);
1162       break;
1163     case PROP_USER_AGENT:
1164       g_free (rtspsrc->user_agent);
1165       rtspsrc->user_agent = g_value_dup_string (value);
1166       break;
1167     case PROP_MAX_RTCP_RTP_TIME_DIFF:
1168       rtspsrc->max_rtcp_rtp_time_diff = g_value_get_int (value);
1169       break;
1170     case PROP_RFC7273_SYNC:
1171       rtspsrc->rfc7273_sync = g_value_get_boolean (value);
1172       break;
1173     default:
1174       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1175       break;
1176   }
1177 }
1178
1179 static void
1180 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
1181     GParamSpec * pspec)
1182 {
1183   GstRTSPSrc *rtspsrc;
1184
1185   rtspsrc = GST_RTSPSRC (object);
1186
1187   switch (prop_id) {
1188     case PROP_LOCATION:
1189       g_value_set_string (value, rtspsrc->conninfo.location);
1190       break;
1191     case PROP_PROTOCOLS:
1192       g_value_set_flags (value, rtspsrc->protocols);
1193       break;
1194     case PROP_DEBUG:
1195       g_value_set_boolean (value, rtspsrc->debug);
1196       break;
1197     case PROP_RETRY:
1198       g_value_set_uint (value, rtspsrc->retry);
1199       break;
1200     case PROP_TIMEOUT:
1201       g_value_set_uint64 (value, rtspsrc->udp_timeout);
1202       break;
1203     case PROP_TCP_TIMEOUT:
1204     {
1205       guint64 timeout;
1206
1207       timeout = ((guint64) rtspsrc->tcp_timeout.tv_sec) * G_USEC_PER_SEC +
1208           rtspsrc->tcp_timeout.tv_usec;
1209       g_value_set_uint64 (value, timeout);
1210       break;
1211     }
1212     case PROP_LATENCY:
1213       g_value_set_uint (value, rtspsrc->latency);
1214       break;
1215     case PROP_DROP_ON_LATENCY:
1216       g_value_set_boolean (value, rtspsrc->drop_on_latency);
1217       break;
1218     case PROP_CONNECTION_SPEED:
1219       g_value_set_uint64 (value, rtspsrc->connection_speed);
1220       break;
1221     case PROP_NAT_METHOD:
1222       g_value_set_enum (value, rtspsrc->nat_method);
1223       break;
1224     case PROP_DO_RTCP:
1225       g_value_set_boolean (value, rtspsrc->do_rtcp);
1226       break;
1227     case PROP_DO_RTSP_KEEP_ALIVE:
1228       g_value_set_boolean (value, rtspsrc->do_rtsp_keep_alive);
1229       break;
1230     case PROP_PROXY:
1231     {
1232       gchar *str;
1233
1234       if (rtspsrc->proxy_host) {
1235         str =
1236             g_strdup_printf ("%s:%d", rtspsrc->proxy_host, rtspsrc->proxy_port);
1237       } else {
1238         str = NULL;
1239       }
1240       g_value_take_string (value, str);
1241       break;
1242     }
1243     case PROP_PROXY_ID:
1244       g_value_set_string (value, rtspsrc->prop_proxy_id);
1245       break;
1246     case PROP_PROXY_PW:
1247       g_value_set_string (value, rtspsrc->prop_proxy_pw);
1248       break;
1249     case PROP_RTP_BLOCKSIZE:
1250       g_value_set_uint (value, rtspsrc->rtp_blocksize);
1251       break;
1252     case PROP_USER_ID:
1253       g_value_set_string (value, rtspsrc->user_id);
1254       break;
1255     case PROP_USER_PW:
1256       g_value_set_string (value, rtspsrc->user_pw);
1257       break;
1258     case PROP_BUFFER_MODE:
1259       g_value_set_enum (value, rtspsrc->buffer_mode);
1260       break;
1261     case PROP_PORT_RANGE:
1262     {
1263       gchar *str;
1264
1265       if (rtspsrc->client_port_range.min != 0) {
1266         str = g_strdup_printf ("%u-%u", rtspsrc->client_port_range.min,
1267             rtspsrc->client_port_range.max);
1268       } else {
1269         str = NULL;
1270       }
1271       g_value_take_string (value, str);
1272       break;
1273     }
1274     case PROP_UDP_BUFFER_SIZE:
1275       g_value_set_int (value, rtspsrc->udp_buffer_size);
1276       break;
1277     case PROP_SHORT_HEADER:
1278       g_value_set_boolean (value, rtspsrc->short_header);
1279       break;
1280     case PROP_PROBATION:
1281       g_value_set_uint (value, rtspsrc->probation);
1282       break;
1283     case PROP_UDP_RECONNECT:
1284       g_value_set_boolean (value, rtspsrc->udp_reconnect);
1285       break;
1286     case PROP_MULTICAST_IFACE:
1287       g_value_set_string (value, rtspsrc->multi_iface);
1288       break;
1289     case PROP_NTP_SYNC:
1290       g_value_set_boolean (value, rtspsrc->ntp_sync);
1291       break;
1292     case PROP_USE_PIPELINE_CLOCK:
1293       g_value_set_boolean (value, rtspsrc->use_pipeline_clock);
1294       break;
1295     case PROP_SDES:
1296       g_value_set_boxed (value, rtspsrc->sdes);
1297       break;
1298     case PROP_TLS_VALIDATION_FLAGS:
1299       g_value_set_flags (value, rtspsrc->tls_validation_flags);
1300       break;
1301     case PROP_TLS_DATABASE:
1302       g_value_set_object (value, rtspsrc->tls_database);
1303       break;
1304     case PROP_TLS_INTERACTION:
1305       g_value_set_object (value, rtspsrc->tls_interaction);
1306       break;
1307     case PROP_DO_RETRANSMISSION:
1308       g_value_set_boolean (value, rtspsrc->do_retransmission);
1309       break;
1310     case PROP_NTP_TIME_SOURCE:
1311       g_value_set_enum (value, rtspsrc->ntp_time_source);
1312       break;
1313     case PROP_USER_AGENT:
1314       g_value_set_string (value, rtspsrc->user_agent);
1315       break;
1316     case PROP_MAX_RTCP_RTP_TIME_DIFF:
1317       g_value_set_int (value, rtspsrc->max_rtcp_rtp_time_diff);
1318       break;
1319     case PROP_RFC7273_SYNC:
1320       g_value_set_boolean (value, rtspsrc->rfc7273_sync);
1321       break;
1322     default:
1323       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1324       break;
1325   }
1326 }
1327
1328 static gint
1329 find_stream_by_id (GstRTSPStream * stream, gint * id)
1330 {
1331   if (stream->id == *id)
1332     return 0;
1333
1334   return -1;
1335 }
1336
1337 static gint
1338 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
1339 {
1340   if (stream->channel[0] == *channel || stream->channel[1] == *channel)
1341     return 0;
1342
1343   return -1;
1344 }
1345
1346 static gint
1347 find_stream_by_udpsrc (GstRTSPStream * stream, gconstpointer a)
1348 {
1349   GstElement *src = (GstElement *) a;
1350
1351   if (stream->udpsrc[0] == src)
1352     return 0;
1353   if (stream->udpsrc[1] == src)
1354     return 0;
1355
1356   return -1;
1357 }
1358
1359 static gint
1360 find_stream_by_setup (GstRTSPStream * stream, gconstpointer a)
1361 {
1362   if (stream->conninfo.location) {
1363     /* check qualified setup_url */
1364     if (!strcmp (stream->conninfo.location, (gchar *) a))
1365       return 0;
1366   }
1367   if (stream->control_url) {
1368     /* check original control_url */
1369     if (!strcmp (stream->control_url, (gchar *) a))
1370       return 0;
1371
1372     /* check if qualified setup_url ends with string */
1373     if (g_str_has_suffix (stream->control_url, (gchar *) a))
1374       return 0;
1375   }
1376
1377   return -1;
1378 }
1379
1380 static GstRTSPStream *
1381 find_stream (GstRTSPSrc * src, gconstpointer data, gconstpointer func)
1382 {
1383   GList *lstream;
1384
1385   /* find and get stream */
1386   if ((lstream = g_list_find_custom (src->streams, data, (GCompareFunc) func)))
1387     return (GstRTSPStream *) lstream->data;
1388
1389   return NULL;
1390 }
1391
1392 static const GstSDPBandwidth *
1393 gst_rtspsrc_get_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1394     const GstSDPMedia * media, const gchar * type)
1395 {
1396   guint i, len;
1397
1398   /* first look in the media specific section */
1399   len = gst_sdp_media_bandwidths_len (media);
1400   for (i = 0; i < len; i++) {
1401     const GstSDPBandwidth *bw = gst_sdp_media_get_bandwidth (media, i);
1402
1403     if (strcmp (bw->bwtype, type) == 0)
1404       return bw;
1405   }
1406   /* then look in the message specific section */
1407   len = gst_sdp_message_bandwidths_len (sdp);
1408   for (i = 0; i < len; i++) {
1409     const GstSDPBandwidth *bw = gst_sdp_message_get_bandwidth (sdp, i);
1410
1411     if (strcmp (bw->bwtype, type) == 0)
1412       return bw;
1413   }
1414   return NULL;
1415 }
1416
1417 static void
1418 gst_rtspsrc_collect_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
1419     const GstSDPMedia * media, GstRTSPStream * stream)
1420 {
1421   const GstSDPBandwidth *bw;
1422
1423   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_AS)))
1424     stream->as_bandwidth = bw->bandwidth;
1425   else
1426     stream->as_bandwidth = -1;
1427
1428   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RR)))
1429     stream->rr_bandwidth = bw->bandwidth;
1430   else
1431     stream->rr_bandwidth = -1;
1432
1433   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RS)))
1434     stream->rs_bandwidth = bw->bandwidth;
1435   else
1436     stream->rs_bandwidth = -1;
1437 }
1438
1439 static void
1440 gst_rtspsrc_do_stream_connection (GstRTSPSrc * src, GstRTSPStream * stream,
1441     const GstSDPConnection * conn)
1442 {
1443   if (conn->nettype == NULL || strcmp (conn->nettype, "IN") != 0)
1444     return;
1445
1446   if (conn->addrtype == NULL)
1447     return;
1448
1449   /* check for IPV6 */
1450   if (strcmp (conn->addrtype, "IP4") == 0)
1451     stream->is_ipv6 = FALSE;
1452   else if (strcmp (conn->addrtype, "IP6") == 0)
1453     stream->is_ipv6 = TRUE;
1454   else
1455     return;
1456
1457   /* save address */
1458   g_free (stream->destination);
1459   stream->destination = g_strdup (conn->address);
1460
1461   /* check for multicast */
1462   stream->is_multicast =
1463       gst_sdp_address_is_multicast (conn->nettype, conn->addrtype,
1464       conn->address);
1465   stream->ttl = conn->ttl;
1466 }
1467
1468 /* Go over the connections for a stream.
1469  * - If we are dealing with IPV6, we will setup IPV6 sockets for sending and
1470  *   receiving.
1471  * - If we are dealing with a localhost address, we disable multicast
1472  */
1473 static void
1474 gst_rtspsrc_collect_connections (GstRTSPSrc * src, const GstSDPMessage * sdp,
1475     const GstSDPMedia * media, GstRTSPStream * stream)
1476 {
1477   const GstSDPConnection *conn;
1478   guint i, len;
1479
1480   /* first look in the media specific section */
1481   len = gst_sdp_media_connections_len (media);
1482   for (i = 0; i < len; i++) {
1483     conn = gst_sdp_media_get_connection (media, i);
1484
1485     gst_rtspsrc_do_stream_connection (src, stream, conn);
1486   }
1487   /* then look in the message specific section */
1488   if ((conn = gst_sdp_message_get_connection (sdp))) {
1489     gst_rtspsrc_do_stream_connection (src, stream, conn);
1490   }
1491 }
1492
1493 /*   m=<media> <UDP port> RTP/AVP <payload>
1494  */
1495 static void
1496 gst_rtspsrc_collect_payloads (GstRTSPSrc * src, const GstSDPMessage * sdp,
1497     const GstSDPMedia * media, GstRTSPStream * stream)
1498 {
1499   guint i, len;
1500   const gchar *proto;
1501   GstCaps *global_caps;
1502
1503   /* get proto */
1504   proto = gst_sdp_media_get_proto (media);
1505   if (proto == NULL)
1506     goto no_proto;
1507
1508   if (g_str_equal (proto, "RTP/AVP"))
1509     stream->profile = GST_RTSP_PROFILE_AVP;
1510   else if (g_str_equal (proto, "RTP/SAVP"))
1511     stream->profile = GST_RTSP_PROFILE_SAVP;
1512   else if (g_str_equal (proto, "RTP/AVPF"))
1513     stream->profile = GST_RTSP_PROFILE_AVPF;
1514   else if (g_str_equal (proto, "RTP/SAVPF"))
1515     stream->profile = GST_RTSP_PROFILE_SAVPF;
1516   else
1517     goto unknown_proto;
1518
1519   /* Parse global SDP attributes once */
1520   global_caps = gst_caps_new_empty_simple ("application/x-unknown");
1521   GST_DEBUG ("mapping sdp session level attributes to caps");
1522   gst_sdp_message_attributes_to_caps (sdp, global_caps);
1523   GST_DEBUG ("mapping sdp media level attributes to caps");
1524   gst_sdp_media_attributes_to_caps (media, global_caps);
1525
1526   /* Keep a copy of the SDP key management */
1527   gst_sdp_media_parse_keymgmt (media, &stream->mikey);
1528   if (stream->mikey == NULL)
1529     gst_sdp_message_parse_keymgmt (sdp, &stream->mikey);
1530
1531   len = gst_sdp_media_formats_len (media);
1532   for (i = 0; i < len; i++) {
1533     gint pt;
1534     GstCaps *caps, *outcaps;
1535     GstStructure *s;
1536     const gchar *enc;
1537     PtMapItem item;
1538
1539     pt = atoi (gst_sdp_media_get_format (media, i));
1540
1541     GST_DEBUG_OBJECT (src, " looking at %d pt: %d", i, pt);
1542
1543     /* convert caps */
1544     caps = gst_sdp_media_get_caps_from_media (media, pt);
1545     if (caps == NULL) {
1546       GST_WARNING_OBJECT (src, " skipping pt %d without caps", pt);
1547       continue;
1548     }
1549
1550     /* do some tweaks */
1551     s = gst_caps_get_structure (caps, 0);
1552     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
1553       stream->is_real = (strstr (enc, "-REAL") != NULL);
1554       if (strcmp (enc, "X-ASF-PF") == 0)
1555         stream->container = TRUE;
1556     }
1557
1558     /* Merge in global caps */
1559     /* Intersect will merge in missing fields to the current caps */
1560     outcaps = gst_caps_intersect (caps, global_caps);
1561     gst_caps_unref (caps);
1562
1563     /* the first pt will be the default */
1564     if (stream->ptmap->len == 0)
1565       stream->default_pt = pt;
1566
1567     item.pt = pt;
1568     item.caps = outcaps;
1569
1570     g_array_append_val (stream->ptmap, item);
1571   }
1572
1573   gst_caps_unref (global_caps);
1574   return;
1575
1576 no_proto:
1577   {
1578     GST_ERROR_OBJECT (src, "can't find proto in media");
1579     return;
1580   }
1581 unknown_proto:
1582   {
1583     GST_ERROR_OBJECT (src, "unknown proto in media %s", proto);
1584     return;
1585   }
1586 }
1587
1588 static const gchar *
1589 get_aggregate_control (GstRTSPSrc * src)
1590 {
1591   const gchar *base;
1592
1593   if (src->control)
1594     base = src->control;
1595   else if (src->content_base)
1596     base = src->content_base;
1597   else if (src->conninfo.url_str)
1598     base = src->conninfo.url_str;
1599   else
1600     base = "/";
1601
1602   return base;
1603 }
1604
1605 static void
1606 clear_ptmap_item (PtMapItem * item)
1607 {
1608   if (item->caps)
1609     gst_caps_unref (item->caps);
1610 }
1611
1612 static GstRTSPStream *
1613 gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
1614 {
1615   GstRTSPStream *stream;
1616   const gchar *control_url;
1617   const GstSDPMedia *media;
1618
1619   /* get media, should not return NULL */
1620   media = gst_sdp_message_get_media (sdp, idx);
1621   if (media == NULL)
1622     return NULL;
1623
1624   stream = g_new0 (GstRTSPStream, 1);
1625   stream->parent = src;
1626   /* we mark the pad as not linked, we will mark it as OK when we add the pad to
1627    * the element. */
1628   stream->last_ret = GST_FLOW_NOT_LINKED;
1629   stream->added = FALSE;
1630   stream->setup = FALSE;
1631   stream->skipped = FALSE;
1632   stream->id = idx;
1633   stream->eos = FALSE;
1634   stream->discont = TRUE;
1635   stream->seqbase = -1;
1636   stream->timebase = -1;
1637   stream->send_ssrc = g_random_int ();
1638   stream->profile = GST_RTSP_PROFILE_AVP;
1639   stream->ptmap = g_array_new (FALSE, FALSE, sizeof (PtMapItem));
1640   stream->mikey = NULL;
1641   g_array_set_clear_func (stream->ptmap, (GDestroyNotify) clear_ptmap_item);
1642
1643   /* collect bandwidth information for this steam. FIXME, configure in the RTP
1644    * session manager to scale RTCP. */
1645   gst_rtspsrc_collect_bandwidth (src, sdp, media, stream);
1646
1647   /* collect connection info */
1648   gst_rtspsrc_collect_connections (src, sdp, media, stream);
1649
1650   /* make the payload type map */
1651   gst_rtspsrc_collect_payloads (src, sdp, media, stream);
1652
1653   /* collect port number */
1654   stream->port = gst_sdp_media_get_port (media);
1655
1656   /* get control url to construct the setup url. The setup url is used to
1657    * configure the transport of the stream and is used to identity the stream in
1658    * the RTP-Info header field returned from PLAY. */
1659   control_url = gst_sdp_media_get_attribute_val (media, "control");
1660   if (control_url == NULL)
1661     control_url = gst_sdp_message_get_attribute_val_n (sdp, "control", 0);
1662
1663   GST_DEBUG_OBJECT (src, "stream %d, (%p)", stream->id, stream);
1664   GST_DEBUG_OBJECT (src, " port: %d", stream->port);
1665   GST_DEBUG_OBJECT (src, " container: %d", stream->container);
1666   GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
1667
1668   if (control_url != NULL) {
1669     stream->control_url = g_strdup (control_url);
1670     /* Build a fully qualified url using the content_base if any or by prefixing
1671      * the original request.
1672      * If the control_url starts with a '/' or a non rtsp: protocol we will most
1673      * likely build a URL that the server will fail to understand, this is ok,
1674      * we will fail then. */
1675     if (g_str_has_prefix (control_url, "rtsp://"))
1676       stream->conninfo.location = g_strdup (control_url);
1677     else {
1678       const gchar *base;
1679       gboolean has_slash;
1680
1681       if (g_strcmp0 (control_url, "*") == 0)
1682         control_url = "";
1683
1684       base = get_aggregate_control (src);
1685
1686       /* check if the base ends or control starts with / */
1687       has_slash = g_str_has_prefix (control_url, "/");
1688       has_slash = has_slash || g_str_has_suffix (base, "/");
1689
1690       /* concatenate the two strings, insert / when not present */
1691       stream->conninfo.location =
1692           g_strdup_printf ("%s%s%s", base, has_slash ? "" : "/", control_url);
1693     }
1694   }
1695   GST_DEBUG_OBJECT (src, " setup: %s",
1696       GST_STR_NULL (stream->conninfo.location));
1697
1698   /* we keep track of all streams */
1699   src->streams = g_list_append (src->streams, stream);
1700
1701   return stream;
1702
1703   /* ERRORS */
1704 }
1705
1706 static void
1707 gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
1708 {
1709   gint i;
1710
1711   GST_DEBUG_OBJECT (src, "free stream %p", stream);
1712
1713   g_array_free (stream->ptmap, TRUE);
1714
1715   g_free (stream->destination);
1716   g_free (stream->control_url);
1717   g_free (stream->conninfo.location);
1718
1719   for (i = 0; i < 2; i++) {
1720     if (stream->udpsrc[i]) {
1721       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
1722       gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
1723       gst_object_unref (stream->udpsrc[i]);
1724     }
1725     if (stream->channelpad[i])
1726       gst_object_unref (stream->channelpad[i]);
1727
1728     if (stream->udpsink[i]) {
1729       gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
1730       gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
1731       gst_object_unref (stream->udpsink[i]);
1732     }
1733   }
1734   if (stream->fakesrc) {
1735     gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
1736     gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
1737     gst_object_unref (stream->fakesrc);
1738   }
1739   if (stream->srcpad) {
1740     gst_pad_set_active (stream->srcpad, FALSE);
1741     if (stream->added)
1742       gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
1743   }
1744   if (stream->srtpenc)
1745     gst_object_unref (stream->srtpenc);
1746   if (stream->srtpdec)
1747     gst_object_unref (stream->srtpdec);
1748   if (stream->srtcpparams)
1749     gst_caps_unref (stream->srtcpparams);
1750   if (stream->mikey)
1751     gst_mikey_message_unref (stream->mikey);
1752   if (stream->rtcppad)
1753     gst_object_unref (stream->rtcppad);
1754   if (stream->session)
1755     g_object_unref (stream->session);
1756   if (stream->rtx_pt_map)
1757     gst_structure_free (stream->rtx_pt_map);
1758   g_free (stream);
1759 }
1760
1761 static void
1762 gst_rtspsrc_cleanup (GstRTSPSrc * src)
1763 {
1764   GList *walk;
1765
1766   GST_DEBUG_OBJECT (src, "cleanup");
1767
1768   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1769     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1770
1771     gst_rtspsrc_stream_free (src, stream);
1772   }
1773   g_list_free (src->streams);
1774   src->streams = NULL;
1775   if (src->manager) {
1776     if (src->manager_sig_id) {
1777       g_signal_handler_disconnect (src->manager, src->manager_sig_id);
1778       src->manager_sig_id = 0;
1779     }
1780     gst_element_set_state (src->manager, GST_STATE_NULL);
1781     gst_bin_remove (GST_BIN_CAST (src), src->manager);
1782     src->manager = NULL;
1783   }
1784   if (src->props)
1785     gst_structure_free (src->props);
1786   src->props = NULL;
1787
1788   g_free (src->content_base);
1789   src->content_base = NULL;
1790
1791   g_free (src->control);
1792   src->control = NULL;
1793
1794   if (src->range)
1795     gst_rtsp_range_free (src->range);
1796   src->range = NULL;
1797
1798   /* don't clear the SDP when it was used in the url */
1799   if (src->sdp && !src->from_sdp) {
1800     gst_sdp_message_free (src->sdp);
1801     src->sdp = NULL;
1802   }
1803
1804   src->need_segment = FALSE;
1805
1806   if (src->provided_clock) {
1807     gst_object_unref (src->provided_clock);
1808     src->provided_clock = NULL;
1809   }
1810 }
1811
1812 static gboolean
1813 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
1814     gint * rtpport, gint * rtcpport)
1815 {
1816   GstRTSPSrc *src;
1817   GstStateChangeReturn ret;
1818   GstElement *udpsrc0, *udpsrc1;
1819   gint tmp_rtp, tmp_rtcp;
1820   guint count;
1821   const gchar *host;
1822
1823   src = stream->parent;
1824
1825   udpsrc0 = NULL;
1826   udpsrc1 = NULL;
1827   count = 0;
1828
1829   /* Start at next port */
1830   tmp_rtp = src->next_port_num;
1831
1832   if (stream->is_ipv6)
1833     host = "udp://[::0]";
1834   else
1835     host = "udp://0.0.0.0";
1836
1837   /* try to allocate 2 UDP ports, the RTP port should be an even
1838    * number and the RTCP port should be the next (uneven) port */
1839 again:
1840
1841   if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
1842       tmp_rtp >= src->client_port_range.max)
1843     goto no_ports;
1844
1845   udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
1846   if (udpsrc0 == NULL)
1847     goto no_udp_protocol;
1848   g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
1849
1850   if (src->udp_buffer_size != 0)
1851     g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
1852         NULL);
1853
1854   ret = gst_element_set_state (udpsrc0, GST_STATE_READY);
1855   if (ret == GST_STATE_CHANGE_FAILURE) {
1856     if (tmp_rtp != 0) {
1857       GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
1858
1859       tmp_rtp += 2;
1860       if (++count > src->retry)
1861         goto no_ports;
1862
1863       GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1864       gst_element_set_state (udpsrc0, GST_STATE_NULL);
1865       gst_object_unref (udpsrc0);
1866       udpsrc0 = NULL;
1867
1868       GST_DEBUG_OBJECT (src, "retry %d", count);
1869       goto again;
1870     }
1871     goto no_udp_protocol;
1872   }
1873
1874   g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
1875   GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
1876
1877   /* check if port is even */
1878   if ((tmp_rtp & 0x01) != 0) {
1879     /* port not even, close and allocate another */
1880     if (++count > src->retry)
1881       goto no_ports;
1882
1883     GST_DEBUG_OBJECT (src, "RTP port not even");
1884
1885     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1886     gst_element_set_state (udpsrc0, GST_STATE_NULL);
1887     gst_object_unref (udpsrc0);
1888     udpsrc0 = NULL;
1889
1890     GST_DEBUG_OBJECT (src, "retry %d", count);
1891     tmp_rtp++;
1892     goto again;
1893   }
1894
1895   /* allocate port+1 for RTCP now */
1896   udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
1897   if (udpsrc1 == NULL)
1898     goto no_udp_rtcp_protocol;
1899
1900   /* set port */
1901   tmp_rtcp = tmp_rtp + 1;
1902   if (src->client_port_range.max > 0 && tmp_rtcp > src->client_port_range.max)
1903     goto no_ports;
1904
1905   g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
1906
1907   GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
1908   ret = gst_element_set_state (udpsrc1, GST_STATE_READY);
1909   /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
1910   if (ret == GST_STATE_CHANGE_FAILURE) {
1911     GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
1912
1913     if (++count > src->retry)
1914       goto no_ports;
1915
1916     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1917     gst_element_set_state (udpsrc0, GST_STATE_NULL);
1918     gst_object_unref (udpsrc0);
1919     udpsrc0 = NULL;
1920
1921     GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
1922     gst_element_set_state (udpsrc1, GST_STATE_NULL);
1923     gst_object_unref (udpsrc1);
1924     udpsrc1 = NULL;
1925
1926     tmp_rtp += 2;
1927     GST_DEBUG_OBJECT (src, "retry %d", count);
1928     goto again;
1929   }
1930
1931   /* all fine, do port check */
1932   g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
1933   g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
1934
1935   /* this should not happen... */
1936   if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
1937     goto port_error;
1938
1939   /* we keep these elements, we configure all in configure_transport when the
1940    * server told us to really use the UDP ports. */
1941   stream->udpsrc[0] = gst_object_ref_sink (udpsrc0);
1942   stream->udpsrc[1] = gst_object_ref_sink (udpsrc1);
1943   gst_element_set_locked_state (stream->udpsrc[0], TRUE);
1944   gst_element_set_locked_state (stream->udpsrc[1], TRUE);
1945
1946   /* keep track of next available port number when we have a range
1947    * configured */
1948   if (src->next_port_num != 0)
1949     src->next_port_num = tmp_rtcp + 1;
1950
1951   return TRUE;
1952
1953   /* ERRORS */
1954 no_udp_protocol:
1955   {
1956     GST_DEBUG_OBJECT (src, "could not get UDP source");
1957     goto cleanup;
1958   }
1959 no_ports:
1960   {
1961     GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
1962         count);
1963     goto cleanup;
1964   }
1965 no_udp_rtcp_protocol:
1966   {
1967     GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
1968     goto cleanup;
1969   }
1970 port_error:
1971   {
1972     GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
1973         tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
1974     goto cleanup;
1975   }
1976 cleanup:
1977   {
1978     if (udpsrc0) {
1979       gst_element_set_state (udpsrc0, GST_STATE_NULL);
1980       gst_object_unref (udpsrc0);
1981     }
1982     if (udpsrc1) {
1983       gst_element_set_state (udpsrc1, GST_STATE_NULL);
1984       gst_object_unref (udpsrc1);
1985     }
1986     return FALSE;
1987   }
1988 }
1989
1990 static void
1991 gst_rtspsrc_set_state (GstRTSPSrc * src, GstState state)
1992 {
1993   GList *walk;
1994
1995   if (src->manager)
1996     gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
1997
1998   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1999     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2000     gint i;
2001
2002     for (i = 0; i < 2; i++) {
2003       if (stream->udpsrc[i])
2004         gst_element_set_state (stream->udpsrc[i], state);
2005     }
2006   }
2007 }
2008
2009 static void
2010 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
2011 {
2012   GstEvent *event;
2013   gint cmd;
2014   GstState state;
2015
2016   if (flush) {
2017     event = gst_event_new_flush_start ();
2018     GST_DEBUG_OBJECT (src, "start flush");
2019     cmd = CMD_WAIT;
2020     state = GST_STATE_PAUSED;
2021   } else {
2022     event = gst_event_new_flush_stop (FALSE);
2023     GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
2024     cmd = CMD_LOOP;
2025     if (playing)
2026       state = GST_STATE_PLAYING;
2027     else
2028       state = GST_STATE_PAUSED;
2029   }
2030   gst_rtspsrc_push_event (src, event);
2031   gst_rtspsrc_loop_send_cmd (src, cmd, CMD_LOOP);
2032   gst_rtspsrc_set_state (src, state);
2033 }
2034
2035 static GstRTSPResult
2036 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
2037     GstRTSPMessage * message, GTimeVal * timeout)
2038 {
2039   GstRTSPResult ret;
2040
2041   if (conn)
2042     ret = gst_rtsp_connection_send (conn, message, timeout);
2043   else
2044     ret = GST_RTSP_ERROR;
2045
2046   return ret;
2047 }
2048
2049 static GstRTSPResult
2050 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
2051     GstRTSPMessage * message, GTimeVal * timeout)
2052 {
2053   GstRTSPResult ret;
2054
2055   if (conn)
2056     ret = gst_rtsp_connection_receive (conn, message, timeout);
2057   else
2058     ret = GST_RTSP_ERROR;
2059
2060   return ret;
2061 }
2062
2063 static void
2064 gst_rtspsrc_get_position (GstRTSPSrc * src)
2065 {
2066   GstQuery *query;
2067   GList *walk;
2068
2069   query = gst_query_new_position (GST_FORMAT_TIME);
2070   /*  should be known somewhere down the stream (e.g. jitterbuffer) */
2071   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2072     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2073     GstFormat fmt;
2074     gint64 pos;
2075
2076     if (stream->srcpad) {
2077       if (gst_pad_query (stream->srcpad, query)) {
2078         gst_query_parse_position (query, &fmt, &pos);
2079         GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
2080             GST_TIME_ARGS (pos));
2081         src->last_pos = pos;
2082         goto out;
2083       }
2084     }
2085   }
2086
2087   src->last_pos = 0;
2088
2089 out:
2090
2091   gst_query_unref (query);
2092 }
2093
2094 static gboolean
2095 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
2096 {
2097   gdouble rate;
2098   GstFormat format;
2099   GstSeekFlags flags;
2100   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
2101   gint64 cur, stop;
2102   gboolean flush, skip;
2103   gboolean update;
2104   gboolean playing;
2105   GstSegment seeksegment = { 0, };
2106   GList *walk;
2107
2108   if (event) {
2109     GST_DEBUG_OBJECT (src, "doing seek with event");
2110
2111     gst_event_parse_seek (event, &rate, &format, &flags,
2112         &cur_type, &cur, &stop_type, &stop);
2113
2114     /* no negative rates yet */
2115     if (rate < 0.0)
2116       goto negative_rate;
2117
2118     /* we need TIME format */
2119     if (format != src->segment.format)
2120       goto no_format;
2121   } else {
2122     GST_DEBUG_OBJECT (src, "doing seek without event");
2123     flags = 0;
2124     cur_type = GST_SEEK_TYPE_SET;
2125     stop_type = GST_SEEK_TYPE_SET;
2126   }
2127
2128   /* get flush flag */
2129   flush = flags & GST_SEEK_FLAG_FLUSH;
2130   skip = flags & GST_SEEK_FLAG_SKIP;
2131
2132   /* now we need to make sure the streaming thread is stopped. We do this by
2133    * either sending a FLUSH_START event downstream which will cause the
2134    * streaming thread to stop with a WRONG_STATE.
2135    * For a non-flushing seek we simply pause the task, which will happen as soon
2136    * as it completes one iteration (and thus might block when the sink is
2137    * blocking in preroll). */
2138   if (flush) {
2139     GST_DEBUG_OBJECT (src, "starting flush");
2140     gst_rtspsrc_flush (src, TRUE, FALSE);
2141   } else {
2142     if (src->task) {
2143       gst_task_pause (src->task);
2144     }
2145   }
2146
2147   /* we should now be able to grab the streaming thread because we stopped it
2148    * with the above flush/pause code */
2149   GST_RTSP_STREAM_LOCK (src);
2150
2151   GST_DEBUG_OBJECT (src, "stopped streaming");
2152
2153   /* stop flushing the rtsp connection so we can send PAUSE/PLAY below */
2154   gst_rtspsrc_connection_flush (src, FALSE);
2155
2156   /* copy segment, we need this because we still need the old
2157    * segment when we close the current segment. */
2158   memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
2159
2160   /* configure the seek parameters in the seeksegment. We will then have the
2161    * right values in the segment to perform the seek */
2162   if (event) {
2163     GST_DEBUG_OBJECT (src, "configuring seek");
2164     gst_segment_do_seek (&seeksegment, rate, format, flags,
2165         cur_type, cur, stop_type, stop, &update);
2166   }
2167
2168   /* figure out the last position we need to play. If it's configured (stop !=
2169    * -1), use that, else we play until the total duration of the file */
2170   if ((stop = seeksegment.stop) == -1)
2171     stop = seeksegment.duration;
2172
2173   playing = (src->state == GST_RTSP_STATE_PLAYING);
2174
2175   /* if we were playing, pause first */
2176   if (playing) {
2177     /* obtain current position in case seek fails */
2178     gst_rtspsrc_get_position (src);
2179     gst_rtspsrc_pause (src, FALSE);
2180   }
2181   src->skip = skip;
2182
2183   src->state = GST_RTSP_STATE_SEEKING;
2184
2185   /* PLAY will add the range header now. */
2186   src->need_range = TRUE;
2187
2188   /* and continue playing */
2189   if (playing)
2190     gst_rtspsrc_play (src, &seeksegment, FALSE);
2191
2192   /* prepare for streaming again */
2193   if (flush) {
2194     /* if we started flush, we stop now */
2195     GST_DEBUG_OBJECT (src, "stopping flush");
2196     gst_rtspsrc_flush (src, FALSE, playing);
2197   }
2198
2199   /* now we did the seek and can activate the new segment values */
2200   memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
2201
2202   /* if we're doing a segment seek, post a SEGMENT_START message */
2203   if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2204     gst_element_post_message (GST_ELEMENT_CAST (src),
2205         gst_message_new_segment_start (GST_OBJECT_CAST (src),
2206             src->segment.format, src->segment.position));
2207   }
2208
2209   /* now create the newsegment */
2210   GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
2211       " to %" G_GINT64_FORMAT, src->segment.position, stop);
2212
2213   /* mark discont */
2214   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
2215   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2216     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2217     stream->discont = TRUE;
2218   }
2219
2220   GST_RTSP_STREAM_UNLOCK (src);
2221
2222   return TRUE;
2223
2224   /* ERRORS */
2225 negative_rate:
2226   {
2227     GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
2228     return FALSE;
2229   }
2230 no_format:
2231   {
2232     GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
2233     return FALSE;
2234   }
2235 }
2236
2237 static gboolean
2238 gst_rtspsrc_handle_src_event (GstPad * pad, GstObject * parent,
2239     GstEvent * event)
2240 {
2241   GstRTSPSrc *src;
2242   gboolean res = TRUE;
2243   gboolean forward;
2244
2245   src = GST_RTSPSRC_CAST (parent);
2246
2247   GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
2248       GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
2249
2250   switch (GST_EVENT_TYPE (event)) {
2251     case GST_EVENT_SEEK:
2252       res = gst_rtspsrc_perform_seek (src, event);
2253       forward = FALSE;
2254       break;
2255     case GST_EVENT_QOS:
2256     case GST_EVENT_NAVIGATION:
2257     case GST_EVENT_LATENCY:
2258     default:
2259       forward = TRUE;
2260       break;
2261   }
2262   if (forward) {
2263     GstPad *target;
2264
2265     if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2266       res = gst_pad_send_event (target, event);
2267       gst_object_unref (target);
2268     } else {
2269       gst_event_unref (event);
2270     }
2271   } else {
2272     gst_event_unref (event);
2273   }
2274
2275   return res;
2276 }
2277
2278 /* this is the final event function we receive on the internal source pad when
2279  * we deal with TCP connections */
2280 static gboolean
2281 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstObject * parent,
2282     GstEvent * event)
2283 {
2284   gboolean res;
2285
2286   GST_DEBUG_OBJECT (pad, "received event %s", GST_EVENT_TYPE_NAME (event));
2287
2288   switch (GST_EVENT_TYPE (event)) {
2289     case GST_EVENT_SEEK:
2290     case GST_EVENT_QOS:
2291     case GST_EVENT_NAVIGATION:
2292     case GST_EVENT_LATENCY:
2293     default:
2294       gst_event_unref (event);
2295       res = TRUE;
2296       break;
2297   }
2298   return res;
2299 }
2300
2301 /* this is the final query function we receive on the internal source pad when
2302  * we deal with TCP connections */
2303 static gboolean
2304 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
2305     GstQuery * query)
2306 {
2307   GstRTSPSrc *src;
2308   gboolean res = TRUE;
2309
2310   src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
2311
2312   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2313       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2314
2315   switch (GST_QUERY_TYPE (query)) {
2316     case GST_QUERY_POSITION:
2317     {
2318       /* no idea */
2319       break;
2320     }
2321     case GST_QUERY_DURATION:
2322     {
2323       GstFormat format;
2324
2325       gst_query_parse_duration (query, &format, NULL);
2326
2327       switch (format) {
2328         case GST_FORMAT_TIME:
2329           gst_query_set_duration (query, format, src->segment.duration);
2330           break;
2331         default:
2332           res = FALSE;
2333           break;
2334       }
2335       break;
2336     }
2337     case GST_QUERY_LATENCY:
2338     {
2339       /* we are live with a min latency of 0 and unlimited max latency, this
2340        * result will be updated by the session manager if there is any. */
2341       gst_query_set_latency (query, TRUE, 0, -1);
2342       break;
2343     }
2344     default:
2345       break;
2346   }
2347
2348   return res;
2349 }
2350
2351 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2352 static gboolean
2353 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2354     GstQuery * query)
2355 {
2356   GstRTSPSrc *src;
2357   gboolean res = FALSE;
2358
2359   src = GST_RTSPSRC_CAST (parent);
2360
2361   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2362       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2363
2364   switch (GST_QUERY_TYPE (query)) {
2365     case GST_QUERY_DURATION:
2366     {
2367       GstFormat format;
2368
2369       gst_query_parse_duration (query, &format, NULL);
2370
2371       switch (format) {
2372         case GST_FORMAT_TIME:
2373           gst_query_set_duration (query, format, src->segment.duration);
2374           res = TRUE;
2375           break;
2376         default:
2377           break;
2378       }
2379       break;
2380     }
2381     case GST_QUERY_SEEKING:
2382     {
2383       GstFormat format;
2384
2385       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2386       if (format == GST_FORMAT_TIME) {
2387         gboolean seekable =
2388             src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2389
2390         /* seeking without duration is unlikely */
2391         seekable = seekable && src->seekable && src->segment.duration &&
2392             GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2393
2394         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0,
2395             src->segment.duration);
2396         res = TRUE;
2397       }
2398       break;
2399     }
2400     case GST_QUERY_URI:
2401     {
2402       gchar *uri;
2403
2404       uri = gst_rtspsrc_uri_get_uri (GST_URI_HANDLER (src));
2405       if (uri != NULL) {
2406         gst_query_set_uri (query, uri);
2407         g_free (uri);
2408         res = TRUE;
2409       }
2410       break;
2411     }
2412     default:
2413     {
2414       GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2415
2416       /* forward the query to the proxy target pad */
2417       if (target) {
2418         res = gst_pad_query (target, query);
2419         gst_object_unref (target);
2420       }
2421       break;
2422     }
2423   }
2424
2425   return res;
2426 }
2427
2428 /* callback for RTCP messages to be sent to the server when operating in TCP
2429  * mode. */
2430 static GstFlowReturn
2431 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2432 {
2433   GstRTSPSrc *src;
2434   GstRTSPStream *stream;
2435   GstFlowReturn res = GST_FLOW_OK;
2436   GstMapInfo map;
2437   guint8 *data;
2438   guint size;
2439   GstRTSPResult ret;
2440   GstRTSPMessage message = { 0 };
2441   GstRTSPConnection *conn;
2442
2443   stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2444   src = stream->parent;
2445
2446   gst_buffer_map (buffer, &map, GST_MAP_READ);
2447   size = map.size;
2448   data = map.data;
2449
2450   gst_rtsp_message_init_data (&message, stream->channel[1]);
2451
2452   /* lend the body data to the message */
2453   gst_rtsp_message_take_body (&message, data, size);
2454
2455   if (stream->conninfo.connection)
2456     conn = stream->conninfo.connection;
2457   else
2458     conn = src->conninfo.connection;
2459
2460   GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2461   ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
2462   GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2463
2464   /* and steal it away again because we will free it when unreffing the
2465    * buffer */
2466   gst_rtsp_message_steal_body (&message, &data, &size);
2467   gst_rtsp_message_unset (&message);
2468
2469   gst_buffer_unmap (buffer, &map);
2470   gst_buffer_unref (buffer);
2471
2472   return res;
2473 }
2474
2475 static GstPadProbeReturn
2476 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2477 {
2478   GstRTSPSrc *src = user_data;
2479
2480   GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2481       GST_DEBUG_PAD_NAME (pad));
2482
2483   /* activate the streams */
2484   GST_OBJECT_LOCK (src);
2485   if (!src->need_activate)
2486     goto was_ok;
2487
2488   src->need_activate = FALSE;
2489   GST_OBJECT_UNLOCK (src);
2490
2491   gst_rtspsrc_activate_streams (src);
2492
2493   return GST_PAD_PROBE_OK;
2494
2495 was_ok:
2496   {
2497     GST_OBJECT_UNLOCK (src);
2498     return GST_PAD_PROBE_OK;
2499   }
2500 }
2501
2502 static gboolean
2503 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
2504 {
2505   GstPad *gpad = GST_PAD_CAST (user_data);
2506
2507   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
2508   gst_pad_store_sticky_event (gpad, *event);
2509
2510   return TRUE;
2511 }
2512
2513 /* this callback is called when the session manager generated a new src pad with
2514  * payloaded RTP packets. We simply ghost the pad here. */
2515 static void
2516 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2517 {
2518   gchar *name;
2519   GstPadTemplate *template;
2520   gint id, ssrc, pt;
2521   GList *ostreams;
2522   GstRTSPStream *stream;
2523   gboolean all_added;
2524
2525   GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2526
2527   GST_RTSP_STATE_LOCK (src);
2528   /* find stream */
2529   name = gst_object_get_name (GST_OBJECT_CAST (pad));
2530   if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2531     goto unknown_stream;
2532
2533   GST_DEBUG_OBJECT (src, "stream: %u, SSRC %08x, PT %d", id, ssrc, pt);
2534
2535   stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2536   if (stream == NULL)
2537     goto unknown_stream;
2538
2539   /* save SSRC */
2540   stream->ssrc = ssrc;
2541
2542   /* we'll add it later see below */
2543   stream->added = TRUE;
2544
2545   /* check if we added all streams */
2546   all_added = TRUE;
2547   for (ostreams = src->streams; ostreams; ostreams = g_list_next (ostreams)) {
2548     GstRTSPStream *ostream = (GstRTSPStream *) ostreams->data;
2549
2550     GST_DEBUG_OBJECT (src, "stream %p, container %d, added %d, setup %d",
2551         ostream, ostream->container, ostream->added, ostream->setup);
2552
2553     /* if we find a stream for which we did a setup that is not added, we
2554      * need to wait some more */
2555     if (ostream->setup && !ostream->added) {
2556       all_added = FALSE;
2557       break;
2558     }
2559   }
2560   GST_RTSP_STATE_UNLOCK (src);
2561
2562   /* create a new pad we will use to stream to */
2563   template = gst_static_pad_template_get (&rtptemplate);
2564   stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
2565   gst_object_unref (template);
2566   g_free (name);
2567
2568   gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
2569   gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
2570   gst_pad_set_active (stream->srcpad, TRUE);
2571   gst_pad_sticky_events_foreach (pad, copy_sticky_events, stream->srcpad);
2572   gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
2573
2574   if (all_added) {
2575     GST_DEBUG_OBJECT (src, "We added all streams");
2576     /* when we get here, all stream are added and we can fire the no-more-pads
2577      * signal. */
2578     gst_element_no_more_pads (GST_ELEMENT_CAST (src));
2579   }
2580
2581   return;
2582
2583   /* ERRORS */
2584 unknown_stream:
2585   {
2586     GST_DEBUG_OBJECT (src, "ignoring unknown stream");
2587     GST_RTSP_STATE_UNLOCK (src);
2588     g_free (name);
2589     return;
2590   }
2591 }
2592
2593 static GstCaps *
2594 stream_get_caps_for_pt (GstRTSPStream * stream, guint pt)
2595 {
2596   guint i, len;
2597
2598   len = stream->ptmap->len;
2599   for (i = 0; i < len; i++) {
2600     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
2601     if (item->pt == pt)
2602       return item->caps;
2603   }
2604   return NULL;
2605 }
2606
2607 static GstCaps *
2608 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
2609 {
2610   GstRTSPStream *stream;
2611   GstCaps *caps;
2612
2613   GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
2614
2615   GST_RTSP_STATE_LOCK (src);
2616   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2617   if (!stream)
2618     goto unknown_stream;
2619
2620   if ((caps = stream_get_caps_for_pt (stream, pt)))
2621     gst_caps_ref (caps);
2622   GST_RTSP_STATE_UNLOCK (src);
2623
2624   return caps;
2625
2626 unknown_stream:
2627   {
2628     GST_DEBUG_OBJECT (src, "unknown stream %d", session);
2629     GST_RTSP_STATE_UNLOCK (src);
2630     return NULL;
2631   }
2632 }
2633
2634 static void
2635 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
2636 {
2637   GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
2638
2639   if (stream->eos)
2640     goto was_eos;
2641
2642   stream->eos = TRUE;
2643   gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos ());
2644   return;
2645
2646   /* ERRORS */
2647 was_eos:
2648   {
2649     GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
2650     return;
2651   }
2652 }
2653
2654 static void
2655 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2656 {
2657   GstRTSPSrc *src = stream->parent;
2658   guint ssrc;
2659
2660   g_object_get (source, "ssrc", &ssrc, NULL);
2661
2662   GST_DEBUG_OBJECT (src, "source %08x, stream %08x, session %u received BYE",
2663       ssrc, stream->ssrc, stream->id);
2664
2665   if (ssrc == stream->ssrc)
2666     gst_rtspsrc_do_stream_eos (src, stream);
2667 }
2668
2669 static void
2670 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2671 {
2672   GstRTSPSrc *src = stream->parent;
2673   guint ssrc;
2674
2675   g_object_get (source, "ssrc", &ssrc, NULL);
2676
2677   GST_WARNING_OBJECT (src, "source %08x, stream %08x in session %u timed out",
2678       ssrc, stream->ssrc, stream->id);
2679
2680   if (ssrc == stream->ssrc)
2681     gst_rtspsrc_do_stream_eos (src, stream);
2682 }
2683
2684 static void
2685 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
2686 {
2687   GstRTSPStream *stream;
2688
2689   GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
2690
2691   /* get stream for session */
2692   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2693   if (stream) {
2694     gst_rtspsrc_do_stream_eos (src, stream);
2695   }
2696 }
2697
2698 static void
2699 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2700 {
2701   GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
2702       stream->id);
2703 }
2704
2705 static void
2706 set_manager_buffer_mode (GstRTSPSrc * src)
2707 {
2708   GObjectClass *klass;
2709
2710   if (src->manager == NULL)
2711     return;
2712
2713   klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2714
2715   if (!g_object_class_find_property (klass, "buffer-mode"))
2716     return;
2717
2718   if (src->buffer_mode != BUFFER_MODE_AUTO) {
2719     g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2720
2721     return;
2722   }
2723
2724   GST_DEBUG_OBJECT (src,
2725       "auto buffering mode, have clock %" GST_PTR_FORMAT, src->provided_clock);
2726
2727   if (src->provided_clock) {
2728     GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
2729
2730     if (clock == src->provided_clock) {
2731       GST_DEBUG_OBJECT (src, "selected synced");
2732       g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SYNCED, NULL);
2733
2734       if (clock)
2735         gst_object_unref (clock);
2736
2737       return;
2738     }
2739
2740     /* Otherwise fall-through and use another buffer mode */
2741     if (clock)
2742       gst_object_unref (clock);
2743   }
2744
2745   GST_DEBUG_OBJECT (src, "auto buffering mode");
2746   if (src->use_buffering) {
2747     GST_DEBUG_OBJECT (src, "selected buffer");
2748     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER, NULL);
2749   } else {
2750     GST_DEBUG_OBJECT (src, "selected slave");
2751     g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
2752   }
2753 }
2754
2755 static GstCaps *
2756 request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
2757 {
2758   guint i;
2759   GstCaps *caps;
2760   GstMIKEYMessage *msg = stream->mikey;
2761
2762   GST_DEBUG ("request key SSRC %u", ssrc);
2763
2764   caps = gst_caps_ref (stream_get_caps_for_pt (stream, stream->default_pt));
2765   caps = gst_caps_make_writable (caps);
2766
2767   /* parse crypto sessions and look for the SSRC rollover counter */
2768   msg = stream->mikey;
2769   for (i = 0; msg && i < gst_mikey_message_get_n_cs (msg); i++) {
2770     const GstMIKEYMapSRTP *map = gst_mikey_message_get_cs_srtp (msg, i);
2771
2772     if (ssrc == map->ssrc) {
2773       gst_caps_set_simple (caps, "roc", G_TYPE_UINT, map->roc, NULL);
2774       break;
2775     }
2776   }
2777
2778   return caps;
2779 }
2780
2781 static GstElement *
2782 request_rtp_decoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
2783 {
2784   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
2785   if (stream->id != session)
2786     return NULL;
2787
2788   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
2789       stream->profile != GST_RTSP_PROFILE_SAVPF)
2790     return NULL;
2791
2792   if (stream->srtpdec == NULL) {
2793     gchar *name;
2794
2795     name = g_strdup_printf ("srtpdec_%u", session);
2796     stream->srtpdec = gst_element_factory_make ("srtpdec", name);
2797     g_free (name);
2798
2799     g_signal_connect (stream->srtpdec, "request-key",
2800         (GCallback) request_key, stream);
2801   }
2802   return gst_object_ref (stream->srtpdec);
2803 }
2804
2805 static GstElement *
2806 request_rtcp_encoder (GstElement * rtpbin, guint session,
2807     GstRTSPStream * stream)
2808 {
2809   gchar *name;
2810   GstPad *pad;
2811
2812   GST_DEBUG ("decoder session %u, stream %p, %d", session, stream, stream->id);
2813   if (stream->id != session)
2814     return NULL;
2815
2816   if (stream->profile != GST_RTSP_PROFILE_SAVP &&
2817       stream->profile != GST_RTSP_PROFILE_SAVPF)
2818     return NULL;
2819
2820   if (stream->srtpenc == NULL) {
2821     GstStructure *s;
2822
2823     name = g_strdup_printf ("srtpenc_%u", session);
2824     stream->srtpenc = gst_element_factory_make ("srtpenc", name);
2825     g_free (name);
2826
2827     /* get RTCP crypto parameters from caps */
2828     s = gst_caps_get_structure (stream->srtcpparams, 0);
2829     if (s) {
2830       GstBuffer *buf;
2831       const gchar *str;
2832       GType ciphertype, authtype;
2833       GValue rtcp_cipher = G_VALUE_INIT, rtcp_auth = G_VALUE_INIT;
2834
2835       ciphertype = g_type_from_name ("GstSrtpCipherType");
2836       authtype = g_type_from_name ("GstSrtpAuthType");
2837       g_value_init (&rtcp_cipher, ciphertype);
2838       g_value_init (&rtcp_auth, authtype);
2839
2840       str = gst_structure_get_string (s, "srtcp-cipher");
2841       gst_value_deserialize (&rtcp_cipher, str);
2842       str = gst_structure_get_string (s, "srtcp-auth");
2843       gst_value_deserialize (&rtcp_auth, str);
2844       gst_structure_get (s, "srtp-key", GST_TYPE_BUFFER, &buf, NULL);
2845
2846       g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-cipher",
2847           &rtcp_cipher);
2848       g_object_set_property (G_OBJECT (stream->srtpenc), "rtp-auth",
2849           &rtcp_auth);
2850       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-cipher",
2851           &rtcp_cipher);
2852       g_object_set_property (G_OBJECT (stream->srtpenc), "rtcp-auth",
2853           &rtcp_auth);
2854       g_object_set (stream->srtpenc, "key", buf, NULL);
2855
2856       g_value_unset (&rtcp_cipher);
2857       g_value_unset (&rtcp_auth);
2858       gst_buffer_unref (buf);
2859     }
2860   }
2861   name = g_strdup_printf ("rtcp_sink_%d", session);
2862   pad = gst_element_get_request_pad (stream->srtpenc, name);
2863   g_free (name);
2864   gst_object_unref (pad);
2865
2866   return gst_object_ref (stream->srtpenc);
2867 }
2868
2869 static GstElement *
2870 request_aux_receiver (GstElement * rtpbin, guint sessid, GstRTSPSrc * src)
2871 {
2872   GstElement *rtx, *bin;
2873   GstPad *pad;
2874   gchar *name;
2875   GstRTSPStream *stream;
2876
2877   stream = find_stream (src, &sessid, (gpointer) find_stream_by_id);
2878   if (!stream) {
2879     GST_WARNING_OBJECT (src, "Stream %u not found", sessid);
2880     return NULL;
2881   }
2882
2883   GST_INFO_OBJECT (src, "creating retransmision receiver for session %u "
2884       "with map %" GST_PTR_FORMAT, sessid, stream->rtx_pt_map);
2885   bin = gst_bin_new (NULL);
2886   rtx = gst_element_factory_make ("rtprtxreceive", NULL);
2887   g_object_set (rtx, "payload-type-map", stream->rtx_pt_map, NULL);
2888   gst_bin_add (GST_BIN (bin), rtx);
2889
2890   pad = gst_element_get_static_pad (rtx, "src");
2891   name = g_strdup_printf ("src_%u", sessid);
2892   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
2893   g_free (name);
2894   gst_object_unref (pad);
2895
2896   pad = gst_element_get_static_pad (rtx, "sink");
2897   name = g_strdup_printf ("sink_%u", sessid);
2898   gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
2899   g_free (name);
2900   gst_object_unref (pad);
2901
2902   return bin;
2903 }
2904
2905 static void
2906 add_retransmission (GstRTSPSrc * src, GstRTSPTransport * transport)
2907 {
2908   GList *walk;
2909   guint signal_id;
2910   gboolean do_retransmission = FALSE;
2911
2912   if (transport->trans != GST_RTSP_TRANS_RTP)
2913     return;
2914   if (transport->profile != GST_RTSP_PROFILE_AVPF &&
2915       transport->profile != GST_RTSP_PROFILE_SAVPF)
2916     return;
2917
2918   signal_id = g_signal_lookup ("request-aux-receiver",
2919       G_OBJECT_TYPE (src->manager));
2920   /* there's already something connected */
2921   if (g_signal_handler_find (src->manager, G_SIGNAL_MATCH_ID, signal_id, 0,
2922           NULL, NULL, NULL) != 0) {
2923     GST_DEBUG_OBJECT (src, "Not adding RTX AUX element as "
2924         "\"request-aux-receiver\" signal is "
2925         "already used by the application");
2926     return;
2927   }
2928
2929   /* build the retransmission payload type map */
2930   for (walk = src->streams; walk; walk = g_list_next (walk)) {
2931     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
2932     gboolean do_retransmission_stream = FALSE;
2933     int i;
2934
2935     if (stream->rtx_pt_map)
2936       gst_structure_free (stream->rtx_pt_map);
2937     stream->rtx_pt_map = gst_structure_new_empty ("application/x-rtp-pt-map");
2938
2939     for (i = 0; i < stream->ptmap->len; i++) {
2940       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
2941       GstStructure *s = gst_caps_get_structure (item->caps, 0);
2942       const gchar *encoding;
2943
2944       /* we only care about RTX streams */
2945       if ((encoding = gst_structure_get_string (s, "encoding-name"))
2946           && g_strcmp0 (encoding, "RTX") == 0) {
2947         const gchar *stream_pt_s;
2948         gint rtx_pt;
2949
2950         if (gst_structure_get_int (s, "payload", &rtx_pt)
2951             && (stream_pt_s = gst_structure_get_string (s, "apt"))) {
2952
2953           if (rtx_pt != 0) {
2954             gst_structure_set (stream->rtx_pt_map, stream_pt_s, G_TYPE_UINT,
2955                 rtx_pt, NULL);
2956             do_retransmission_stream = TRUE;
2957           }
2958         }
2959       }
2960     }
2961
2962     if (do_retransmission_stream) {
2963       GST_DEBUG_OBJECT (src, "built retransmission payload map for stream "
2964           "id %i: %" GST_PTR_FORMAT, stream->id, stream->rtx_pt_map);
2965       do_retransmission = TRUE;
2966     } else {
2967       GST_DEBUG_OBJECT (src, "no retransmission payload map for stream "
2968           "id %i", stream->id);
2969       gst_structure_free (stream->rtx_pt_map);
2970       stream->rtx_pt_map = NULL;
2971     }
2972   }
2973
2974   if (do_retransmission) {
2975     GST_DEBUG_OBJECT (src, "Enabling retransmissions");
2976
2977     g_object_set (src->manager, "do-retransmission", TRUE, NULL);
2978
2979     /* enable RFC4588 retransmission handling by setting rtprtxreceive
2980      * as the "aux" element of rtpbin */
2981     g_signal_connect (src->manager, "request-aux-receiver",
2982         (GCallback) request_aux_receiver, src);
2983   } else {
2984     GST_DEBUG_OBJECT (src,
2985         "Not enabling retransmissions as no stream had a retransmission payload map");
2986   }
2987 }
2988
2989 /* try to get and configure a manager */
2990 static gboolean
2991 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
2992     GstRTSPTransport * transport)
2993 {
2994   const gchar *manager;
2995   gchar *name;
2996   GstStateChangeReturn ret;
2997
2998   /* find a manager */
2999   if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
3000     goto no_manager;
3001
3002   if (manager) {
3003     GST_DEBUG_OBJECT (src, "using manager %s", manager);
3004
3005     /* configure the manager */
3006     if (src->manager == NULL) {
3007       GObjectClass *klass;
3008
3009       if (!(src->manager = gst_element_factory_make (manager, "manager"))) {
3010         /* fallback */
3011         if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
3012           goto no_manager;
3013
3014         if (!manager)
3015           goto use_no_manager;
3016
3017         if (!(src->manager = gst_element_factory_make (manager, "manager")))
3018           goto manager_failed;
3019       }
3020
3021       /* we manage this element */
3022       gst_element_set_locked_state (src->manager, TRUE);
3023       gst_bin_add (GST_BIN_CAST (src), src->manager);
3024
3025       ret = gst_element_set_state (src->manager, GST_STATE_PAUSED);
3026       if (ret == GST_STATE_CHANGE_FAILURE)
3027         goto start_manager_failure;
3028
3029       g_object_set (src->manager, "latency", src->latency, NULL);
3030
3031       klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
3032
3033       if (g_object_class_find_property (klass, "ntp-sync")) {
3034         g_object_set (src->manager, "ntp-sync", src->ntp_sync, NULL);
3035       }
3036
3037       if (g_object_class_find_property (klass, "rfc7273-sync")) {
3038         g_object_set (src->manager, "rfc7273-sync", src->rfc7273_sync, NULL);
3039       }
3040
3041       if (src->use_pipeline_clock) {
3042         if (g_object_class_find_property (klass, "use-pipeline-clock")) {
3043           g_object_set (src->manager, "use-pipeline-clock", TRUE, NULL);
3044         }
3045       } else {
3046         if (g_object_class_find_property (klass, "ntp-time-source")) {
3047           g_object_set (src->manager, "ntp-time-source", src->ntp_time_source,
3048               NULL);
3049         }
3050       }
3051
3052       if (src->sdes && g_object_class_find_property (klass, "sdes")) {
3053         g_object_set (src->manager, "sdes", src->sdes, NULL);
3054       }
3055
3056       if (g_object_class_find_property (klass, "drop-on-latency")) {
3057         g_object_set (src->manager, "drop-on-latency", src->drop_on_latency,
3058             NULL);
3059       }
3060
3061       if (g_object_class_find_property (klass, "max-rtcp-rtp-time-diff")) {
3062         g_object_set (src->manager, "max-rtcp-rtp-time-diff",
3063             src->max_rtcp_rtp_time_diff, NULL);
3064       }
3065
3066       /* buffer mode pauses are handled by adding offsets to buffer times,
3067        * but some depayloaders may have a hard time syncing output times
3068        * with such input times, e.g. container ones, most notably ASF */
3069       /* TODO alternatives are having an event that indicates these shifts,
3070        * or having rtsp extensions provide suggestion on buffer mode */
3071       /* valid duration implies not likely live pipeline,
3072        * so slaving in jitterbuffer does not make much sense
3073        * (and might mess things up due to bursts) */
3074       if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
3075           src->segment.duration && stream->container) {
3076         src->use_buffering = TRUE;
3077       } else {
3078         src->use_buffering = FALSE;
3079       }
3080
3081       set_manager_buffer_mode (src);
3082
3083       /* connect to signals */
3084       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
3085           stream);
3086       src->manager_sig_id =
3087           g_signal_connect (src->manager, "pad-added",
3088           (GCallback) new_manager_pad, src);
3089       src->manager_ptmap_id =
3090           g_signal_connect (src->manager, "request-pt-map",
3091           (GCallback) request_pt_map, src);
3092
3093       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
3094           src);
3095
3096       g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_NEW_MANAGER], 0,
3097           src->manager);
3098
3099       if (src->do_retransmission)
3100         add_retransmission (src, transport);
3101     }
3102     g_signal_connect (src->manager, "request-rtp-decoder",
3103         (GCallback) request_rtp_decoder, stream);
3104     g_signal_connect (src->manager, "request-rtcp-decoder",
3105         (GCallback) request_rtp_decoder, stream);
3106     g_signal_connect (src->manager, "request-rtcp-encoder",
3107         (GCallback) request_rtcp_encoder, stream);
3108
3109     /* we stream directly to the manager, get some pads. Each RTSP stream goes
3110      * into a separate RTP session. */
3111     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
3112     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
3113     g_free (name);
3114     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
3115     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
3116     g_free (name);
3117
3118     /* now configure the bandwidth in the manager */
3119     if (g_signal_lookup ("get-internal-session",
3120             G_OBJECT_TYPE (src->manager)) != 0) {
3121       GObject *rtpsession;
3122
3123       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
3124           &rtpsession);
3125       if (rtpsession) {
3126         GstRTPProfile rtp_profile;
3127
3128         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
3129
3130         stream->session = rtpsession;
3131
3132         if (stream->as_bandwidth != -1) {
3133           GST_INFO_OBJECT (src, "setting AS: %f",
3134               (gdouble) (stream->as_bandwidth * 1000));
3135           g_object_set (rtpsession, "bandwidth",
3136               (gdouble) (stream->as_bandwidth * 1000), NULL);
3137         }
3138         if (stream->rr_bandwidth != -1) {
3139           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
3140           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
3141               NULL);
3142         }
3143         if (stream->rs_bandwidth != -1) {
3144           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
3145           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
3146               NULL);
3147         }
3148
3149         switch (stream->profile) {
3150           case GST_RTSP_PROFILE_AVPF:
3151             rtp_profile = GST_RTP_PROFILE_AVPF;
3152             break;
3153           case GST_RTSP_PROFILE_SAVP:
3154             rtp_profile = GST_RTP_PROFILE_SAVP;
3155             break;
3156           case GST_RTSP_PROFILE_SAVPF:
3157             rtp_profile = GST_RTP_PROFILE_SAVPF;
3158             break;
3159           case GST_RTSP_PROFILE_AVP:
3160           default:
3161             rtp_profile = GST_RTP_PROFILE_AVP;
3162             break;
3163         }
3164
3165         g_object_set (rtpsession, "rtp-profile", rtp_profile, NULL);
3166
3167         g_object_set (rtpsession, "probation", src->probation, NULL);
3168
3169         g_object_set (rtpsession, "internal-ssrc", stream->send_ssrc, NULL);
3170
3171         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
3172             stream);
3173         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
3174             stream);
3175         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
3176             stream);
3177         g_signal_connect (rtpsession, "on-ssrc-active",
3178             (GCallback) on_ssrc_active, stream);
3179       }
3180     }
3181   }
3182
3183 use_no_manager:
3184   return TRUE;
3185
3186   /* ERRORS */
3187 no_manager:
3188   {
3189     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3190     return FALSE;
3191   }
3192 manager_failed:
3193   {
3194     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
3195     return FALSE;
3196   }
3197 start_manager_failure:
3198   {
3199     GST_DEBUG_OBJECT (src, "could not start session manager");
3200     return FALSE;
3201   }
3202 }
3203
3204 /* free the UDP sources allocated when negotiating a transport.
3205  * This function is called when the server negotiated to a transport where the
3206  * UDP sources are not needed anymore, such as TCP or multicast. */
3207 static void
3208 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
3209 {
3210   gint i;
3211
3212   for (i = 0; i < 2; i++) {
3213     if (stream->udpsrc[i]) {
3214       GST_DEBUG ("free UDP source %d for stream %p", i, stream);
3215       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
3216       gst_object_unref (stream->udpsrc[i]);
3217       stream->udpsrc[i] = NULL;
3218     }
3219   }
3220 }
3221
3222 /* for TCP, create pads to send and receive data to and from the manager and to
3223  * intercept various events and queries
3224  */
3225 static gboolean
3226 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
3227     GstRTSPTransport * transport, GstPad ** outpad)
3228 {
3229   gchar *name;
3230   GstPadTemplate *template;
3231   GstPad *pad0, *pad1;
3232
3233   /* configure for interleaved delivery, nothing needs to be done
3234    * here, the loop function will call the chain functions of the
3235    * session manager. */
3236   stream->channel[0] = transport->interleaved.min;
3237   stream->channel[1] = transport->interleaved.max;
3238   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
3239       stream->channel[0], stream->channel[1]);
3240
3241   /* we can remove the allocated UDP ports now */
3242   gst_rtspsrc_stream_free_udp (stream);
3243
3244   /* no session manager, send data to srcpad directly */
3245   if (!stream->channelpad[0]) {
3246     GST_DEBUG_OBJECT (src, "no manager, creating pad");
3247
3248     /* create a new pad we will use to stream to */
3249     name = g_strdup_printf ("stream_%u", stream->id);
3250     template = gst_static_pad_template_get (&rtptemplate);
3251     stream->channelpad[0] = gst_pad_new_from_template (template, name);
3252     gst_object_unref (template);
3253     g_free (name);
3254
3255     /* set caps and activate */
3256     gst_pad_use_fixed_caps (stream->channelpad[0]);
3257     gst_pad_set_active (stream->channelpad[0], TRUE);
3258
3259     *outpad = gst_object_ref (stream->channelpad[0]);
3260   } else {
3261     GST_DEBUG_OBJECT (src, "using manager source pad");
3262
3263     template = gst_static_pad_template_get (&anysrctemplate);
3264
3265     /* allocate pads for sending the channel data into the manager */
3266     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
3267     gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
3268     gst_object_unref (stream->channelpad[0]);
3269     stream->channelpad[0] = pad0;
3270     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
3271     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
3272     gst_pad_set_element_private (pad0, src);
3273     gst_pad_set_active (pad0, TRUE);
3274
3275     if (stream->channelpad[1]) {
3276       /* if we have a sinkpad for the other channel, create a pad and link to the
3277        * manager. */
3278       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
3279       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
3280       gst_pad_link_full (pad1, stream->channelpad[1],
3281           GST_PAD_LINK_CHECK_NOTHING);
3282       gst_object_unref (stream->channelpad[1]);
3283       stream->channelpad[1] = pad1;
3284       gst_pad_set_active (pad1, TRUE);
3285     }
3286     gst_object_unref (template);
3287   }
3288   /* setup RTCP transport back to the server if we have to. */
3289   if (src->manager && src->do_rtcp) {
3290     GstPad *pad;
3291
3292     template = gst_static_pad_template_get (&anysinktemplate);
3293
3294     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
3295     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
3296     gst_pad_set_element_private (stream->rtcppad, stream);
3297     gst_pad_set_active (stream->rtcppad, TRUE);
3298
3299     /* get session RTCP pad */
3300     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3301     pad = gst_element_get_request_pad (src->manager, name);
3302     g_free (name);
3303
3304     /* and link */
3305     if (pad) {
3306       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3307       gst_object_unref (pad);
3308     }
3309
3310     gst_object_unref (template);
3311   }
3312   return TRUE;
3313 }
3314
3315 static void
3316 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
3317     GstRTSPTransport * transport, const gchar ** destination, gint * min,
3318     gint * max, guint * ttl)
3319 {
3320   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3321     if (destination) {
3322       if (!(*destination = transport->destination))
3323         *destination = stream->destination;
3324     }
3325     if (min && max) {
3326       /* transport first */
3327       *min = transport->port.min;
3328       *max = transport->port.max;
3329       if (*min == -1 && *max == -1) {
3330         /* then try from SDP */
3331         if (stream->port != 0) {
3332           *min = stream->port;
3333           *max = stream->port + 1;
3334         }
3335       }
3336     }
3337
3338     if (ttl) {
3339       if (!(*ttl = transport->ttl))
3340         *ttl = stream->ttl;
3341     }
3342   } else {
3343     if (destination) {
3344       /* first take the source, then the endpoint to figure out where to send
3345        * the RTCP. */
3346       if (!(*destination = transport->source)) {
3347         if (src->conninfo.connection)
3348           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3349         else if (stream->conninfo.connection)
3350           *destination =
3351               gst_rtsp_connection_get_ip (stream->conninfo.connection);
3352       }
3353     }
3354     if (min && max) {
3355       /* for unicast we only expect the ports here */
3356       *min = transport->server_port.min;
3357       *max = transport->server_port.max;
3358     }
3359   }
3360 }
3361
3362 /* For multicast create UDP sources and join the multicast group. */
3363 static gboolean
3364 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3365     GstRTSPTransport * transport, GstPad ** outpad)
3366 {
3367   gchar *uri;
3368   const gchar *destination;
3369   gint min, max;
3370
3371   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3372
3373   /* we can remove the allocated UDP ports now */
3374   gst_rtspsrc_stream_free_udp (stream);
3375
3376   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3377       &max, NULL);
3378
3379   /* we need a destination now */
3380   if (destination == NULL)
3381     goto no_destination;
3382
3383   /* we really need ports now or we won't be able to receive anything at all */
3384   if (min == -1 && max == -1)
3385     goto no_ports;
3386
3387   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3388       destination, min, max);
3389
3390   /* creating UDP source for RTP */
3391   if (min != -1) {
3392     uri = g_strdup_printf ("udp://%s:%d", destination, min);
3393     stream->udpsrc[0] =
3394         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3395     g_free (uri);
3396     if (stream->udpsrc[0] == NULL)
3397       goto no_element;
3398
3399     /* take ownership */
3400     gst_object_ref_sink (stream->udpsrc[0]);
3401
3402     if (src->udp_buffer_size != 0)
3403       g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3404           src->udp_buffer_size, NULL);
3405
3406     if (src->multi_iface != NULL)
3407       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3408           src->multi_iface, NULL);
3409
3410     /* change state */
3411     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3412     gst_element_set_state (stream->udpsrc[0], GST_STATE_READY);
3413   }
3414
3415   /* creating another UDP source for RTCP */
3416   if (max != -1) {
3417     GstCaps *caps;
3418
3419     uri = g_strdup_printf ("udp://%s:%d", destination, max);
3420     stream->udpsrc[1] =
3421         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3422     g_free (uri);
3423     if (stream->udpsrc[1] == NULL)
3424       goto no_element;
3425
3426     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3427         stream->profile == GST_RTSP_PROFILE_SAVPF)
3428       caps = gst_caps_new_empty_simple ("application/x-srtcp");
3429     else
3430       caps = gst_caps_new_empty_simple ("application/x-rtcp");
3431     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3432     gst_caps_unref (caps);
3433
3434     /* take ownership */
3435     gst_object_ref_sink (stream->udpsrc[1]);
3436
3437     if (src->multi_iface != NULL)
3438       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3439           src->multi_iface, NULL);
3440
3441     gst_element_set_state (stream->udpsrc[1], GST_STATE_READY);
3442   }
3443   return TRUE;
3444
3445   /* ERRORS */
3446 no_element:
3447   {
3448     GST_DEBUG_OBJECT (src, "no UDP source element found");
3449     return FALSE;
3450   }
3451 no_destination:
3452   {
3453     GST_DEBUG_OBJECT (src, "no destination found");
3454     return FALSE;
3455   }
3456 no_ports:
3457   {
3458     GST_DEBUG_OBJECT (src, "no ports found");
3459     return FALSE;
3460   }
3461 }
3462
3463 /* configure the remainder of the UDP ports */
3464 static gboolean
3465 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3466     GstRTSPTransport * transport, GstPad ** outpad)
3467 {
3468   /* we manage the UDP elements now. For unicast, the UDP sources where
3469    * allocated in the stream when we suggested a transport. */
3470   if (stream->udpsrc[0]) {
3471     GstCaps *caps;
3472
3473     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3474     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3475
3476     GST_DEBUG_OBJECT (src, "setting up UDP source");
3477
3478     /* configure a timeout on the UDP port. When the timeout message is
3479      * posted, we assume UDP transport is not possible. We reconnect using TCP
3480      * if we can. */
3481     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3482         src->udp_timeout * 1000, NULL);
3483
3484     if ((caps = stream_get_caps_for_pt (stream, stream->default_pt)))
3485       g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3486
3487     /* get output pad of the UDP source. */
3488     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3489
3490     /* save it so we can unblock */
3491     stream->blockedpad = *outpad;
3492
3493     /* configure pad block on the pad. As soon as there is dataflow on the
3494      * UDP source, we know that UDP is not blocked by a firewall and we can
3495      * configure all the streams to let the application autoplug decoders. */
3496     stream->blockid =
3497         gst_pad_add_probe (stream->blockedpad,
3498         GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
3499         GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocked, src, NULL);
3500
3501     if (stream->channelpad[0]) {
3502       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3503       /* configure for UDP delivery, we need to connect the UDP pads to
3504        * the session plugin. */
3505       gst_pad_link_full (*outpad, stream->channelpad[0],
3506           GST_PAD_LINK_CHECK_NOTHING);
3507       gst_object_unref (*outpad);
3508       *outpad = NULL;
3509       /* we connected to pad-added signal to get pads from the manager */
3510     } else {
3511       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3512     }
3513   }
3514
3515   /* RTCP port */
3516   if (stream->udpsrc[1]) {
3517     GstCaps *caps;
3518
3519     gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3520     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3521
3522     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
3523         stream->profile == GST_RTSP_PROFILE_SAVPF)
3524       caps = gst_caps_new_empty_simple ("application/x-srtcp");
3525     else
3526       caps = gst_caps_new_empty_simple ("application/x-rtcp");
3527     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3528     gst_caps_unref (caps);
3529
3530     if (stream->channelpad[1]) {
3531       GstPad *pad;
3532
3533       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3534
3535       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3536       gst_pad_link_full (pad, stream->channelpad[1],
3537           GST_PAD_LINK_CHECK_NOTHING);
3538       gst_object_unref (pad);
3539     } else {
3540       /* leave unlinked */
3541     }
3542   }
3543   return TRUE;
3544 }
3545
3546 /* configure the UDP sink back to the server for status reports */
3547 static gboolean
3548 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3549     GstRTSPStream * stream, GstRTSPTransport * transport)
3550 {
3551   GstPad *pad;
3552   gint rtp_port, rtcp_port;
3553   gboolean do_rtp, do_rtcp;
3554   const gchar *destination;
3555   gchar *uri, *name;
3556   guint ttl = 0;
3557   GSocket *socket;
3558
3559   /* get transport info */
3560   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3561       &rtp_port, &rtcp_port, &ttl);
3562
3563   /* see what we need to do */
3564   do_rtp = (rtp_port != -1);
3565   /* it's possible that the server does not want us to send RTCP in which case
3566    * the port is -1 */
3567   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3568
3569   /* we need a destination when we have RTP or RTCP ports */
3570   if (destination == NULL && (do_rtp || do_rtcp))
3571     goto no_destination;
3572
3573   /* try to construct the fakesrc to the RTP port of the server to open up any
3574    * NAT firewalls */
3575   if (do_rtp) {
3576     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3577         rtp_port);
3578
3579     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3580     stream->udpsink[0] =
3581         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3582     g_free (uri);
3583     if (stream->udpsink[0] == NULL)
3584       goto no_sink_element;
3585
3586     /* don't join multicast group, we will have the source socket do that */
3587     /* no sync or async state changes needed */
3588     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
3589         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3590     if (ttl > 0)
3591       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3592
3593     if (stream->udpsrc[0]) {
3594       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
3595        * so that NAT firewalls will open a hole for us */
3596       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
3597       if (!socket)
3598         goto no_socket;
3599
3600       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
3601       /* configure socket and make sure udpsink does not close it when shutting
3602        * down, it belongs to udpsrc after all. */
3603       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
3604           "close-socket", FALSE, NULL);
3605       g_object_unref (socket);
3606     }
3607
3608     /* the source for the dummy packets to open up NAT */
3609     stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
3610     if (stream->fakesrc == NULL)
3611       goto no_fakesrc_element;
3612
3613     /* random data in 5 buffers, a size of 200 bytes should be fine */
3614     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
3615         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
3616
3617     /* we don't want to consider this a sink */
3618     GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
3619
3620     /* keep everything locked */
3621     gst_element_set_locked_state (stream->udpsink[0], TRUE);
3622     gst_element_set_locked_state (stream->fakesrc, TRUE);
3623
3624     gst_object_ref (stream->udpsink[0]);
3625     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
3626     gst_object_ref (stream->fakesrc);
3627     gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
3628
3629     gst_element_link_pads_full (stream->fakesrc, "src", stream->udpsink[0],
3630         "sink", GST_PAD_LINK_CHECK_NOTHING);
3631   }
3632   if (do_rtcp) {
3633     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
3634         rtcp_port);
3635
3636     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
3637     stream->udpsink[1] =
3638         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3639     g_free (uri);
3640     if (stream->udpsink[1] == NULL)
3641       goto no_sink_element;
3642
3643     /* don't join multicast group, we will have the source socket do that */
3644     /* no sync or async state changes needed */
3645     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
3646         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3647     if (ttl > 0)
3648       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3649
3650     if (stream->udpsrc[1]) {
3651       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
3652        * because some servers check the port number of where it sends RTCP to identify
3653        * the RTCP packets it receives */
3654       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
3655       if (!socket)
3656         goto no_socket;
3657
3658       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
3659       /* configure socket and make sure udpsink does not close it when shutting
3660        * down, it belongs to udpsrc after all. */
3661       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
3662           "close-socket", FALSE, NULL);
3663       g_object_unref (socket);
3664     }
3665
3666     /* we don't want to consider this a sink */
3667     GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
3668
3669     /* we keep this playing always */
3670     gst_element_set_locked_state (stream->udpsink[1], TRUE);
3671     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
3672
3673     gst_object_ref (stream->udpsink[1]);
3674     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
3675
3676     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
3677
3678     /* get session RTCP pad */
3679     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3680     pad = gst_element_get_request_pad (src->manager, name);
3681     g_free (name);
3682
3683     /* and link */
3684     if (pad) {
3685       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3686       gst_object_unref (pad);
3687     }
3688   }
3689
3690   return TRUE;
3691
3692   /* ERRORS */
3693 no_destination:
3694   {
3695     GST_ERROR_OBJECT (src, "no destination address specified");
3696     return FALSE;
3697   }
3698 no_sink_element:
3699   {
3700     GST_ERROR_OBJECT (src, "no UDP sink element found");
3701     return FALSE;
3702   }
3703 no_fakesrc_element:
3704   {
3705     GST_ERROR_OBJECT (src, "no fakesrc element found");
3706     return FALSE;
3707   }
3708 no_socket:
3709   {
3710     GST_ERROR_OBJECT (src, "failed to create socket");
3711     return FALSE;
3712   }
3713 }
3714
3715 /* sets up all elements needed for streaming over the specified transport.
3716  * Does not yet expose the element pads, this will be done when there is actuall
3717  * dataflow detected, which might never happen when UDP is blocked in a
3718  * firewall, for example.
3719  */
3720 static gboolean
3721 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3722     GstRTSPTransport * transport)
3723 {
3724   GstRTSPSrc *src;
3725   GstPad *outpad = NULL;
3726   GstPadTemplate *template;
3727   gchar *name;
3728   const gchar *media_type;
3729   guint i, len;
3730
3731   src = stream->parent;
3732
3733   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3734
3735   /* get the proper media type for this stream now */
3736   if (gst_rtsp_transport_get_media_type (transport, &media_type) < 0)
3737     goto unknown_transport;
3738   if (!media_type)
3739     goto unknown_transport;
3740
3741   /* configure the final media type */
3742   GST_DEBUG_OBJECT (src, "setting media type to %s", media_type);
3743
3744   len = stream->ptmap->len;
3745   for (i = 0; i < len; i++) {
3746     GstStructure *s;
3747     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
3748
3749     if (item->caps == NULL)
3750       continue;
3751
3752     s = gst_caps_get_structure (item->caps, 0);
3753     gst_structure_set_name (s, media_type);
3754     /* set ssrc if known */
3755     if (transport->ssrc)
3756       gst_structure_set (s, "ssrc", G_TYPE_UINT, transport->ssrc, NULL);
3757   }
3758
3759   /* try to get and configure a manager, channelpad[0-1] will be configured with
3760    * the pads for the manager, or NULL when no manager is needed. */
3761   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3762     goto no_manager;
3763
3764   switch (transport->lower_transport) {
3765     case GST_RTSP_LOWER_TRANS_TCP:
3766       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3767         goto transport_failed;
3768       break;
3769     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3770       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3771         goto transport_failed;
3772       /* fallthrough, the rest is the same for UDP and MCAST */
3773     case GST_RTSP_LOWER_TRANS_UDP:
3774       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
3775         goto transport_failed;
3776       /* configure udpsinks back to the server for RTCP messages and for the
3777        * dummy RTP messages to open NAT. */
3778       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
3779         goto transport_failed;
3780       break;
3781     default:
3782       goto unknown_transport;
3783   }
3784
3785   if (outpad) {
3786     GST_DEBUG_OBJECT (src, "creating ghostpad");
3787
3788     gst_pad_use_fixed_caps (outpad);
3789
3790     /* create ghostpad, don't add just yet, this will be done when we activate
3791      * the stream. */
3792     name = g_strdup_printf ("stream_%u", stream->id);
3793     template = gst_static_pad_template_get (&rtptemplate);
3794     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3795     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3796     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3797     gst_object_unref (template);
3798     g_free (name);
3799
3800     gst_object_unref (outpad);
3801   }
3802   /* mark pad as ok */
3803   stream->last_ret = GST_FLOW_OK;
3804
3805   return TRUE;
3806
3807   /* ERRORS */
3808 transport_failed:
3809   {
3810     GST_DEBUG_OBJECT (src, "failed to configure transport");
3811     return FALSE;
3812   }
3813 unknown_transport:
3814   {
3815     GST_DEBUG_OBJECT (src, "unknown transport");
3816     return FALSE;
3817   }
3818 no_manager:
3819   {
3820     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3821     return FALSE;
3822   }
3823 }
3824
3825 /* send a couple of dummy random packets on the receiver RTP port to the server,
3826  * this should make a firewall think we initiated the data transfer and
3827  * hopefully allow packets to go from the sender port to our RTP receiver port */
3828 static gboolean
3829 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3830 {
3831   GList *walk;
3832
3833   if (src->nat_method != GST_RTSP_NAT_DUMMY)
3834     return TRUE;
3835
3836   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3837     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3838
3839     if (stream->fakesrc && stream->udpsink[0]) {
3840       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3841       gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3842       gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3843       gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3844       gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3845     }
3846   }
3847   return TRUE;
3848 }
3849
3850 /* Adds the source pads of all configured streams to the element.
3851  * This code is performed when we detected dataflow.
3852  *
3853  * We detect dataflow from either the _loop function or with pad probes on the
3854  * udp sources.
3855  */
3856 static gboolean
3857 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3858 {
3859   GList *walk;
3860
3861   GST_DEBUG_OBJECT (src, "activating streams");
3862
3863   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3864     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3865
3866     if (stream->udpsrc[0]) {
3867       /* remove timeout, we are streaming now and timeouts will be handled by
3868        * the session manager and jitter buffer */
3869       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3870     }
3871     if (stream->srcpad) {
3872       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3873       gst_pad_set_active (stream->srcpad, TRUE);
3874
3875       /* if we don't have a session manager, set the caps now. If we have a
3876        * session, we will get a notification of the pad and the caps. */
3877       if (!src->manager) {
3878         GstCaps *caps;
3879
3880         caps = stream_get_caps_for_pt (stream, stream->default_pt);
3881         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3882         gst_pad_set_caps (stream->srcpad, caps);
3883       }
3884       /* add the pad */
3885       if (!stream->added) {
3886         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3887         gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3888         stream->added = TRUE;
3889       }
3890     }
3891   }
3892
3893   /* unblock all pads */
3894   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3895     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3896
3897     if (stream->blockid) {
3898       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3899       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3900       stream->blockid = 0;
3901     }
3902   }
3903
3904   return TRUE;
3905 }
3906
3907 static void
3908 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
3909     gboolean reset_manager)
3910 {
3911   GList *walk;
3912   guint64 start, stop;
3913   gdouble play_speed, play_scale;
3914
3915   GST_DEBUG_OBJECT (src, "configuring stream caps");
3916
3917   start = segment->position;
3918   stop = segment->duration;
3919   play_speed = segment->rate;
3920   play_scale = segment->applied_rate;
3921
3922   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3923     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3924     guint j, len;
3925
3926     if (!stream->setup)
3927       continue;
3928
3929     len = stream->ptmap->len;
3930     for (j = 0; j < len; j++) {
3931       GstCaps *caps;
3932       PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, j);
3933
3934       if (item->caps == NULL)
3935         continue;
3936
3937       caps = gst_caps_make_writable (item->caps);
3938       /* update caps */
3939       if (stream->timebase != -1)
3940         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
3941             (guint) stream->timebase, NULL);
3942       if (stream->seqbase != -1)
3943         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
3944             (guint) stream->seqbase, NULL);
3945       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
3946       if (stop != -1)
3947         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
3948       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
3949       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
3950
3951       item->caps = caps;
3952       GST_DEBUG_OBJECT (src, "stream %p, pt %d, caps %" GST_PTR_FORMAT, stream,
3953           item->pt, caps);
3954
3955       if (item->pt == stream->default_pt) {
3956         if (stream->udpsrc[0])
3957           g_object_set (stream->udpsrc[0], "caps", caps, NULL);
3958         stream->need_caps = TRUE;
3959       }
3960     }
3961   }
3962   if (reset_manager && src->manager) {
3963     GST_DEBUG_OBJECT (src, "clear session");
3964     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
3965   }
3966 }
3967
3968 static GstFlowReturn
3969 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
3970     GstFlowReturn ret)
3971 {
3972   GList *streams;
3973
3974   /* store the value */
3975   stream->last_ret = ret;
3976
3977   /* if it's success we can return the value right away */
3978   if (ret == GST_FLOW_OK)
3979     goto done;
3980
3981   /* any other error that is not-linked can be returned right
3982    * away */
3983   if (ret != GST_FLOW_NOT_LINKED)
3984     goto done;
3985
3986   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3987   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3988     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3989
3990     ret = ostream->last_ret;
3991     /* some other return value (must be SUCCESS but we can return
3992      * other values as well) */
3993     if (ret != GST_FLOW_NOT_LINKED)
3994       goto done;
3995   }
3996   /* if we get here, all other pads were unlinked and we return
3997    * NOT_LINKED then */
3998 done:
3999   return ret;
4000 }
4001
4002 static gboolean
4003 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
4004     GstEvent * event)
4005 {
4006   gboolean res = TRUE;
4007
4008   /* only streams that have a connection to the outside world */
4009   if (!stream->setup)
4010     goto done;
4011
4012   if (stream->udpsrc[0]) {
4013     gst_event_ref (event);
4014     res = gst_element_send_event (stream->udpsrc[0], event);
4015   } else if (stream->channelpad[0]) {
4016     gst_event_ref (event);
4017     if (GST_PAD_IS_SRC (stream->channelpad[0]))
4018       res = gst_pad_push_event (stream->channelpad[0], event);
4019     else
4020       res = gst_pad_send_event (stream->channelpad[0], event);
4021   }
4022
4023   if (stream->udpsrc[1]) {
4024     gst_event_ref (event);
4025     res &= gst_element_send_event (stream->udpsrc[1], event);
4026   } else if (stream->channelpad[1]) {
4027     gst_event_ref (event);
4028     if (GST_PAD_IS_SRC (stream->channelpad[1]))
4029       res &= gst_pad_push_event (stream->channelpad[1], event);
4030     else
4031       res &= gst_pad_send_event (stream->channelpad[1], event);
4032   }
4033
4034 done:
4035   gst_event_unref (event);
4036
4037   return res;
4038 }
4039
4040 static gboolean
4041 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
4042 {
4043   GList *streams;
4044   gboolean res = TRUE;
4045
4046   for (streams = src->streams; streams; streams = g_list_next (streams)) {
4047     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4048
4049     gst_event_ref (event);
4050     res &= gst_rtspsrc_stream_push_event (src, ostream, event);
4051   }
4052   gst_event_unref (event);
4053
4054   return res;
4055 }
4056
4057 static GstRTSPResult
4058 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4059     gboolean async)
4060 {
4061   GstRTSPResult res;
4062   GstRTSPMessage response;
4063   gboolean retry = FALSE;
4064   memset (&response, 0, sizeof (response));
4065   gst_rtsp_message_init (&response);
4066   do {
4067     if (info->connection == NULL) {
4068       if (info->url == NULL) {
4069         GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
4070         if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
4071           goto parse_error;
4072       }
4073       /* create connection */
4074       GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
4075       if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
4076         goto could_not_create;
4077
4078       if (retry) {
4079         gst_rtspsrc_setup_auth (src, &response);
4080       }
4081
4082       g_free (info->url_str);
4083       info->url_str = gst_rtsp_url_get_request_uri (info->url);
4084
4085       GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
4086
4087       if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
4088         if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
4089                 src->tls_validation_flags))
4090           GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
4091
4092         if (src->tls_database)
4093           gst_rtsp_connection_set_tls_database (info->connection,
4094               src->tls_database);
4095
4096         if (src->tls_interaction)
4097           gst_rtsp_connection_set_tls_interaction (info->connection,
4098               src->tls_interaction);
4099       }
4100
4101       if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
4102         gst_rtsp_connection_set_tunneled (info->connection, TRUE);
4103
4104       if (src->proxy_host) {
4105         GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
4106             src->proxy_port);
4107         gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
4108             src->proxy_port);
4109       }
4110     }
4111
4112     if (!info->connected) {
4113       /* connect */
4114       if (async)
4115         GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
4116             ("Connecting to %s", info->location));
4117       GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
4118       res = gst_rtsp_connection_connect_with_response (info->connection,
4119           src->ptcp_timeout, &response);
4120
4121       if (response.type == GST_RTSP_MESSAGE_HTTP_RESPONSE &&
4122           response.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4123         gst_rtsp_conninfo_close (src, info, TRUE);
4124         if (!retry)
4125           retry = TRUE;
4126         else
4127           retry = FALSE;        // we should not retry more than once
4128       } else {
4129         retry = FALSE;
4130       }
4131
4132       if (res == GST_RTSP_OK)
4133         info->connected = TRUE;
4134       else if (!retry)
4135         goto could_not_connect;
4136     }
4137   } while (!info->connected && retry);
4138   gst_rtsp_message_unset (&response);
4139   return GST_RTSP_OK;
4140
4141   /* ERRORS */
4142 parse_error:
4143   {
4144     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
4145     gst_rtsp_message_unset (&response);
4146     return res;
4147   }
4148 could_not_create:
4149   {
4150     gchar *str = gst_rtsp_strresult (res);
4151     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
4152     g_free (str);
4153     gst_rtsp_message_unset (&response);
4154     return res;
4155   }
4156 could_not_connect:
4157   {
4158     gchar *str = gst_rtsp_strresult (res);
4159     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
4160     g_free (str);
4161     gst_rtsp_message_unset (&response);
4162     return res;
4163   }
4164 }
4165
4166 static GstRTSPResult
4167 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
4168     gboolean free)
4169 {
4170   GST_RTSP_STATE_LOCK (src);
4171   if (info->connected) {
4172     GST_DEBUG_OBJECT (src, "closing connection...");
4173     gst_rtsp_connection_close (info->connection);
4174     info->connected = FALSE;
4175   }
4176   if (free && info->connection) {
4177     /* free connection */
4178     GST_DEBUG_OBJECT (src, "freeing connection...");
4179     gst_rtsp_connection_free (info->connection);
4180     info->connection = NULL;
4181   }
4182   GST_RTSP_STATE_UNLOCK (src);
4183   return GST_RTSP_OK;
4184 }
4185
4186 static GstRTSPResult
4187 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
4188     gboolean async)
4189 {
4190   GstRTSPResult res;
4191
4192   GST_DEBUG_OBJECT (src, "reconnecting connection...");
4193   gst_rtsp_conninfo_close (src, info, FALSE);
4194   res = gst_rtsp_conninfo_connect (src, info, async);
4195
4196   return res;
4197 }
4198
4199 static void
4200 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
4201 {
4202   GList *walk;
4203
4204   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
4205   GST_RTSP_STATE_LOCK (src);
4206   if (src->conninfo.connection && src->conninfo.flushing != flush) {
4207     GST_DEBUG_OBJECT (src, "connection flush");
4208     gst_rtsp_connection_flush (src->conninfo.connection, flush);
4209     src->conninfo.flushing = flush;
4210   }
4211   for (walk = src->streams; walk; walk = g_list_next (walk)) {
4212     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
4213     if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
4214       GST_DEBUG_OBJECT (src, "stream %p flush", stream);
4215       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
4216       stream->conninfo.flushing = flush;
4217     }
4218   }
4219   GST_RTSP_STATE_UNLOCK (src);
4220 }
4221
4222 static GstRTSPResult
4223 gst_rtspsrc_init_request (GstRTSPSrc * src, GstRTSPMessage * msg,
4224     GstRTSPMethod method, const gchar * uri)
4225 {
4226   GstRTSPResult res;
4227
4228   res = gst_rtsp_message_init_request (msg, method, uri);
4229   if (res < 0)
4230     return res;
4231
4232   /* set user-agent */
4233   if (src->user_agent)
4234     gst_rtsp_message_add_header (msg, GST_RTSP_HDR_USER_AGENT, src->user_agent);
4235
4236   return res;
4237 }
4238
4239 /* FIXME, handle server request, reply with OK, for now */
4240 static GstRTSPResult
4241 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
4242     GstRTSPMessage * request)
4243 {
4244   GstRTSPMessage response = { 0 };
4245   GstRTSPResult res;
4246
4247   GST_DEBUG_OBJECT (src, "got server request message");
4248
4249   if (src->debug)
4250     gst_rtsp_message_dump (request);
4251
4252   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
4253
4254   if (res == GST_RTSP_ENOTIMPL) {
4255     /* default implementation, send OK */
4256     GST_DEBUG_OBJECT (src, "prepare OK reply");
4257     res =
4258         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
4259         request);
4260     if (res < 0)
4261       goto send_error;
4262
4263     /* let app parse and reply */
4264     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
4265         0, request, &response);
4266
4267     if (src->debug)
4268       gst_rtsp_message_dump (&response);
4269
4270     res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
4271     if (res < 0)
4272       goto send_error;
4273
4274     gst_rtsp_message_unset (&response);
4275   } else if (res == GST_RTSP_EEOF)
4276     return res;
4277
4278   return GST_RTSP_OK;
4279
4280   /* ERRORS */
4281 send_error:
4282   {
4283     gst_rtsp_message_unset (&response);
4284     return res;
4285   }
4286 }
4287
4288 /* send server keep-alive */
4289 static GstRTSPResult
4290 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
4291 {
4292   GstRTSPMessage request = { 0 };
4293   GstRTSPResult res;
4294   GstRTSPMethod method;
4295   const gchar *control;
4296
4297   if (src->do_rtsp_keep_alive == FALSE) {
4298     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
4299     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4300     return GST_RTSP_OK;
4301   }
4302
4303   GST_DEBUG_OBJECT (src, "creating server keep-alive");
4304
4305   /* find a method to use for keep-alive */
4306   if (src->methods & GST_RTSP_GET_PARAMETER)
4307     method = GST_RTSP_GET_PARAMETER;
4308   else
4309     method = GST_RTSP_OPTIONS;
4310
4311   control = get_aggregate_control (src);
4312   if (control == NULL)
4313     goto no_control;
4314
4315   res = gst_rtspsrc_init_request (src, &request, method, control);
4316   if (res < 0)
4317     goto send_error;
4318
4319   if (src->debug)
4320     gst_rtsp_message_dump (&request);
4321
4322   res =
4323       gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
4324       NULL);
4325   if (res < 0)
4326     goto send_error;
4327
4328   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
4329   gst_rtsp_message_unset (&request);
4330
4331   return GST_RTSP_OK;
4332
4333   /* ERRORS */
4334 no_control:
4335   {
4336     GST_WARNING_OBJECT (src, "no control url to send keepalive");
4337     return GST_RTSP_OK;
4338   }
4339 send_error:
4340   {
4341     gchar *str = gst_rtsp_strresult (res);
4342
4343     gst_rtsp_message_unset (&request);
4344     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
4345         ("Could not send keep-alive. (%s)", str));
4346     g_free (str);
4347     return res;
4348   }
4349 }
4350
4351 static GstFlowReturn
4352 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
4353 {
4354   GstFlowReturn ret = GST_FLOW_OK;
4355   gint channel;
4356   GstRTSPStream *stream;
4357   GstPad *outpad = NULL;
4358   guint8 *data;
4359   guint size;
4360   GstBuffer *buf;
4361   gboolean is_rtcp;
4362
4363   channel = message->type_data.data.channel;
4364
4365   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
4366   if (!stream)
4367     goto unknown_stream;
4368
4369   if (channel == stream->channel[0]) {
4370     outpad = stream->channelpad[0];
4371     is_rtcp = FALSE;
4372   } else if (channel == stream->channel[1]) {
4373     outpad = stream->channelpad[1];
4374     is_rtcp = TRUE;
4375   } else {
4376     is_rtcp = FALSE;
4377   }
4378
4379   /* take a look at the body to figure out what we have */
4380   gst_rtsp_message_get_body (message, &data, &size);
4381   if (size < 2)
4382     goto invalid_length;
4383
4384   /* channels are not correct on some servers, do extra check */
4385   if (data[1] >= 200 && data[1] <= 204) {
4386     /* hmm RTCP message switch to the RTCP pad of the same stream. */
4387     outpad = stream->channelpad[1];
4388     is_rtcp = TRUE;
4389   }
4390
4391   /* we have no clue what this is, just ignore then. */
4392   if (outpad == NULL)
4393     goto unknown_stream;
4394
4395   /* take the message body for further processing */
4396   gst_rtsp_message_steal_body (message, &data, &size);
4397
4398   /* strip the trailing \0 */
4399   size -= 1;
4400
4401   buf = gst_buffer_new ();
4402   gst_buffer_append_memory (buf,
4403       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
4404
4405   /* don't need message anymore */
4406   gst_rtsp_message_unset (message);
4407
4408   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
4409       channel);
4410
4411   if (src->need_activate) {
4412     gchar *stream_id;
4413     GstEvent *event;
4414     GChecksum *cs;
4415     gchar *uri;
4416     GList *streams;
4417     guint group_id = gst_util_group_id_next ();
4418
4419     /* generate an SHA256 sum of the URI */
4420     cs = g_checksum_new (G_CHECKSUM_SHA256);
4421     uri = src->conninfo.location;
4422     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4423
4424     for (streams = src->streams; streams; streams = g_list_next (streams)) {
4425       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4426       GstCaps *caps;
4427
4428       stream_id =
4429           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4430       event = gst_event_new_stream_start (stream_id);
4431       gst_event_set_group_id (event, group_id);
4432
4433       g_free (stream_id);
4434       gst_rtspsrc_stream_push_event (src, ostream, event);
4435
4436       if ((caps = stream_get_caps_for_pt (ostream, ostream->default_pt))) {
4437         /* only streams that have a connection to the outside world */
4438         if (ostream->setup) {
4439           if (ostream->udpsrc[0]) {
4440             gst_element_send_event (ostream->udpsrc[0],
4441                 gst_event_new_caps (caps));
4442           } else if (ostream->channelpad[0]) {
4443             if (GST_PAD_IS_SRC (ostream->channelpad[0]))
4444               gst_pad_push_event (ostream->channelpad[0],
4445                   gst_event_new_caps (caps));
4446             else
4447               gst_pad_send_event (ostream->channelpad[0],
4448                   gst_event_new_caps (caps));
4449           }
4450           ostream->need_caps = FALSE;
4451
4452           if (ostream->profile == GST_RTSP_PROFILE_SAVP ||
4453               ostream->profile == GST_RTSP_PROFILE_SAVPF)
4454             caps = gst_caps_new_empty_simple ("application/x-srtcp");
4455           else
4456             caps = gst_caps_new_empty_simple ("application/x-rtcp");
4457
4458           if (ostream->udpsrc[1]) {
4459             gst_element_send_event (ostream->udpsrc[1],
4460                 gst_event_new_caps (caps));
4461           } else if (ostream->channelpad[1]) {
4462             if (GST_PAD_IS_SRC (ostream->channelpad[1]))
4463               gst_pad_push_event (ostream->channelpad[1],
4464                   gst_event_new_caps (caps));
4465             else
4466               gst_pad_send_event (ostream->channelpad[1],
4467                   gst_event_new_caps (caps));
4468           }
4469
4470           gst_caps_unref (caps);
4471         }
4472       }
4473     }
4474     g_checksum_free (cs);
4475
4476     gst_rtspsrc_activate_streams (src);
4477     src->need_activate = FALSE;
4478     src->need_segment = TRUE;
4479   }
4480
4481   if (src->base_time == -1) {
4482     /* Take current running_time. This timestamp will be put on
4483      * the first buffer of each stream because we are a live source and so we
4484      * timestamp with the running_time. When we are dealing with TCP, we also
4485      * only timestamp the first buffer (using the DISCONT flag) because a server
4486      * typically bursts data, for which we don't want to compensate by speeding
4487      * up the media. The other timestamps will be interpollated from this one
4488      * using the RTP timestamps. */
4489     GST_OBJECT_LOCK (src);
4490     if (GST_ELEMENT_CLOCK (src)) {
4491       GstClockTime now;
4492       GstClockTime base_time;
4493
4494       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4495       base_time = GST_ELEMENT_CAST (src)->base_time;
4496
4497       src->base_time = now - base_time;
4498
4499       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4500           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4501     }
4502     GST_OBJECT_UNLOCK (src);
4503   }
4504
4505   /* If needed send a new segment, don't forget we are live and buffer are
4506    * timestamped with running time */
4507   if (src->need_segment) {
4508     GstSegment segment;
4509     src->need_segment = FALSE;
4510     gst_segment_init (&segment, GST_FORMAT_TIME);
4511     gst_rtspsrc_push_event (src, gst_event_new_segment (&segment));
4512   }
4513
4514   if (stream->need_caps) {
4515     GstCaps *caps;
4516
4517     if ((caps = stream_get_caps_for_pt (stream, stream->default_pt))) {
4518       /* only streams that have a connection to the outside world */
4519       if (stream->setup) {
4520         /* Only need to update the TCP caps here, UDP is already handled */
4521         if (stream->channelpad[0]) {
4522           if (GST_PAD_IS_SRC (stream->channelpad[0]))
4523             gst_pad_push_event (stream->channelpad[0],
4524                 gst_event_new_caps (caps));
4525           else
4526             gst_pad_send_event (stream->channelpad[0],
4527                 gst_event_new_caps (caps));
4528         }
4529         stream->need_caps = FALSE;
4530       }
4531     }
4532
4533     stream->need_caps = FALSE;
4534   }
4535
4536   if (stream->discont && !is_rtcp) {
4537     /* mark first RTP buffer as discont */
4538     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4539     stream->discont = FALSE;
4540     /* first buffer gets the timestamp, other buffers are not timestamped and
4541      * their presentation time will be interpollated from the rtp timestamps. */
4542     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4543         GST_TIME_ARGS (src->base_time));
4544
4545     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4546   }
4547
4548   /* chain to the peer pad */
4549   if (GST_PAD_IS_SINK (outpad))
4550     ret = gst_pad_chain (outpad, buf);
4551   else
4552     ret = gst_pad_push (outpad, buf);
4553
4554   if (!is_rtcp) {
4555     /* combine all stream flows for the data transport */
4556     ret = gst_rtspsrc_combine_flows (src, stream, ret);
4557   }
4558   return ret;
4559
4560   /* ERRORS */
4561 unknown_stream:
4562   {
4563     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4564     gst_rtsp_message_unset (message);
4565     return GST_FLOW_OK;
4566   }
4567 invalid_length:
4568   {
4569     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4570         ("Short message received, ignoring."));
4571     gst_rtsp_message_unset (message);
4572     return GST_FLOW_OK;
4573   }
4574 }
4575
4576 static GstFlowReturn
4577 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4578 {
4579   GstRTSPMessage message = { 0 };
4580   GstRTSPResult res;
4581   GstFlowReturn ret = GST_FLOW_OK;
4582   GTimeVal tv_timeout;
4583
4584   while (TRUE) {
4585     /* get the next timeout interval */
4586     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4587
4588     /* see if the timeout period expired */
4589     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4590       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4591       /* send keep-alive, only act on interrupt, a warning will be posted for
4592        * other errors. */
4593       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4594         goto interrupt;
4595       /* get new timeout */
4596       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4597     }
4598
4599     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4600         tv_timeout.tv_sec, tv_timeout.tv_usec);
4601
4602     /* protect the connection with the connection lock so that we can see when
4603      * we are finished doing server communication */
4604     res =
4605         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4606         &message, src->ptcp_timeout);
4607
4608     switch (res) {
4609       case GST_RTSP_OK:
4610         GST_DEBUG_OBJECT (src, "we received a server message");
4611         break;
4612       case GST_RTSP_EINTR:
4613         /* we got interrupted this means we need to stop */
4614         goto interrupt;
4615       case GST_RTSP_ETIMEOUT:
4616         /* no reply, send keep alive */
4617         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4618         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4619           goto interrupt;
4620         continue;
4621       case GST_RTSP_EEOF:
4622         /* go EOS when the server closed the connection */
4623         goto server_eof;
4624       default:
4625         goto receive_error;
4626     }
4627
4628     switch (message.type) {
4629       case GST_RTSP_MESSAGE_REQUEST:
4630         /* server sends us a request message, handle it */
4631         res =
4632             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4633             &message);
4634         if (res == GST_RTSP_EEOF)
4635           goto server_eof;
4636         else if (res < 0)
4637           goto handle_request_failed;
4638         break;
4639       case GST_RTSP_MESSAGE_RESPONSE:
4640         /* we ignore response messages */
4641         GST_DEBUG_OBJECT (src, "ignoring response message");
4642         if (src->debug)
4643           gst_rtsp_message_dump (&message);
4644         break;
4645       case GST_RTSP_MESSAGE_DATA:
4646         GST_DEBUG_OBJECT (src, "got data message");
4647         ret = gst_rtspsrc_handle_data (src, &message);
4648         if (ret != GST_FLOW_OK)
4649           goto handle_data_failed;
4650         break;
4651       default:
4652         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4653             message.type);
4654         break;
4655     }
4656   }
4657   g_assert_not_reached ();
4658
4659   /* ERRORS */
4660 server_eof:
4661   {
4662     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4663     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4664         ("The server closed the connection."));
4665     src->conninfo.connected = FALSE;
4666     gst_rtsp_message_unset (&message);
4667     return GST_FLOW_EOS;
4668   }
4669 interrupt:
4670   {
4671     gst_rtsp_message_unset (&message);
4672     GST_DEBUG_OBJECT (src, "got interrupted");
4673     return GST_FLOW_FLUSHING;
4674   }
4675 receive_error:
4676   {
4677     gchar *str = gst_rtsp_strresult (res);
4678
4679     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4680         ("Could not receive message. (%s)", str));
4681     g_free (str);
4682
4683     gst_rtsp_message_unset (&message);
4684     return GST_FLOW_ERROR;
4685   }
4686 handle_request_failed:
4687   {
4688     gchar *str = gst_rtsp_strresult (res);
4689
4690     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4691         ("Could not handle server message. (%s)", str));
4692     g_free (str);
4693     gst_rtsp_message_unset (&message);
4694     return GST_FLOW_ERROR;
4695   }
4696 handle_data_failed:
4697   {
4698     GST_DEBUG_OBJECT (src, "could no handle data message");
4699     return ret;
4700   }
4701 }
4702
4703 static GstFlowReturn
4704 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4705 {
4706   GstRTSPResult res;
4707   GstRTSPMessage message = { 0 };
4708   gint retry = 0;
4709
4710   while (TRUE) {
4711     GTimeVal tv_timeout;
4712
4713     /* get the next timeout interval */
4714     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4715
4716     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4717         (gint) tv_timeout.tv_sec);
4718
4719     gst_rtsp_message_unset (&message);
4720
4721     /* we should continue reading the TCP socket because the server might
4722      * send us requests. When the session timeout expires, we need to send a
4723      * keep-alive request to keep the session open. */
4724     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4725         &message, &tv_timeout);
4726
4727     switch (res) {
4728       case GST_RTSP_OK:
4729         GST_DEBUG_OBJECT (src, "we received a server message");
4730         break;
4731       case GST_RTSP_EINTR:
4732         /* we got interrupted, see what we have to do */
4733         goto interrupt;
4734       case GST_RTSP_ETIMEOUT:
4735         /* send keep-alive, ignore the result, a warning will be posted. */
4736         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4737         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4738           goto interrupt;
4739         continue;
4740       case GST_RTSP_EEOF:
4741         /* server closed the connection. not very fatal for UDP, reconnect and
4742          * see what happens. */
4743         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4744             ("The server closed the connection."));
4745         if (src->udp_reconnect) {
4746           if ((res =
4747                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4748             goto connect_error;
4749         } else {
4750           goto server_eof;
4751         }
4752         continue;
4753       case GST_RTSP_ENET:
4754         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4755       default:
4756         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4757             ("Unhandled return value %d.", res));
4758         goto receive_error;
4759     }
4760
4761     switch (message.type) {
4762       case GST_RTSP_MESSAGE_REQUEST:
4763         /* server sends us a request message, handle it */
4764         res =
4765             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4766             &message);
4767         if (res == GST_RTSP_EEOF)
4768           goto server_eof;
4769         else if (res < 0)
4770           goto handle_request_failed;
4771         break;
4772       case GST_RTSP_MESSAGE_RESPONSE:
4773         /* we ignore response and data messages */
4774         GST_DEBUG_OBJECT (src, "ignoring response message");
4775         if (src->debug)
4776           gst_rtsp_message_dump (&message);
4777         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4778           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4779           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4780             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4781             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4782               goto interrupt;
4783           }
4784         } else {
4785           retry = 0;
4786         }
4787         break;
4788       case GST_RTSP_MESSAGE_DATA:
4789         /* we ignore response and data messages */
4790         GST_DEBUG_OBJECT (src, "ignoring data message");
4791         break;
4792       default:
4793         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4794             message.type);
4795         break;
4796     }
4797   }
4798   g_assert_not_reached ();
4799
4800   /* we get here when the connection got interrupted */
4801 interrupt:
4802   {
4803     gst_rtsp_message_unset (&message);
4804     GST_DEBUG_OBJECT (src, "got interrupted");
4805     return GST_FLOW_FLUSHING;
4806   }
4807 connect_error:
4808   {
4809     gchar *str = gst_rtsp_strresult (res);
4810     GstFlowReturn ret;
4811
4812     src->conninfo.connected = FALSE;
4813     if (res != GST_RTSP_EINTR) {
4814       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4815           ("Could not connect to server. (%s)", str));
4816       g_free (str);
4817       ret = GST_FLOW_ERROR;
4818     } else {
4819       ret = GST_FLOW_FLUSHING;
4820     }
4821     return ret;
4822   }
4823 receive_error:
4824   {
4825     gchar *str = gst_rtsp_strresult (res);
4826
4827     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4828         ("Could not receive message. (%s)", str));
4829     g_free (str);
4830     return GST_FLOW_ERROR;
4831   }
4832 handle_request_failed:
4833   {
4834     gchar *str = gst_rtsp_strresult (res);
4835     GstFlowReturn ret;
4836
4837     gst_rtsp_message_unset (&message);
4838     if (res != GST_RTSP_EINTR) {
4839       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4840           ("Could not handle server message. (%s)", str));
4841       g_free (str);
4842       ret = GST_FLOW_ERROR;
4843     } else {
4844       ret = GST_FLOW_FLUSHING;
4845     }
4846     return ret;
4847   }
4848 server_eof:
4849   {
4850     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4851     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4852         ("The server closed the connection."));
4853     src->conninfo.connected = FALSE;
4854     gst_rtsp_message_unset (&message);
4855     return GST_FLOW_EOS;
4856   }
4857 }
4858
4859 static GstRTSPResult
4860 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4861 {
4862   GstRTSPResult res = GST_RTSP_OK;
4863   gboolean restart;
4864
4865   GST_DEBUG_OBJECT (src, "doing reconnect");
4866
4867   GST_OBJECT_LOCK (src);
4868   /* only restart when the pads were not yet activated, else we were
4869    * streaming over UDP */
4870   restart = src->need_activate;
4871   GST_OBJECT_UNLOCK (src);
4872
4873   /* no need to restart, we're done */
4874   if (!restart)
4875     goto done;
4876
4877   /* we can try only TCP now */
4878   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4879
4880   /* close and cleanup our state */
4881   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4882     goto done;
4883
4884   /* see if we have TCP left to try. Also don't try TCP when we were configured
4885    * with an SDP. */
4886   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4887     goto no_protocols;
4888
4889   /* We post a warning message now to inform the user
4890    * that nothing happened. It's most likely a firewall thing. */
4891   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4892       ("Could not receive any UDP packets for %.4f seconds, maybe your "
4893           "firewall is blocking it. Retrying using a TCP connection.",
4894           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4895
4896   /* open new connection using tcp */
4897   if (gst_rtspsrc_open (src, async) < 0)
4898     goto open_failed;
4899
4900   /* start playback */
4901   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4902     goto play_failed;
4903
4904 done:
4905   return res;
4906
4907   /* ERRORS */
4908 no_protocols:
4909   {
4910     src->cur_protocols = 0;
4911     /* no transport possible, post an error and stop */
4912     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4913         ("Could not receive any UDP packets for %.4f seconds, maybe your "
4914             "firewall is blocking it. No other protocols to try.",
4915             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4916     return GST_RTSP_ERROR;
4917   }
4918 open_failed:
4919   {
4920     GST_DEBUG_OBJECT (src, "open failed");
4921     return GST_RTSP_OK;
4922   }
4923 play_failed:
4924   {
4925     GST_DEBUG_OBJECT (src, "play failed");
4926     return GST_RTSP_OK;
4927   }
4928 }
4929
4930 static void
4931 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4932 {
4933   switch (cmd) {
4934     case CMD_OPEN:
4935       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4936       break;
4937     case CMD_PLAY:
4938       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4939       break;
4940     case CMD_PAUSE:
4941       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4942       break;
4943     case CMD_CLOSE:
4944       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4945       break;
4946     default:
4947       break;
4948   }
4949 }
4950
4951 static void
4952 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4953 {
4954   switch (cmd) {
4955     case CMD_OPEN:
4956       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4957       break;
4958     case CMD_PLAY:
4959       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4960       break;
4961     case CMD_PAUSE:
4962       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4963       break;
4964     case CMD_CLOSE:
4965       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4966       break;
4967     default:
4968       break;
4969   }
4970 }
4971
4972 static void
4973 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4974 {
4975   switch (cmd) {
4976     case CMD_OPEN:
4977       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4978       break;
4979     case CMD_PLAY:
4980       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4981       break;
4982     case CMD_PAUSE:
4983       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4984       break;
4985     case CMD_CLOSE:
4986       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4987       break;
4988     default:
4989       break;
4990   }
4991 }
4992
4993 static void
4994 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4995 {
4996   switch (cmd) {
4997     case CMD_OPEN:
4998       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4999       break;
5000     case CMD_PLAY:
5001       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
5002       break;
5003     case CMD_PAUSE:
5004       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
5005       break;
5006     case CMD_CLOSE:
5007       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
5008       break;
5009     default:
5010       break;
5011   }
5012 }
5013
5014 static void
5015 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
5016 {
5017   if (ret == GST_RTSP_OK)
5018     gst_rtspsrc_loop_complete_cmd (src, cmd);
5019   else if (ret == GST_RTSP_EINTR)
5020     gst_rtspsrc_loop_cancel_cmd (src, cmd);
5021   else
5022     gst_rtspsrc_loop_error_cmd (src, cmd);
5023 }
5024
5025 static gboolean
5026 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
5027 {
5028   gint old;
5029   gboolean flushed = FALSE;
5030
5031   /* start new request */
5032   gst_rtspsrc_loop_start_cmd (src, cmd);
5033
5034   GST_DEBUG_OBJECT (src, "sending cmd %s", cmd_to_string (cmd));
5035
5036   GST_OBJECT_LOCK (src);
5037   old = src->pending_cmd;
5038   if (old == CMD_RECONNECT) {
5039     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
5040     cmd = CMD_RECONNECT;
5041   }
5042   if (old != CMD_WAIT) {
5043     src->pending_cmd = CMD_WAIT;
5044     GST_OBJECT_UNLOCK (src);
5045     /* cancel previous request */
5046     GST_DEBUG_OBJECT (src, "cancel previous request %s", cmd_to_string (old));
5047     gst_rtspsrc_loop_cancel_cmd (src, old);
5048     GST_OBJECT_LOCK (src);
5049   }
5050   src->pending_cmd = cmd;
5051   /* interrupt if allowed */
5052   if (src->busy_cmd & mask) {
5053     GST_DEBUG_OBJECT (src, "connection flush busy %s",
5054         cmd_to_string (src->busy_cmd));
5055     gst_rtspsrc_connection_flush (src, TRUE);
5056     flushed = TRUE;
5057   } else {
5058     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %s",
5059         cmd_to_string (src->busy_cmd));
5060   }
5061   if (src->task)
5062     gst_task_start (src->task);
5063   GST_OBJECT_UNLOCK (src);
5064
5065   return flushed;
5066 }
5067
5068 static gboolean
5069 gst_rtspsrc_loop (GstRTSPSrc * src)
5070 {
5071   GstFlowReturn ret;
5072
5073   if (!src->conninfo.connection || !src->conninfo.connected)
5074     goto no_connection;
5075
5076   if (src->interleaved)
5077     ret = gst_rtspsrc_loop_interleaved (src);
5078   else
5079     ret = gst_rtspsrc_loop_udp (src);
5080
5081   if (ret != GST_FLOW_OK)
5082     goto pause;
5083
5084   return TRUE;
5085
5086   /* ERRORS */
5087 no_connection:
5088   {
5089     GST_WARNING_OBJECT (src, "we are not connected");
5090     ret = GST_FLOW_FLUSHING;
5091     goto pause;
5092   }
5093 pause:
5094   {
5095     const gchar *reason = gst_flow_get_name (ret);
5096
5097     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
5098     src->running = FALSE;
5099     if (ret == GST_FLOW_EOS) {
5100       /* perform EOS logic */
5101       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5102         gst_element_post_message (GST_ELEMENT_CAST (src),
5103             gst_message_new_segment_done (GST_OBJECT_CAST (src),
5104                 src->segment.format, src->segment.position));
5105         gst_rtspsrc_push_event (src,
5106             gst_event_new_segment_done (src->segment.format,
5107                 src->segment.position));
5108       } else {
5109         gst_rtspsrc_push_event (src, gst_event_new_eos ());
5110       }
5111     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
5112       /* for fatal errors we post an error message, post the error before the
5113        * EOS so the app knows about the error first. */
5114       GST_ELEMENT_ERROR (src, STREAM, FAILED,
5115           ("Internal data flow error."),
5116           ("streaming task paused, reason %s (%d)", reason, ret));
5117       gst_rtspsrc_push_event (src, gst_event_new_eos ());
5118     }
5119     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
5120     return FALSE;
5121   }
5122 }
5123
5124 #ifndef GST_DISABLE_GST_DEBUG
5125 static const gchar *
5126 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
5127 {
5128   gint index = 0;
5129
5130   while (method != 0) {
5131     index++;
5132     method >>= 1;
5133   }
5134   switch (index) {
5135     case 0:
5136       return "None";
5137     case 1:
5138       return "Basic";
5139     case 2:
5140       return "Digest";
5141   }
5142
5143   return "Unknown";
5144 }
5145 #endif
5146
5147 static const gchar *
5148 gst_rtspsrc_skip_lws (const gchar * s)
5149 {
5150   while (g_ascii_isspace (*s))
5151     s++;
5152   return s;
5153 }
5154
5155 static const gchar *
5156 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
5157 {
5158   while (s > start && g_ascii_isspace (*(s - 1)))
5159     s--;
5160   return s;
5161 }
5162
5163 static const gchar *
5164 gst_rtspsrc_skip_commas (const gchar * s)
5165 {
5166   /* The grammar allows for multiple commas */
5167   while (g_ascii_isspace (*s) || *s == ',')
5168     s++;
5169   return s;
5170 }
5171
5172 static const gchar *
5173 gst_rtspsrc_skip_item (const gchar * s)
5174 {
5175   gboolean quoted = FALSE;
5176   const gchar *start = s;
5177
5178   /* A list item ends at the last non-whitespace character
5179    * before a comma which is not inside a quoted-string. Or at
5180    * the end of the string.
5181    */
5182   while (*s) {
5183     if (*s == '"')
5184       quoted = !quoted;
5185     else if (quoted) {
5186       if (*s == '\\' && *(s + 1))
5187         s++;
5188     } else {
5189       if (*s == ',')
5190         break;
5191     }
5192     s++;
5193   }
5194
5195   return gst_rtspsrc_unskip_lws (s, start);
5196 }
5197
5198 static void
5199 gst_rtsp_decode_quoted_string (gchar * quoted_string)
5200 {
5201   gchar *src, *dst;
5202
5203   src = quoted_string + 1;
5204   dst = quoted_string;
5205   while (*src && *src != '"') {
5206     if (*src == '\\' && *(src + 1))
5207       src++;
5208     *dst++ = *src++;
5209   }
5210   *dst = '\0';
5211 }
5212
5213 /* Extract the authentication tokens that the server provided for each method
5214  * into an array of structures and give those to the connection object.
5215  */
5216 static void
5217 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
5218     const gchar * header, gboolean * stale)
5219 {
5220   GSList *list = NULL, *iter;
5221   const gchar *end;
5222   gchar *item, *eq, *name_end, *value;
5223
5224   g_return_if_fail (stale != NULL);
5225
5226   gst_rtsp_connection_clear_auth_params (conn);
5227   *stale = FALSE;
5228
5229   /* Parse a header whose content is described by RFC2616 as
5230    * "#something", where "something" does not itself contain commas,
5231    * except as part of quoted-strings, into a list of allocated strings.
5232    */
5233   header = gst_rtspsrc_skip_commas (header);
5234   while (*header) {
5235     end = gst_rtspsrc_skip_item (header);
5236     list = g_slist_prepend (list, g_strndup (header, end - header));
5237     header = gst_rtspsrc_skip_commas (end);
5238   }
5239   if (!list)
5240     return;
5241
5242   list = g_slist_reverse (list);
5243   for (iter = list; iter; iter = iter->next) {
5244     item = iter->data;
5245
5246     eq = strchr (item, '=');
5247     if (eq) {
5248       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
5249       if (name_end == item) {
5250         /* That's no good... */
5251         g_free (item);
5252         continue;
5253       }
5254
5255       *name_end = '\0';
5256
5257       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
5258       if (*value == '"')
5259         gst_rtsp_decode_quoted_string (value);
5260     } else
5261       value = NULL;
5262
5263     if (value && strcmp (item, "stale") == 0 && strcmp (value, "TRUE") == 0)
5264       *stale = TRUE;
5265     gst_rtsp_connection_set_auth_param (conn, item, value);
5266     g_free (item);
5267   }
5268
5269   g_slist_free (list);
5270 }
5271
5272 /* Parse a WWW-Authenticate Response header and determine the
5273  * available authentication methods
5274  *
5275  * This code should also cope with the fact that each WWW-Authenticate
5276  * header can contain multiple challenge methods + tokens
5277  *
5278  * At the moment, for Basic auth, we just do a minimal check and don't
5279  * even parse out the realm */
5280 static void
5281 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
5282     GstRTSPConnection * conn, gboolean * stale)
5283 {
5284   gchar *start;
5285
5286   g_return_if_fail (hdr != NULL);
5287   g_return_if_fail (methods != NULL);
5288   g_return_if_fail (stale != NULL);
5289
5290   /* Skip whitespace at the start of the string */
5291   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
5292
5293   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
5294     *methods |= GST_RTSP_AUTH_BASIC;
5295   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
5296     *methods |= GST_RTSP_AUTH_DIGEST;
5297     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
5298   }
5299 }
5300
5301 /**
5302  * gst_rtspsrc_setup_auth:
5303  * @src: the rtsp source
5304  *
5305  * Configure a username and password and auth method on the
5306  * connection object based on a response we received from the
5307  * peer.
5308  *
5309  * Currently, this requires that a username and password were supplied
5310  * in the uri. In the future, they may be requested on demand by sending
5311  * a message up the bus.
5312  *
5313  * Returns: TRUE if authentication information could be set up correctly.
5314  */
5315 static gboolean
5316 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
5317 {
5318   gchar *user = NULL;
5319   gchar *pass = NULL;
5320   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
5321   GstRTSPAuthMethod method;
5322   GstRTSPResult auth_result;
5323   GstRTSPUrl *url;
5324   GstRTSPConnection *conn;
5325   gchar *hdr;
5326   gboolean stale = FALSE;
5327
5328   conn = src->conninfo.connection;
5329
5330   /* Identify the available auth methods and see if any are supported */
5331   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
5332           &hdr, 0) == GST_RTSP_OK) {
5333     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
5334   }
5335
5336   if (avail_methods == GST_RTSP_AUTH_NONE)
5337     goto no_auth_available;
5338
5339   /* For digest auth, if the response indicates that the session
5340    * data are stale, we just update them in the connection object and
5341    * return TRUE to retry the request */
5342   if (stale)
5343     src->tried_url_auth = FALSE;
5344
5345   url = gst_rtsp_connection_get_url (conn);
5346
5347   /* Do we have username and password available? */
5348   if (url != NULL && !src->tried_url_auth && url->user != NULL
5349       && url->passwd != NULL) {
5350     user = url->user;
5351     pass = url->passwd;
5352     src->tried_url_auth = TRUE;
5353     GST_DEBUG_OBJECT (src,
5354         "Attempting authentication using credentials from the URL");
5355   } else {
5356     user = src->user_id;
5357     pass = src->user_pw;
5358     GST_DEBUG_OBJECT (src,
5359         "Attempting authentication using credentials from the properties");
5360   }
5361
5362   /* FIXME: If the url didn't contain username and password or we tried them
5363    * already, request a username and passwd from the application via some kind
5364    * of credentials request message */
5365
5366   /* If we don't have a username and passwd at this point, bail out. */
5367   if (user == NULL || pass == NULL)
5368     goto no_user_pass;
5369
5370   /* Try to configure for each available authentication method, strongest to
5371    * weakest */
5372   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
5373     /* Check if this method is available on the server */
5374     if ((method & avail_methods) == 0)
5375       continue;
5376
5377     /* Pass the credentials to the connection to try on the next request */
5378     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
5379     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
5380      * ignore it and end up retrying later */
5381     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
5382       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
5383           gst_rtsp_auth_method_to_string (method));
5384       break;
5385     }
5386   }
5387
5388   if (method == GST_RTSP_AUTH_NONE)
5389     goto no_auth_available;
5390
5391   return TRUE;
5392
5393 no_auth_available:
5394   {
5395     /* Output an error indicating that we couldn't connect because there were
5396      * no supported authentication protocols */
5397     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5398         ("No supported authentication protocol was found"));
5399     return FALSE;
5400   }
5401 no_user_pass:
5402   {
5403     /* We don't fire an error message, we just return FALSE and let the
5404      * normal NOT_AUTHORIZED error be propagated */
5405     return FALSE;
5406   }
5407 }
5408
5409 static GstRTSPResult
5410 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5411     GstRTSPMessage * request, GstRTSPMessage * response,
5412     GstRTSPStatusCode * code)
5413 {
5414   GstRTSPResult res;
5415   GstRTSPStatusCode thecode;
5416   gchar *content_base = NULL;
5417   gint try = 0;
5418
5419 again:
5420   if (!src->short_header)
5421     gst_rtsp_ext_list_before_send (src->extensions, request);
5422
5423   GST_DEBUG_OBJECT (src, "sending message");
5424
5425   if (src->debug)
5426     gst_rtsp_message_dump (request);
5427
5428   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
5429   if (res < 0)
5430     goto send_error;
5431
5432   gst_rtsp_connection_reset_timeout (conn);
5433
5434 next:
5435   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
5436   if (res < 0)
5437     goto receive_error;
5438
5439   if (src->debug)
5440     gst_rtsp_message_dump (response);
5441
5442   switch (response->type) {
5443     case GST_RTSP_MESSAGE_REQUEST:
5444       res = gst_rtspsrc_handle_request (src, conn, response);
5445       if (res == GST_RTSP_EEOF)
5446         goto server_eof;
5447       else if (res < 0)
5448         goto handle_request_failed;
5449       goto next;
5450     case GST_RTSP_MESSAGE_RESPONSE:
5451       /* ok, a response is good */
5452       GST_DEBUG_OBJECT (src, "received response message");
5453       break;
5454     case GST_RTSP_MESSAGE_DATA:
5455       /* get next response */
5456       GST_DEBUG_OBJECT (src, "handle data response message");
5457       gst_rtspsrc_handle_data (src, response);
5458       goto next;
5459     default:
5460       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
5461           response->type);
5462       goto next;
5463   }
5464
5465   thecode = response->type_data.response.code;
5466
5467   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
5468
5469   /* if the caller wanted the result code, we store it. */
5470   if (code)
5471     *code = thecode;
5472
5473   /* If the request didn't succeed, bail out before doing any more */
5474   if (thecode != GST_RTSP_STS_OK)
5475     return GST_RTSP_OK;
5476
5477   /* store new content base if any */
5478   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
5479       &content_base, 0);
5480   if (content_base) {
5481     g_free (src->content_base);
5482     src->content_base = g_strdup (content_base);
5483   }
5484   gst_rtsp_ext_list_after_send (src->extensions, request, response);
5485
5486   return GST_RTSP_OK;
5487
5488   /* ERRORS */
5489 send_error:
5490   {
5491     gchar *str = gst_rtsp_strresult (res);
5492
5493     if (res != GST_RTSP_EINTR) {
5494       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5495           ("Could not send message. (%s)", str));
5496     } else {
5497       GST_WARNING_OBJECT (src, "send interrupted");
5498     }
5499     g_free (str);
5500     return res;
5501   }
5502 receive_error:
5503   {
5504     switch (res) {
5505       case GST_RTSP_EEOF:
5506         GST_WARNING_OBJECT (src, "server closed connection");
5507         if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5508           try++;
5509           /* if reconnect succeeds, try again */
5510           if ((res =
5511                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
5512                       FALSE)) == 0)
5513             goto again;
5514         }
5515         /* only try once after reconnect, then fallthrough and error out */
5516       default:
5517       {
5518         gchar *str = gst_rtsp_strresult (res);
5519
5520         if (res != GST_RTSP_EINTR) {
5521           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5522               ("Could not receive message. (%s)", str));
5523         } else {
5524           GST_WARNING_OBJECT (src, "receive interrupted");
5525         }
5526         g_free (str);
5527         break;
5528       }
5529     }
5530     return res;
5531   }
5532 handle_request_failed:
5533   {
5534     /* ERROR was posted */
5535     gst_rtsp_message_unset (response);
5536     return res;
5537   }
5538 server_eof:
5539   {
5540     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5541     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5542         ("The server closed the connection."));
5543     gst_rtsp_message_unset (response);
5544     return res;
5545   }
5546 }
5547
5548 /**
5549  * gst_rtspsrc_send:
5550  * @src: the rtsp source
5551  * @conn: the connection to send on
5552  * @request: must point to a valid request
5553  * @response: must point to an empty #GstRTSPMessage
5554  * @code: an optional code result
5555  *
5556  * send @request and retrieve the response in @response. optionally @code can be
5557  * non-NULL in which case it will contain the status code of the response.
5558  *
5559  * If This function returns #GST_RTSP_OK, @response will contain a valid response
5560  * message that should be cleaned with gst_rtsp_message_unset() after usage.
5561  *
5562  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5563  * @response message) if the response code was not 200 (OK).
5564  *
5565  * If the attempt results in an authentication failure, then this will attempt
5566  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5567  * the request.
5568  *
5569  * Returns: #GST_RTSP_OK if the processing was successful.
5570  */
5571 static GstRTSPResult
5572 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5573     GstRTSPMessage * request, GstRTSPMessage * response,
5574     GstRTSPStatusCode * code)
5575 {
5576   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5577   GstRTSPResult res = GST_RTSP_ERROR;
5578   gint count;
5579   gboolean retry;
5580   GstRTSPMethod method = GST_RTSP_INVALID;
5581
5582   count = 0;
5583   do {
5584     retry = FALSE;
5585
5586     /* make sure we don't loop forever */
5587     if (count++ > 8)
5588       break;
5589
5590     /* save method so we can disable it when the server complains */
5591     method = request->type_data.request.method;
5592
5593     if ((res =
5594             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5595       goto error;
5596
5597     switch (int_code) {
5598       case GST_RTSP_STS_UNAUTHORIZED:
5599       case GST_RTSP_STS_NOT_FOUND:
5600         if (gst_rtspsrc_setup_auth (src, response)) {
5601           /* Try the request/response again after configuring the auth info
5602            * and loop again */
5603           retry = TRUE;
5604         }
5605         break;
5606       default:
5607         break;
5608     }
5609   } while (retry == TRUE);
5610
5611   /* If the user requested the code, let them handle errors, otherwise
5612    * post an error below */
5613   if (code != NULL)
5614     *code = int_code;
5615   else if (int_code != GST_RTSP_STS_OK)
5616     goto error_response;
5617
5618   return res;
5619
5620   /* ERRORS */
5621 error:
5622   {
5623     GST_DEBUG_OBJECT (src, "got error %d", res);
5624     return res;
5625   }
5626 error_response:
5627   {
5628     res = GST_RTSP_ERROR;
5629
5630     switch (response->type_data.response.code) {
5631       case GST_RTSP_STS_NOT_FOUND:
5632         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5633                 response->type_data.response.reason));
5634         break;
5635       case GST_RTSP_STS_UNAUTHORIZED:
5636         GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED, (NULL), ("%s",
5637                 response->type_data.response.reason));
5638         break;
5639       case GST_RTSP_STS_MOVED_PERMANENTLY:
5640       case GST_RTSP_STS_MOVE_TEMPORARILY:
5641       {
5642         gchar *new_location;
5643         GstRTSPLowerTrans transports;
5644
5645         GST_DEBUG_OBJECT (src, "got redirection");
5646         /* if we don't have a Location Header, we must error */
5647         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5648                 &new_location, 0) < 0)
5649           break;
5650
5651         /* When we receive a redirect result, we go back to the INIT state after
5652          * parsing the new URI. The caller should do the needed steps to issue
5653          * a new setup when it detects this state change. */
5654         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5655
5656         /* save current transports */
5657         if (src->conninfo.url)
5658           transports = src->conninfo.url->transports;
5659         else
5660           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5661
5662         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5663
5664         /* set old transports */
5665         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5666           src->conninfo.url->transports = transports;
5667
5668         src->need_redirect = TRUE;
5669         src->state = GST_RTSP_STATE_INIT;
5670         res = GST_RTSP_OK;
5671         break;
5672       }
5673       case GST_RTSP_STS_NOT_ACCEPTABLE:
5674       case GST_RTSP_STS_NOT_IMPLEMENTED:
5675       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5676         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5677             gst_rtsp_method_as_text (method));
5678         src->methods &= ~method;
5679         res = GST_RTSP_OK;
5680         break;
5681       default:
5682         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5683             ("Got error response: %d (%s).", response->type_data.response.code,
5684                 response->type_data.response.reason));
5685         break;
5686     }
5687     /* if we return ERROR we should unset the response ourselves */
5688     if (res == GST_RTSP_ERROR)
5689       gst_rtsp_message_unset (response);
5690
5691     return res;
5692   }
5693 }
5694
5695 static GstRTSPResult
5696 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5697     GstRTSPMessage * response, GstRTSPSrc * src)
5698 {
5699   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5700       NULL);
5701 }
5702
5703
5704 /* parse the response and collect all the supported methods. We need this
5705  * information so that we don't try to send an unsupported request to the
5706  * server.
5707  */
5708 static gboolean
5709 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5710 {
5711   GstRTSPHeaderField field;
5712   gchar *respoptions;
5713   gint indx = 0;
5714
5715   /* reset supported methods */
5716   src->methods = 0;
5717
5718   /* Try Allow Header first */
5719   field = GST_RTSP_HDR_ALLOW;
5720   while (TRUE) {
5721     respoptions = NULL;
5722     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5723     if (indx == 0 && !respoptions) {
5724       /* if no Allow header was found then try the Public header... */
5725       field = GST_RTSP_HDR_PUBLIC;
5726       gst_rtsp_message_get_header (response, field, &respoptions, indx);
5727     }
5728     if (!respoptions)
5729       break;
5730
5731     src->methods |= gst_rtsp_options_from_text (respoptions);
5732
5733     indx++;
5734   }
5735
5736   if (src->methods == 0) {
5737     /* neither Allow nor Public are required, assume the server supports
5738      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5739      * well. */
5740     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5741     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5742   }
5743   /* always assume PLAY, FIXME, extensions should be able to override
5744    * this */
5745   src->methods |= GST_RTSP_PLAY;
5746   /* also assume it will support Range */
5747   src->seekable = TRUE;
5748
5749   /* we need describe and setup */
5750   if (!(src->methods & GST_RTSP_DESCRIBE))
5751     goto no_describe;
5752   if (!(src->methods & GST_RTSP_SETUP))
5753     goto no_setup;
5754
5755   return TRUE;
5756
5757   /* ERRORS */
5758 no_describe:
5759   {
5760     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5761         ("Server does not support DESCRIBE."));
5762     return FALSE;
5763   }
5764 no_setup:
5765   {
5766     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5767         ("Server does not support SETUP."));
5768     return FALSE;
5769   }
5770 }
5771
5772 /* masks to be kept in sync with the hardcoded protocol order of preference
5773  * in code below */
5774 static const guint protocol_masks[] = {
5775   GST_RTSP_LOWER_TRANS_UDP,
5776   GST_RTSP_LOWER_TRANS_UDP_MCAST,
5777   GST_RTSP_LOWER_TRANS_TCP,
5778   0
5779 };
5780
5781 static GstRTSPResult
5782 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5783     GstRTSPLowerTrans protocols, GstRTSPProfile profile, gchar ** transports)
5784 {
5785   GstRTSPResult res;
5786   GString *result;
5787   gboolean add_udp_str;
5788
5789   *transports = NULL;
5790
5791   res =
5792       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5793
5794   if (res < 0)
5795     goto failed;
5796
5797   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5798
5799   /* extension listed transports, use those */
5800   if (*transports != NULL)
5801     return GST_RTSP_OK;
5802
5803   /* it's the default */
5804   add_udp_str = FALSE;
5805
5806   /* the default RTSP transports */
5807   result = g_string_new ("RTP");
5808
5809   switch (profile) {
5810     case GST_RTSP_PROFILE_AVP:
5811       g_string_append (result, "/AVP");
5812       break;
5813     case GST_RTSP_PROFILE_SAVP:
5814       g_string_append (result, "/SAVP");
5815       break;
5816     case GST_RTSP_PROFILE_AVPF:
5817       g_string_append (result, "/AVPF");
5818       break;
5819     case GST_RTSP_PROFILE_SAVPF:
5820       g_string_append (result, "/SAVPF");
5821       break;
5822     default:
5823       break;
5824   }
5825
5826   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5827     GST_DEBUG_OBJECT (src, "adding UDP unicast");
5828     if (add_udp_str)
5829       g_string_append (result, "/UDP");
5830     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5831   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5832     GST_DEBUG_OBJECT (src, "adding UDP multicast");
5833     /* we don't have to allocate any UDP ports yet, if the selected transport
5834      * turns out to be multicast we can create them and join the multicast
5835      * group indicated in the transport reply */
5836     if (add_udp_str)
5837       g_string_append (result, "/UDP");
5838     g_string_append (result, ";multicast");
5839     if (src->next_port_num != 0) {
5840       if (src->client_port_range.max > 0 &&
5841           src->next_port_num >= src->client_port_range.max)
5842         goto no_ports;
5843
5844       g_string_append_printf (result, ";client_port=%d-%d",
5845           src->next_port_num, src->next_port_num + 1);
5846     }
5847   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5848     GST_DEBUG_OBJECT (src, "adding TCP");
5849
5850     g_string_append (result, "/TCP;unicast;interleaved=%%i1-%%i2");
5851   }
5852   *transports = g_string_free (result, FALSE);
5853
5854   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5855
5856   return GST_RTSP_OK;
5857
5858   /* ERRORS */
5859 failed:
5860   {
5861     GST_ERROR ("extension gave error %d", res);
5862     return res;
5863   }
5864 no_ports:
5865   {
5866     GST_ERROR ("no more ports available");
5867     return GST_RTSP_ERROR;
5868   }
5869 }
5870
5871 static GstRTSPResult
5872 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5873     gint orig_rtpport, gint orig_rtcpport)
5874 {
5875   GstRTSPSrc *src;
5876   gint nr_udp, nr_int;
5877   gchar *next, *p;
5878   gint rtpport = 0, rtcpport = 0;
5879   GString *str;
5880
5881   src = stream->parent;
5882
5883   /* find number of placeholders first */
5884   if (strstr (*transports, "%%i2"))
5885     nr_int = 2;
5886   else if (strstr (*transports, "%%i1"))
5887     nr_int = 1;
5888   else
5889     nr_int = 0;
5890
5891   if (strstr (*transports, "%%u2"))
5892     nr_udp = 2;
5893   else if (strstr (*transports, "%%u1"))
5894     nr_udp = 1;
5895   else
5896     nr_udp = 0;
5897
5898   if (nr_udp == 0 && nr_int == 0)
5899     goto done;
5900
5901   if (nr_udp > 0) {
5902     if (!orig_rtpport || !orig_rtcpport) {
5903       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5904         goto failed;
5905     } else {
5906       rtpport = orig_rtpport;
5907       rtcpport = orig_rtcpport;
5908     }
5909   }
5910
5911   str = g_string_new ("");
5912   p = *transports;
5913   while ((next = strstr (p, "%%"))) {
5914     g_string_append_len (str, p, next - p);
5915     if (next[2] == 'u') {
5916       if (next[3] == '1')
5917         g_string_append_printf (str, "%d", rtpport);
5918       else if (next[3] == '2')
5919         g_string_append_printf (str, "%d", rtcpport);
5920     }
5921     if (next[2] == 'i') {
5922       if (next[3] == '1')
5923         g_string_append_printf (str, "%d", src->free_channel);
5924       else if (next[3] == '2')
5925         g_string_append_printf (str, "%d", src->free_channel + 1);
5926     }
5927
5928     p = next + 4;
5929   }
5930   /* append final part */
5931   g_string_append (str, p);
5932
5933   g_free (*transports);
5934   *transports = g_string_free (str, FALSE);
5935
5936 done:
5937   return GST_RTSP_OK;
5938
5939   /* ERRORS */
5940 failed:
5941   {
5942     GST_ERROR ("failed to allocate udp ports");
5943     return GST_RTSP_ERROR;
5944   }
5945 }
5946
5947 static GstCaps *
5948 signal_get_srtcp_params (GstRTSPSrc * src, GstRTSPStream * stream)
5949 {
5950   GstCaps *caps = NULL;
5951
5952   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_REQUEST_RTCP_KEY], 0,
5953       stream->id, &caps);
5954
5955   if (caps != NULL)
5956     GST_DEBUG_OBJECT (src, "SRTP parameters received");
5957
5958   return caps;
5959 }
5960
5961 static GstCaps *
5962 default_srtcp_params (void)
5963 {
5964   guint i;
5965   GstCaps *caps;
5966   GstBuffer *buf;
5967   guint8 *key_data;
5968 #define KEY_SIZE 30
5969   guint data_size = GST_ROUND_UP_4 (KEY_SIZE);
5970
5971   /* create a random key */
5972   key_data = g_malloc (data_size);
5973   for (i = 0; i < data_size; i += 4)
5974     GST_WRITE_UINT32_BE (key_data + i, g_random_int ());
5975
5976   buf = gst_buffer_new_wrapped (key_data, KEY_SIZE);
5977
5978   caps = gst_caps_new_simple ("application/x-srtcp",
5979       "srtp-key", GST_TYPE_BUFFER, buf,
5980       "srtp-cipher", G_TYPE_STRING, "aes-128-icm",
5981       "srtp-auth", G_TYPE_STRING, "hmac-sha1-80",
5982       "srtcp-cipher", G_TYPE_STRING, "aes-128-icm",
5983       "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL);
5984
5985   gst_buffer_unref (buf);
5986
5987   return caps;
5988 }
5989
5990 static gchar *
5991 gst_rtspsrc_stream_make_keymgmt (GstRTSPSrc * src, GstRTSPStream * stream)
5992 {
5993   gchar *base64, *result = NULL;
5994   GstMIKEYMessage *mikey_msg;
5995
5996   stream->srtcpparams = signal_get_srtcp_params (src, stream);
5997   if (stream->srtcpparams == NULL)
5998     stream->srtcpparams = default_srtcp_params ();
5999
6000   mikey_msg = gst_mikey_message_new_from_caps (stream->srtcpparams);
6001   if (mikey_msg) {
6002     /* add policy '0' for our SSRC */
6003     gst_mikey_message_add_cs_srtp (mikey_msg, 0, stream->send_ssrc, 0);
6004
6005     base64 = gst_mikey_message_base64_encode (mikey_msg);
6006     gst_mikey_message_unref (mikey_msg);
6007
6008     if (base64) {
6009       result = gst_sdp_make_keymgmt (stream->conninfo.location, base64);
6010       g_free (base64);
6011     }
6012   }
6013
6014   return result;
6015 }
6016
6017 /* Perform the SETUP request for all the streams.
6018  *
6019  * We ask the server for a specific transport, which initially includes all the
6020  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
6021  * two local UDP ports that we send to the server.
6022  *
6023  * Once the server replied with a transport, we configure the other streams
6024  * with the same transport.
6025  *
6026  * This function will also configure the stream for the selected transport,
6027  * which basically means creating the pipeline.
6028  */
6029 static GstRTSPResult
6030 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
6031 {
6032   GList *walk;
6033   GstRTSPResult res = GST_RTSP_ERROR;
6034   GstRTSPMessage request = { 0 };
6035   GstRTSPMessage response = { 0 };
6036   GstRTSPStream *stream = NULL;
6037   GstRTSPLowerTrans protocols;
6038   GstRTSPStatusCode code;
6039   gboolean unsupported_real = FALSE;
6040   gint rtpport, rtcpport;
6041   GstRTSPUrl *url;
6042   gchar *hval;
6043
6044   if (src->conninfo.connection) {
6045     url = gst_rtsp_connection_get_url (src->conninfo.connection);
6046     /* we initially allow all configured lower transports. based on the URL
6047      * transports and the replies from the server we narrow them down. */
6048     protocols = url->transports & src->cur_protocols;
6049   } else {
6050     url = NULL;
6051     protocols = src->cur_protocols;
6052   }
6053
6054   if (protocols == 0)
6055     goto no_protocols;
6056
6057   /* reset some state */
6058   src->free_channel = 0;
6059   src->interleaved = FALSE;
6060   src->need_activate = FALSE;
6061   /* keep track of next port number, 0 is random */
6062   src->next_port_num = src->client_port_range.min;
6063   rtpport = rtcpport = 0;
6064
6065   if (G_UNLIKELY (src->streams == NULL))
6066     goto no_streams;
6067
6068   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6069     GstRTSPConnection *conn;
6070     gchar *transports;
6071     gint retry = 0;
6072     guint mask = 0;
6073     gboolean selected;
6074     GstCaps *caps;
6075
6076     stream = (GstRTSPStream *) walk->data;
6077
6078     caps = stream_get_caps_for_pt (stream, stream->default_pt);
6079     if (caps == NULL) {
6080       GST_DEBUG_OBJECT (src, "skipping stream %p, no caps", stream);
6081       continue;
6082     }
6083
6084     if (stream->skipped) {
6085       GST_DEBUG_OBJECT (src, "skipping stream %p", stream);
6086       continue;
6087     }
6088
6089     /* see if we need to configure this stream */
6090     if (!gst_rtsp_ext_list_configure_stream (src->extensions, caps)) {
6091       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
6092           stream);
6093       continue;
6094     }
6095
6096     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
6097         stream->id, caps, &selected);
6098     if (!selected) {
6099       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
6100       continue;
6101     }
6102
6103     /* merge/overwrite global caps */
6104     if (caps) {
6105       guint j, num;
6106       GstStructure *s;
6107
6108       s = gst_caps_get_structure (caps, 0);
6109
6110       num = gst_structure_n_fields (src->props);
6111       for (j = 0; j < num; j++) {
6112         const gchar *name;
6113         const GValue *val;
6114
6115         name = gst_structure_nth_field_name (src->props, j);
6116         val = gst_structure_get_value (src->props, name);
6117         gst_structure_set_value (s, name, val);
6118
6119         GST_DEBUG_OBJECT (src, "copied %s", name);
6120       }
6121     }
6122
6123     /* skip setup if we have no URL for it */
6124     if (stream->conninfo.location == NULL) {
6125       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
6126       continue;
6127     }
6128
6129     if (src->conninfo.connection == NULL) {
6130       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
6131         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
6132         continue;
6133       }
6134       conn = stream->conninfo.connection;
6135     } else {
6136       conn = src->conninfo.connection;
6137     }
6138     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
6139         stream->conninfo.location);
6140
6141     /* if we have a multicast connection, only suggest multicast from now on */
6142     if (stream->is_multicast)
6143       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
6144
6145   next_protocol:
6146     /* first selectable protocol */
6147     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6148       mask++;
6149     if (!protocol_masks[mask])
6150       goto no_protocols;
6151
6152   retry:
6153     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
6154         protocol_masks[mask]);
6155     /* create a string with first transport in line */
6156     transports = NULL;
6157     res = gst_rtspsrc_create_transports_string (src,
6158         protocols & protocol_masks[mask], stream->profile, &transports);
6159     if (res < 0 || transports == NULL)
6160       goto setup_transport_failed;
6161
6162     if (strlen (transports) == 0) {
6163       g_free (transports);
6164       GST_DEBUG_OBJECT (src, "no transports found");
6165       mask++;
6166       goto next_protocol;
6167     }
6168
6169     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
6170
6171     /* replace placeholders with real values, this function will optionally
6172      * allocate UDP ports and other info needed to execute the setup request */
6173     res = gst_rtspsrc_prepare_transports (stream, &transports,
6174         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
6175     if (res < 0) {
6176       g_free (transports);
6177       goto setup_transport_failed;
6178     }
6179
6180     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
6181
6182     /* create SETUP request */
6183     res =
6184         gst_rtspsrc_init_request (src, &request, GST_RTSP_SETUP,
6185         stream->conninfo.location);
6186     if (res < 0) {
6187       g_free (transports);
6188       goto create_request_failed;
6189     }
6190
6191     /* select transport */
6192     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
6193
6194     /* set up keys */
6195     if (stream->profile == GST_RTSP_PROFILE_SAVP ||
6196         stream->profile == GST_RTSP_PROFILE_SAVPF) {
6197       hval = gst_rtspsrc_stream_make_keymgmt (src, stream);
6198       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_KEYMGMT, hval);
6199     }
6200
6201     /* if the user wants a non default RTP packet size we add the blocksize
6202      * parameter */
6203     if (src->rtp_blocksize > 0) {
6204       hval = g_strdup_printf ("%d", src->rtp_blocksize);
6205       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
6206     }
6207
6208     if (async)
6209       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
6210               stream->id));
6211
6212     /* handle the code ourselves */
6213     res = gst_rtspsrc_send (src, conn, &request, &response, &code);
6214     if (res < 0)
6215       goto send_error;
6216
6217     switch (code) {
6218       case GST_RTSP_STS_OK:
6219         break;
6220       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
6221         gst_rtsp_message_unset (&request);
6222         gst_rtsp_message_unset (&response);
6223         /* cleanup of leftover transport */
6224         gst_rtspsrc_stream_free_udp (stream);
6225         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
6226          * we might be in this case */
6227         if (stream->container && rtpport && rtcpport && !retry) {
6228           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
6229               rtpport, rtcpport);
6230           retry++;
6231           goto retry;
6232         }
6233         /* this transport did not go down well, but we may have others to try
6234          * that we did not send yet, try those and only give up then
6235          * but not without checking for lost cause/extension so we can
6236          * post a nicer/more useful error message later */
6237         if (!unsupported_real)
6238           unsupported_real = stream->is_real;
6239         /* select next available protocol, give up on this stream if none */
6240         mask++;
6241         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
6242           mask++;
6243         if (!protocol_masks[mask] || unsupported_real)
6244           continue;
6245         else
6246           goto retry;
6247       default:
6248         /* cleanup of leftover transport and move to the next stream */
6249         gst_rtspsrc_stream_free_udp (stream);
6250         goto response_error;
6251     }
6252
6253     /* parse response transport */
6254     {
6255       gchar *resptrans = NULL;
6256       GstRTSPTransport transport = { 0 };
6257
6258       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
6259           &resptrans, 0);
6260       if (!resptrans) {
6261         gst_rtspsrc_stream_free_udp (stream);
6262         goto no_transport;
6263       }
6264
6265       /* parse transport, go to next stream on parse error */
6266       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
6267         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
6268         goto next;
6269       }
6270
6271       /* update allowed transports for other streams. once the transport of
6272        * one stream has been determined, we make sure that all other streams
6273        * are configured in the same way */
6274       switch (transport.lower_transport) {
6275         case GST_RTSP_LOWER_TRANS_TCP:
6276           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
6277           protocols = GST_RTSP_LOWER_TRANS_TCP;
6278           src->interleaved = TRUE;
6279           /* update free channels */
6280           src->free_channel =
6281               MAX (transport.interleaved.min, src->free_channel);
6282           src->free_channel =
6283               MAX (transport.interleaved.max, src->free_channel);
6284           src->free_channel++;
6285           break;
6286         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
6287           /* only allow multicast for other streams */
6288           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
6289           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
6290           /* if the server selected our ports, increment our counters so that
6291            * we select a new port later */
6292           if (src->next_port_num == transport.port.min &&
6293               src->next_port_num + 1 == transport.port.max) {
6294             src->next_port_num += 2;
6295           }
6296           break;
6297         case GST_RTSP_LOWER_TRANS_UDP:
6298           /* only allow unicast for other streams */
6299           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
6300           protocols = GST_RTSP_LOWER_TRANS_UDP;
6301           break;
6302         default:
6303           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
6304               transport.lower_transport);
6305           break;
6306       }
6307
6308       if (!src->interleaved || !retry) {
6309         /* now configure the stream with the selected transport */
6310         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
6311           GST_DEBUG_OBJECT (src,
6312               "could not configure stream %p transport, skipping stream",
6313               stream);
6314           goto next;
6315         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
6316           /* retain the first allocated UDP port pair */
6317           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
6318           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
6319         }
6320       }
6321       /* we need to activate at least one streams when we detect activity */
6322       src->need_activate = TRUE;
6323
6324       /* stream is setup now */
6325       stream->setup = TRUE;
6326       {
6327         GList *skip = walk;
6328
6329         while (TRUE) {
6330           GstRTSPStream *sskip;
6331
6332           skip = g_list_next (skip);
6333           if (skip == NULL)
6334             break;
6335
6336           sskip = (GstRTSPStream *) skip->data;
6337
6338           /* skip all streams with the same control url */
6339           if (g_str_equal (stream->conninfo.location, sskip->conninfo.location)) {
6340             GST_DEBUG_OBJECT (src, "found stream %p with same control %s",
6341                 sskip, sskip->conninfo.location);
6342             sskip->skipped = TRUE;
6343           }
6344         }
6345       }
6346     next:
6347       /* clean up our transport struct */
6348       gst_rtsp_transport_init (&transport);
6349       /* clean up used RTSP messages */
6350       gst_rtsp_message_unset (&request);
6351       gst_rtsp_message_unset (&response);
6352     }
6353   }
6354
6355   /* store the transport protocol that was configured */
6356   src->cur_protocols = protocols;
6357
6358   gst_rtsp_ext_list_stream_select (src->extensions, url);
6359
6360   /* if there is nothing to activate, error out */
6361   if (!src->need_activate)
6362     goto nothing_to_activate;
6363
6364   return res;
6365
6366   /* ERRORS */
6367 no_protocols:
6368   {
6369     /* no transport possible, post an error and stop */
6370     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
6371         ("Could not connect to server, no protocols left"));
6372     return GST_RTSP_ERROR;
6373   }
6374 no_streams:
6375   {
6376     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6377         ("SDP contains no streams"));
6378     return GST_RTSP_ERROR;
6379   }
6380 create_request_failed:
6381   {
6382     gchar *str = gst_rtsp_strresult (res);
6383
6384     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6385         ("Could not create request. (%s)", str));
6386     g_free (str);
6387     goto cleanup_error;
6388   }
6389 setup_transport_failed:
6390   {
6391     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6392         ("Could not setup transport."));
6393     res = GST_RTSP_ERROR;
6394     goto cleanup_error;
6395   }
6396 response_error:
6397   {
6398     const gchar *str = gst_rtsp_status_as_text (code);
6399
6400     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6401         ("Error (%d): %s", code, GST_STR_NULL (str)));
6402     res = GST_RTSP_ERROR;
6403     goto cleanup_error;
6404   }
6405 send_error:
6406   {
6407     gchar *str = gst_rtsp_strresult (res);
6408
6409     if (res != GST_RTSP_EINTR) {
6410       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6411           ("Could not send message. (%s)", str));
6412     } else {
6413       GST_WARNING_OBJECT (src, "send interrupted");
6414     }
6415     g_free (str);
6416     goto cleanup_error;
6417   }
6418 no_transport:
6419   {
6420     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6421         ("Server did not select transport."));
6422     res = GST_RTSP_ERROR;
6423     goto cleanup_error;
6424   }
6425 nothing_to_activate:
6426   {
6427     /* none of the available error codes is really right .. */
6428     if (unsupported_real) {
6429       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6430           (_("No supported stream was found. You might need to install a "
6431                   "GStreamer RTSP extension plugin for Real media streams.")),
6432           (NULL));
6433     } else {
6434       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
6435           (_("No supported stream was found. You might need to allow "
6436                   "more transport protocols or may otherwise be missing "
6437                   "the right GStreamer RTSP extension plugin.")), (NULL));
6438     }
6439     return GST_RTSP_ERROR;
6440   }
6441 cleanup_error:
6442   {
6443     gst_rtsp_message_unset (&request);
6444     gst_rtsp_message_unset (&response);
6445     return res;
6446   }
6447 }
6448
6449 static gboolean
6450 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
6451     GstSegment * segment)
6452 {
6453   gint64 seconds;
6454   GstRTSPTimeRange *therange;
6455
6456   if (src->range)
6457     gst_rtsp_range_free (src->range);
6458
6459   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
6460     GST_DEBUG_OBJECT (src, "parsed range %s", range);
6461     src->range = therange;
6462   } else {
6463     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
6464     src->range = NULL;
6465     gst_segment_init (segment, GST_FORMAT_TIME);
6466     return FALSE;
6467   }
6468
6469   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
6470       therange->min.type, therange->min.seconds, therange->max.type,
6471       therange->max.seconds);
6472
6473   if (therange->min.type == GST_RTSP_TIME_NOW)
6474     seconds = 0;
6475   else if (therange->min.type == GST_RTSP_TIME_END)
6476     seconds = 0;
6477   else
6478     seconds = therange->min.seconds * GST_SECOND;
6479
6480   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
6481       GST_TIME_ARGS (seconds));
6482
6483   /* we need to start playback without clipping from the position reported by
6484    * the server */
6485   segment->start = seconds;
6486   segment->position = seconds;
6487
6488   if (therange->max.type == GST_RTSP_TIME_NOW)
6489     seconds = -1;
6490   else if (therange->max.type == GST_RTSP_TIME_END)
6491     seconds = -1;
6492   else
6493     seconds = therange->max.seconds * GST_SECOND;
6494
6495   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
6496       GST_TIME_ARGS (seconds));
6497
6498   /* live (WMS) server might send overflowed large max as its idea of infinity,
6499    * compensate to prevent problems later on */
6500   if (seconds != -1 && seconds < 0) {
6501     seconds = -1;
6502     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
6503   }
6504
6505   /* live (WMS) might send min == max, which is not worth recording */
6506   if (segment->duration == -1 && seconds == segment->start)
6507     seconds = -1;
6508
6509   /* don't change duration with unknown value, we might have a valid value
6510    * there that we want to keep. */
6511   if (seconds != -1)
6512     segment->duration = seconds;
6513
6514   return TRUE;
6515 }
6516
6517 /* Parse clock profived by the server with following syntax:
6518  *
6519  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
6520  */
6521 static gboolean
6522 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
6523 {
6524   gboolean res = FALSE;
6525
6526   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
6527     gchar **fields = NULL, **parts = NULL;
6528     gchar *remote_ip, *str;
6529     gint port;
6530     GstClockTime base_time;
6531     GstClock *netclock;
6532
6533     fields = g_strsplit (gstclock, " ", 0);
6534
6535     /* wrapped clock, not very interesting for now */
6536     if (fields[1] == NULL)
6537       goto cleanup;
6538
6539     /* remote IP address and port */
6540     if ((str = fields[2]) == NULL)
6541       goto cleanup;
6542
6543     parts = g_strsplit (str, ":", 0);
6544
6545     if ((remote_ip = parts[0]) == NULL)
6546       goto cleanup;
6547
6548     if ((str = parts[1]) == NULL)
6549       goto cleanup;
6550
6551     port = atoi (str);
6552     if (port == 0)
6553       goto cleanup;
6554
6555     /* base-time */
6556     if ((str = fields[3]) == NULL)
6557       goto cleanup;
6558
6559     base_time = g_ascii_strtoull (str, NULL, 10);
6560
6561     netclock =
6562         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
6563         base_time);
6564
6565     if (src->provided_clock)
6566       gst_object_unref (src->provided_clock);
6567     src->provided_clock = netclock;
6568
6569     gst_element_post_message (GST_ELEMENT_CAST (src),
6570         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
6571             src->provided_clock, TRUE));
6572
6573     res = TRUE;
6574   cleanup:
6575     g_strfreev (fields);
6576     g_strfreev (parts);
6577   }
6578   return res;
6579 }
6580
6581 /* must be called with the RTSP state lock */
6582 static GstRTSPResult
6583 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
6584     gboolean async)
6585 {
6586   GstRTSPResult res;
6587   gint i, n_streams;
6588
6589   /* prepare global stream caps properties */
6590   if (src->props)
6591     gst_structure_remove_all_fields (src->props);
6592   else
6593     src->props = gst_structure_new_empty ("RTSPProperties");
6594
6595   if (src->debug)
6596     gst_sdp_message_dump (sdp);
6597
6598   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
6599
6600   /* let the app inspect and change the SDP */
6601   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
6602
6603   gst_segment_init (&src->segment, GST_FORMAT_TIME);
6604
6605   /* parse range for duration reporting. */
6606   {
6607     const gchar *range;
6608
6609     for (i = 0;; i++) {
6610       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
6611       if (range == NULL)
6612         break;
6613
6614       /* keep track of the range and configure it in the segment */
6615       if (gst_rtspsrc_parse_range (src, range, &src->segment))
6616         break;
6617     }
6618   }
6619   /* parse clock information. This is GStreamer specific, a server can tell the
6620    * client what clock it is using and wrap that in a network clock. The
6621    * advantage of that is that we can slave to it. */
6622   {
6623     const gchar *gstclock;
6624
6625     for (i = 0;; i++) {
6626       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
6627       if (gstclock == NULL)
6628         break;
6629
6630       /* parse the clock and expose it in the provide_clock method */
6631       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
6632         break;
6633     }
6634   }
6635   /* try to find a global control attribute. Note that a '*' means that we should
6636    * do aggregate control with the current url (so we don't do anything and
6637    * leave the current connection as is) */
6638   {
6639     const gchar *control;
6640
6641     for (i = 0;; i++) {
6642       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
6643       if (control == NULL)
6644         break;
6645
6646       /* only take fully qualified urls */
6647       if (g_str_has_prefix (control, "rtsp://"))
6648         break;
6649     }
6650     if (control) {
6651       g_free (src->conninfo.location);
6652       src->conninfo.location = g_strdup (control);
6653       /* make a connection for this, if there was a connection already, nothing
6654        * happens. */
6655       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
6656         GST_ERROR_OBJECT (src, "could not connect");
6657       }
6658     }
6659     /* we need to keep the control url separate from the connection url because
6660      * the rules for constructing the media control url need it */
6661     g_free (src->control);
6662     src->control = g_strdup (control);
6663   }
6664
6665   /* create streams */
6666   n_streams = gst_sdp_message_medias_len (sdp);
6667   for (i = 0; i < n_streams; i++) {
6668     gst_rtspsrc_create_stream (src, sdp, i);
6669   }
6670
6671   src->state = GST_RTSP_STATE_INIT;
6672
6673   /* setup streams */
6674   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
6675     goto setup_failed;
6676
6677   /* reset our state */
6678   src->need_range = TRUE;
6679   src->skip = FALSE;
6680
6681   src->state = GST_RTSP_STATE_READY;
6682
6683   return res;
6684
6685   /* ERRORS */
6686 setup_failed:
6687   {
6688     GST_ERROR_OBJECT (src, "setup failed");
6689     gst_rtspsrc_cleanup (src);
6690     return res;
6691   }
6692 }
6693
6694 static GstRTSPResult
6695 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
6696     gboolean async)
6697 {
6698   GstRTSPResult res;
6699   GstRTSPMessage request = { 0 };
6700   GstRTSPMessage response = { 0 };
6701   guint8 *data;
6702   guint size;
6703   gchar *respcont = NULL;
6704
6705 restart:
6706   src->need_redirect = FALSE;
6707
6708   /* can't continue without a valid url */
6709   if (G_UNLIKELY (src->conninfo.url == NULL)) {
6710     res = GST_RTSP_EINVAL;
6711     goto no_url;
6712   }
6713   src->tried_url_auth = FALSE;
6714
6715   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
6716     goto connect_failed;
6717
6718   /* create OPTIONS */
6719   GST_DEBUG_OBJECT (src, "create options...");
6720   res =
6721       gst_rtspsrc_init_request (src, &request, GST_RTSP_OPTIONS,
6722       src->conninfo.url_str);
6723   if (res < 0)
6724     goto create_request_failed;
6725
6726   /* send OPTIONS */
6727   GST_DEBUG_OBJECT (src, "send options...");
6728
6729   if (async)
6730     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
6731
6732   if ((res =
6733           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6734               NULL)) < 0)
6735     goto send_error;
6736
6737   /* parse OPTIONS */
6738   if (!gst_rtspsrc_parse_methods (src, &response))
6739     goto methods_error;
6740
6741   /* create DESCRIBE */
6742   GST_DEBUG_OBJECT (src, "create describe...");
6743   res =
6744       gst_rtspsrc_init_request (src, &request, GST_RTSP_DESCRIBE,
6745       src->conninfo.url_str);
6746   if (res < 0)
6747     goto create_request_failed;
6748
6749   /* we only accept SDP for now */
6750   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
6751       "application/sdp");
6752
6753   /* send DESCRIBE */
6754   GST_DEBUG_OBJECT (src, "send describe...");
6755
6756   if (async)
6757     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
6758
6759   if ((res =
6760           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6761               NULL)) < 0)
6762     goto send_error;
6763
6764   /* we only perform redirect for the describe, currently */
6765   if (src->need_redirect) {
6766     /* close connection, we don't have to send a TEARDOWN yet, ignore the
6767      * result. */
6768     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6769
6770     gst_rtsp_message_unset (&request);
6771     gst_rtsp_message_unset (&response);
6772
6773     /* and now retry */
6774     goto restart;
6775   }
6776
6777   /* it could be that the DESCRIBE method was not implemented */
6778   if (!(src->methods & GST_RTSP_DESCRIBE))
6779     goto no_describe;
6780
6781   /* check if reply is SDP */
6782   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
6783       0);
6784   /* could not be set but since the request returned OK, we assume it
6785    * was SDP, else check it. */
6786   if (respcont) {
6787     if (g_ascii_strcasecmp (respcont, "application/sdp") != 0)
6788       goto wrong_content_type;
6789   }
6790
6791   /* get message body and parse as SDP */
6792   gst_rtsp_message_get_body (&response, &data, &size);
6793   if (data == NULL || size == 0)
6794     goto no_describe;
6795
6796   GST_DEBUG_OBJECT (src, "parse SDP...");
6797   gst_sdp_message_new (sdp);
6798   gst_sdp_message_parse_buffer (data, size, *sdp);
6799
6800   /* clean up any messages */
6801   gst_rtsp_message_unset (&request);
6802   gst_rtsp_message_unset (&response);
6803
6804   return res;
6805
6806   /* ERRORS */
6807 no_url:
6808   {
6809     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6810         ("No valid RTSP URL was provided"));
6811     goto cleanup_error;
6812   }
6813 connect_failed:
6814   {
6815     gchar *str = gst_rtsp_strresult (res);
6816
6817     if (res != GST_RTSP_EINTR) {
6818       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6819           ("Failed to connect. (%s)", str));
6820     } else {
6821       GST_WARNING_OBJECT (src, "connect interrupted");
6822     }
6823     g_free (str);
6824     goto cleanup_error;
6825   }
6826 create_request_failed:
6827   {
6828     gchar *str = gst_rtsp_strresult (res);
6829
6830     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6831         ("Could not create request. (%s)", str));
6832     g_free (str);
6833     goto cleanup_error;
6834   }
6835 send_error:
6836   {
6837     /* Don't post a message - the rtsp_send method will have
6838      * taken care of it because we passed NULL for the response code */
6839     goto cleanup_error;
6840   }
6841 methods_error:
6842   {
6843     /* error was posted */
6844     res = GST_RTSP_ERROR;
6845     goto cleanup_error;
6846   }
6847 wrong_content_type:
6848   {
6849     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6850         ("Server does not support SDP, got %s.", respcont));
6851     res = GST_RTSP_ERROR;
6852     goto cleanup_error;
6853   }
6854 no_describe:
6855   {
6856     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6857         ("Server can not provide an SDP."));
6858     res = GST_RTSP_ERROR;
6859     goto cleanup_error;
6860   }
6861 cleanup_error:
6862   {
6863     if (src->conninfo.connection) {
6864       GST_DEBUG_OBJECT (src, "free connection");
6865       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6866     }
6867     gst_rtsp_message_unset (&request);
6868     gst_rtsp_message_unset (&response);
6869     return res;
6870   }
6871 }
6872
6873 static GstRTSPResult
6874 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6875 {
6876   GstRTSPResult ret;
6877
6878   src->methods =
6879       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6880
6881   if (src->sdp == NULL) {
6882     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6883       goto no_sdp;
6884   }
6885
6886   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6887     goto open_failed;
6888
6889 done:
6890   if (async)
6891     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6892
6893   return ret;
6894
6895   /* ERRORS */
6896 no_sdp:
6897   {
6898     GST_WARNING_OBJECT (src, "can't get sdp");
6899     src->open_error = TRUE;
6900     goto done;
6901   }
6902 open_failed:
6903   {
6904     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6905     src->open_error = TRUE;
6906     goto done;
6907   }
6908 }
6909
6910 static GstRTSPResult
6911 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6912 {
6913   GstRTSPMessage request = { 0 };
6914   GstRTSPMessage response = { 0 };
6915   GstRTSPResult res = GST_RTSP_OK;
6916   GList *walk;
6917   const gchar *control;
6918
6919   GST_DEBUG_OBJECT (src, "TEARDOWN...");
6920
6921   gst_rtspsrc_set_state (src, GST_STATE_READY);
6922
6923   if (src->state < GST_RTSP_STATE_READY) {
6924     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6925     goto close;
6926   }
6927
6928   if (only_close)
6929     goto close;
6930
6931   /* construct a control url */
6932   control = get_aggregate_control (src);
6933
6934   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6935     goto not_supported;
6936
6937   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6938     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6939     const gchar *setup_url;
6940     GstRTSPConnInfo *info;
6941
6942     /* try aggregate control first but do non-aggregate control otherwise */
6943     if (control)
6944       setup_url = control;
6945     else if ((setup_url = stream->conninfo.location) == NULL)
6946       continue;
6947
6948     if (src->conninfo.connection) {
6949       info = &src->conninfo;
6950     } else if (stream->conninfo.connection) {
6951       info = &stream->conninfo;
6952     } else {
6953       continue;
6954     }
6955     if (!info->connected)
6956       goto next;
6957
6958     /* do TEARDOWN */
6959     res =
6960         gst_rtspsrc_init_request (src, &request, GST_RTSP_TEARDOWN, setup_url);
6961     if (res < 0)
6962       goto create_request_failed;
6963
6964     if (async)
6965       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
6966
6967     if ((res =
6968             gst_rtspsrc_send (src, info->connection, &request, &response,
6969                 NULL)) < 0)
6970       goto send_error;
6971
6972     /* FIXME, parse result? */
6973     gst_rtsp_message_unset (&request);
6974     gst_rtsp_message_unset (&response);
6975
6976   next:
6977     /* early exit when we did aggregate control */
6978     if (control)
6979       break;
6980   }
6981
6982 close:
6983   /* close connections */
6984   GST_DEBUG_OBJECT (src, "closing connection...");
6985   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6986   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6987     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6988     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
6989   }
6990
6991   /* cleanup */
6992   gst_rtspsrc_cleanup (src);
6993
6994   src->state = GST_RTSP_STATE_INVALID;
6995
6996   if (async)
6997     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
6998
6999   return res;
7000
7001   /* ERRORS */
7002 create_request_failed:
7003   {
7004     gchar *str = gst_rtsp_strresult (res);
7005
7006     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7007         ("Could not create request. (%s)", str));
7008     g_free (str);
7009     goto close;
7010   }
7011 send_error:
7012   {
7013     gchar *str = gst_rtsp_strresult (res);
7014
7015     gst_rtsp_message_unset (&request);
7016     if (res != GST_RTSP_EINTR) {
7017       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7018           ("Could not send message. (%s)", str));
7019     } else {
7020       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
7021     }
7022     g_free (str);
7023     goto close;
7024   }
7025 not_supported:
7026   {
7027     GST_DEBUG_OBJECT (src,
7028         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
7029     goto close;
7030   }
7031 }
7032
7033 /* RTP-Info is of the format:
7034  *
7035  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
7036  *
7037  * rtptime corresponds to the timestamp for the NPT time given in the header
7038  * seqbase corresponds to the next sequence number we received. This number
7039  * indicates the first seqnum after the seek and should be used to discard
7040  * packets that are from before the seek.
7041  */
7042 static gboolean
7043 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
7044 {
7045   gchar **infos;
7046   gint i, j;
7047
7048   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
7049
7050   infos = g_strsplit (rtpinfo, ",", 0);
7051   for (i = 0; infos[i]; i++) {
7052     gchar **fields;
7053     GstRTSPStream *stream;
7054     gint32 seqbase;
7055     gint64 timebase;
7056
7057     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
7058
7059     /* init values, types of seqbase and timebase are bigger than needed so we
7060      * can store -1 as uninitialized values */
7061     stream = NULL;
7062     seqbase = -1;
7063     timebase = -1;
7064
7065     /* parse url, find stream for url.
7066      * parse seq and rtptime. The seq number should be configured in the rtp
7067      * depayloader or session manager to detect gaps. Same for the rtptime, it
7068      * should be used to create an initial time newsegment. */
7069     fields = g_strsplit (infos[i], ";", 0);
7070     for (j = 0; fields[j]; j++) {
7071       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
7072       /* remove leading whitespace */
7073       fields[j] = g_strchug (fields[j]);
7074       if (g_str_has_prefix (fields[j], "url=")) {
7075         /* get the url and the stream */
7076         stream =
7077             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
7078       } else if (g_str_has_prefix (fields[j], "seq=")) {
7079         seqbase = atoi (fields[j] + 4);
7080       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
7081         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
7082       }
7083     }
7084     g_strfreev (fields);
7085     /* now we need to store the values for the caps of the stream */
7086     if (stream != NULL) {
7087       GST_DEBUG_OBJECT (src,
7088           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
7089           stream, seqbase, timebase);
7090
7091       /* we have a stream, configure detected params */
7092       stream->seqbase = seqbase;
7093       stream->timebase = timebase;
7094     }
7095   }
7096   g_strfreev (infos);
7097
7098   return TRUE;
7099 }
7100
7101 static void
7102 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
7103 {
7104   guint64 interval;
7105   GList *walk;
7106
7107   interval = strtoul (rtcp, NULL, 10);
7108   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
7109
7110   if (!interval)
7111     return;
7112
7113   interval *= GST_MSECOND;
7114
7115   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7116     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7117
7118     /* already (optionally) retrieved this when configuring manager */
7119     if (stream->session) {
7120       GObject *rtpsession = stream->session;
7121
7122       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
7123           rtpsession);
7124       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
7125     }
7126   }
7127
7128   /* now it happens that (Xenon) server sending this may also provide bogus
7129    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
7130    * and just use RTP-Info to sync */
7131   if (src->manager) {
7132     GObjectClass *klass;
7133
7134     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
7135     if (g_object_class_find_property (klass, "rtcp-sync")) {
7136       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
7137       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
7138     }
7139   }
7140 }
7141
7142 static gdouble
7143 gst_rtspsrc_get_float (const gchar * dstr)
7144 {
7145   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7146
7147   /* canonicalise floating point string so we can handle float strings
7148    * in the form "24.930" or "24,930" irrespective of the current locale */
7149   g_strlcpy (s, dstr, sizeof (s));
7150   g_strdelimit (s, ",", '.');
7151   return g_ascii_strtod (s, NULL);
7152 }
7153
7154 static gchar *
7155 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
7156 {
7157   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
7158
7159   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
7160     g_strlcpy (val_str, "now", sizeof (val_str));
7161   } else {
7162     if (segment->position == 0) {
7163       g_strlcpy (val_str, "0", sizeof (val_str));
7164     } else {
7165       g_ascii_dtostr (val_str, sizeof (val_str),
7166           ((gdouble) segment->position) / GST_SECOND);
7167     }
7168   }
7169   return g_strdup_printf ("npt=%s-", val_str);
7170 }
7171
7172 static void
7173 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
7174 {
7175   guint i, len;
7176
7177   stream->timebase = -1;
7178   stream->seqbase = -1;
7179
7180   len = stream->ptmap->len;
7181   for (i = 0; i < len; i++) {
7182     PtMapItem *item = &g_array_index (stream->ptmap, PtMapItem, i);
7183     GstStructure *s;
7184
7185     if (item->caps == NULL)
7186       continue;
7187
7188     item->caps = gst_caps_make_writable (item->caps);
7189     s = gst_caps_get_structure (item->caps, 0);
7190     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
7191     if (item->pt == stream->default_pt && stream->udpsrc[0])
7192       g_object_set (stream->udpsrc[0], "caps", item->caps, NULL);
7193   }
7194   stream->need_caps = TRUE;
7195 }
7196
7197 static GstRTSPResult
7198 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
7199 {
7200   GstRTSPResult res = GST_RTSP_OK;
7201
7202   if (src->state < GST_RTSP_STATE_READY) {
7203     res = GST_RTSP_ERROR;
7204     if (src->open_error) {
7205       GST_DEBUG_OBJECT (src, "the stream was in error");
7206       goto done;
7207     }
7208     if (async)
7209       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
7210
7211     if ((res = gst_rtspsrc_open (src, async)) < 0) {
7212       GST_DEBUG_OBJECT (src, "failed to open stream");
7213       goto done;
7214     }
7215   }
7216
7217 done:
7218   return res;
7219 }
7220
7221 static GstRTSPResult
7222 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
7223 {
7224   GstRTSPMessage request = { 0 };
7225   GstRTSPMessage response = { 0 };
7226   GstRTSPResult res = GST_RTSP_OK;
7227   GList *walk;
7228   gchar *hval;
7229   gint hval_idx;
7230   const gchar *control;
7231
7232   GST_DEBUG_OBJECT (src, "PLAY...");
7233
7234   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7235     goto open_failed;
7236
7237   if (!(src->methods & GST_RTSP_PLAY))
7238     goto not_supported;
7239
7240   if (src->state == GST_RTSP_STATE_PLAYING)
7241     goto was_playing;
7242
7243   if (!src->conninfo.connection || !src->conninfo.connected)
7244     goto done;
7245
7246   /* send some dummy packets before we activate the receive in the
7247    * udp sources */
7248   gst_rtspsrc_send_dummy_packets (src);
7249
7250   /* require new SR packets */
7251   if (src->manager)
7252     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
7253
7254   /* construct a control url */
7255   control = get_aggregate_control (src);
7256
7257   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7258     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7259     const gchar *setup_url;
7260     GstRTSPConnection *conn;
7261
7262     /* try aggregate control first but do non-aggregate control otherwise */
7263     if (control)
7264       setup_url = control;
7265     else if ((setup_url = stream->conninfo.location) == NULL)
7266       continue;
7267
7268     if (src->conninfo.connection) {
7269       conn = src->conninfo.connection;
7270     } else if (stream->conninfo.connection) {
7271       conn = stream->conninfo.connection;
7272     } else {
7273       continue;
7274     }
7275
7276     /* do play */
7277     res = gst_rtspsrc_init_request (src, &request, GST_RTSP_PLAY, setup_url);
7278     if (res < 0)
7279       goto create_request_failed;
7280
7281     if (src->need_range) {
7282       hval = gen_range_header (src, segment);
7283
7284       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
7285
7286       /* store the newsegment event so it can be sent from the streaming thread. */
7287       src->need_segment = TRUE;
7288     }
7289
7290     if (segment->rate != 1.0) {
7291       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
7292
7293       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
7294       if (src->skip)
7295         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
7296       else
7297         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
7298     }
7299
7300     if (async)
7301       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
7302
7303     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7304       goto send_error;
7305
7306     /* seek may have silently failed as it is not supported */
7307     if (!(src->methods & GST_RTSP_PLAY)) {
7308       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
7309       /* obviously it is supported as we made it here */
7310       src->methods |= GST_RTSP_PLAY;
7311       src->seekable = FALSE;
7312       /* but there is nothing to parse in the response,
7313        * so convey we have no idea and not to expect anything particular */
7314       clear_rtp_base (src, stream);
7315       if (control) {
7316         GList *run;
7317
7318         /* need to do for all streams */
7319         for (run = src->streams; run; run = g_list_next (run))
7320           clear_rtp_base (src, (GstRTSPStream *) run->data);
7321       }
7322       /* NOTE the above also disables npt based eos detection */
7323       /* and below forces position to 0,
7324        * which is visible feedback we lost the plot */
7325       segment->start = segment->position = src->last_pos;
7326     }
7327
7328     gst_rtsp_message_unset (&request);
7329
7330     /* parse RTP npt field. This is the current position in the stream (Normal
7331      * Play Time) and should be put in the NEWSEGMENT position field. */
7332     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
7333             0) == GST_RTSP_OK)
7334       gst_rtspsrc_parse_range (src, hval, segment);
7335
7336     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
7337     segment->rate = 1.0;
7338
7339     /* parse Speed header. This is the intended playback rate of the stream
7340      * and should be put in the NEWSEGMENT rate field. */
7341     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
7342             0) == GST_RTSP_OK) {
7343       segment->rate = gst_rtspsrc_get_float (hval);
7344     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
7345             &hval, 0) == GST_RTSP_OK) {
7346       segment->rate = gst_rtspsrc_get_float (hval);
7347     }
7348
7349     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
7350      * for the RTP packets. If this is not present, we assume all starts from 0...
7351      * This is info for the RTP session manager that we pass to it in caps. */
7352     hval_idx = 0;
7353     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
7354             &hval, hval_idx++) == GST_RTSP_OK)
7355       gst_rtspsrc_parse_rtpinfo (src, hval);
7356
7357     /* some servers indicate RTCP parameters in PLAY response,
7358      * rather than properly in SDP */
7359     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
7360             &hval, 0) == GST_RTSP_OK)
7361       gst_rtspsrc_handle_rtcp_interval (src, hval);
7362
7363     gst_rtsp_message_unset (&response);
7364
7365     /* early exit when we did aggregate control */
7366     if (control)
7367       break;
7368   }
7369   /* configure the caps of the streams after we parsed all headers. Only reset
7370    * the manager object when we set a new Range header (we did a seek) */
7371   gst_rtspsrc_configure_caps (src, segment, src->need_range);
7372
7373   /* set to PLAYING after we have configured the caps, otherwise we
7374    * might end up calling request_key (with SRTP) while caps are still
7375    * being configured. */
7376   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
7377
7378   /* set again when needed */
7379   src->need_range = FALSE;
7380
7381   src->running = TRUE;
7382   src->base_time = -1;
7383   src->state = GST_RTSP_STATE_PLAYING;
7384
7385   /* mark discont */
7386   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
7387   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7388     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7389     stream->discont = TRUE;
7390   }
7391
7392 done:
7393   if (async)
7394     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
7395
7396   return res;
7397
7398   /* ERRORS */
7399 open_failed:
7400   {
7401     GST_DEBUG_OBJECT (src, "failed to open stream");
7402     goto done;
7403   }
7404 not_supported:
7405   {
7406     GST_DEBUG_OBJECT (src, "PLAY is not supported");
7407     goto done;
7408   }
7409 was_playing:
7410   {
7411     GST_DEBUG_OBJECT (src, "we were already PLAYING");
7412     goto done;
7413   }
7414 create_request_failed:
7415   {
7416     gchar *str = gst_rtsp_strresult (res);
7417
7418     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7419         ("Could not create request. (%s)", str));
7420     g_free (str);
7421     goto done;
7422   }
7423 send_error:
7424   {
7425     gchar *str = gst_rtsp_strresult (res);
7426
7427     gst_rtsp_message_unset (&request);
7428     if (res != GST_RTSP_EINTR) {
7429       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7430           ("Could not send message. (%s)", str));
7431     } else {
7432       GST_WARNING_OBJECT (src, "PLAY interrupted");
7433     }
7434     g_free (str);
7435     goto done;
7436   }
7437 }
7438
7439 static GstRTSPResult
7440 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
7441 {
7442   GstRTSPResult res = GST_RTSP_OK;
7443   GstRTSPMessage request = { 0 };
7444   GstRTSPMessage response = { 0 };
7445   GList *walk;
7446   const gchar *control;
7447
7448   GST_DEBUG_OBJECT (src, "PAUSE...");
7449
7450   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
7451     goto open_failed;
7452
7453   if (!(src->methods & GST_RTSP_PAUSE))
7454     goto not_supported;
7455
7456   if (src->state == GST_RTSP_STATE_READY)
7457     goto was_paused;
7458
7459   if (!src->conninfo.connection || !src->conninfo.connected)
7460     goto no_connection;
7461
7462   /* construct a control url */
7463   control = get_aggregate_control (src);
7464
7465   /* loop over the streams. We might exit the loop early when we could do an
7466    * aggregate control */
7467   for (walk = src->streams; walk; walk = g_list_next (walk)) {
7468     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
7469     GstRTSPConnection *conn;
7470     const gchar *setup_url;
7471
7472     /* try aggregate control first but do non-aggregate control otherwise */
7473     if (control)
7474       setup_url = control;
7475     else if ((setup_url = stream->conninfo.location) == NULL)
7476       continue;
7477
7478     if (src->conninfo.connection) {
7479       conn = src->conninfo.connection;
7480     } else if (stream->conninfo.connection) {
7481       conn = stream->conninfo.connection;
7482     } else {
7483       continue;
7484     }
7485
7486     if (async)
7487       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
7488           ("Sending PAUSE request"));
7489
7490     if ((res =
7491             gst_rtspsrc_init_request (src, &request, GST_RTSP_PAUSE,
7492                 setup_url)) < 0)
7493       goto create_request_failed;
7494
7495     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
7496       goto send_error;
7497
7498     gst_rtsp_message_unset (&request);
7499     gst_rtsp_message_unset (&response);
7500
7501     /* exit early when we did agregate control */
7502     if (control)
7503       break;
7504   }
7505
7506   /* change element states now */
7507   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
7508
7509 no_connection:
7510   src->state = GST_RTSP_STATE_READY;
7511
7512 done:
7513   if (async)
7514     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
7515
7516   return res;
7517
7518   /* ERRORS */
7519 open_failed:
7520   {
7521     GST_DEBUG_OBJECT (src, "failed to open stream");
7522     goto done;
7523   }
7524 not_supported:
7525   {
7526     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
7527     goto done;
7528   }
7529 was_paused:
7530   {
7531     GST_DEBUG_OBJECT (src, "we were already PAUSED");
7532     goto done;
7533   }
7534 create_request_failed:
7535   {
7536     gchar *str = gst_rtsp_strresult (res);
7537
7538     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
7539         ("Could not create request. (%s)", str));
7540     g_free (str);
7541     goto done;
7542   }
7543 send_error:
7544   {
7545     gchar *str = gst_rtsp_strresult (res);
7546
7547     gst_rtsp_message_unset (&request);
7548     if (res != GST_RTSP_EINTR) {
7549       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
7550           ("Could not send message. (%s)", str));
7551     } else {
7552       GST_WARNING_OBJECT (src, "PAUSE interrupted");
7553     }
7554     g_free (str);
7555     goto done;
7556   }
7557 }
7558
7559 static void
7560 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
7561 {
7562   GstRTSPSrc *rtspsrc;
7563
7564   rtspsrc = GST_RTSPSRC (bin);
7565
7566   switch (GST_MESSAGE_TYPE (message)) {
7567     case GST_MESSAGE_EOS:
7568       gst_message_unref (message);
7569       break;
7570     case GST_MESSAGE_ELEMENT:
7571     {
7572       const GstStructure *s = gst_message_get_structure (message);
7573
7574       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
7575         gboolean ignore_timeout;
7576
7577         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
7578
7579         GST_OBJECT_LOCK (rtspsrc);
7580         ignore_timeout = rtspsrc->ignore_timeout;
7581         rtspsrc->ignore_timeout = TRUE;
7582         GST_OBJECT_UNLOCK (rtspsrc);
7583
7584         /* we only act on the first udp timeout message, others are irrelevant
7585          * and can be ignored. */
7586         if (!ignore_timeout)
7587           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
7588         /* eat and free */
7589         gst_message_unref (message);
7590         return;
7591       }
7592       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7593       break;
7594     }
7595     case GST_MESSAGE_ERROR:
7596     {
7597       GstObject *udpsrc;
7598       GstRTSPStream *stream;
7599       GstFlowReturn ret;
7600
7601       udpsrc = GST_MESSAGE_SRC (message);
7602
7603       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
7604           GST_ELEMENT_NAME (udpsrc));
7605
7606       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
7607       if (!stream)
7608         goto forward;
7609
7610       /* we ignore the RTCP udpsrc */
7611       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
7612         goto done;
7613
7614       /* if we get error messages from the udp sources, that's not a problem as
7615        * long as not all of them error out. We also don't really know what the
7616        * problem is, the message does not give enough detail... */
7617       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
7618       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
7619       if (ret != GST_FLOW_OK)
7620         goto forward;
7621
7622     done:
7623       gst_message_unref (message);
7624       break;
7625
7626     forward:
7627       /* fatal but not our message, forward */
7628       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7629       break;
7630     }
7631     default:
7632     {
7633       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7634       break;
7635     }
7636   }
7637 }
7638
7639 /* the thread where everything happens */
7640 static void
7641 gst_rtspsrc_thread (GstRTSPSrc * src)
7642 {
7643   gint cmd;
7644
7645   GST_OBJECT_LOCK (src);
7646   cmd = src->pending_cmd;
7647   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
7648       || cmd == CMD_LOOP || cmd == CMD_OPEN)
7649     src->pending_cmd = CMD_LOOP;
7650   else
7651     src->pending_cmd = CMD_WAIT;
7652   GST_DEBUG_OBJECT (src, "got command %s", cmd_to_string (cmd));
7653
7654   /* we got the message command, so ensure communication is possible again */
7655   gst_rtspsrc_connection_flush (src, FALSE);
7656
7657   src->busy_cmd = cmd;
7658   GST_OBJECT_UNLOCK (src);
7659
7660   switch (cmd) {
7661     case CMD_OPEN:
7662       gst_rtspsrc_open (src, TRUE);
7663       break;
7664     case CMD_PLAY:
7665       gst_rtspsrc_play (src, &src->segment, TRUE);
7666       break;
7667     case CMD_PAUSE:
7668       gst_rtspsrc_pause (src, TRUE);
7669       break;
7670     case CMD_CLOSE:
7671       gst_rtspsrc_close (src, TRUE, FALSE);
7672       break;
7673     case CMD_LOOP:
7674       gst_rtspsrc_loop (src);
7675       break;
7676     case CMD_RECONNECT:
7677       gst_rtspsrc_reconnect (src, FALSE);
7678       break;
7679     default:
7680       break;
7681   }
7682
7683   GST_OBJECT_LOCK (src);
7684   /* and go back to sleep */
7685   if (src->pending_cmd == CMD_WAIT) {
7686     if (src->task)
7687       gst_task_pause (src->task);
7688   }
7689   /* reset waiting */
7690   src->busy_cmd = CMD_WAIT;
7691   GST_OBJECT_UNLOCK (src);
7692 }
7693
7694 static gboolean
7695 gst_rtspsrc_start (GstRTSPSrc * src)
7696 {
7697   GST_DEBUG_OBJECT (src, "starting");
7698
7699   GST_OBJECT_LOCK (src);
7700
7701   src->pending_cmd = CMD_WAIT;
7702
7703   if (src->task == NULL) {
7704     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
7705     if (src->task == NULL)
7706       goto task_error;
7707
7708     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
7709   }
7710   GST_OBJECT_UNLOCK (src);
7711
7712   return TRUE;
7713
7714   /* ERRORS */
7715 task_error:
7716   {
7717     GST_OBJECT_UNLOCK (src);
7718     GST_ERROR_OBJECT (src, "failed to create task");
7719     return FALSE;
7720   }
7721 }
7722
7723 static gboolean
7724 gst_rtspsrc_stop (GstRTSPSrc * src)
7725 {
7726   GstTask *task;
7727
7728   GST_DEBUG_OBJECT (src, "stopping");
7729
7730   /* also cancels pending task */
7731   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
7732
7733   GST_OBJECT_LOCK (src);
7734   if ((task = src->task)) {
7735     src->task = NULL;
7736     GST_OBJECT_UNLOCK (src);
7737
7738     gst_task_stop (task);
7739
7740     /* make sure it is not running */
7741     GST_RTSP_STREAM_LOCK (src);
7742     GST_RTSP_STREAM_UNLOCK (src);
7743
7744     /* now wait for the task to finish */
7745     gst_task_join (task);
7746
7747     /* and free the task */
7748     gst_object_unref (GST_OBJECT (task));
7749
7750     GST_OBJECT_LOCK (src);
7751   }
7752   GST_OBJECT_UNLOCK (src);
7753
7754   /* ensure synchronously all is closed and clean */
7755   gst_rtspsrc_close (src, FALSE, TRUE);
7756
7757   return TRUE;
7758 }
7759
7760 static GstStateChangeReturn
7761 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
7762 {
7763   GstRTSPSrc *rtspsrc;
7764   GstStateChangeReturn ret;
7765
7766   rtspsrc = GST_RTSPSRC (element);
7767
7768   switch (transition) {
7769     case GST_STATE_CHANGE_NULL_TO_READY:
7770       if (!gst_rtspsrc_start (rtspsrc))
7771         goto start_failed;
7772       break;
7773     case GST_STATE_CHANGE_READY_TO_PAUSED:
7774       /* init some state */
7775       rtspsrc->cur_protocols = rtspsrc->protocols;
7776       /* first attempt, don't ignore timeouts */
7777       rtspsrc->ignore_timeout = FALSE;
7778       rtspsrc->open_error = FALSE;
7779       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
7780       break;
7781     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7782       set_manager_buffer_mode (rtspsrc);
7783       /* fall-through */
7784     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7785       /* unblock the tcp tasks and make the loop waiting */
7786       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
7787         /* make sure it is waiting before we send PAUSE or PLAY below */
7788         GST_RTSP_STREAM_LOCK (rtspsrc);
7789         GST_RTSP_STREAM_UNLOCK (rtspsrc);
7790       }
7791       break;
7792     case GST_STATE_CHANGE_PAUSED_TO_READY:
7793       break;
7794     default:
7795       break;
7796   }
7797
7798   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7799   if (ret == GST_STATE_CHANGE_FAILURE)
7800     goto done;
7801
7802   switch (transition) {
7803     case GST_STATE_CHANGE_NULL_TO_READY:
7804       ret = GST_STATE_CHANGE_SUCCESS;
7805       break;
7806     case GST_STATE_CHANGE_READY_TO_PAUSED:
7807       ret = GST_STATE_CHANGE_NO_PREROLL;
7808       break;
7809     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7810       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7811       ret = GST_STATE_CHANGE_SUCCESS;
7812       break;
7813     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7814       /* send pause request and keep the idle task around */
7815       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7816       ret = GST_STATE_CHANGE_NO_PREROLL;
7817       break;
7818     case GST_STATE_CHANGE_PAUSED_TO_READY:
7819       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7820       ret = GST_STATE_CHANGE_SUCCESS;
7821       break;
7822     case GST_STATE_CHANGE_READY_TO_NULL:
7823       gst_rtspsrc_stop (rtspsrc);
7824       ret = GST_STATE_CHANGE_SUCCESS;
7825       break;
7826     default:
7827       /* Otherwise it's success, we don't want to return spurious
7828        * NO_PREROLL or ASYNC from internal elements as we care for
7829        * state changes ourselves here
7830        *
7831        * This is to catch PAUSED->PAUSED and PLAYING->PLAYING transitions.
7832        */
7833       if (GST_STATE_TRANSITION_NEXT (transition) == GST_STATE_PAUSED)
7834         ret = GST_STATE_CHANGE_NO_PREROLL;
7835       else
7836         ret = GST_STATE_CHANGE_SUCCESS;
7837       break;
7838   }
7839
7840 done:
7841   return ret;
7842
7843 start_failed:
7844   {
7845     GST_DEBUG_OBJECT (rtspsrc, "start failed");
7846     return GST_STATE_CHANGE_FAILURE;
7847   }
7848 }
7849
7850 static gboolean
7851 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7852 {
7853   gboolean res;
7854   GstRTSPSrc *rtspsrc;
7855
7856   rtspsrc = GST_RTSPSRC (element);
7857
7858   if (GST_EVENT_IS_DOWNSTREAM (event)) {
7859     res = gst_rtspsrc_push_event (rtspsrc, event);
7860   } else {
7861     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7862   }
7863
7864   return res;
7865 }
7866
7867
7868 /*** GSTURIHANDLER INTERFACE *************************************************/
7869
7870 static GstURIType
7871 gst_rtspsrc_uri_get_type (GType type)
7872 {
7873   return GST_URI_SRC;
7874 }
7875
7876 static const gchar *const *
7877 gst_rtspsrc_uri_get_protocols (GType type)
7878 {
7879   static const gchar *protocols[] =
7880       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7881     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7882   };
7883
7884   return protocols;
7885 }
7886
7887 static gchar *
7888 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7889 {
7890   GstRTSPSrc *src = GST_RTSPSRC (handler);
7891
7892   /* FIXME: make thread-safe */
7893   return g_strdup (src->conninfo.location);
7894 }
7895
7896 static gboolean
7897 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7898     GError ** error)
7899 {
7900   GstRTSPSrc *src;
7901   GstRTSPResult res;
7902   GstSDPResult sres;
7903   GstRTSPUrl *newurl = NULL;
7904   GstSDPMessage *sdp = NULL;
7905
7906   src = GST_RTSPSRC (handler);
7907
7908   /* same URI, we're fine */
7909   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7910     goto was_ok;
7911
7912   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7913     sres = gst_sdp_message_new (&sdp);
7914     if (sres < 0)
7915       goto sdp_failed;
7916
7917     GST_DEBUG_OBJECT (src, "parsing SDP message");
7918     sres = gst_sdp_message_parse_uri (uri, sdp);
7919     if (sres < 0)
7920       goto invalid_sdp;
7921   } else {
7922     /* try to parse */
7923     GST_DEBUG_OBJECT (src, "parsing URI");
7924     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7925       goto parse_error;
7926   }
7927
7928   /* if worked, free previous and store new url object along with the original
7929    * location. */
7930   GST_DEBUG_OBJECT (src, "configuring URI");
7931   g_free (src->conninfo.location);
7932   src->conninfo.location = g_strdup (uri);
7933   gst_rtsp_url_free (src->conninfo.url);
7934   src->conninfo.url = newurl;
7935   g_free (src->conninfo.url_str);
7936   if (newurl)
7937     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7938   else
7939     src->conninfo.url_str = NULL;
7940
7941   if (src->sdp)
7942     gst_sdp_message_free (src->sdp);
7943   src->sdp = sdp;
7944   src->from_sdp = sdp != NULL;
7945
7946   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7947   GST_DEBUG_OBJECT (src, "request uri is: %s",
7948       GST_STR_NULL (src->conninfo.url_str));
7949
7950   return TRUE;
7951
7952   /* Special cases */
7953 was_ok:
7954   {
7955     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7956     return TRUE;
7957   }
7958 sdp_failed:
7959   {
7960     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", sres);
7961     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7962         "Could not create SDP");
7963     return FALSE;
7964   }
7965 invalid_sdp:
7966   {
7967     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", sres,
7968         GST_STR_NULL (uri));
7969     gst_sdp_message_free (sdp);
7970     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7971         "Invalid SDP");
7972     return FALSE;
7973   }
7974 parse_error:
7975   {
7976     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7977         GST_STR_NULL (uri), res);
7978     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7979         "Invalid RTSP URI");
7980     return FALSE;
7981   }
7982 }
7983
7984 static void
7985 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
7986 {
7987   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
7988
7989   iface->get_type = gst_rtspsrc_uri_get_type;
7990   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
7991   iface->get_uri = gst_rtspsrc_uri_get_uri;
7992   iface->set_uri = gst_rtspsrc_uri_set_uri;
7993 }