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