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