more memory API porting
[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   GstRTSPSrc *src;
1954   gboolean res;
1955
1956   src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
1957
1958   GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
1959       GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
1960
1961   switch (GST_EVENT_TYPE (event)) {
1962     case GST_EVENT_SEEK:
1963     case GST_EVENT_QOS:
1964     case GST_EVENT_NAVIGATION:
1965     case GST_EVENT_LATENCY:
1966     default:
1967       gst_event_unref (event);
1968       res = TRUE;
1969       break;
1970   }
1971   return res;
1972 }
1973
1974 /* this is the final query function we receive on the internal source pad when
1975  * we deal with TCP connections */
1976 static gboolean
1977 gst_rtspsrc_handle_internal_src_query (GstPad * pad, GstObject * parent,
1978     GstQuery * query)
1979 {
1980   GstRTSPSrc *src;
1981   gboolean res = TRUE;
1982
1983   src = GST_RTSPSRC_CAST (gst_pad_get_element_private (pad));
1984
1985   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
1986       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
1987
1988   switch (GST_QUERY_TYPE (query)) {
1989     case GST_QUERY_POSITION:
1990     {
1991       /* no idea */
1992       break;
1993     }
1994     case GST_QUERY_DURATION:
1995     {
1996       GstFormat format;
1997
1998       gst_query_parse_duration (query, &format, NULL);
1999
2000       switch (format) {
2001         case GST_FORMAT_TIME:
2002           gst_query_set_duration (query, format, src->segment.duration);
2003           break;
2004         default:
2005           res = FALSE;
2006           break;
2007       }
2008       break;
2009     }
2010     case GST_QUERY_LATENCY:
2011     {
2012       /* we are live with a min latency of 0 and unlimited max latency, this
2013        * result will be updated by the session manager if there is any. */
2014       gst_query_set_latency (query, TRUE, 0, -1);
2015       break;
2016     }
2017     default:
2018       break;
2019   }
2020
2021   return res;
2022 }
2023
2024 /* this query is executed on the ghost source pad exposed on rtspsrc. */
2025 static gboolean
2026 gst_rtspsrc_handle_src_query (GstPad * pad, GstObject * parent,
2027     GstQuery * query)
2028 {
2029   GstRTSPSrc *src;
2030   gboolean res = FALSE;
2031
2032   src = GST_RTSPSRC_CAST (parent);
2033
2034   GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
2035       GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
2036
2037   switch (GST_QUERY_TYPE (query)) {
2038     case GST_QUERY_DURATION:
2039     {
2040       GstFormat format;
2041
2042       gst_query_parse_duration (query, &format, NULL);
2043
2044       switch (format) {
2045         case GST_FORMAT_TIME:
2046           gst_query_set_duration (query, format, src->segment.duration);
2047           res = TRUE;
2048           break;
2049         default:
2050           break;
2051       }
2052       break;
2053     }
2054     case GST_QUERY_SEEKING:
2055     {
2056       GstFormat format;
2057
2058       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2059       if (format == GST_FORMAT_TIME) {
2060         gboolean seekable =
2061             src->cur_protocols != GST_RTSP_LOWER_TRANS_UDP_MCAST;
2062
2063         /* seeking without duration is unlikely */
2064         seekable = seekable && src->seekable && src->segment.duration &&
2065             GST_CLOCK_TIME_IS_VALID (src->segment.duration);
2066
2067         /* FIXME ?? should we have 0 and segment.duration here; see demuxers */
2068         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
2069             src->segment.start, src->segment.stop);
2070         res = TRUE;
2071       }
2072       break;
2073     }
2074     default:
2075     {
2076       GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
2077
2078       /* forward the query to the proxy target pad */
2079       if (target) {
2080         res = gst_pad_query (target, query);
2081         gst_object_unref (target);
2082       }
2083       break;
2084     }
2085   }
2086
2087   return res;
2088 }
2089
2090 /* callback for RTCP messages to be sent to the server when operating in TCP
2091  * mode. */
2092 static GstFlowReturn
2093 gst_rtspsrc_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2094 {
2095   GstRTSPSrc *src;
2096   GstRTSPStream *stream;
2097   GstFlowReturn res = GST_FLOW_OK;
2098   GstMapInfo map;
2099   guint8 *data;
2100   guint size;
2101   GstRTSPResult ret;
2102   GstRTSPMessage message = { 0 };
2103   GstRTSPConnection *conn;
2104
2105   stream = (GstRTSPStream *) gst_pad_get_element_private (pad);
2106   src = stream->parent;
2107
2108   gst_buffer_map (buffer, &map, GST_MAP_READ);
2109   size = map.size;
2110   data = map.data;
2111
2112   gst_rtsp_message_init_data (&message, stream->channel[1]);
2113
2114   /* lend the body data to the message */
2115   gst_rtsp_message_take_body (&message, data, size);
2116
2117   if (stream->conninfo.connection)
2118     conn = stream->conninfo.connection;
2119   else
2120     conn = src->conninfo.connection;
2121
2122   GST_DEBUG_OBJECT (src, "sending %u bytes RTCP", size);
2123   ret = gst_rtspsrc_connection_send (src, conn, &message, NULL);
2124   GST_DEBUG_OBJECT (src, "sent RTCP, %d", ret);
2125
2126   /* and steal it away again because we will free it when unreffing the
2127    * buffer */
2128   gst_rtsp_message_steal_body (&message, &data, &size);
2129   gst_rtsp_message_unset (&message);
2130
2131   gst_buffer_unmap (buffer, &map);
2132   gst_buffer_unref (buffer);
2133
2134   return res;
2135 }
2136
2137 static GstPadProbeReturn
2138 pad_blocked (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2139 {
2140   GstRTSPSrc *src = user_data;
2141
2142   GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
2143       GST_DEBUG_PAD_NAME (pad));
2144
2145   /* activate the streams */
2146   GST_OBJECT_LOCK (src);
2147   if (!src->need_activate)
2148     goto was_ok;
2149
2150   src->need_activate = FALSE;
2151   GST_OBJECT_UNLOCK (src);
2152
2153   gst_rtspsrc_activate_streams (src);
2154
2155   return GST_PAD_PROBE_OK;
2156
2157 was_ok:
2158   {
2159     GST_OBJECT_UNLOCK (src);
2160     return GST_PAD_PROBE_OK;
2161   }
2162 }
2163
2164 /* this callback is called when the session manager generated a new src pad with
2165  * payloaded RTP packets. We simply ghost the pad here. */
2166 static void
2167 new_manager_pad (GstElement * manager, GstPad * pad, GstRTSPSrc * src)
2168 {
2169   gchar *name;
2170   GstPadTemplate *template;
2171   gint id, ssrc, pt;
2172   GList *lstream;
2173   GstRTSPStream *stream;
2174   gboolean all_added;
2175
2176   GST_DEBUG_OBJECT (src, "got new manager pad %" GST_PTR_FORMAT, pad);
2177
2178   GST_RTSP_STATE_LOCK (src);
2179   /* find stream */
2180   name = gst_object_get_name (GST_OBJECT_CAST (pad));
2181   if (sscanf (name, "recv_rtp_src_%u_%u_%u", &id, &ssrc, &pt) != 3)
2182     goto unknown_stream;
2183
2184   GST_DEBUG_OBJECT (src, "stream: %u, SSRC %d, PT %d", id, ssrc, pt);
2185
2186   stream = find_stream (src, &id, (gpointer) find_stream_by_id);
2187   if (stream == NULL)
2188     goto unknown_stream;
2189
2190   /* create a new pad we will use to stream to */
2191   template = gst_static_pad_template_get (&rtptemplate);
2192   stream->srcpad = gst_ghost_pad_new_from_template (name, pad, template);
2193   gst_object_unref (template);
2194   g_free (name);
2195
2196   stream->added = TRUE;
2197   gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
2198   gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
2199   gst_pad_set_active (stream->srcpad, TRUE);
2200   gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
2201
2202   /* check if we added all streams */
2203   all_added = TRUE;
2204   for (lstream = src->streams; lstream; lstream = g_list_next (lstream)) {
2205     stream = (GstRTSPStream *) lstream->data;
2206
2207     GST_DEBUG_OBJECT (src, "stream %p, container %d, disabled %d, added %d",
2208         stream, stream->container, stream->disabled, stream->added);
2209
2210     /* a container stream only needs one pad added. Also disabled streams don't
2211      * count */
2212     if (!stream->container && !stream->disabled && !stream->added) {
2213       all_added = FALSE;
2214       break;
2215     }
2216   }
2217   GST_RTSP_STATE_UNLOCK (src);
2218
2219   if (all_added) {
2220     GST_DEBUG_OBJECT (src, "We added all streams");
2221     /* when we get here, all stream are added and we can fire the no-more-pads
2222      * signal. */
2223     gst_element_no_more_pads (GST_ELEMENT_CAST (src));
2224   }
2225
2226   return;
2227
2228   /* ERRORS */
2229 unknown_stream:
2230   {
2231     GST_DEBUG_OBJECT (src, "ignoring unknown stream");
2232     GST_RTSP_STATE_UNLOCK (src);
2233     g_free (name);
2234     return;
2235   }
2236 }
2237
2238 static GstCaps *
2239 request_pt_map (GstElement * manager, guint session, guint pt, GstRTSPSrc * src)
2240 {
2241   GstRTSPStream *stream;
2242   GstCaps *caps;
2243
2244   GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session);
2245
2246   GST_RTSP_STATE_LOCK (src);
2247   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2248   if (!stream)
2249     goto unknown_stream;
2250
2251   caps = stream->caps;
2252   if (caps)
2253     gst_caps_ref (caps);
2254   GST_RTSP_STATE_UNLOCK (src);
2255
2256   return caps;
2257
2258 unknown_stream:
2259   {
2260     GST_DEBUG_OBJECT (src, "unknown stream %d", session);
2261     GST_RTSP_STATE_UNLOCK (src);
2262     return NULL;
2263   }
2264 }
2265
2266 static void
2267 gst_rtspsrc_do_stream_eos (GstRTSPSrc * src, GstRTSPStream * stream)
2268 {
2269   GST_DEBUG_OBJECT (src, "setting stream for session %u to EOS", stream->id);
2270
2271   if (stream->eos)
2272     goto was_eos;
2273
2274   stream->eos = TRUE;
2275   gst_rtspsrc_stream_push_event (src, stream, gst_event_new_eos (), TRUE);
2276   return;
2277
2278   /* ERRORS */
2279 was_eos:
2280   {
2281     GST_DEBUG_OBJECT (src, "stream for session %u was already EOS", stream->id);
2282     return;
2283   }
2284 }
2285
2286 static void
2287 on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
2288 {
2289   GstRTSPSrc *src = stream->parent;
2290
2291   GST_DEBUG_OBJECT (src, "source in session %u received BYE", stream->id);
2292
2293   gst_rtspsrc_do_stream_eos (src, stream);
2294 }
2295
2296 static void
2297 on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
2298 {
2299   GstRTSPSrc *src = stream->parent;
2300
2301   GST_DEBUG_OBJECT (src, "source in session %u timed out", stream->id);
2302
2303   gst_rtspsrc_do_stream_eos (src, stream);
2304 }
2305
2306 static void
2307 on_npt_stop (GstElement * rtpbin, guint session, guint ssrc, GstRTSPSrc * src)
2308 {
2309   GstRTSPStream *stream;
2310
2311   GST_DEBUG_OBJECT (src, "source in session %u reached NPT stop", session);
2312
2313   /* get stream for session */
2314   stream = find_stream (src, &session, (gpointer) find_stream_by_id);
2315   if (stream) {
2316     gst_rtspsrc_do_stream_eos (src, stream);
2317   }
2318 }
2319
2320 static void
2321 on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
2322 {
2323   GST_DEBUG_OBJECT (stream->parent, "source in session %u is active",
2324       stream->id);
2325 }
2326
2327 /* try to get and configure a manager */
2328 static gboolean
2329 gst_rtspsrc_stream_configure_manager (GstRTSPSrc * src, GstRTSPStream * stream,
2330     GstRTSPTransport * transport)
2331 {
2332   const gchar *manager;
2333   gchar *name;
2334   GstStateChangeReturn ret;
2335
2336   /* find a manager */
2337   if (gst_rtsp_transport_get_manager (transport->trans, &manager, 0) < 0)
2338     goto no_manager;
2339
2340   if (manager) {
2341     GST_DEBUG_OBJECT (src, "using manager %s", manager);
2342
2343     /* configure the manager */
2344     if (src->manager == NULL) {
2345       GObjectClass *klass;
2346       GstState target;
2347
2348       if (!(src->manager = gst_element_factory_make (manager, NULL))) {
2349         /* fallback */
2350         if (gst_rtsp_transport_get_manager (transport->trans, &manager, 1) < 0)
2351           goto no_manager;
2352
2353         if (!manager)
2354           goto use_no_manager;
2355
2356         if (!(src->manager = gst_element_factory_make (manager, NULL)))
2357           goto manager_failed;
2358       }
2359
2360       /* we manage this element */
2361       gst_bin_add (GST_BIN_CAST (src), src->manager);
2362
2363       GST_OBJECT_LOCK (src);
2364       target = GST_STATE_TARGET (src);
2365       GST_OBJECT_UNLOCK (src);
2366
2367       ret = gst_element_set_state (src->manager, target);
2368       if (ret == GST_STATE_CHANGE_FAILURE)
2369         goto start_manager_failure;
2370
2371       g_object_set (src->manager, "latency", src->latency, NULL);
2372
2373       klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
2374       if (g_object_class_find_property (klass, "buffer-mode")) {
2375         if (src->buffer_mode != BUFFER_MODE_AUTO) {
2376           g_object_set (src->manager, "buffer-mode", src->buffer_mode, NULL);
2377         } else {
2378           gboolean need_slave;
2379           GstStructure *s;
2380           const gchar *encoding;
2381
2382           /* buffer mode pauses are handled by adding offsets to buffer times,
2383            * but some depayloaders may have a hard time syncing output times
2384            * with such input times, e.g. container ones, most notably ASF */
2385           /* TODO alternatives are having an event that indicates these shifts,
2386            * or having rtsp extensions provide suggestion on buffer mode */
2387           need_slave = stream->container;
2388           if (stream->caps && (s = gst_caps_get_structure (stream->caps, 0)) &&
2389               (encoding = gst_structure_get_string (s, "encoding-name")))
2390             need_slave = need_slave || (strcmp (encoding, "X-ASF-PF") == 0);
2391           GST_DEBUG_OBJECT (src, "auto buffering mode, need_slave %d",
2392               need_slave);
2393           /* valid duration implies not likely live pipeline,
2394            * so slaving in jitterbuffer does not make much sense
2395            * (and might mess things up due to bursts) */
2396           if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
2397               src->segment.duration && !need_slave) {
2398             GST_DEBUG_OBJECT (src, "selected buffer");
2399             g_object_set (src->manager, "buffer-mode", BUFFER_MODE_BUFFER,
2400                 NULL);
2401           } else {
2402             GST_DEBUG_OBJECT (src, "selected slave");
2403             g_object_set (src->manager, "buffer-mode", BUFFER_MODE_SLAVE, NULL);
2404           }
2405         }
2406       }
2407
2408       /* connect to signals if we did not already do so */
2409       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
2410           stream);
2411       src->manager_sig_id =
2412           g_signal_connect (src->manager, "pad-added",
2413           (GCallback) new_manager_pad, src);
2414       src->manager_ptmap_id =
2415           g_signal_connect (src->manager, "request-pt-map",
2416           (GCallback) request_pt_map, src);
2417
2418       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
2419           src);
2420     }
2421
2422     /* we stream directly to the manager, get some pads. Each RTSP stream goes
2423      * into a separate RTP session. */
2424     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
2425     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
2426     g_free (name);
2427     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
2428     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
2429     g_free (name);
2430
2431     /* now configure the bandwidth in the manager */
2432     if (g_signal_lookup ("get-internal-session",
2433             G_OBJECT_TYPE (src->manager)) != 0) {
2434       GObject *rtpsession;
2435
2436       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
2437           &rtpsession);
2438       if (rtpsession) {
2439         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
2440
2441         stream->session = rtpsession;
2442
2443         if (stream->as_bandwidth != -1) {
2444           GST_INFO_OBJECT (src, "setting AS: %f",
2445               (gdouble) (stream->as_bandwidth * 1000));
2446           g_object_set (rtpsession, "bandwidth",
2447               (gdouble) (stream->as_bandwidth * 1000), NULL);
2448         }
2449         if (stream->rr_bandwidth != -1) {
2450           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
2451           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
2452               NULL);
2453         }
2454         if (stream->rs_bandwidth != -1) {
2455           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
2456           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
2457               NULL);
2458         }
2459         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
2460             stream);
2461         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
2462             stream);
2463         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
2464             stream);
2465         g_signal_connect (rtpsession, "on-ssrc-active",
2466             (GCallback) on_ssrc_active, stream);
2467       }
2468     }
2469   }
2470
2471 use_no_manager:
2472   return TRUE;
2473
2474   /* ERRORS */
2475 no_manager:
2476   {
2477     GST_DEBUG_OBJECT (src, "cannot get a session manager");
2478     return FALSE;
2479   }
2480 manager_failed:
2481   {
2482     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
2483     return FALSE;
2484   }
2485 start_manager_failure:
2486   {
2487     GST_DEBUG_OBJECT (src, "could not start session manager");
2488     return FALSE;
2489   }
2490 }
2491
2492 /* free the UDP sources allocated when negotiating a transport.
2493  * This function is called when the server negotiated to a transport where the
2494  * UDP sources are not needed anymore, such as TCP or multicast. */
2495 static void
2496 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
2497 {
2498   gint i;
2499
2500   for (i = 0; i < 2; i++) {
2501     if (stream->udpsrc[i]) {
2502       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
2503       gst_object_unref (stream->udpsrc[i]);
2504       stream->udpsrc[i] = NULL;
2505     }
2506   }
2507 }
2508
2509 /* for TCP, create pads to send and receive data to and from the manager and to
2510  * intercept various events and queries
2511  */
2512 static gboolean
2513 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
2514     GstRTSPTransport * transport, GstPad ** outpad)
2515 {
2516   gchar *name;
2517   GstPadTemplate *template;
2518   GstPad *pad0, *pad1;
2519
2520   /* configure for interleaved delivery, nothing needs to be done
2521    * here, the loop function will call the chain functions of the
2522    * session manager. */
2523   stream->channel[0] = transport->interleaved.min;
2524   stream->channel[1] = transport->interleaved.max;
2525   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
2526       stream->channel[0], stream->channel[1]);
2527
2528   /* we can remove the allocated UDP ports now */
2529   gst_rtspsrc_stream_free_udp (stream);
2530
2531   /* no session manager, send data to srcpad directly */
2532   if (!stream->channelpad[0]) {
2533     GST_DEBUG_OBJECT (src, "no manager, creating pad");
2534
2535     /* create a new pad we will use to stream to */
2536     name = g_strdup_printf ("stream_%u", stream->id);
2537     template = gst_static_pad_template_get (&rtptemplate);
2538     stream->channelpad[0] = gst_pad_new_from_template (template, name);
2539     gst_object_unref (template);
2540     g_free (name);
2541
2542     /* set caps and activate */
2543     gst_pad_use_fixed_caps (stream->channelpad[0]);
2544     gst_pad_set_active (stream->channelpad[0], TRUE);
2545
2546     *outpad = gst_object_ref (stream->channelpad[0]);
2547   } else {
2548     GST_DEBUG_OBJECT (src, "using manager source pad");
2549
2550     template = gst_static_pad_template_get (&anysrctemplate);
2551
2552     /* allocate pads for sending the channel data into the manager */
2553     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
2554     gst_pad_link (pad0, stream->channelpad[0]);
2555     gst_object_unref (stream->channelpad[0]);
2556     stream->channelpad[0] = pad0;
2557     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
2558     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
2559     gst_pad_set_element_private (pad0, src);
2560     gst_pad_set_active (pad0, TRUE);
2561
2562     if (stream->channelpad[1]) {
2563       /* if we have a sinkpad for the other channel, create a pad and link to the
2564        * manager. */
2565       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
2566       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
2567       gst_pad_link (pad1, stream->channelpad[1]);
2568       gst_object_unref (stream->channelpad[1]);
2569       stream->channelpad[1] = pad1;
2570       gst_pad_set_active (pad1, TRUE);
2571     }
2572     gst_object_unref (template);
2573   }
2574   /* setup RTCP transport back to the server if we have to. */
2575   if (src->manager && src->do_rtcp) {
2576     GstPad *pad;
2577
2578     template = gst_static_pad_template_get (&anysinktemplate);
2579
2580     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
2581     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
2582     gst_pad_set_element_private (stream->rtcppad, stream);
2583     gst_pad_set_active (stream->rtcppad, TRUE);
2584
2585     /* get session RTCP pad */
2586     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
2587     pad = gst_element_get_request_pad (src->manager, name);
2588     g_free (name);
2589
2590     /* and link */
2591     if (pad) {
2592       gst_pad_link (pad, stream->rtcppad);
2593       gst_object_unref (pad);
2594     }
2595
2596     gst_object_unref (template);
2597   }
2598   return TRUE;
2599 }
2600
2601 static void
2602 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
2603     GstRTSPTransport * transport, const gchar ** destination, gint * min,
2604     gint * max, guint * ttl)
2605 {
2606   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
2607     if (destination) {
2608       if (!(*destination = transport->destination))
2609         *destination = stream->destination;
2610     }
2611     if (min && max) {
2612       /* transport first */
2613       *min = transport->port.min;
2614       *max = transport->port.max;
2615       if (*min == -1 && *max == -1) {
2616         /* then try from SDP */
2617         if (stream->port != 0) {
2618           *min = stream->port;
2619           *max = stream->port + 1;
2620         }
2621       }
2622     }
2623
2624     if (ttl) {
2625       if (!(*ttl = transport->ttl))
2626         *ttl = stream->ttl;
2627     }
2628   } else {
2629     if (destination) {
2630       /* first take the source, then the endpoint to figure out where to send
2631        * the RTCP. */
2632       if (!(*destination = transport->source)) {
2633         if (src->conninfo.connection)
2634           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
2635         else if (stream->conninfo.connection)
2636           *destination =
2637               gst_rtsp_connection_get_ip (stream->conninfo.connection);
2638       }
2639     }
2640     if (min && max) {
2641       /* for unicast we only expect the ports here */
2642       *min = transport->server_port.min;
2643       *max = transport->server_port.max;
2644     }
2645   }
2646 }
2647
2648 /* For multicast create UDP sources and join the multicast group. */
2649 static gboolean
2650 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
2651     GstRTSPTransport * transport, GstPad ** outpad)
2652 {
2653   gchar *uri;
2654   const gchar *destination;
2655   gint min, max;
2656
2657   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
2658
2659   /* we can remove the allocated UDP ports now */
2660   gst_rtspsrc_stream_free_udp (stream);
2661
2662   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
2663       &max, NULL);
2664
2665   /* we need a destination now */
2666   if (destination == NULL)
2667     goto no_destination;
2668
2669   /* we really need ports now or we won't be able to receive anything at all */
2670   if (min == -1 && max == -1)
2671     goto no_ports;
2672
2673   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
2674       destination, min, max);
2675
2676   /* creating UDP source for RTP */
2677   if (min != -1) {
2678     uri = g_strdup_printf ("udp://%s:%d", destination, min);
2679     stream->udpsrc[0] = gst_element_make_from_uri (GST_URI_SRC, uri, NULL);
2680     g_free (uri);
2681     if (stream->udpsrc[0] == NULL)
2682       goto no_element;
2683
2684     /* take ownership */
2685     gst_object_ref_sink (stream->udpsrc[0]);
2686
2687     /* change state */
2688     gst_element_set_state (stream->udpsrc[0], GST_STATE_PAUSED);
2689   }
2690
2691   /* creating another UDP source for RTCP */
2692   if (max != -1) {
2693     uri = g_strdup_printf ("udp://%s:%d", destination, max);
2694     stream->udpsrc[1] = gst_element_make_from_uri (GST_URI_SRC, uri, NULL);
2695     g_free (uri);
2696     if (stream->udpsrc[1] == NULL)
2697       goto no_element;
2698
2699     /* take ownership */
2700     gst_object_ref_sink (stream->udpsrc[1]);
2701
2702     gst_element_set_state (stream->udpsrc[1], GST_STATE_PAUSED);
2703   }
2704   return TRUE;
2705
2706   /* ERRORS */
2707 no_element:
2708   {
2709     GST_DEBUG_OBJECT (src, "no UDP source element found");
2710     return FALSE;
2711   }
2712 no_destination:
2713   {
2714     GST_DEBUG_OBJECT (src, "no destination found");
2715     return FALSE;
2716   }
2717 no_ports:
2718   {
2719     GST_DEBUG_OBJECT (src, "no ports found");
2720     return FALSE;
2721   }
2722 }
2723
2724 /* configure the remainder of the UDP ports */
2725 static gboolean
2726 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
2727     GstRTSPTransport * transport, GstPad ** outpad)
2728 {
2729   /* we manage the UDP elements now. For unicast, the UDP sources where
2730    * allocated in the stream when we suggested a transport. */
2731   if (stream->udpsrc[0]) {
2732     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
2733
2734     GST_DEBUG_OBJECT (src, "setting up UDP source");
2735
2736     /* configure a timeout on the UDP port. When the timeout message is
2737      * posted, we assume UDP transport is not possible. We reconnect using TCP
2738      * if we can. */
2739     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", src->udp_timeout,
2740         NULL);
2741
2742     /* get output pad of the UDP source. */
2743     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
2744
2745     /* save it so we can unblock */
2746     stream->blockedpad = *outpad;
2747
2748     /* configure pad block on the pad. As soon as there is dataflow on the
2749      * UDP source, we know that UDP is not blocked by a firewall and we can
2750      * configure all the streams to let the application autoplug decoders. */
2751     stream->blockid =
2752         gst_pad_add_probe (stream->blockedpad,
2753         GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, pad_blocked, src, NULL);
2754
2755     if (stream->channelpad[0]) {
2756       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
2757       /* configure for UDP delivery, we need to connect the UDP pads to
2758        * the session plugin. */
2759       gst_pad_link (*outpad, stream->channelpad[0]);
2760       gst_object_unref (*outpad);
2761       *outpad = NULL;
2762       /* we connected to pad-added signal to get pads from the manager */
2763     } else {
2764       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
2765     }
2766   }
2767
2768   /* RTCP port */
2769   if (stream->udpsrc[1]) {
2770     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
2771
2772     if (stream->channelpad[1]) {
2773       GstPad *pad;
2774
2775       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
2776
2777       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
2778       gst_pad_link (pad, stream->channelpad[1]);
2779       gst_object_unref (pad);
2780     } else {
2781       /* leave unlinked */
2782     }
2783   }
2784   return TRUE;
2785 }
2786
2787 /* configure the UDP sink back to the server for status reports */
2788 static gboolean
2789 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
2790     GstRTSPStream * stream, GstRTSPTransport * transport)
2791 {
2792   GstPad *pad;
2793   gint rtp_port, rtcp_port;
2794   gboolean do_rtp, do_rtcp;
2795   const gchar *destination;
2796   gchar *uri, *name;
2797   guint ttl = 0;
2798   GSocket *socket;
2799
2800   /* get transport info */
2801   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
2802       &rtp_port, &rtcp_port, &ttl);
2803
2804   /* see what we need to do */
2805   do_rtp = (rtp_port != -1);
2806   /* it's possible that the server does not want us to send RTCP in which case
2807    * the port is -1 */
2808   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
2809
2810   /* we need a destination when we have RTP or RTCP ports */
2811   if (destination == NULL && (do_rtp || do_rtcp))
2812     goto no_destination;
2813
2814   /* try to construct the fakesrc to the RTP port of the server to open up any
2815    * NAT firewalls */
2816   if (do_rtp) {
2817     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
2818         rtp_port);
2819
2820     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
2821     stream->udpsink[0] = gst_element_make_from_uri (GST_URI_SINK, uri, NULL);
2822     g_free (uri);
2823     if (stream->udpsink[0] == NULL)
2824       goto no_sink_element;
2825
2826     /* don't join multicast group, we will have the source socket do that */
2827     /* no sync or async state changes needed */
2828     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
2829         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
2830     if (ttl > 0)
2831       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
2832
2833     if (stream->udpsrc[0]) {
2834       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
2835        * so that NAT firewalls will open a hole for us */
2836       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
2837       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
2838       /* configure socket and make sure udpsink does not close it when shutting
2839        * down, it belongs to udpsrc after all. */
2840       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
2841           "close-socket", FALSE, NULL);
2842       g_object_unref (socket);
2843     }
2844
2845     /* the source for the dummy packets to open up NAT */
2846     stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
2847     if (stream->fakesrc == NULL)
2848       goto no_fakesrc_element;
2849
2850     /* random data in 5 buffers, a size of 200 bytes should be fine */
2851     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
2852         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
2853
2854     /* we don't want to consider this a sink */
2855     GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
2856
2857     /* keep everything locked */
2858     gst_element_set_locked_state (stream->udpsink[0], TRUE);
2859     gst_element_set_locked_state (stream->fakesrc, TRUE);
2860
2861     gst_object_ref (stream->udpsink[0]);
2862     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
2863     gst_object_ref (stream->fakesrc);
2864     gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
2865
2866     gst_element_link (stream->fakesrc, stream->udpsink[0]);
2867   }
2868   if (do_rtcp) {
2869     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
2870         rtcp_port);
2871
2872     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
2873     stream->udpsink[1] = gst_element_make_from_uri (GST_URI_SINK, uri, NULL);
2874     g_free (uri);
2875     if (stream->udpsink[1] == NULL)
2876       goto no_sink_element;
2877
2878     /* don't join multicast group, we will have the source socket do that */
2879     /* no sync or async state changes needed */
2880     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
2881         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
2882     if (ttl > 0)
2883       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
2884
2885     if (stream->udpsrc[1]) {
2886       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
2887        * because some servers check the port number of where it sends RTCP to identify
2888        * the RTCP packets it receives */
2889       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
2890       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
2891       /* configure socket and make sure udpsink does not close it when shutting
2892        * down, it belongs to udpsrc after all. */
2893       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
2894           "close-socket", FALSE, NULL);
2895       g_object_unref (socket);
2896     }
2897
2898     /* we don't want to consider this a sink */
2899     GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
2900
2901     /* we keep this playing always */
2902     gst_element_set_locked_state (stream->udpsink[1], TRUE);
2903     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
2904
2905     gst_object_ref (stream->udpsink[1]);
2906     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
2907
2908     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
2909
2910     /* get session RTCP pad */
2911     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
2912     pad = gst_element_get_request_pad (src->manager, name);
2913     g_free (name);
2914
2915     /* and link */
2916     if (pad) {
2917       gst_pad_link (pad, stream->rtcppad);
2918       gst_object_unref (pad);
2919     }
2920   }
2921
2922   return TRUE;
2923
2924   /* ERRORS */
2925 no_destination:
2926   {
2927     GST_DEBUG_OBJECT (src, "no destination address specified");
2928     return FALSE;
2929   }
2930 no_sink_element:
2931   {
2932     GST_DEBUG_OBJECT (src, "no UDP sink element found");
2933     return FALSE;
2934   }
2935 no_fakesrc_element:
2936   {
2937     GST_DEBUG_OBJECT (src, "no fakesrc element found");
2938     return FALSE;
2939   }
2940 }
2941
2942 /* sets up all elements needed for streaming over the specified transport.
2943  * Does not yet expose the element pads, this will be done when there is actuall
2944  * dataflow detected, which might never happen when UDP is blocked in a
2945  * firewall, for example.
2946  */
2947 static gboolean
2948 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
2949     GstRTSPTransport * transport)
2950 {
2951   GstRTSPSrc *src;
2952   GstPad *outpad = NULL;
2953   GstPadTemplate *template;
2954   gchar *name;
2955   GstStructure *s;
2956   const gchar *mime;
2957
2958   src = stream->parent;
2959
2960   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
2961
2962   s = gst_caps_get_structure (stream->caps, 0);
2963
2964   /* get the proper mime type for this stream now */
2965   if (gst_rtsp_transport_get_mime (transport->trans, &mime) < 0)
2966     goto unknown_transport;
2967   if (!mime)
2968     goto unknown_transport;
2969
2970   /* configure the final mime type */
2971   GST_DEBUG_OBJECT (src, "setting mime to %s", mime);
2972   gst_structure_set_name (s, mime);
2973
2974   /* try to get and configure a manager, channelpad[0-1] will be configured with
2975    * the pads for the manager, or NULL when no manager is needed. */
2976   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
2977     goto no_manager;
2978
2979   switch (transport->lower_transport) {
2980     case GST_RTSP_LOWER_TRANS_TCP:
2981       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
2982         goto transport_failed;
2983       break;
2984     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
2985       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
2986         goto transport_failed;
2987       /* fallthrough, the rest is the same for UDP and MCAST */
2988     case GST_RTSP_LOWER_TRANS_UDP:
2989       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
2990         goto transport_failed;
2991       /* configure udpsinks back to the server for RTCP messages and for the
2992        * dummy RTP messages to open NAT. */
2993       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
2994         goto transport_failed;
2995       break;
2996     default:
2997       goto unknown_transport;
2998   }
2999
3000   if (outpad) {
3001     GST_DEBUG_OBJECT (src, "creating ghostpad");
3002
3003     gst_pad_use_fixed_caps (outpad);
3004
3005     /* create ghostpad, don't add just yet, this will be done when we activate
3006      * the stream. */
3007     name = g_strdup_printf ("stream_%u", stream->id);
3008     template = gst_static_pad_template_get (&rtptemplate);
3009     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3010     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3011     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3012     gst_object_unref (template);
3013     g_free (name);
3014
3015     gst_object_unref (outpad);
3016   }
3017   /* mark pad as ok */
3018   stream->last_ret = GST_FLOW_OK;
3019
3020   return TRUE;
3021
3022   /* ERRORS */
3023 transport_failed:
3024   {
3025     GST_DEBUG_OBJECT (src, "failed to configure transport");
3026     return FALSE;
3027   }
3028 unknown_transport:
3029   {
3030     GST_DEBUG_OBJECT (src, "unknown transport");
3031     return FALSE;
3032   }
3033 no_manager:
3034   {
3035     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3036     return FALSE;
3037   }
3038 }
3039
3040 /* send a couple of dummy random packets on the receiver RTP port to the server,
3041  * this should make a firewall think we initiated the data transfer and
3042  * hopefully allow packets to go from the sender port to our RTP receiver port */
3043 static gboolean
3044 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3045 {
3046   GList *walk;
3047
3048   if (src->nat_method != GST_RTSP_NAT_DUMMY)
3049     return TRUE;
3050
3051   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3052     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3053
3054     if (stream->fakesrc && stream->udpsink[0]) {
3055       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3056       gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3057       gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3058       gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3059       gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3060     }
3061   }
3062   return TRUE;
3063 }
3064
3065 /* Adds the source pads of all configured streams to the element.
3066  * This code is performed when we detected dataflow.
3067  *
3068  * We detect dataflow from either the _loop function or with pad probes on the
3069  * udp sources.
3070  */
3071 static gboolean
3072 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3073 {
3074   GList *walk;
3075
3076   GST_DEBUG_OBJECT (src, "activating streams");
3077
3078   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3079     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3080
3081     if (stream->udpsrc[0]) {
3082       /* remove timeout, we are streaming now and timeouts will be handled by
3083        * the session manager and jitter buffer */
3084       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3085     }
3086     if (stream->srcpad) {
3087       /* if we don't have a session manager, set the caps now. If we have a
3088        * session, we will get a notification of the pad and the caps. */
3089       if (!src->manager) {
3090         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3091         gst_pad_set_caps (stream->srcpad, stream->caps);
3092       }
3093
3094       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3095       gst_pad_set_active (stream->srcpad, TRUE);
3096       /* add the pad */
3097       if (!stream->added) {
3098         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3099         gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3100         stream->added = TRUE;
3101       }
3102     }
3103   }
3104
3105   /* unblock all pads */
3106   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3107     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3108
3109     if (stream->blockid) {
3110       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3111       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3112       stream->blockid = 0;
3113     }
3114   }
3115
3116   return TRUE;
3117 }
3118
3119 static void
3120 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment)
3121 {
3122   GList *walk;
3123   guint64 start, stop;
3124   gdouble play_speed, play_scale;
3125
3126   GST_DEBUG_OBJECT (src, "configuring stream caps");
3127
3128   start = segment->position;
3129   stop = segment->duration;
3130   play_speed = segment->rate;
3131   play_scale = segment->applied_rate;
3132
3133   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3134     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3135     GstCaps *caps;
3136
3137     if ((caps = stream->caps)) {
3138       caps = gst_caps_make_writable (caps);
3139       /* update caps */
3140       if (stream->timebase != -1)
3141         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
3142             (guint) stream->timebase, NULL);
3143       if (stream->seqbase != -1)
3144         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
3145             (guint) stream->seqbase, NULL);
3146       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
3147       if (stop != -1)
3148         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
3149       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
3150       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
3151
3152       stream->caps = caps;
3153     }
3154     GST_DEBUG_OBJECT (src, "stream %p, caps %" GST_PTR_FORMAT, stream, caps);
3155   }
3156   if (src->manager) {
3157     GST_DEBUG_OBJECT (src, "clear session");
3158     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
3159   }
3160 }
3161
3162 static GstFlowReturn
3163 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
3164     GstFlowReturn ret)
3165 {
3166   GList *streams;
3167
3168   /* store the value */
3169   stream->last_ret = ret;
3170
3171   /* if it's success we can return the value right away */
3172   if (ret == GST_FLOW_OK)
3173     goto done;
3174
3175   /* any other error that is not-linked can be returned right
3176    * away */
3177   if (ret != GST_FLOW_NOT_LINKED)
3178     goto done;
3179
3180   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3181   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3182     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3183
3184     ret = ostream->last_ret;
3185     /* some other return value (must be SUCCESS but we can return
3186      * other values as well) */
3187     if (ret != GST_FLOW_NOT_LINKED)
3188       goto done;
3189   }
3190   /* if we get here, all other pads were unlinked and we return
3191    * NOT_LINKED then */
3192 done:
3193   return ret;
3194 }
3195
3196 static gboolean
3197 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
3198     GstEvent * event, gboolean source)
3199 {
3200   gboolean res = TRUE;
3201
3202   /* only streams that have a connection to the outside world */
3203   if (stream->srcpad == NULL)
3204     goto done;
3205
3206   if (source && stream->udpsrc[0]) {
3207     gst_event_ref (event);
3208     res = gst_element_send_event (stream->udpsrc[0], event);
3209   } else if (stream->channelpad[0]) {
3210     gst_event_ref (event);
3211     if (GST_PAD_IS_SRC (stream->channelpad[0]))
3212       res = gst_pad_push_event (stream->channelpad[0], event);
3213     else
3214       res = gst_pad_send_event (stream->channelpad[0], event);
3215   }
3216
3217   if (source && stream->udpsrc[1]) {
3218     gst_event_ref (event);
3219     res &= gst_element_send_event (stream->udpsrc[1], event);
3220   } else if (stream->channelpad[1]) {
3221     gst_event_ref (event);
3222     if (GST_PAD_IS_SRC (stream->channelpad[1]))
3223       res &= gst_pad_push_event (stream->channelpad[1], event);
3224     else
3225       res &= gst_pad_send_event (stream->channelpad[1], event);
3226   }
3227
3228 done:
3229   gst_event_unref (event);
3230
3231   return res;
3232 }
3233
3234 static gboolean
3235 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event, gboolean source)
3236 {
3237   GList *streams;
3238   gboolean res = TRUE;
3239
3240   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3241     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3242
3243     gst_event_ref (event);
3244     res &= gst_rtspsrc_stream_push_event (src, ostream, event, source);
3245   }
3246   gst_event_unref (event);
3247
3248   return res;
3249 }
3250
3251 static GstRTSPResult
3252 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3253     gboolean async)
3254 {
3255   GstRTSPResult res;
3256
3257   if (info->connection == NULL) {
3258     if (info->url == NULL) {
3259       GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
3260       if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
3261         goto parse_error;
3262     }
3263
3264     /* create connection */
3265     GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
3266     if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
3267       goto could_not_create;
3268
3269     if (info->url_str)
3270       g_free (info->url_str);
3271     info->url_str = gst_rtsp_url_get_request_uri (info->url);
3272
3273     GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
3274
3275     if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
3276       gst_rtsp_connection_set_tunneled (info->connection, TRUE);
3277
3278     if (src->proxy_host) {
3279       GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
3280           src->proxy_port);
3281       gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
3282           src->proxy_port);
3283     }
3284   }
3285
3286   if (!info->connected) {
3287     /* connect */
3288     if (async)
3289       GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
3290           ("Connecting to %s", info->location));
3291     GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
3292     if ((res =
3293             gst_rtsp_connection_connect (info->connection,
3294                 src->ptcp_timeout)) < 0)
3295       goto could_not_connect;
3296
3297     info->connected = TRUE;
3298   }
3299   return GST_RTSP_OK;
3300
3301   /* ERRORS */
3302 parse_error:
3303   {
3304     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
3305     return res;
3306   }
3307 could_not_create:
3308   {
3309     gchar *str = gst_rtsp_strresult (res);
3310     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
3311     g_free (str);
3312     return res;
3313   }
3314 could_not_connect:
3315   {
3316     gchar *str = gst_rtsp_strresult (res);
3317     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
3318     g_free (str);
3319     return res;
3320   }
3321 }
3322
3323 static GstRTSPResult
3324 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
3325     gboolean free)
3326 {
3327   if (info->connected) {
3328     GST_DEBUG_OBJECT (src, "closing connection...");
3329     gst_rtsp_connection_close (info->connection);
3330     info->connected = FALSE;
3331   }
3332   if (free && info->connection) {
3333     /* free connection */
3334     GST_DEBUG_OBJECT (src, "freeing connection...");
3335     gst_rtsp_connection_free (info->connection);
3336     info->connection = NULL;
3337   }
3338   return GST_RTSP_OK;
3339 }
3340
3341 static GstRTSPResult
3342 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3343     gboolean async)
3344 {
3345   GstRTSPResult res;
3346
3347   GST_DEBUG_OBJECT (src, "reconnecting connection...");
3348   gst_rtsp_conninfo_close (src, info, FALSE);
3349   res = gst_rtsp_conninfo_connect (src, info, async);
3350
3351   return res;
3352 }
3353
3354 static void
3355 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
3356 {
3357   GList *walk;
3358
3359   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
3360   if (src->conninfo.connection) {
3361     GST_DEBUG_OBJECT (src, "connection flush");
3362     gst_rtsp_connection_flush (src->conninfo.connection, flush);
3363   }
3364   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3365     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3366     GST_DEBUG_OBJECT (src, "stream %p flush", stream);
3367     if (stream->conninfo.connection)
3368       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
3369   }
3370 }
3371
3372 /* FIXME, handle server request, reply with OK, for now */
3373 static GstRTSPResult
3374 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
3375     GstRTSPMessage * request)
3376 {
3377   GstRTSPMessage response = { 0 };
3378   GstRTSPResult res;
3379
3380   GST_DEBUG_OBJECT (src, "got server request message");
3381
3382   if (src->debug)
3383     gst_rtsp_message_dump (request);
3384
3385   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
3386
3387   if (res == GST_RTSP_ENOTIMPL) {
3388     /* default implementation, send OK */
3389     res =
3390         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
3391         request);
3392     if (res < 0)
3393       goto send_error;
3394
3395     GST_DEBUG_OBJECT (src, "replying with OK");
3396
3397     if (src->debug)
3398       gst_rtsp_message_dump (&response);
3399
3400     res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
3401     if (res < 0)
3402       goto send_error;
3403
3404     gst_rtsp_message_unset (&response);
3405   } else if (res == GST_RTSP_EEOF)
3406     return res;
3407
3408   return GST_RTSP_OK;
3409
3410   /* ERRORS */
3411 send_error:
3412   {
3413     gst_rtsp_message_unset (&response);
3414     return res;
3415   }
3416 }
3417
3418 /* send server keep-alive */
3419 static GstRTSPResult
3420 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
3421 {
3422   GstRTSPMessage request = { 0 };
3423   GstRTSPResult res;
3424   GstRTSPMethod method;
3425   gchar *control;
3426
3427   GST_DEBUG_OBJECT (src, "creating server keep-alive");
3428
3429   /* find a method to use for keep-alive */
3430   if (src->methods & GST_RTSP_GET_PARAMETER)
3431     method = GST_RTSP_GET_PARAMETER;
3432   else
3433     method = GST_RTSP_OPTIONS;
3434
3435   if (src->control)
3436     control = src->control;
3437   else
3438     control = src->conninfo.url_str;
3439
3440   if (control == NULL)
3441     goto no_control;
3442
3443   res = gst_rtsp_message_init_request (&request, method, control);
3444   if (res < 0)
3445     goto send_error;
3446
3447   if (src->debug)
3448     gst_rtsp_message_dump (&request);
3449
3450   res =
3451       gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
3452       NULL);
3453   if (res < 0)
3454     goto send_error;
3455
3456   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3457   gst_rtsp_message_unset (&request);
3458
3459   return GST_RTSP_OK;
3460
3461   /* ERRORS */
3462 no_control:
3463   {
3464     GST_WARNING_OBJECT (src, "no control url to send keepalive");
3465     return GST_RTSP_OK;
3466   }
3467 send_error:
3468   {
3469     gchar *str = gst_rtsp_strresult (res);
3470
3471     gst_rtsp_message_unset (&request);
3472     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
3473         ("Could not send keep-alive. (%s)", str));
3474     g_free (str);
3475     return res;
3476   }
3477 }
3478
3479 static GstFlowReturn
3480 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
3481 {
3482   GstRTSPMessage message = { 0 };
3483   GstRTSPResult res;
3484   gint channel;
3485   GstRTSPStream *stream;
3486   GstPad *outpad = NULL;
3487   guint8 *data;
3488   guint size;
3489   GstFlowReturn ret = GST_FLOW_OK;
3490   GstBuffer *buf;
3491   gboolean is_rtcp, have_data;
3492
3493   /* here we are only interested in data messages */
3494   have_data = FALSE;
3495   do {
3496     GTimeVal tv_timeout;
3497
3498     /* get the next timeout interval */
3499     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3500
3501     /* see if the timeout period expired */
3502     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
3503       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
3504       /* send keep-alive, only act on interrupt, a warning will be posted for
3505        * other errors. */
3506       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3507         goto interrupt;
3508       /* get new timeout */
3509       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3510     }
3511
3512     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
3513         tv_timeout.tv_sec, tv_timeout.tv_usec);
3514
3515     /* protect the connection with the connection lock so that we can see when
3516      * we are finished doing server communication */
3517     res =
3518         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
3519         &message, src->ptcp_timeout);
3520
3521     switch (res) {
3522       case GST_RTSP_OK:
3523         GST_DEBUG_OBJECT (src, "we received a server message");
3524         break;
3525       case GST_RTSP_EINTR:
3526         /* we got interrupted this means we need to stop */
3527         goto interrupt;
3528       case GST_RTSP_ETIMEOUT:
3529         /* no reply, send keep alive */
3530         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
3531         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3532           goto interrupt;
3533         continue;
3534       case GST_RTSP_EEOF:
3535         /* go EOS when the server closed the connection */
3536         goto server_eof;
3537       default:
3538         goto receive_error;
3539     }
3540
3541     switch (message.type) {
3542       case GST_RTSP_MESSAGE_REQUEST:
3543         /* server sends us a request message, handle it */
3544         res =
3545             gst_rtspsrc_handle_request (src, src->conninfo.connection,
3546             &message);
3547         if (res == GST_RTSP_EEOF)
3548           goto server_eof;
3549         else if (res < 0)
3550           goto handle_request_failed;
3551         break;
3552       case GST_RTSP_MESSAGE_RESPONSE:
3553         /* we ignore response messages */
3554         GST_DEBUG_OBJECT (src, "ignoring response message");
3555         if (src->debug)
3556           gst_rtsp_message_dump (&message);
3557         break;
3558       case GST_RTSP_MESSAGE_DATA:
3559         GST_DEBUG_OBJECT (src, "got data message");
3560         have_data = TRUE;
3561         break;
3562       default:
3563         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
3564             message.type);
3565         break;
3566     }
3567   }
3568   while (!have_data);
3569
3570   channel = message.type_data.data.channel;
3571
3572   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
3573   if (!stream)
3574     goto unknown_stream;
3575
3576   if (channel == stream->channel[0]) {
3577     outpad = stream->channelpad[0];
3578     is_rtcp = FALSE;
3579   } else if (channel == stream->channel[1]) {
3580     outpad = stream->channelpad[1];
3581     is_rtcp = TRUE;
3582   } else {
3583     is_rtcp = FALSE;
3584   }
3585
3586   /* take a look at the body to figure out what we have */
3587   gst_rtsp_message_get_body (&message, &data, &size);
3588   if (size < 2)
3589     goto invalid_length;
3590
3591   /* channels are not correct on some servers, do extra check */
3592   if (data[1] >= 200 && data[1] <= 204) {
3593     /* hmm RTCP message switch to the RTCP pad of the same stream. */
3594     outpad = stream->channelpad[1];
3595     is_rtcp = TRUE;
3596   }
3597
3598   /* we have no clue what this is, just ignore then. */
3599   if (outpad == NULL)
3600     goto unknown_stream;
3601
3602   /* take the message body for further processing */
3603   gst_rtsp_message_steal_body (&message, &data, &size);
3604
3605   /* strip the trailing \0 */
3606   size -= 1;
3607
3608   buf = gst_buffer_new ();
3609   gst_buffer_take_memory (buf, -1,
3610       gst_memory_new_wrapped (0, data, g_free, size, 0, size));
3611
3612   /* don't need message anymore */
3613   gst_rtsp_message_unset (&message);
3614
3615   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
3616       channel);
3617
3618   if (src->need_activate) {
3619     gst_rtspsrc_activate_streams (src);
3620     src->need_activate = FALSE;
3621   }
3622
3623   if (src->base_time == -1) {
3624     /* Take current running_time. This timestamp will be put on
3625      * the first buffer of each stream because we are a live source and so we
3626      * timestamp with the running_time. When we are dealing with TCP, we also
3627      * only timestamp the first buffer (using the DISCONT flag) because a server
3628      * typically bursts data, for which we don't want to compensate by speeding
3629      * up the media. The other timestamps will be interpollated from this one
3630      * using the RTP timestamps. */
3631     GST_OBJECT_LOCK (src);
3632     if (GST_ELEMENT_CLOCK (src)) {
3633       GstClockTime now;
3634       GstClockTime base_time;
3635
3636       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
3637       base_time = GST_ELEMENT_CAST (src)->base_time;
3638
3639       src->base_time = now - base_time;
3640
3641       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
3642           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
3643     }
3644     GST_OBJECT_UNLOCK (src);
3645   }
3646
3647   if (stream->discont && !is_rtcp) {
3648     /* mark first RTP buffer as discont */
3649     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3650     stream->discont = FALSE;
3651     /* first buffer gets the timestamp, other buffers are not timestamped and
3652      * their presentation time will be interpollated from the rtp timestamps. */
3653     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
3654         GST_TIME_ARGS (src->base_time));
3655
3656     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
3657   }
3658
3659   /* chain to the peer pad */
3660   if (GST_PAD_IS_SINK (outpad))
3661     ret = gst_pad_chain (outpad, buf);
3662   else
3663     ret = gst_pad_push (outpad, buf);
3664
3665   if (!is_rtcp) {
3666     /* combine all stream flows for the data transport */
3667     ret = gst_rtspsrc_combine_flows (src, stream, ret);
3668   }
3669   return ret;
3670
3671   /* ERRORS */
3672 unknown_stream:
3673   {
3674     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
3675     gst_rtsp_message_unset (&message);
3676     return GST_FLOW_OK;
3677   }
3678 server_eof:
3679   {
3680     GST_DEBUG_OBJECT (src, "we got an eof from the server");
3681     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3682         ("The server closed the connection."));
3683     src->conninfo.connected = FALSE;
3684     gst_rtsp_message_unset (&message);
3685     return GST_FLOW_EOS;
3686   }
3687 interrupt:
3688   {
3689     gst_rtsp_message_unset (&message);
3690     GST_DEBUG_OBJECT (src, "got interrupted: stop connection flush");
3691     gst_rtspsrc_connection_flush (src, FALSE);
3692     return GST_FLOW_WRONG_STATE;
3693   }
3694 receive_error:
3695   {
3696     gchar *str = gst_rtsp_strresult (res);
3697
3698     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
3699         ("Could not receive message. (%s)", str));
3700     g_free (str);
3701
3702     gst_rtsp_message_unset (&message);
3703     return GST_FLOW_ERROR;
3704   }
3705 handle_request_failed:
3706   {
3707     gchar *str = gst_rtsp_strresult (res);
3708
3709     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
3710         ("Could not handle server message. (%s)", str));
3711     g_free (str);
3712     gst_rtsp_message_unset (&message);
3713     return GST_FLOW_ERROR;
3714   }
3715 invalid_length:
3716   {
3717     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3718         ("Short message received, ignoring."));
3719     gst_rtsp_message_unset (&message);
3720     return GST_FLOW_OK;
3721   }
3722 }
3723
3724 static GstFlowReturn
3725 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
3726 {
3727   GstRTSPResult res;
3728   GstRTSPMessage message = { 0 };
3729   gint retry = 0;
3730
3731   while (TRUE) {
3732     GTimeVal tv_timeout;
3733
3734     /* get the next timeout interval */
3735     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
3736
3737     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
3738         (gint) tv_timeout.tv_sec);
3739
3740     gst_rtsp_message_unset (&message);
3741
3742     /* we should continue reading the TCP socket because the server might
3743      * send us requests. When the session timeout expires, we need to send a
3744      * keep-alive request to keep the session open. */
3745     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
3746         &message, &tv_timeout);
3747
3748     switch (res) {
3749       case GST_RTSP_OK:
3750         GST_DEBUG_OBJECT (src, "we received a server message");
3751         break;
3752       case GST_RTSP_EINTR:
3753         /* we got interrupted, see what we have to do */
3754         goto interrupt;
3755       case GST_RTSP_ETIMEOUT:
3756         /* send keep-alive, ignore the result, a warning will be posted. */
3757         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
3758         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3759           goto interrupt;
3760         continue;
3761       case GST_RTSP_EEOF:
3762         /* server closed the connection. not very fatal for UDP, reconnect and
3763          * see what happens. */
3764         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3765             ("The server closed the connection."));
3766         if ((res =
3767                 gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
3768           goto connect_error;
3769
3770         continue;
3771       default:
3772         goto receive_error;
3773     }
3774
3775     switch (message.type) {
3776       case GST_RTSP_MESSAGE_REQUEST:
3777         /* server sends us a request message, handle it */
3778         res =
3779             gst_rtspsrc_handle_request (src, src->conninfo.connection,
3780             &message);
3781         if (res == GST_RTSP_EEOF)
3782           goto server_eof;
3783         else if (res < 0)
3784           goto handle_request_failed;
3785         break;
3786       case GST_RTSP_MESSAGE_RESPONSE:
3787         /* we ignore response and data messages */
3788         GST_DEBUG_OBJECT (src, "ignoring response message");
3789         if (src->debug)
3790           gst_rtsp_message_dump (&message);
3791         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
3792           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
3793           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
3794             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
3795             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
3796               goto interrupt;
3797           }
3798         } else {
3799           retry = 0;
3800         }
3801         break;
3802       case GST_RTSP_MESSAGE_DATA:
3803         /* we ignore response and data messages */
3804         GST_DEBUG_OBJECT (src, "ignoring data message");
3805         break;
3806       default:
3807         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
3808             message.type);
3809         break;
3810     }
3811   }
3812
3813   /* we get here when the connection got interrupted */
3814 interrupt:
3815   {
3816     gst_rtsp_message_unset (&message);
3817     GST_DEBUG_OBJECT (src, "got interrupted: stop connection flush");
3818     gst_rtspsrc_connection_flush (src, FALSE);
3819     return GST_FLOW_WRONG_STATE;
3820   }
3821 connect_error:
3822   {
3823     gchar *str = gst_rtsp_strresult (res);
3824     GstFlowReturn ret;
3825
3826     src->conninfo.connected = FALSE;
3827     if (res != GST_RTSP_EINTR) {
3828       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
3829           ("Could not connect to server. (%s)", str));
3830       g_free (str);
3831       ret = GST_FLOW_ERROR;
3832     } else {
3833       ret = GST_FLOW_WRONG_STATE;
3834     }
3835     return ret;
3836   }
3837 receive_error:
3838   {
3839     gchar *str = gst_rtsp_strresult (res);
3840
3841     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
3842         ("Could not receive message. (%s)", str));
3843     g_free (str);
3844     return GST_FLOW_ERROR;
3845   }
3846 handle_request_failed:
3847   {
3848     gchar *str = gst_rtsp_strresult (res);
3849     GstFlowReturn ret;
3850
3851     gst_rtsp_message_unset (&message);
3852     if (res != GST_RTSP_EINTR) {
3853       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
3854           ("Could not handle server message. (%s)", str));
3855       g_free (str);
3856       ret = GST_FLOW_ERROR;
3857     } else {
3858       ret = GST_FLOW_WRONG_STATE;
3859     }
3860     return ret;
3861   }
3862 server_eof:
3863   {
3864     GST_DEBUG_OBJECT (src, "we got an eof from the server");
3865     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3866         ("The server closed the connection."));
3867     src->conninfo.connected = FALSE;
3868     gst_rtsp_message_unset (&message);
3869     return GST_FLOW_EOS;
3870   }
3871 }
3872
3873 static GstRTSPResult
3874 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
3875 {
3876   GstRTSPResult res = GST_RTSP_OK;
3877   gboolean restart;
3878
3879   GST_DEBUG_OBJECT (src, "doing reconnect");
3880
3881   GST_OBJECT_LOCK (src);
3882   /* only restart when the pads were not yet activated, else we were
3883    * streaming over UDP */
3884   restart = src->need_activate;
3885   GST_OBJECT_UNLOCK (src);
3886
3887   /* no need to restart, we're done */
3888   if (!restart)
3889     goto done;
3890
3891   /* we can try only TCP now */
3892   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
3893
3894   /* close and cleanup our state */
3895   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
3896     goto done;
3897
3898   /* see if we have TCP left to try. Also don't try TCP when we were configured
3899    * with an SDP. */
3900   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
3901     goto no_protocols;
3902
3903   /* We post a warning message now to inform the user
3904    * that nothing happened. It's most likely a firewall thing. */
3905   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
3906       ("Could not receive any UDP packets for %.4f seconds, maybe your "
3907           "firewall is blocking it. Retrying using a TCP connection.",
3908           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
3909
3910   /* open new connection using tcp */
3911   if (gst_rtspsrc_open (src, async) < 0)
3912     goto open_failed;
3913
3914   /* start playback */
3915   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
3916     goto play_failed;
3917
3918 done:
3919   return res;
3920
3921   /* ERRORS */
3922 no_protocols:
3923   {
3924     src->cur_protocols = 0;
3925     /* no transport possible, post an error and stop */
3926     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
3927         ("Could not receive any UDP packets for %.4f seconds, maybe your "
3928             "firewall is blocking it. No other protocols to try.",
3929             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
3930     return GST_FLOW_ERROR;
3931   }
3932 open_failed:
3933   {
3934     GST_DEBUG_OBJECT (src, "open failed");
3935     return GST_FLOW_OK;
3936   }
3937 play_failed:
3938   {
3939     GST_DEBUG_OBJECT (src, "play failed");
3940     return GST_FLOW_OK;
3941   }
3942 }
3943
3944 static void
3945 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
3946 {
3947   switch (cmd) {
3948     case CMD_OPEN:
3949       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
3950       break;
3951     case CMD_PLAY:
3952       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
3953       break;
3954     case CMD_PAUSE:
3955       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
3956       break;
3957     case CMD_CLOSE:
3958       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
3959       break;
3960     default:
3961       break;
3962   }
3963 }
3964
3965 static void
3966 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
3967 {
3968   switch (cmd) {
3969     case CMD_OPEN:
3970       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
3971       break;
3972     case CMD_PLAY:
3973       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
3974       break;
3975     case CMD_PAUSE:
3976       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
3977       break;
3978     case CMD_CLOSE:
3979       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
3980       break;
3981     default:
3982       break;
3983   }
3984 }
3985
3986 static void
3987 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
3988 {
3989   switch (cmd) {
3990     case CMD_OPEN:
3991       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
3992       break;
3993     case CMD_PLAY:
3994       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
3995       break;
3996     case CMD_PAUSE:
3997       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
3998       break;
3999     case CMD_CLOSE:
4000       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4001       break;
4002     default:
4003       break;
4004   }
4005 }
4006
4007 static void
4008 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4009 {
4010   switch (cmd) {
4011     case CMD_OPEN:
4012       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4013       break;
4014     case CMD_PLAY:
4015       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4016       break;
4017     case CMD_PAUSE:
4018       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4019       break;
4020     case CMD_CLOSE:
4021       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4022       break;
4023     default:
4024       break;
4025   }
4026 }
4027
4028 static void
4029 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4030 {
4031   if (ret == GST_RTSP_OK)
4032     gst_rtspsrc_loop_complete_cmd (src, cmd);
4033   else if (ret == GST_RTSP_EINTR)
4034     gst_rtspsrc_loop_cancel_cmd (src, cmd);
4035   else
4036     gst_rtspsrc_loop_error_cmd (src, cmd);
4037 }
4038
4039 static void
4040 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd)
4041 {
4042   gint old;
4043
4044   /* start new request */
4045   gst_rtspsrc_loop_start_cmd (src, cmd);
4046
4047   GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4048
4049   GST_OBJECT_LOCK (src);
4050   old = src->loop_cmd;
4051   if (old != CMD_WAIT) {
4052     src->loop_cmd = CMD_WAIT;
4053     GST_OBJECT_UNLOCK (src);
4054     /* cancel previous request */
4055     gst_rtspsrc_loop_cancel_cmd (src, old);
4056     GST_OBJECT_LOCK (src);
4057   }
4058   src->loop_cmd = cmd;
4059   /* interrupt if allowed */
4060   if (src->waiting) {
4061     GST_DEBUG_OBJECT (src, "start connection flush");
4062     gst_rtspsrc_connection_flush (src, TRUE);
4063   }
4064   if (src->task)
4065     gst_task_start (src->task);
4066   GST_OBJECT_UNLOCK (src);
4067 }
4068
4069 static gboolean
4070 gst_rtspsrc_loop (GstRTSPSrc * src)
4071 {
4072   GstFlowReturn ret;
4073
4074   if (!src->conninfo.connection || !src->conninfo.connected)
4075     goto no_connection;
4076
4077   if (src->interleaved)
4078     ret = gst_rtspsrc_loop_interleaved (src);
4079   else
4080     ret = gst_rtspsrc_loop_udp (src);
4081
4082   if (ret != GST_FLOW_OK)
4083     goto pause;
4084
4085   return TRUE;
4086
4087   /* ERRORS */
4088 no_connection:
4089   {
4090     GST_WARNING_OBJECT (src, "we are not connected");
4091     ret = GST_FLOW_WRONG_STATE;
4092     goto pause;
4093   }
4094 pause:
4095   {
4096     const gchar *reason = gst_flow_get_name (ret);
4097
4098     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4099     src->running = FALSE;
4100     if (ret == GST_FLOW_EOS) {
4101       /* perform EOS logic */
4102       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4103         gst_element_post_message (GST_ELEMENT_CAST (src),
4104             gst_message_new_segment_done (GST_OBJECT_CAST (src),
4105                 src->segment.format, src->segment.position));
4106       } else {
4107         gst_rtspsrc_push_event (src, gst_event_new_eos (), FALSE);
4108       }
4109     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4110       /* for fatal errors we post an error message, post the error before the
4111        * EOS so the app knows about the error first. */
4112       GST_ELEMENT_ERROR (src, STREAM, FAILED,
4113           ("Internal data flow error."),
4114           ("streaming task paused, reason %s (%d)", reason, ret));
4115       gst_rtspsrc_push_event (src, gst_event_new_eos (), FALSE);
4116     }
4117     return FALSE;
4118   }
4119 }
4120
4121 #ifndef GST_DISABLE_GST_DEBUG
4122 static const gchar *
4123 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
4124 {
4125   gint index = 0;
4126
4127   while (method != 0) {
4128     index++;
4129     method >>= 1;
4130   }
4131   switch (index) {
4132     case 0:
4133       return "None";
4134     case 1:
4135       return "Basic";
4136     case 2:
4137       return "Digest";
4138   }
4139
4140   return "Unknown";
4141 }
4142 #endif
4143
4144 static const gchar *
4145 gst_rtspsrc_skip_lws (const gchar * s)
4146 {
4147   while (g_ascii_isspace (*s))
4148     s++;
4149   return s;
4150 }
4151
4152 static const gchar *
4153 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
4154 {
4155   while (s > start && g_ascii_isspace (*(s - 1)))
4156     s--;
4157   return s;
4158 }
4159
4160 static const gchar *
4161 gst_rtspsrc_skip_commas (const gchar * s)
4162 {
4163   /* The grammar allows for multiple commas */
4164   while (g_ascii_isspace (*s) || *s == ',')
4165     s++;
4166   return s;
4167 }
4168
4169 static const gchar *
4170 gst_rtspsrc_skip_item (const gchar * s)
4171 {
4172   gboolean quoted = FALSE;
4173   const gchar *start = s;
4174
4175   /* A list item ends at the last non-whitespace character
4176    * before a comma which is not inside a quoted-string. Or at
4177    * the end of the string.
4178    */
4179   while (*s) {
4180     if (*s == '"')
4181       quoted = !quoted;
4182     else if (quoted) {
4183       if (*s == '\\' && *(s + 1))
4184         s++;
4185     } else {
4186       if (*s == ',')
4187         break;
4188     }
4189     s++;
4190   }
4191
4192   return gst_rtspsrc_unskip_lws (s, start);
4193 }
4194
4195 static void
4196 gst_rtsp_decode_quoted_string (gchar * quoted_string)
4197 {
4198   gchar *src, *dst;
4199
4200   src = quoted_string + 1;
4201   dst = quoted_string;
4202   while (*src && *src != '"') {
4203     if (*src == '\\' && *(src + 1))
4204       src++;
4205     *dst++ = *src++;
4206   }
4207   *dst = '\0';
4208 }
4209
4210 /* Extract the authentication tokens that the server provided for each method
4211  * into an array of structures and give those to the connection object.
4212  */
4213 static void
4214 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
4215     const gchar * header, gboolean * stale)
4216 {
4217   GSList *list = NULL, *iter;
4218   const gchar *end;
4219   gchar *item, *eq, *name_end, *value;
4220
4221   g_return_if_fail (stale != NULL);
4222
4223   gst_rtsp_connection_clear_auth_params (conn);
4224   *stale = FALSE;
4225
4226   /* Parse a header whose content is described by RFC2616 as
4227    * "#something", where "something" does not itself contain commas,
4228    * except as part of quoted-strings, into a list of allocated strings.
4229    */
4230   header = gst_rtspsrc_skip_commas (header);
4231   while (*header) {
4232     end = gst_rtspsrc_skip_item (header);
4233     list = g_slist_prepend (list, g_strndup (header, end - header));
4234     header = gst_rtspsrc_skip_commas (end);
4235   }
4236   if (!list)
4237     return;
4238
4239   list = g_slist_reverse (list);
4240   for (iter = list; iter; iter = iter->next) {
4241     item = iter->data;
4242
4243     eq = strchr (item, '=');
4244     if (eq) {
4245       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
4246       if (name_end == item) {
4247         /* That's no good... */
4248         g_free (item);
4249         continue;
4250       }
4251
4252       *name_end = '\0';
4253
4254       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
4255       if (*value == '"')
4256         gst_rtsp_decode_quoted_string (value);
4257     } else
4258       value = NULL;
4259
4260     if ((strcmp (item, "stale") == 0) && (strcmp (value, "TRUE") == 0))
4261       *stale = TRUE;
4262     gst_rtsp_connection_set_auth_param (conn, item, value);
4263     g_free (item);
4264   }
4265
4266   g_slist_free (list);
4267 }
4268
4269 /* Parse a WWW-Authenticate Response header and determine the
4270  * available authentication methods
4271  *
4272  * This code should also cope with the fact that each WWW-Authenticate
4273  * header can contain multiple challenge methods + tokens
4274  *
4275  * At the moment, for Basic auth, we just do a minimal check and don't
4276  * even parse out the realm */
4277 static void
4278 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4279     GstRTSPConnection * conn, gboolean * stale)
4280 {
4281   gchar *start;
4282
4283   g_return_if_fail (hdr != NULL);
4284   g_return_if_fail (methods != NULL);
4285   g_return_if_fail (stale != NULL);
4286
4287   /* Skip whitespace at the start of the string */
4288   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4289
4290   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4291     *methods |= GST_RTSP_AUTH_BASIC;
4292   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4293     *methods |= GST_RTSP_AUTH_DIGEST;
4294     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4295   }
4296 }
4297
4298 /**
4299  * gst_rtspsrc_setup_auth:
4300  * @src: the rtsp source
4301  *
4302  * Configure a username and password and auth method on the
4303  * connection object based on a response we received from the
4304  * peer.
4305  *
4306  * Currently, this requires that a username and password were supplied
4307  * in the uri. In the future, they may be requested on demand by sending
4308  * a message up the bus.
4309  *
4310  * Returns: TRUE if authentication information could be set up correctly.
4311  */
4312 static gboolean
4313 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4314 {
4315   gchar *user = NULL;
4316   gchar *pass = NULL;
4317   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4318   GstRTSPAuthMethod method;
4319   GstRTSPResult auth_result;
4320   GstRTSPUrl *url;
4321   GstRTSPConnection *conn;
4322   gchar *hdr;
4323   gboolean stale = FALSE;
4324
4325   conn = src->conninfo.connection;
4326
4327   /* Identify the available auth methods and see if any are supported */
4328   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4329           &hdr, 0) == GST_RTSP_OK) {
4330     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4331   }
4332
4333   if (avail_methods == GST_RTSP_AUTH_NONE)
4334     goto no_auth_available;
4335
4336   /* For digest auth, if the response indicates that the session
4337    * data are stale, we just update them in the connection object and
4338    * return TRUE to retry the request */
4339   if (stale)
4340     src->tried_url_auth = FALSE;
4341
4342   url = gst_rtsp_connection_get_url (conn);
4343
4344   /* Do we have username and password available? */
4345   if (url != NULL && !src->tried_url_auth && url->user != NULL
4346       && url->passwd != NULL) {
4347     user = url->user;
4348     pass = url->passwd;
4349     src->tried_url_auth = TRUE;
4350     GST_DEBUG_OBJECT (src,
4351         "Attempting authentication using credentials from the URL");
4352   } else {
4353     user = src->user_id;
4354     pass = src->user_pw;
4355     GST_DEBUG_OBJECT (src,
4356         "Attempting authentication using credentials from the properties");
4357   }
4358
4359   /* FIXME: If the url didn't contain username and password or we tried them
4360    * already, request a username and passwd from the application via some kind
4361    * of credentials request message */
4362
4363   /* If we don't have a username and passwd at this point, bail out. */
4364   if (user == NULL || pass == NULL)
4365     goto no_user_pass;
4366
4367   /* Try to configure for each available authentication method, strongest to
4368    * weakest */
4369   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4370     /* Check if this method is available on the server */
4371     if ((method & avail_methods) == 0)
4372       continue;
4373
4374     /* Pass the credentials to the connection to try on the next request */
4375     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4376     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4377      * ignore it and end up retrying later */
4378     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4379       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4380           gst_rtsp_auth_method_to_string (method));
4381       break;
4382     }
4383   }
4384
4385   if (method == GST_RTSP_AUTH_NONE)
4386     goto no_auth_available;
4387
4388   return TRUE;
4389
4390 no_auth_available:
4391   {
4392     /* Output an error indicating that we couldn't connect because there were
4393      * no supported authentication protocols */
4394     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4395         ("No supported authentication protocol was found"));
4396     return FALSE;
4397   }
4398 no_user_pass:
4399   {
4400     /* We don't fire an error message, we just return FALSE and let the
4401      * normal NOT_AUTHORIZED error be propagated */
4402     return FALSE;
4403   }
4404 }
4405
4406 static GstRTSPResult
4407 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4408     GstRTSPMessage * request, GstRTSPMessage * response,
4409     GstRTSPStatusCode * code)
4410 {
4411   GstRTSPResult res;
4412   GstRTSPStatusCode thecode;
4413   gchar *content_base = NULL;
4414   gint try = 0;
4415
4416 again:
4417   if (!src->short_header)
4418     gst_rtsp_ext_list_before_send (src->extensions, request);
4419
4420   GST_DEBUG_OBJECT (src, "sending message");
4421
4422   if (src->debug)
4423     gst_rtsp_message_dump (request);
4424
4425   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4426   if (res < 0)
4427     goto send_error;
4428
4429   gst_rtsp_connection_reset_timeout (conn);
4430
4431 next:
4432   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4433   if (res < 0)
4434     goto receive_error;
4435
4436   if (src->debug)
4437     gst_rtsp_message_dump (response);
4438
4439   switch (response->type) {
4440     case GST_RTSP_MESSAGE_REQUEST:
4441       res = gst_rtspsrc_handle_request (src, conn, response);
4442       if (res == GST_RTSP_EEOF)
4443         goto server_eof;
4444       else if (res < 0)
4445         goto handle_request_failed;
4446       goto next;
4447     case GST_RTSP_MESSAGE_RESPONSE:
4448       /* ok, a response is good */
4449       GST_DEBUG_OBJECT (src, "received response message");
4450       break;
4451     case GST_RTSP_MESSAGE_DATA:
4452       /* get next response */
4453       GST_DEBUG_OBJECT (src, "ignoring data response message");
4454       goto next;
4455     default:
4456       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4457           response->type);
4458       goto next;
4459   }
4460
4461   thecode = response->type_data.response.code;
4462
4463   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4464
4465   /* if the caller wanted the result code, we store it. */
4466   if (code)
4467     *code = thecode;
4468
4469   /* If the request didn't succeed, bail out before doing any more */
4470   if (thecode != GST_RTSP_STS_OK)
4471     return GST_RTSP_OK;
4472
4473   /* store new content base if any */
4474   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4475       &content_base, 0);
4476   if (content_base) {
4477     g_free (src->content_base);
4478     src->content_base = g_strdup (content_base);
4479   }
4480   gst_rtsp_ext_list_after_send (src->extensions, request, response);
4481
4482   return GST_RTSP_OK;
4483
4484   /* ERRORS */
4485 send_error:
4486   {
4487     gchar *str = gst_rtsp_strresult (res);
4488
4489     if (res != GST_RTSP_EINTR) {
4490       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4491           ("Could not send message. (%s)", str));
4492     } else {
4493       GST_WARNING_OBJECT (src, "send interrupted");
4494     }
4495     g_free (str);
4496     return res;
4497   }
4498 receive_error:
4499   {
4500     switch (res) {
4501       case GST_RTSP_EEOF:
4502         GST_WARNING_OBJECT (src, "server closed connection, doing reconnect");
4503         if (try == 0) {
4504           try++;
4505           /* if reconnect succeeds, try again */
4506           if ((res =
4507                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
4508                       FALSE)) == 0)
4509             goto again;
4510         }
4511         /* only try once after reconnect, then fallthrough and error out */
4512       default:
4513       {
4514         gchar *str = gst_rtsp_strresult (res);
4515
4516         if (res != GST_RTSP_EINTR) {
4517           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4518               ("Could not receive message. (%s)", str));
4519         } else {
4520           GST_WARNING_OBJECT (src, "receive interrupted");
4521         }
4522         g_free (str);
4523         break;
4524       }
4525     }
4526     return res;
4527   }
4528 handle_request_failed:
4529   {
4530     /* ERROR was posted */
4531     gst_rtsp_message_unset (response);
4532     return res;
4533   }
4534 server_eof:
4535   {
4536     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4537     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4538         ("The server closed the connection."));
4539     gst_rtsp_message_unset (response);
4540     return res;
4541   }
4542 }
4543
4544 /**
4545  * gst_rtspsrc_send:
4546  * @src: the rtsp source
4547  * @conn: the connection to send on
4548  * @request: must point to a valid request
4549  * @response: must point to an empty #GstRTSPMessage
4550  * @code: an optional code result
4551  *
4552  * send @request and retrieve the response in @response. optionally @code can be
4553  * non-NULL in which case it will contain the status code of the response.
4554  *
4555  * If This function returns #GST_RTSP_OK, @response will contain a valid response
4556  * message that should be cleaned with gst_rtsp_message_unset() after usage.
4557  *
4558  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
4559  * @response message) if the response code was not 200 (OK).
4560  *
4561  * If the attempt results in an authentication failure, then this will attempt
4562  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
4563  * the request.
4564  *
4565  * Returns: #GST_RTSP_OK if the processing was successful.
4566  */
4567 static GstRTSPResult
4568 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4569     GstRTSPMessage * request, GstRTSPMessage * response,
4570     GstRTSPStatusCode * code)
4571 {
4572   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
4573   GstRTSPResult res = GST_RTSP_ERROR;
4574   gint count;
4575   gboolean retry;
4576   GstRTSPMethod method = GST_RTSP_INVALID;
4577
4578   count = 0;
4579   do {
4580     retry = FALSE;
4581
4582     /* make sure we don't loop forever */
4583     if (count++ > 8)
4584       break;
4585
4586     /* save method so we can disable it when the server complains */
4587     method = request->type_data.request.method;
4588
4589     if ((res =
4590             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
4591       goto error;
4592
4593     switch (int_code) {
4594       case GST_RTSP_STS_UNAUTHORIZED:
4595         if (gst_rtspsrc_setup_auth (src, response)) {
4596           /* Try the request/response again after configuring the auth info
4597            * and loop again */
4598           retry = TRUE;
4599         }
4600         break;
4601       default:
4602         break;
4603     }
4604   } while (retry == TRUE);
4605
4606   /* If the user requested the code, let them handle errors, otherwise
4607    * post an error below */
4608   if (code != NULL)
4609     *code = int_code;
4610   else if (int_code != GST_RTSP_STS_OK)
4611     goto error_response;
4612
4613   return res;
4614
4615   /* ERRORS */
4616 error:
4617   {
4618     GST_DEBUG_OBJECT (src, "got error %d", res);
4619     return res;
4620   }
4621 error_response:
4622   {
4623     res = GST_RTSP_ERROR;
4624
4625     switch (response->type_data.response.code) {
4626       case GST_RTSP_STS_NOT_FOUND:
4627         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
4628                 response->type_data.response.reason));
4629         break;
4630       case GST_RTSP_STS_MOVED_PERMANENTLY:
4631       case GST_RTSP_STS_MOVE_TEMPORARILY:
4632       {
4633         gchar *new_location;
4634         GstRTSPLowerTrans transports;
4635
4636         GST_DEBUG_OBJECT (src, "got redirection");
4637         /* if we don't have a Location Header, we must error */
4638         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
4639                 &new_location, 0) < 0)
4640           break;
4641
4642         /* When we receive a redirect result, we go back to the INIT state after
4643          * parsing the new URI. The caller should do the needed steps to issue
4644          * a new setup when it detects this state change. */
4645         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
4646
4647         /* save current transports */
4648         if (src->conninfo.url)
4649           transports = src->conninfo.url->transports;
4650         else
4651           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
4652
4653         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
4654
4655         /* set old transports */
4656         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
4657           src->conninfo.url->transports = transports;
4658
4659         src->need_redirect = TRUE;
4660         src->state = GST_RTSP_STATE_INIT;
4661         res = GST_RTSP_OK;
4662         break;
4663       }
4664       case GST_RTSP_STS_NOT_ACCEPTABLE:
4665       case GST_RTSP_STS_NOT_IMPLEMENTED:
4666       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
4667         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
4668             gst_rtsp_method_as_text (method));
4669         src->methods &= ~method;
4670         res = GST_RTSP_OK;
4671         break;
4672       default:
4673         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4674             ("Got error response: %d (%s).", response->type_data.response.code,
4675                 response->type_data.response.reason));
4676         break;
4677     }
4678     /* if we return ERROR we should unset the response ourselves */
4679     if (res == GST_RTSP_ERROR)
4680       gst_rtsp_message_unset (response);
4681
4682     return res;
4683   }
4684 }
4685
4686 static GstRTSPResult
4687 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
4688     GstRTSPMessage * response, GstRTSPSrc * src)
4689 {
4690   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
4691       NULL);
4692 }
4693
4694
4695 /* parse the response and collect all the supported methods. We need this
4696  * information so that we don't try to send an unsupported request to the
4697  * server.
4698  */
4699 static gboolean
4700 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
4701 {
4702   GstRTSPHeaderField field;
4703   gchar *respoptions;
4704   gchar **options;
4705   gint indx = 0;
4706   gint i;
4707
4708   /* reset supported methods */
4709   src->methods = 0;
4710
4711   /* Try Allow Header first */
4712   field = GST_RTSP_HDR_ALLOW;
4713   while (TRUE) {
4714     respoptions = NULL;
4715     gst_rtsp_message_get_header (response, field, &respoptions, indx);
4716     if (indx == 0 && !respoptions) {
4717       /* if no Allow header was found then try the Public header... */
4718       field = GST_RTSP_HDR_PUBLIC;
4719       gst_rtsp_message_get_header (response, field, &respoptions, indx);
4720     }
4721     if (!respoptions)
4722       break;
4723
4724     /* If we get here, the server gave a list of supported methods, parse
4725      * them here. The string is like:
4726      *
4727      * OPTIONS, DESCRIBE, ANNOUNCE, PLAY, SETUP, ...
4728      */
4729     options = g_strsplit (respoptions, ",", 0);
4730
4731     for (i = 0; options[i]; i++) {
4732       gchar *stripped;
4733       gint method;
4734
4735       stripped = g_strstrip (options[i]);
4736       method = gst_rtsp_find_method (stripped);
4737
4738       /* keep bitfield of supported methods */
4739       if (method != GST_RTSP_INVALID)
4740         src->methods |= method;
4741     }
4742     g_strfreev (options);
4743
4744     indx++;
4745   }
4746
4747   if (src->methods == 0) {
4748     /* neither Allow nor Public are required, assume the server supports
4749      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
4750      * well. */
4751     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
4752     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
4753   }
4754   /* always assume PLAY, FIXME, extensions should be able to override
4755    * this */
4756   src->methods |= GST_RTSP_PLAY;
4757   /* also assume it will support Range */
4758   src->seekable = TRUE;
4759
4760   /* we need describe and setup */
4761   if (!(src->methods & GST_RTSP_DESCRIBE))
4762     goto no_describe;
4763   if (!(src->methods & GST_RTSP_SETUP))
4764     goto no_setup;
4765
4766   return TRUE;
4767
4768   /* ERRORS */
4769 no_describe:
4770   {
4771     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4772         ("Server does not support DESCRIBE."));
4773     return FALSE;
4774   }
4775 no_setup:
4776   {
4777     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4778         ("Server does not support SETUP."));
4779     return FALSE;
4780   }
4781 }
4782
4783 /* masks to be kept in sync with the hardcoded protocol order of preference
4784  * in code below */
4785 static guint protocol_masks[] = {
4786   GST_RTSP_LOWER_TRANS_UDP,
4787   GST_RTSP_LOWER_TRANS_UDP_MCAST,
4788   GST_RTSP_LOWER_TRANS_TCP,
4789   0
4790 };
4791
4792 static GstRTSPResult
4793 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
4794     GstRTSPLowerTrans protocols, gchar ** transports)
4795 {
4796   GstRTSPResult res;
4797   GString *result;
4798   gboolean add_udp_str;
4799
4800   *transports = NULL;
4801
4802   res =
4803       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
4804
4805   if (res < 0)
4806     goto failed;
4807
4808   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
4809
4810   /* extension listed transports, use those */
4811   if (*transports != NULL)
4812     return GST_RTSP_OK;
4813
4814   /* it's the default */
4815   add_udp_str = FALSE;
4816
4817   /* the default RTSP transports */
4818   result = g_string_new ("");
4819   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
4820     GST_DEBUG_OBJECT (src, "adding UDP unicast");
4821
4822     g_string_append (result, "RTP/AVP");
4823     if (add_udp_str)
4824       g_string_append (result, "/UDP");
4825     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
4826   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
4827     GST_DEBUG_OBJECT (src, "adding UDP multicast");
4828
4829     /* we don't have to allocate any UDP ports yet, if the selected transport
4830      * turns out to be multicast we can create them and join the multicast
4831      * group indicated in the transport reply */
4832     if (result->len > 0)
4833       g_string_append (result, ",");
4834     g_string_append (result, "RTP/AVP");
4835     if (add_udp_str)
4836       g_string_append (result, "/UDP");
4837     g_string_append (result, ";multicast");
4838   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
4839     GST_DEBUG_OBJECT (src, "adding TCP");
4840
4841     if (result->len > 0)
4842       g_string_append (result, ",");
4843     g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
4844   }
4845   *transports = g_string_free (result, FALSE);
4846
4847   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
4848
4849   return GST_RTSP_OK;
4850
4851   /* ERRORS */
4852 failed:
4853   {
4854     return res;
4855   }
4856 }
4857
4858 static GstRTSPResult
4859 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
4860     gint orig_rtpport, gint orig_rtcpport)
4861 {
4862   GstRTSPSrc *src;
4863   gint nr_udp, nr_int;
4864   gchar *next, *p;
4865   gint rtpport = 0, rtcpport = 0;
4866   GString *str;
4867
4868   src = stream->parent;
4869
4870   /* find number of placeholders first */
4871   if (strstr (*transports, "%%i2"))
4872     nr_int = 2;
4873   else if (strstr (*transports, "%%i1"))
4874     nr_int = 1;
4875   else
4876     nr_int = 0;
4877
4878   if (strstr (*transports, "%%u2"))
4879     nr_udp = 2;
4880   else if (strstr (*transports, "%%u1"))
4881     nr_udp = 1;
4882   else
4883     nr_udp = 0;
4884
4885   if (nr_udp == 0 && nr_int == 0)
4886     goto done;
4887
4888   if (nr_udp > 0) {
4889     if (!orig_rtpport || !orig_rtcpport) {
4890       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
4891         goto failed;
4892     } else {
4893       rtpport = orig_rtpport;
4894       rtcpport = orig_rtcpport;
4895     }
4896   }
4897
4898   str = g_string_new ("");
4899   p = *transports;
4900   while ((next = strstr (p, "%%"))) {
4901     g_string_append_len (str, p, next - p);
4902     if (next[2] == 'u') {
4903       if (next[3] == '1')
4904         g_string_append_printf (str, "%d", rtpport);
4905       else if (next[3] == '2')
4906         g_string_append_printf (str, "%d", rtcpport);
4907     }
4908     if (next[2] == 'i') {
4909       if (next[3] == '1')
4910         g_string_append_printf (str, "%d", src->free_channel);
4911       else if (next[3] == '2')
4912         g_string_append_printf (str, "%d", src->free_channel + 1);
4913     }
4914
4915     p = next + 4;
4916   }
4917   /* append final part */
4918   g_string_append (str, p);
4919
4920   g_free (*transports);
4921   *transports = g_string_free (str, FALSE);
4922
4923 done:
4924   return GST_RTSP_OK;
4925
4926   /* ERRORS */
4927 failed:
4928   {
4929     return GST_RTSP_ERROR;
4930   }
4931 }
4932
4933 static gboolean
4934 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
4935 {
4936   gboolean res = FALSE;
4937
4938   if (stream->caps) {
4939     GstStructure *s;
4940     const gchar *enc = NULL;
4941
4942     s = gst_caps_get_structure (stream->caps, 0);
4943     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
4944       res = (strstr (enc, "-REAL") != NULL);
4945     }
4946   }
4947   return res;
4948 }
4949
4950 /* Perform the SETUP request for all the streams.
4951  *
4952  * We ask the server for a specific transport, which initially includes all the
4953  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
4954  * two local UDP ports that we send to the server.
4955  *
4956  * Once the server replied with a transport, we configure the other streams
4957  * with the same transport.
4958  *
4959  * This function will also configure the stream for the selected transport,
4960  * which basically means creating the pipeline.
4961  */
4962 static GstRTSPResult
4963 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
4964 {
4965   GList *walk;
4966   GstRTSPResult res = GST_RTSP_ERROR;
4967   GstRTSPMessage request = { 0 };
4968   GstRTSPMessage response = { 0 };
4969   GstRTSPStream *stream = NULL;
4970   GstRTSPLowerTrans protocols;
4971   GstRTSPStatusCode code;
4972   gboolean unsupported_real = FALSE;
4973   gint rtpport, rtcpport;
4974   GstRTSPUrl *url;
4975   gchar *hval;
4976
4977   if (src->conninfo.connection) {
4978     url = gst_rtsp_connection_get_url (src->conninfo.connection);
4979     /* we initially allow all configured lower transports. based on the URL
4980      * transports and the replies from the server we narrow them down. */
4981     protocols = url->transports & src->cur_protocols;
4982   } else {
4983     url = NULL;
4984     protocols = src->cur_protocols;
4985   }
4986
4987   if (protocols == 0)
4988     goto no_protocols;
4989
4990   /* reset some state */
4991   src->free_channel = 0;
4992   src->interleaved = FALSE;
4993   src->need_activate = FALSE;
4994   /* keep track of next port number, 0 is random */
4995   src->next_port_num = src->client_port_range.min;
4996   rtpport = rtcpport = 0;
4997
4998   if (G_UNLIKELY (src->streams == NULL))
4999     goto no_streams;
5000
5001   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5002     GstRTSPConnection *conn;
5003     gchar *transports;
5004     gint retry = 0;
5005     guint mask = 0;
5006
5007     stream = (GstRTSPStream *) walk->data;
5008
5009     /* see if we need to configure this stream */
5010     if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5011       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5012           stream);
5013       stream->disabled = TRUE;
5014       continue;
5015     }
5016
5017     /* merge/overwrite global caps */
5018     if (stream->caps) {
5019       guint j, num;
5020       GstStructure *s;
5021
5022       s = gst_caps_get_structure (stream->caps, 0);
5023
5024       num = gst_structure_n_fields (src->props);
5025       for (j = 0; j < num; j++) {
5026         const gchar *name;
5027         const GValue *val;
5028
5029         name = gst_structure_nth_field_name (src->props, j);
5030         val = gst_structure_get_value (src->props, name);
5031         gst_structure_set_value (s, name, val);
5032
5033         GST_DEBUG_OBJECT (src, "copied %s", name);
5034       }
5035     }
5036
5037     /* skip setup if we have no URL for it */
5038     if (stream->conninfo.location == NULL) {
5039       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5040       continue;
5041     }
5042
5043     if (src->conninfo.connection == NULL) {
5044       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5045         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5046         continue;
5047       }
5048       conn = stream->conninfo.connection;
5049     } else {
5050       conn = src->conninfo.connection;
5051     }
5052     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5053         stream->conninfo.location);
5054
5055     /* if we have a multicast connection, only suggest multicast from now on */
5056     if (stream->is_multicast)
5057       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5058
5059   next_protocol:
5060     /* first selectable protocol */
5061     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5062       mask++;
5063     if (!protocol_masks[mask])
5064       goto no_protocols;
5065
5066   retry:
5067     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5068         protocol_masks[mask]);
5069     /* create a string with first transport in line */
5070     transports = NULL;
5071     res = gst_rtspsrc_create_transports_string (src,
5072         protocols & protocol_masks[mask], &transports);
5073     if (res < 0 || transports == NULL)
5074       goto setup_transport_failed;
5075
5076     if (strlen (transports) == 0) {
5077       g_free (transports);
5078       GST_DEBUG_OBJECT (src, "no transports found");
5079       mask++;
5080       goto next_protocol;
5081     }
5082
5083     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5084
5085     /* replace placeholders with real values, this function will optionally
5086      * allocate UDP ports and other info needed to execute the setup request */
5087     res = gst_rtspsrc_prepare_transports (stream, &transports,
5088         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5089     if (res < 0) {
5090       g_free (transports);
5091       goto setup_transport_failed;
5092     }
5093
5094     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5095
5096     /* create SETUP request */
5097     res =
5098         gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5099         stream->conninfo.location);
5100     if (res < 0) {
5101       g_free (transports);
5102       goto create_request_failed;
5103     }
5104
5105     /* select transport, copy is made when adding to header so we can free it. */
5106     gst_rtsp_message_add_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5107     g_free (transports);
5108
5109     /* if the user wants a non default RTP packet size we add the blocksize
5110      * parameter */
5111     if (src->rtp_blocksize > 0) {
5112       hval = g_strdup_printf ("%d", src->rtp_blocksize);
5113       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5114       g_free (hval);
5115     }
5116
5117     if (async)
5118       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5119               stream->id));
5120
5121     /* handle the code ourselves */
5122     if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5123       goto send_error;
5124
5125     switch (code) {
5126       case GST_RTSP_STS_OK:
5127         break;
5128       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5129         gst_rtsp_message_unset (&request);
5130         gst_rtsp_message_unset (&response);
5131         /* cleanup of leftover transport */
5132         gst_rtspsrc_stream_free_udp (stream);
5133         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5134          * we might be in this case */
5135         if (stream->container && rtpport && rtcpport && !retry) {
5136           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5137               rtpport, rtcpport);
5138           retry++;
5139           goto retry;
5140         }
5141         /* this transport did not go down well, but we may have others to try
5142          * that we did not send yet, try those and only give up then
5143          * but not without checking for lost cause/extension so we can
5144          * post a nicer/more useful error message later */
5145         if (!unsupported_real)
5146           unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5147         /* select next available protocol, give up on this stream if none */
5148         mask++;
5149         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5150           mask++;
5151         if (!protocol_masks[mask] || unsupported_real)
5152           continue;
5153         else
5154           goto retry;
5155       default:
5156         /* cleanup of leftover transport and move to the next stream */
5157         gst_rtspsrc_stream_free_udp (stream);
5158         goto response_error;
5159     }
5160
5161     /* parse response transport */
5162     {
5163       gchar *resptrans = NULL;
5164       GstRTSPTransport transport = { 0 };
5165
5166       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5167           &resptrans, 0);
5168       if (!resptrans) {
5169         gst_rtspsrc_stream_free_udp (stream);
5170         goto no_transport;
5171       }
5172
5173       /* parse transport, go to next stream on parse error */
5174       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5175         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5176         goto next;
5177       }
5178
5179       /* update allowed transports for other streams. once the transport of
5180        * one stream has been determined, we make sure that all other streams
5181        * are configured in the same way */
5182       switch (transport.lower_transport) {
5183         case GST_RTSP_LOWER_TRANS_TCP:
5184           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5185           protocols = GST_RTSP_LOWER_TRANS_TCP;
5186           src->interleaved = TRUE;
5187           /* update free channels */
5188           src->free_channel =
5189               MAX (transport.interleaved.min, src->free_channel);
5190           src->free_channel =
5191               MAX (transport.interleaved.max, src->free_channel);
5192           src->free_channel++;
5193           break;
5194         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5195           /* only allow multicast for other streams */
5196           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5197           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5198           break;
5199         case GST_RTSP_LOWER_TRANS_UDP:
5200           /* only allow unicast for other streams */
5201           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5202           protocols = GST_RTSP_LOWER_TRANS_UDP;
5203           break;
5204         default:
5205           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5206               transport.lower_transport);
5207           break;
5208       }
5209
5210       if (!stream->container || (!src->interleaved && !retry)) {
5211         /* now configure the stream with the selected transport */
5212         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5213           GST_DEBUG_OBJECT (src,
5214               "could not configure stream %p transport, skipping stream",
5215               stream);
5216           goto next;
5217         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5218           /* retain the first allocated UDP port pair */
5219           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5220           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5221         }
5222       }
5223       /* we need to activate at least one streams when we detect activity */
5224       src->need_activate = TRUE;
5225     next:
5226       /* clean up our transport struct */
5227       gst_rtsp_transport_init (&transport);
5228       /* clean up used RTSP messages */
5229       gst_rtsp_message_unset (&request);
5230       gst_rtsp_message_unset (&response);
5231     }
5232   }
5233
5234   /* store the transport protocol that was configured */
5235   src->cur_protocols = protocols;
5236
5237   gst_rtsp_ext_list_stream_select (src->extensions, url);
5238
5239   /* if there is nothing to activate, error out */
5240   if (!src->need_activate)
5241     goto nothing_to_activate;
5242
5243   return res;
5244
5245   /* ERRORS */
5246 no_protocols:
5247   {
5248     /* no transport possible, post an error and stop */
5249     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5250         ("Could not connect to server, no protocols left"));
5251     return GST_RTSP_ERROR;
5252   }
5253 no_streams:
5254   {
5255     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5256         ("SDP contains no streams"));
5257     return GST_RTSP_ERROR;
5258   }
5259 create_request_failed:
5260   {
5261     gchar *str = gst_rtsp_strresult (res);
5262
5263     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5264         ("Could not create request. (%s)", str));
5265     g_free (str);
5266     goto cleanup_error;
5267   }
5268 setup_transport_failed:
5269   {
5270     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5271         ("Could not setup transport."));
5272     res = GST_RTSP_ERROR;
5273     goto cleanup_error;
5274   }
5275 response_error:
5276   {
5277     const gchar *str = gst_rtsp_status_as_text (code);
5278
5279     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5280         ("Error (%d): %s", code, GST_STR_NULL (str)));
5281     res = GST_RTSP_ERROR;
5282     goto cleanup_error;
5283   }
5284 send_error:
5285   {
5286     gchar *str = gst_rtsp_strresult (res);
5287
5288     if (res != GST_RTSP_EINTR) {
5289       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5290           ("Could not send message. (%s)", str));
5291     } else {
5292       GST_WARNING_OBJECT (src, "send interrupted");
5293     }
5294     g_free (str);
5295     goto cleanup_error;
5296   }
5297 no_transport:
5298   {
5299     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5300         ("Server did not select transport."));
5301     res = GST_RTSP_ERROR;
5302     goto cleanup_error;
5303   }
5304 nothing_to_activate:
5305   {
5306     /* none of the available error codes is really right .. */
5307     if (unsupported_real) {
5308       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5309           (_("No supported stream was found. You might need to install a "
5310                   "GStreamer RTSP extension plugin for Real media streams.")),
5311           (NULL));
5312     } else {
5313       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5314           (_("No supported stream was found. You might need to allow "
5315                   "more transport protocols or may otherwise be missing "
5316                   "the right GStreamer RTSP extension plugin.")), (NULL));
5317     }
5318     return GST_RTSP_ERROR;
5319   }
5320 cleanup_error:
5321   {
5322     gst_rtsp_message_unset (&request);
5323     gst_rtsp_message_unset (&response);
5324     return res;
5325   }
5326 }
5327
5328 static gboolean
5329 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5330     GstSegment * segment)
5331 {
5332   gint64 seconds;
5333   GstRTSPTimeRange *therange;
5334
5335   if (src->range)
5336     gst_rtsp_range_free (src->range);
5337
5338   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5339     GST_DEBUG_OBJECT (src, "parsed range %s", range);
5340     src->range = therange;
5341   } else {
5342     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5343     src->range = NULL;
5344     gst_segment_init (segment, GST_FORMAT_TIME);
5345     return FALSE;
5346   }
5347
5348   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
5349       therange->min.type, therange->min.seconds, therange->max.type,
5350       therange->max.seconds);
5351
5352   if (therange->min.type == GST_RTSP_TIME_NOW)
5353     seconds = 0;
5354   else if (therange->min.type == GST_RTSP_TIME_END)
5355     seconds = 0;
5356   else
5357     seconds = therange->min.seconds * GST_SECOND;
5358
5359   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5360       GST_TIME_ARGS (seconds));
5361
5362   /* we need to start playback without clipping from the position reported by
5363    * the server */
5364   segment->start = seconds;
5365   segment->position = seconds;
5366
5367   if (therange->max.type == GST_RTSP_TIME_NOW)
5368     seconds = -1;
5369   else if (therange->max.type == GST_RTSP_TIME_END)
5370     seconds = -1;
5371   else
5372     seconds = therange->max.seconds * GST_SECOND;
5373
5374   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5375       GST_TIME_ARGS (seconds));
5376
5377   /* live (WMS) server might send overflowed large max as its idea of infinity,
5378    * compensate to prevent problems later on */
5379   if (seconds != -1 && seconds < 0) {
5380     seconds = -1;
5381     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5382   }
5383
5384   /* live (WMS) might send min == max, which is not worth recording */
5385   if (segment->duration == -1 && seconds == segment->start)
5386     seconds = -1;
5387
5388   /* don't change duration with unknown value, we might have a valid value
5389    * there that we want to keep. */
5390   if (seconds != -1)
5391     segment->duration = seconds;
5392
5393   return TRUE;
5394 }
5395
5396 /* must be called with the RTSP state lock */
5397 static GstRTSPResult
5398 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5399     gboolean async)
5400 {
5401   GstRTSPResult res;
5402   gint i, n_streams;
5403
5404   /* prepare global stream caps properties */
5405   if (src->props)
5406     gst_structure_remove_all_fields (src->props);
5407   else
5408     src->props = gst_structure_new_empty ("RTSPProperties");
5409
5410   if (src->debug)
5411     gst_sdp_message_dump (sdp);
5412
5413   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
5414
5415   gst_segment_init (&src->segment, GST_FORMAT_TIME);
5416
5417   /* parse range for duration reporting. */
5418   {
5419     const gchar *range;
5420
5421     for (i = 0;; i++) {
5422       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
5423       if (range == NULL)
5424         break;
5425
5426       /* keep track of the range and configure it in the segment */
5427       if (gst_rtspsrc_parse_range (src, range, &src->segment))
5428         break;
5429     }
5430   }
5431   /* try to find a global control attribute. Note that a '*' means that we should
5432    * do aggregate control with the current url (so we don't do anything and
5433    * leave the current connection as is) */
5434   {
5435     const gchar *control;
5436
5437     for (i = 0;; i++) {
5438       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
5439       if (control == NULL)
5440         break;
5441
5442       /* only take fully qualified urls */
5443       if (g_str_has_prefix (control, "rtsp://"))
5444         break;
5445     }
5446     if (control) {
5447       g_free (src->conninfo.location);
5448       src->conninfo.location = g_strdup (control);
5449       /* make a connection for this, if there was a connection already, nothing
5450        * happens. */
5451       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
5452         GST_ERROR_OBJECT (src, "could not connect");
5453       }
5454     }
5455     /* we need to keep the control url separate from the connection url because
5456      * the rules for constructing the media control url need it */
5457     g_free (src->control);
5458     src->control = g_strdup (control);
5459   }
5460
5461   /* create streams */
5462   n_streams = gst_sdp_message_medias_len (sdp);
5463   for (i = 0; i < n_streams; i++) {
5464     gst_rtspsrc_create_stream (src, sdp, i);
5465   }
5466
5467   src->state = GST_RTSP_STATE_INIT;
5468
5469   /* setup streams */
5470   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
5471     goto setup_failed;
5472
5473   /* reset our state */
5474   src->need_range = TRUE;
5475   src->skip = FALSE;
5476
5477   src->state = GST_RTSP_STATE_READY;
5478
5479   return res;
5480
5481   /* ERRORS */
5482 setup_failed:
5483   {
5484     GST_ERROR_OBJECT (src, "setup failed");
5485     return res;
5486   }
5487 }
5488
5489 static GstRTSPResult
5490 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
5491     gboolean async)
5492 {
5493   GstRTSPResult res;
5494   GstRTSPMessage request = { 0 };
5495   GstRTSPMessage response = { 0 };
5496   guint8 *data;
5497   guint size;
5498   gchar *respcont = NULL;
5499
5500 restart:
5501   src->need_redirect = FALSE;
5502
5503   /* can't continue without a valid url */
5504   if (G_UNLIKELY (src->conninfo.url == NULL)) {
5505     res = GST_RTSP_EINVAL;
5506     goto no_url;
5507   }
5508   src->tried_url_auth = FALSE;
5509
5510   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
5511     goto connect_failed;
5512
5513   /* create OPTIONS */
5514   GST_DEBUG_OBJECT (src, "create options...");
5515   res =
5516       gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
5517       src->conninfo.url_str);
5518   if (res < 0)
5519     goto create_request_failed;
5520
5521   /* send OPTIONS */
5522   GST_DEBUG_OBJECT (src, "send options...");
5523
5524   if (async)
5525     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
5526
5527   if ((res =
5528           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5529               NULL)) < 0)
5530     goto send_error;
5531
5532   /* parse OPTIONS */
5533   if (!gst_rtspsrc_parse_methods (src, &response))
5534     goto methods_error;
5535
5536   /* create DESCRIBE */
5537   GST_DEBUG_OBJECT (src, "create describe...");
5538   res =
5539       gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
5540       src->conninfo.url_str);
5541   if (res < 0)
5542     goto create_request_failed;
5543
5544   /* we only accept SDP for now */
5545   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
5546       "application/sdp");
5547
5548   /* send DESCRIBE */
5549   GST_DEBUG_OBJECT (src, "send describe...");
5550
5551   if (async)
5552     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
5553
5554   if ((res =
5555           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5556               NULL)) < 0)
5557     goto send_error;
5558
5559   /* we only perform redirect for the describe, currently */
5560   if (src->need_redirect) {
5561     /* close connection, we don't have to send a TEARDOWN yet, ignore the
5562      * result. */
5563     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5564
5565     gst_rtsp_message_unset (&request);
5566     gst_rtsp_message_unset (&response);
5567
5568     /* and now retry */
5569     goto restart;
5570   }
5571
5572   /* it could be that the DESCRIBE method was not implemented */
5573   if (!src->methods & GST_RTSP_DESCRIBE)
5574     goto no_describe;
5575
5576   /* check if reply is SDP */
5577   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
5578       0);
5579   /* could not be set but since the request returned OK, we assume it
5580    * was SDP, else check it. */
5581   if (respcont) {
5582     if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
5583       goto wrong_content_type;
5584   }
5585
5586   /* get message body and parse as SDP */
5587   gst_rtsp_message_get_body (&response, &data, &size);
5588   if (data == NULL || size == 0)
5589     goto no_describe;
5590
5591   GST_DEBUG_OBJECT (src, "parse SDP...");
5592   gst_sdp_message_new (sdp);
5593   gst_sdp_message_parse_buffer (data, size, *sdp);
5594
5595   /* clean up any messages */
5596   gst_rtsp_message_unset (&request);
5597   gst_rtsp_message_unset (&response);
5598
5599   return res;
5600
5601   /* ERRORS */
5602 no_url:
5603   {
5604     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
5605         ("No valid RTSP URL was provided"));
5606     goto cleanup_error;
5607   }
5608 connect_failed:
5609   {
5610     gchar *str = gst_rtsp_strresult (res);
5611
5612     if (res != GST_RTSP_EINTR) {
5613       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
5614           ("Failed to connect. (%s)", str));
5615     } else {
5616       GST_WARNING_OBJECT (src, "connect interrupted");
5617     }
5618     g_free (str);
5619     goto cleanup_error;
5620   }
5621 create_request_failed:
5622   {
5623     gchar *str = gst_rtsp_strresult (res);
5624
5625     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5626         ("Could not create request. (%s)", str));
5627     g_free (str);
5628     goto cleanup_error;
5629   }
5630 send_error:
5631   {
5632     /* Don't post a message - the rtsp_send method will have
5633      * taken care of it because we passed NULL for the response code */
5634     goto cleanup_error;
5635   }
5636 methods_error:
5637   {
5638     /* error was posted */
5639     res = GST_RTSP_ERROR;
5640     goto cleanup_error;
5641   }
5642 wrong_content_type:
5643   {
5644     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5645         ("Server does not support SDP, got %s.", respcont));
5646     res = GST_RTSP_ERROR;
5647     goto cleanup_error;
5648   }
5649 no_describe:
5650   {
5651     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5652         ("Server can not provide an SDP."));
5653     res = GST_RTSP_ERROR;
5654     goto cleanup_error;
5655   }
5656 cleanup_error:
5657   {
5658     if (src->conninfo.connection) {
5659       GST_DEBUG_OBJECT (src, "free connection");
5660       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5661     }
5662     gst_rtsp_message_unset (&request);
5663     gst_rtsp_message_unset (&response);
5664     return res;
5665   }
5666 }
5667
5668 static GstRTSPResult
5669 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
5670 {
5671   GstRTSPResult ret;
5672
5673   src->methods =
5674       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
5675
5676   if (src->sdp == NULL) {
5677     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
5678       goto no_sdp;
5679   }
5680
5681   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
5682     goto open_failed;
5683
5684 done:
5685   if (async)
5686     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
5687
5688   return ret;
5689
5690   /* ERRORS */
5691 no_sdp:
5692   {
5693     GST_WARNING_OBJECT (src, "can't get sdp");
5694     src->open_error = TRUE;
5695     goto done;
5696   }
5697 open_failed:
5698   {
5699     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
5700     src->open_error = TRUE;
5701     goto done;
5702   }
5703 }
5704
5705 static GstRTSPResult
5706 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
5707 {
5708   GstRTSPMessage request = { 0 };
5709   GstRTSPMessage response = { 0 };
5710   GstRTSPResult res = GST_RTSP_OK;
5711   GList *walk;
5712   gchar *control;
5713
5714   GST_DEBUG_OBJECT (src, "TEARDOWN...");
5715
5716   if (src->state < GST_RTSP_STATE_READY) {
5717     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
5718     goto close;
5719   }
5720
5721   if (only_close)
5722     goto close;
5723
5724   /* construct a control url */
5725   if (src->control)
5726     control = src->control;
5727   else
5728     control = src->conninfo.url_str;
5729
5730   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
5731     goto not_supported;
5732
5733   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5734     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5735     gchar *setup_url;
5736     GstRTSPConnInfo *info;
5737
5738     /* try aggregate control first but do non-aggregate control otherwise */
5739     if (control)
5740       setup_url = control;
5741     else if ((setup_url = stream->conninfo.location) == NULL)
5742       continue;
5743
5744     if (src->conninfo.connection) {
5745       info = &src->conninfo;
5746     } else if (stream->conninfo.connection) {
5747       info = &stream->conninfo;
5748     } else {
5749       continue;
5750     }
5751     if (!info->connected)
5752       goto next;
5753
5754     /* do TEARDOWN */
5755     res =
5756         gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
5757     if (res < 0)
5758       goto create_request_failed;
5759
5760     if (async)
5761       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
5762
5763     if ((res =
5764             gst_rtspsrc_send (src, info->connection, &request, &response,
5765                 NULL)) < 0)
5766       goto send_error;
5767
5768     /* FIXME, parse result? */
5769     gst_rtsp_message_unset (&request);
5770     gst_rtsp_message_unset (&response);
5771
5772   next:
5773     /* early exit when we did aggregate control */
5774     if (control)
5775       break;
5776   }
5777
5778 close:
5779   /* close connections */
5780   GST_DEBUG_OBJECT (src, "closing connection...");
5781   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5782   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5783     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5784     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
5785   }
5786
5787   /* cleanup */
5788   gst_rtspsrc_cleanup (src);
5789
5790   src->state = GST_RTSP_STATE_INVALID;
5791
5792   if (async)
5793     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
5794
5795   return res;
5796
5797   /* ERRORS */
5798 create_request_failed:
5799   {
5800     gchar *str = gst_rtsp_strresult (res);
5801
5802     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5803         ("Could not create request. (%s)", str));
5804     g_free (str);
5805     goto close;
5806   }
5807 send_error:
5808   {
5809     gchar *str = gst_rtsp_strresult (res);
5810
5811     gst_rtsp_message_unset (&request);
5812     if (res != GST_RTSP_EINTR) {
5813       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5814           ("Could not send message. (%s)", str));
5815     } else {
5816       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
5817     }
5818     g_free (str);
5819     goto close;
5820   }
5821 not_supported:
5822   {
5823     GST_DEBUG_OBJECT (src,
5824         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
5825     goto close;
5826   }
5827 }
5828
5829 /* RTP-Info is of the format:
5830  *
5831  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
5832  *
5833  * rtptime corresponds to the timestamp for the NPT time given in the header
5834  * seqbase corresponds to the next sequence number we received. This number
5835  * indicates the first seqnum after the seek and should be used to discard
5836  * packets that are from before the seek.
5837  */
5838 static gboolean
5839 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
5840 {
5841   gchar **infos;
5842   gint i, j;
5843
5844   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
5845
5846   infos = g_strsplit (rtpinfo, ",", 0);
5847   for (i = 0; infos[i]; i++) {
5848     gchar **fields;
5849     GstRTSPStream *stream;
5850     gint32 seqbase;
5851     gint64 timebase;
5852
5853     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
5854
5855     /* init values, types of seqbase and timebase are bigger than needed so we
5856      * can store -1 as uninitialized values */
5857     stream = NULL;
5858     seqbase = -1;
5859     timebase = -1;
5860
5861     /* parse url, find stream for url.
5862      * parse seq and rtptime. The seq number should be configured in the rtp
5863      * depayloader or session manager to detect gaps. Same for the rtptime, it
5864      * should be used to create an initial time newsegment. */
5865     fields = g_strsplit (infos[i], ";", 0);
5866     for (j = 0; fields[j]; j++) {
5867       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
5868       /* remove leading whitespace */
5869       fields[j] = g_strchug (fields[j]);
5870       if (g_str_has_prefix (fields[j], "url=")) {
5871         /* get the url and the stream */
5872         stream =
5873             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
5874       } else if (g_str_has_prefix (fields[j], "seq=")) {
5875         seqbase = atoi (fields[j] + 4);
5876       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
5877         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
5878       }
5879     }
5880     g_strfreev (fields);
5881     /* now we need to store the values for the caps of the stream */
5882     if (stream != NULL) {
5883       GST_DEBUG_OBJECT (src,
5884           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
5885           stream, seqbase, timebase);
5886
5887       /* we have a stream, configure detected params */
5888       stream->seqbase = seqbase;
5889       stream->timebase = timebase;
5890     }
5891   }
5892   g_strfreev (infos);
5893
5894   return TRUE;
5895 }
5896
5897 static void
5898 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
5899 {
5900   guint64 interval;
5901   GList *walk;
5902
5903   interval = strtoul (rtcp, NULL, 10);
5904   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
5905
5906   if (!interval)
5907     return;
5908
5909   interval *= GST_MSECOND;
5910
5911   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5912     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5913
5914     /* already (optionally) retrieved this when configuring manager */
5915     if (stream->session) {
5916       GObject *rtpsession = stream->session;
5917
5918       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
5919           rtpsession);
5920       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
5921     }
5922   }
5923
5924   /* now it happens that (Xenon) server sending this may also provide bogus
5925    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
5926    * and just use RTP-Info to sync */
5927   if (src->manager) {
5928     GObjectClass *klass;
5929
5930     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
5931     if (g_object_class_find_property (klass, "rtcp-sync")) {
5932       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
5933       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
5934     }
5935   }
5936 }
5937
5938 static gdouble
5939 gst_rtspsrc_get_float (const gchar * dstr)
5940 {
5941   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
5942
5943   /* canonicalise floating point string so we can handle float strings
5944    * in the form "24.930" or "24,930" irrespective of the current locale */
5945   g_strlcpy (s, dstr, sizeof (s));
5946   g_strdelimit (s, ",", '.');
5947   return g_ascii_strtod (s, NULL);
5948 }
5949
5950 static gchar *
5951 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
5952 {
5953   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
5954
5955   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
5956     g_strlcpy (val_str, "now", sizeof (val_str));
5957   } else {
5958     if (segment->position == 0) {
5959       g_strlcpy (val_str, "0", sizeof (val_str));
5960     } else {
5961       g_ascii_dtostr (val_str, sizeof (val_str),
5962           ((gdouble) segment->position) / GST_SECOND);
5963     }
5964   }
5965   return g_strdup_printf ("npt=%s-", val_str);
5966 }
5967
5968 static void
5969 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
5970 {
5971   stream->timebase = -1;
5972   stream->seqbase = -1;
5973   if (stream->caps) {
5974     GstStructure *s;
5975
5976     stream->caps = gst_caps_make_writable (stream->caps);
5977     s = gst_caps_get_structure (stream->caps, 0);
5978     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
5979   }
5980 }
5981
5982 static GstRTSPResult
5983 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
5984 {
5985   GstRTSPResult res = GST_RTSP_OK;
5986
5987   if (src->state < GST_RTSP_STATE_READY) {
5988     res = GST_RTSP_ERROR;
5989     if (src->open_error) {
5990       GST_DEBUG_OBJECT (src, "the stream was in error");
5991       goto done;
5992     }
5993     if (async)
5994       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
5995
5996     if ((res = gst_rtspsrc_open (src, async)) < 0) {
5997       GST_DEBUG_OBJECT (src, "failed to open stream");
5998       goto done;
5999     }
6000   }
6001
6002 done:
6003   return res;
6004 }
6005
6006 static GstRTSPResult
6007 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6008 {
6009   GstRTSPMessage request = { 0 };
6010   GstRTSPMessage response = { 0 };
6011   GstRTSPResult res = GST_RTSP_OK;
6012   GList *walk;
6013   gchar *hval;
6014   gint hval_idx;
6015   gchar *control;
6016
6017   GST_DEBUG_OBJECT (src, "PLAY...");
6018
6019   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6020     goto open_failed;
6021
6022   if (!(src->methods & GST_RTSP_PLAY))
6023     goto not_supported;
6024
6025   if (src->state == GST_RTSP_STATE_PLAYING)
6026     goto was_playing;
6027
6028   if (!src->conninfo.connection || !src->conninfo.connected)
6029     goto done;
6030
6031   /* send some dummy packets before we activate the receive in the
6032    * udp sources */
6033   gst_rtspsrc_send_dummy_packets (src);
6034
6035   /* activate receive elements;
6036    * only in async case, since receive elements may not have been affected
6037    * by overall state change (e.g. not around yet),
6038    * do not mess with state in sync case (e.g. seeking) */
6039   if (async)
6040     gst_element_set_state (GST_ELEMENT_CAST (src), GST_STATE_PLAYING);
6041
6042   /* construct a control url */
6043   if (src->control)
6044     control = src->control;
6045   else
6046     control = src->conninfo.url_str;
6047
6048   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6049     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6050     gchar *setup_url;
6051     GstRTSPConnection *conn;
6052
6053     /* try aggregate control first but do non-aggregate control otherwise */
6054     if (control)
6055       setup_url = control;
6056     else if ((setup_url = stream->conninfo.location) == NULL)
6057       continue;
6058
6059     if (src->conninfo.connection) {
6060       conn = src->conninfo.connection;
6061     } else if (stream->conninfo.connection) {
6062       conn = stream->conninfo.connection;
6063     } else {
6064       continue;
6065     }
6066
6067     /* do play */
6068     res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6069     if (res < 0)
6070       goto create_request_failed;
6071
6072     if (src->need_range) {
6073       hval = gen_range_header (src, segment);
6074
6075       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_RANGE, hval);
6076       g_free (hval);
6077     }
6078
6079     if (segment->rate != 1.0) {
6080       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6081
6082       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6083       if (src->skip)
6084         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6085       else
6086         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6087     }
6088
6089     if (async)
6090       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6091
6092     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6093       goto send_error;
6094
6095     /* seek may have silently failed as it is not supported */
6096     if (!(src->methods & GST_RTSP_PLAY)) {
6097       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6098       /* obviously it is supported as we made it here */
6099       src->methods |= GST_RTSP_PLAY;
6100       src->seekable = FALSE;
6101       /* but there is nothing to parse in the response,
6102        * so convey we have no idea and not to expect anything particular */
6103       clear_rtp_base (src, stream);
6104       if (control) {
6105         GList *run;
6106
6107         /* need to do for all streams */
6108         for (run = src->streams; run; run = g_list_next (run))
6109           clear_rtp_base (src, (GstRTSPStream *) run->data);
6110       }
6111       /* NOTE the above also disables npt based eos detection */
6112       /* and below forces position to 0,
6113        * which is visible feedback we lost the plot */
6114       segment->start = segment->position = src->last_pos;
6115     }
6116
6117     gst_rtsp_message_unset (&request);
6118
6119     /* parse RTP npt field. This is the current position in the stream (Normal
6120      * Play Time) and should be put in the NEWSEGMENT position field. */
6121     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6122             0) == GST_RTSP_OK)
6123       gst_rtspsrc_parse_range (src, hval, segment);
6124
6125     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6126     segment->rate = 1.0;
6127
6128     /* parse Speed header. This is the intended playback rate of the stream
6129      * and should be put in the NEWSEGMENT rate field. */
6130     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6131             0) == GST_RTSP_OK) {
6132       segment->rate = gst_rtspsrc_get_float (hval);
6133     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6134             &hval, 0) == GST_RTSP_OK) {
6135       segment->rate = gst_rtspsrc_get_float (hval);
6136     }
6137
6138     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6139      * for the RTP packets. If this is not present, we assume all starts from 0...
6140      * This is info for the RTP session manager that we pass to it in caps. */
6141     hval_idx = 0;
6142     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6143             &hval, hval_idx++) == GST_RTSP_OK)
6144       gst_rtspsrc_parse_rtpinfo (src, hval);
6145
6146     /* some servers indicate RTCP parameters in PLAY response,
6147      * rather than properly in SDP */
6148     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6149             &hval, 0) == GST_RTSP_OK)
6150       gst_rtspsrc_handle_rtcp_interval (src, hval);
6151
6152     gst_rtsp_message_unset (&response);
6153
6154     /* early exit when we did aggregate control */
6155     if (control)
6156       break;
6157   }
6158   /* set again when needed */
6159   src->need_range = FALSE;
6160
6161   /* configure the caps of the streams after we parsed all headers. */
6162   gst_rtspsrc_configure_caps (src, segment);
6163
6164   src->running = TRUE;
6165   src->base_time = -1;
6166   src->state = GST_RTSP_STATE_PLAYING;
6167
6168   /* mark discont */
6169   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6170   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6171     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6172     stream->discont = TRUE;
6173   }
6174
6175 done:
6176   if (async)
6177     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6178
6179   return res;
6180
6181   /* ERRORS */
6182 open_failed:
6183   {
6184     GST_DEBUG_OBJECT (src, "failed to open stream");
6185     goto done;
6186   }
6187 not_supported:
6188   {
6189     GST_DEBUG_OBJECT (src, "PLAY is not supported");
6190     goto done;
6191   }
6192 was_playing:
6193   {
6194     GST_DEBUG_OBJECT (src, "we were already PLAYING");
6195     goto done;
6196   }
6197 create_request_failed:
6198   {
6199     gchar *str = gst_rtsp_strresult (res);
6200
6201     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6202         ("Could not create request. (%s)", str));
6203     g_free (str);
6204     goto done;
6205   }
6206 send_error:
6207   {
6208     gchar *str = gst_rtsp_strresult (res);
6209
6210     gst_rtsp_message_unset (&request);
6211     if (res != GST_RTSP_EINTR) {
6212       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6213           ("Could not send message. (%s)", str));
6214     } else {
6215       GST_WARNING_OBJECT (src, "PLAY interrupted");
6216     }
6217     g_free (str);
6218     goto done;
6219   }
6220 }
6221
6222 static GstRTSPResult
6223 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean idle, gboolean async)
6224 {
6225   GstRTSPResult res = GST_RTSP_OK;
6226   GstRTSPMessage request = { 0 };
6227   GstRTSPMessage response = { 0 };
6228   GList *walk;
6229   gchar *control;
6230
6231   GST_DEBUG_OBJECT (src, "PAUSE...");
6232
6233   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6234     goto open_failed;
6235
6236   if (!(src->methods & GST_RTSP_PAUSE))
6237     goto not_supported;
6238
6239   if (src->state == GST_RTSP_STATE_READY)
6240     goto was_paused;
6241
6242   if (!src->conninfo.connection || !src->conninfo.connected)
6243     goto no_connection;
6244
6245   /* construct a control url */
6246   if (src->control)
6247     control = src->control;
6248   else
6249     control = src->conninfo.url_str;
6250
6251   /* loop over the streams. We might exit the loop early when we could do an
6252    * aggregate control */
6253   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6254     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6255     GstRTSPConnection *conn;
6256     gchar *setup_url;
6257
6258     /* try aggregate control first but do non-aggregate control otherwise */
6259     if (control)
6260       setup_url = control;
6261     else if ((setup_url = stream->conninfo.location) == NULL)
6262       continue;
6263
6264     if (src->conninfo.connection) {
6265       conn = src->conninfo.connection;
6266     } else if (stream->conninfo.connection) {
6267       conn = stream->conninfo.connection;
6268     } else {
6269       continue;
6270     }
6271
6272     if (async)
6273       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6274           ("Sending PAUSE request"));
6275
6276     if ((res =
6277             gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6278                 setup_url)) < 0)
6279       goto create_request_failed;
6280
6281     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6282       goto send_error;
6283
6284     gst_rtsp_message_unset (&request);
6285     gst_rtsp_message_unset (&response);
6286
6287     /* exit early when we did agregate control */
6288     if (control)
6289       break;
6290   }
6291
6292 no_connection:
6293   src->state = GST_RTSP_STATE_READY;
6294
6295 done:
6296   if (async)
6297     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6298
6299   return res;
6300
6301   /* ERRORS */
6302 open_failed:
6303   {
6304     GST_DEBUG_OBJECT (src, "failed to open stream");
6305     goto done;
6306   }
6307 not_supported:
6308   {
6309     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6310     goto done;
6311   }
6312 was_paused:
6313   {
6314     GST_DEBUG_OBJECT (src, "we were already PAUSED");
6315     goto done;
6316   }
6317 create_request_failed:
6318   {
6319     gchar *str = gst_rtsp_strresult (res);
6320
6321     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6322         ("Could not create request. (%s)", str));
6323     g_free (str);
6324     goto done;
6325   }
6326 send_error:
6327   {
6328     gchar *str = gst_rtsp_strresult (res);
6329
6330     gst_rtsp_message_unset (&request);
6331     if (res != GST_RTSP_EINTR) {
6332       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6333           ("Could not send message. (%s)", str));
6334     } else {
6335       GST_WARNING_OBJECT (src, "PAUSE interrupted");
6336     }
6337     g_free (str);
6338     goto done;
6339   }
6340 }
6341
6342 static void
6343 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6344 {
6345   GstRTSPSrc *rtspsrc;
6346
6347   rtspsrc = GST_RTSPSRC (bin);
6348
6349   switch (GST_MESSAGE_TYPE (message)) {
6350     case GST_MESSAGE_EOS:
6351       gst_message_unref (message);
6352       break;
6353     case GST_MESSAGE_ELEMENT:
6354     {
6355       const GstStructure *s = gst_message_get_structure (message);
6356
6357       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6358         gboolean ignore_timeout;
6359
6360         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6361
6362         GST_OBJECT_LOCK (rtspsrc);
6363         ignore_timeout = rtspsrc->ignore_timeout;
6364         rtspsrc->ignore_timeout = TRUE;
6365         GST_OBJECT_UNLOCK (rtspsrc);
6366
6367         /* we only act on the first udp timeout message, others are irrelevant
6368          * and can be ignored. */
6369         if (!ignore_timeout)
6370           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT);
6371         /* eat and free */
6372         gst_message_unref (message);
6373         return;
6374       }
6375       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6376       break;
6377     }
6378     case GST_MESSAGE_ERROR:
6379     {
6380       GstObject *udpsrc;
6381       GstRTSPStream *stream;
6382       GstFlowReturn ret;
6383
6384       udpsrc = GST_MESSAGE_SRC (message);
6385
6386       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
6387           GST_ELEMENT_NAME (udpsrc));
6388
6389       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
6390       if (!stream)
6391         goto forward;
6392
6393       /* we ignore the RTCP udpsrc */
6394       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
6395         goto done;
6396
6397       /* if we get error messages from the udp sources, that's not a problem as
6398        * long as not all of them error out. We also don't really know what the
6399        * problem is, the message does not give enough detail... */
6400       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
6401       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
6402       if (ret != GST_FLOW_OK)
6403         goto forward;
6404
6405     done:
6406       gst_message_unref (message);
6407       break;
6408
6409     forward:
6410       /* fatal but not our message, forward */
6411       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6412       break;
6413     }
6414     default:
6415     {
6416       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6417       break;
6418     }
6419   }
6420 }
6421
6422 /* the thread where everything happens */
6423 static void
6424 gst_rtspsrc_thread (GstRTSPSrc * src)
6425 {
6426   gint cmd;
6427   GstRTSPResult ret;
6428   gboolean running = FALSE;
6429
6430   GST_OBJECT_LOCK (src);
6431   cmd = src->loop_cmd;
6432   src->loop_cmd = CMD_WAIT;
6433   GST_DEBUG_OBJECT (src, "got command %d", cmd);
6434
6435   /* we got the message command, so ensure communication is possible again */
6436   gst_rtspsrc_connection_flush (src, FALSE);
6437
6438   /* we allow these to be interrupted */
6439   if (cmd == CMD_LOOP || cmd == CMD_CLOSE || cmd == CMD_PAUSE)
6440     src->waiting = TRUE;
6441   GST_OBJECT_UNLOCK (src);
6442
6443   switch (cmd) {
6444     case CMD_OPEN:
6445       ret = gst_rtspsrc_open (src, TRUE);
6446       break;
6447     case CMD_PLAY:
6448       ret = gst_rtspsrc_play (src, &src->segment, TRUE);
6449       if (ret == GST_RTSP_OK)
6450         running = TRUE;
6451       break;
6452     case CMD_PAUSE:
6453       ret = gst_rtspsrc_pause (src, TRUE, TRUE);
6454       if (ret == GST_RTSP_OK)
6455         running = TRUE;
6456       break;
6457     case CMD_CLOSE:
6458       ret = gst_rtspsrc_close (src, TRUE, FALSE);
6459       break;
6460     case CMD_LOOP:
6461       running = gst_rtspsrc_loop (src);
6462       break;
6463     case CMD_RECONNECT:
6464       ret = gst_rtspsrc_reconnect (src, FALSE);
6465       if (ret == GST_RTSP_OK)
6466         running = TRUE;
6467       break;
6468     default:
6469       break;
6470   }
6471
6472   GST_OBJECT_LOCK (src);
6473   /* and go back to sleep */
6474   if (src->loop_cmd == CMD_WAIT) {
6475     if (running)
6476       src->loop_cmd = CMD_LOOP;
6477     else if (src->task)
6478       gst_task_pause (src->task);
6479   }
6480   /* reset waiting */
6481   src->waiting = FALSE;
6482   GST_OBJECT_UNLOCK (src);
6483 }
6484
6485 static gboolean
6486 gst_rtspsrc_start (GstRTSPSrc * src)
6487 {
6488   GST_DEBUG_OBJECT (src, "starting");
6489
6490   GST_OBJECT_LOCK (src);
6491
6492   src->loop_cmd = CMD_WAIT;
6493
6494   if (src->task == NULL) {
6495     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src);
6496     if (src->task == NULL)
6497       goto task_error;
6498
6499     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
6500   }
6501   GST_OBJECT_UNLOCK (src);
6502
6503   return TRUE;
6504
6505   /* ERRORS */
6506 task_error:
6507   {
6508     GST_ERROR_OBJECT (src, "failed to create task");
6509     return FALSE;
6510   }
6511 }
6512
6513 static gboolean
6514 gst_rtspsrc_stop (GstRTSPSrc * src)
6515 {
6516   GstTask *task;
6517
6518   GST_DEBUG_OBJECT (src, "stopping");
6519
6520   /* also cancels pending task */
6521   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT);
6522
6523   GST_OBJECT_LOCK (src);
6524   if ((task = src->task)) {
6525     src->task = NULL;
6526     GST_OBJECT_UNLOCK (src);
6527
6528     gst_task_stop (task);
6529
6530     /* make sure it is not running */
6531     GST_RTSP_STREAM_LOCK (src);
6532     GST_RTSP_STREAM_UNLOCK (src);
6533
6534     /* now wait for the task to finish */
6535     gst_task_join (task);
6536
6537     /* and free the task */
6538     gst_object_unref (GST_OBJECT (task));
6539
6540     GST_OBJECT_LOCK (src);
6541   }
6542   GST_OBJECT_UNLOCK (src);
6543
6544   /* ensure synchronously all is closed and clean */
6545   gst_rtspsrc_close (src, FALSE, TRUE);
6546
6547   return TRUE;
6548 }
6549
6550 static GstStateChangeReturn
6551 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
6552 {
6553   GstRTSPSrc *rtspsrc;
6554   GstStateChangeReturn ret;
6555
6556   rtspsrc = GST_RTSPSRC (element);
6557
6558   switch (transition) {
6559     case GST_STATE_CHANGE_NULL_TO_READY:
6560       if (!gst_rtspsrc_start (rtspsrc))
6561         goto start_failed;
6562       break;
6563     case GST_STATE_CHANGE_READY_TO_PAUSED:
6564       /* init some state */
6565       rtspsrc->cur_protocols = rtspsrc->protocols;
6566       /* first attempt, don't ignore timeouts */
6567       rtspsrc->ignore_timeout = FALSE;
6568       rtspsrc->open_error = FALSE;
6569       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN);
6570       break;
6571     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6572     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6573       /* unblock the tcp tasks and make the loop waiting */
6574       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT);
6575       break;
6576     case GST_STATE_CHANGE_PAUSED_TO_READY:
6577       break;
6578     default:
6579       break;
6580   }
6581
6582   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6583   if (ret == GST_STATE_CHANGE_FAILURE)
6584     goto done;
6585
6586   switch (transition) {
6587     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6588       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY);
6589       break;
6590     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6591       /* send pause request and keep the idle task around */
6592       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE);
6593       ret = GST_STATE_CHANGE_NO_PREROLL;
6594       break;
6595     case GST_STATE_CHANGE_READY_TO_PAUSED:
6596       ret = GST_STATE_CHANGE_NO_PREROLL;
6597       break;
6598     case GST_STATE_CHANGE_PAUSED_TO_READY:
6599       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE);
6600       break;
6601     case GST_STATE_CHANGE_READY_TO_NULL:
6602       gst_rtspsrc_stop (rtspsrc);
6603       break;
6604     default:
6605       break;
6606   }
6607
6608 done:
6609   return ret;
6610
6611 start_failed:
6612   {
6613     GST_DEBUG_OBJECT (rtspsrc, "start failed");
6614     return GST_STATE_CHANGE_FAILURE;
6615   }
6616 }
6617
6618 static gboolean
6619 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
6620 {
6621   gboolean res;
6622   GstRTSPSrc *rtspsrc;
6623
6624   rtspsrc = GST_RTSPSRC (element);
6625
6626   if (GST_EVENT_IS_DOWNSTREAM (event)) {
6627     res = gst_rtspsrc_push_event (rtspsrc, event, TRUE);
6628   } else {
6629     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
6630   }
6631
6632   return res;
6633 }
6634
6635
6636 /*** GSTURIHANDLER INTERFACE *************************************************/
6637
6638 static GstURIType
6639 gst_rtspsrc_uri_get_type (GType type)
6640 {
6641   return GST_URI_SRC;
6642 }
6643
6644 static const gchar *const *
6645 gst_rtspsrc_uri_get_protocols (GType type)
6646 {
6647   static const gchar *protocols[] =
6648       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp", NULL };
6649
6650   return protocols;
6651 }
6652
6653 static gchar *
6654 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
6655 {
6656   GstRTSPSrc *src = GST_RTSPSRC (handler);
6657
6658   /* FIXME: make thread-safe */
6659   return g_strdup (src->conninfo.location);
6660 }
6661
6662 static gboolean
6663 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
6664     GError ** error)
6665 {
6666   GstRTSPSrc *src;
6667   GstRTSPResult res;
6668   GstRTSPUrl *newurl = NULL;
6669   GstSDPMessage *sdp = NULL;
6670
6671   src = GST_RTSPSRC (handler);
6672
6673   /* same URI, we're fine */
6674   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
6675     goto was_ok;
6676
6677   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
6678     if ((res = gst_sdp_message_new (&sdp) < 0))
6679       goto sdp_failed;
6680
6681     GST_DEBUG_OBJECT (src, "parsing SDP message");
6682     if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
6683       goto invalid_sdp;
6684   } else {
6685     /* try to parse */
6686     GST_DEBUG_OBJECT (src, "parsing URI");
6687     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
6688       goto parse_error;
6689   }
6690
6691   /* if worked, free previous and store new url object along with the original
6692    * location. */
6693   GST_DEBUG_OBJECT (src, "configuring URI");
6694   g_free (src->conninfo.location);
6695   src->conninfo.location = g_strdup (uri);
6696   gst_rtsp_url_free (src->conninfo.url);
6697   src->conninfo.url = newurl;
6698   g_free (src->conninfo.url_str);
6699   if (newurl)
6700     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
6701   else
6702     src->conninfo.url_str = NULL;
6703
6704   if (src->sdp)
6705     gst_sdp_message_free (src->sdp);
6706   src->sdp = sdp;
6707   src->from_sdp = sdp != NULL;
6708
6709   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
6710   GST_DEBUG_OBJECT (src, "request uri is: %s",
6711       GST_STR_NULL (src->conninfo.url_str));
6712
6713   return TRUE;
6714
6715   /* Special cases */
6716 was_ok:
6717   {
6718     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
6719     return TRUE;
6720   }
6721 sdp_failed:
6722   {
6723     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
6724     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
6725         "Could not create SDP");
6726     return FALSE;
6727   }
6728 invalid_sdp:
6729   {
6730     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
6731         GST_STR_NULL (uri));
6732     gst_sdp_message_free (sdp);
6733     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
6734         "Invalid SDP");
6735     return FALSE;
6736   }
6737 parse_error:
6738   {
6739     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
6740         GST_STR_NULL (uri), res);
6741     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
6742         "Invalid RTSP URI");
6743     return FALSE;
6744   }
6745 }
6746
6747 static void
6748 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
6749 {
6750   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
6751
6752   iface->get_type = gst_rtspsrc_uri_get_type;
6753   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
6754   iface->get_uri = gst_rtspsrc_uri_get_uri;
6755   iface->set_uri = gst_rtspsrc_uri_set_uri;
6756 }