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