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