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