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