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