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