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