tizen 2.0 init
[framework/multimedia/gst-plugins-good0.10.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 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
85  * with newer GLib versions (>= 2.31.0) */
86 #define GLIB_DISABLE_DEPRECATION_WARNINGS
87
88 #ifdef HAVE_UNISTD_H
89 #include <unistd.h>
90 #endif /* HAVE_UNISTD_H */
91 #include <stdlib.h>
92 #include <string.h>
93 #include <locale.h>
94 #include <stdio.h>
95 #include <stdarg.h>
96
97 #include <gst/sdp/gstsdpmessage.h>
98 #include <gst/rtp/gstrtppayloads.h>
99
100 #include "gst/gst-i18n-plugin.h"
101
102 #include "gstrtspsrc.h"
103
104 #ifdef G_OS_WIN32
105 #include <winsock2.h>
106 #endif
107
108 GST_DEBUG_CATEGORY_STATIC (rtspsrc_debug);
109 #define GST_CAT_DEFAULT (rtspsrc_debug)
110
111 static GstStaticPadTemplate rtptemplate = GST_STATIC_PAD_TEMPLATE ("stream%d",
112     GST_PAD_SRC,
113     GST_PAD_SOMETIMES,
114     GST_STATIC_CAPS ("application/x-rtp; application/x-rdt"));
115
116 /* templates used internally */
117 static GstStaticPadTemplate anysrctemplate =
118 GST_STATIC_PAD_TEMPLATE ("internalsrc%d",
119     GST_PAD_SRC,
120     GST_PAD_SOMETIMES,
121     GST_STATIC_CAPS_ANY);
122
123 static GstStaticPadTemplate anysinktemplate =
124 GST_STATIC_PAD_TEMPLATE ("internalsink%d",
125     GST_PAD_SINK,
126     GST_PAD_SOMETIMES,
127     GST_STATIC_CAPS_ANY);
128
129 enum
130 {
131   /* FILL ME */
132   LAST_SIGNAL
133 };
134
135 enum _GstRtspSrcRtcpSyncMode
136 {
137   RTCP_SYNC_ALWAYS,
138   RTCP_SYNC_INITIAL,
139   RTCP_SYNC_RTP
140 };
141
142 enum _GstRtspSrcBufferMode
143 {
144   BUFFER_MODE_NONE,
145   BUFFER_MODE_SLAVE,
146   BUFFER_MODE_BUFFER,
147   BUFFER_MODE_AUTO
148 };
149
150 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
151 static GType
152 gst_rtsp_src_buffer_mode_get_type (void)
153 {
154   static GType buffer_mode_type = 0;
155   static const GEnumValue buffer_modes[] = {
156     {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
157     {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
158     {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
159     {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
160     {0, NULL, NULL},
161   };
162
163   if (!buffer_mode_type) {
164     buffer_mode_type =
165         g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
166   }
167   return buffer_mode_type;
168 }
169
170 #define DEFAULT_LOCATION         NULL
171 #define DEFAULT_PROTOCOLS        GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
172 #define DEFAULT_DEBUG            FALSE
173 #define DEFAULT_RETRY            20
174 #define DEFAULT_TIMEOUT          5000000
175 #define DEFAULT_UDP_BUFFER_SIZE  0x80000
176 #define DEFAULT_TCP_TIMEOUT      20000000
177 #define DEFAULT_LATENCY_MS       2000
178 #define DEFAULT_CONNECTION_SPEED 0
179 #define DEFAULT_NAT_METHOD       GST_RTSP_NAT_DUMMY
180 #define DEFAULT_DO_RTCP          TRUE
181 #define DEFAULT_PROXY            NULL
182 #define DEFAULT_RTP_BLOCKSIZE    0
183 #define DEFAULT_USER_ID          NULL
184 #define DEFAULT_USER_PW          NULL
185 #define DEFAULT_BUFFER_MODE      BUFFER_MODE_AUTO
186 #define DEFAULT_PORT_RANGE       NULL
187 #define DEFAULT_SHORT_HEADER     FALSE
188
189 enum
190 {
191   PROP_0,
192   PROP_LOCATION,
193   PROP_PROTOCOLS,
194   PROP_DEBUG,
195   PROP_RETRY,
196   PROP_TIMEOUT,
197   PROP_TCP_TIMEOUT,
198   PROP_LATENCY,
199   PROP_CONNECTION_SPEED,
200   PROP_NAT_METHOD,
201   PROP_DO_RTCP,
202   PROP_PROXY,
203   PROP_RTP_BLOCKSIZE,
204   PROP_USER_ID,
205   PROP_USER_PW,
206   PROP_BUFFER_MODE,
207   PROP_PORT_RANGE,
208   PROP_UDP_BUFFER_SIZE,
209   PROP_SHORT_HEADER,
210   PROP_LAST
211 };
212
213 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
214 static GType
215 gst_rtsp_nat_method_get_type (void)
216 {
217   static GType rtsp_nat_method_type = 0;
218   static const GEnumValue rtsp_nat_method[] = {
219     {GST_RTSP_NAT_NONE, "None", "none"},
220     {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
221     {0, NULL, NULL},
222   };
223
224   if (!rtsp_nat_method_type) {
225     rtsp_nat_method_type =
226         g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
227   }
228   return rtsp_nat_method_type;
229 }
230
231 static void gst_rtspsrc_finalize (GObject * object);
232
233 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
234     const GValue * value, GParamSpec * pspec);
235 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
236     GValue * value, GParamSpec * pspec);
237
238 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
239     gpointer iface_data);
240
241 static void gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes,
242     GstCaps * caps);
243
244 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
245 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
246
247 static GstCaps *gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media);
248
249 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
250     GstStateChange transition);
251 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
252 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
253
254 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
255     GstRTSPMessage * response);
256
257 static void gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd,
258     gboolean flush);
259 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
260     GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
261
262 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
263 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
264     gboolean async);
265 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean idle,
266     gboolean async);
267 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
268     gboolean only_close);
269
270 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
271     const gchar * uri);
272
273 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
274 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
275 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
276     GstRTSPStream * stream, GstEvent * event, gboolean source);
277 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event,
278     gboolean source);
279
280 /* commands we send to out loop to notify it of events */
281 #define CMD_OPEN        0
282 #define CMD_PLAY        1
283 #define CMD_PAUSE       2
284 #define CMD_CLOSE       3
285 #define CMD_WAIT        4
286 #define CMD_RECONNECT   5
287 #define CMD_LOOP        6
288
289 #define GST_ELEMENT_PROGRESS(el, type, code, text)      \
290 G_STMT_START {                                          \
291   gchar *__txt = _gst_element_error_printf text;        \
292   gst_element_post_message (GST_ELEMENT_CAST (el),      \
293       gst_message_new_progress (GST_OBJECT_CAST (el),   \
294           GST_PROGRESS_TYPE_ ##type, code, __txt));     \
295   g_free (__txt);                                       \
296 } G_STMT_END
297
298 /*static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 }; */
299
300 static void
301 _do_init (GType rtspsrc_type)
302 {
303   static const GInterfaceInfo urihandler_info = {
304     gst_rtspsrc_uri_handler_init,
305     NULL,
306     NULL
307   };
308
309   GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
310
311   g_type_add_interface_static (rtspsrc_type, GST_TYPE_URI_HANDLER,
312       &urihandler_info);
313 }
314
315 GST_BOILERPLATE_FULL (GstRTSPSrc, gst_rtspsrc, GstBin, GST_TYPE_BIN, _do_init);
316
317 static void
318 gst_rtspsrc_base_init (gpointer g_class)
319 {
320   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
321
322   gst_element_class_add_static_pad_template (element_class, &rtptemplate);
323
324   gst_element_class_set_details_simple (element_class, "RTSP packet receiver",
325       "Source/Network",
326       "Receive data over the network via RTSP (RFC 2326)",
327       "Wim Taymans <wim@fluendo.com>, "
328       "Thijs Vermeir <thijs.vermeir@barco.com>, "
329       "Lutz Mueller <lutz@topfrose.de>");
330 }
331
332 static void
333 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
334 {
335   GObjectClass *gobject_class;
336   GstElementClass *gstelement_class;
337   GstBinClass *gstbin_class;
338
339   gobject_class = (GObjectClass *) klass;
340   gstelement_class = (GstElementClass *) klass;
341   gstbin_class = (GstBinClass *) klass;
342
343   gobject_class->set_property = gst_rtspsrc_set_property;
344   gobject_class->get_property = gst_rtspsrc_get_property;
345
346   gobject_class->finalize = gst_rtspsrc_finalize;
347
348   g_object_class_install_property (gobject_class, PROP_LOCATION,
349       g_param_spec_string ("location", "RTSP Location",
350           "Location of the RTSP url to read",
351           DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
352
353   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
354       g_param_spec_flags ("protocols", "Protocols",
355           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
356           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
357
358   g_object_class_install_property (gobject_class, PROP_DEBUG,
359       g_param_spec_boolean ("debug", "Debug",
360           "Dump request and response messages to stdout",
361           DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
362
363   g_object_class_install_property (gobject_class, PROP_RETRY,
364       g_param_spec_uint ("retry", "Retry",
365           "Max number of retries when allocating RTP ports.",
366           0, G_MAXUINT16, DEFAULT_RETRY,
367           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
368
369   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
370       g_param_spec_uint64 ("timeout", "Timeout",
371           "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
372           0, G_MAXUINT64, DEFAULT_TIMEOUT,
373           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
374
375   g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
376       g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
377           "Fail after timeout microseconds on TCP connections (0 = disabled)",
378           0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
379           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
380
381   g_object_class_install_property (gobject_class, PROP_LATENCY,
382       g_param_spec_uint ("latency", "Buffer latency in ms",
383           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
384           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
385
386   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
387       g_param_spec_uint ("connection-speed", "Connection Speed",
388           "Network connection speed in kbps (0 = unknown)",
389           0, G_MAXINT / 1000, DEFAULT_CONNECTION_SPEED,
390           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
391
392   g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
393       g_param_spec_enum ("nat-method", "NAT Method",
394           "Method to use for traversing firewalls and NAT",
395           GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
396           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
397
398   /**
399    * GstRTSPSrc::do-rtcp
400    *
401    * Enable RTCP support. Some old server don't like RTCP and then this property
402    * needs to be set to FALSE.
403    *
404    * Since: 0.10.15
405    */
406   g_object_class_install_property (gobject_class, PROP_DO_RTCP,
407       g_param_spec_boolean ("do-rtcp", "Do RTCP",
408           "Send RTCP packets, disable for old incompatible server.",
409           DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
410
411   /**
412    * GstRTSPSrc::proxy
413    *
414    * Set the proxy parameters. This has to be a string of the format
415    * [http://][user:passwd@]host[:port].
416    *
417    * Since: 0.10.15
418    */
419   g_object_class_install_property (gobject_class, PROP_PROXY,
420       g_param_spec_string ("proxy", "Proxy",
421           "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
422           DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
423
424   /**
425    * GstRTSPSrc::rtp_blocksize
426    *
427    * RTP package size to suggest to server.
428    *
429    * Since: 0.10.16
430    */
431   g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
432       g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
433           "RTP package size to suggest to server (0 = disabled)",
434           0, 65536, DEFAULT_RTP_BLOCKSIZE,
435           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
436
437   g_object_class_install_property (gobject_class,
438       PROP_USER_ID,
439       g_param_spec_string ("user-id", "user-id",
440           "RTSP location URI user id for authentication", DEFAULT_USER_ID,
441           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
442   g_object_class_install_property (gobject_class, PROP_USER_PW,
443       g_param_spec_string ("user-pw", "user-pw",
444           "RTSP location URI user password for authentication", DEFAULT_USER_PW,
445           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446
447   /**
448    * GstRTSPSrc::buffer-mode:
449    *
450    * Control the buffering and timestamping mode used by the jitterbuffer.
451    *
452    * Since: 0.10.22
453    */
454   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
455       g_param_spec_enum ("buffer-mode", "Buffer Mode",
456           "Control the buffering algorithm in use",
457           GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
458           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
459
460   /**
461    * GstRTSPSrc::port-range:
462    *
463    * Configure the client port numbers that can be used to recieve RTP and
464    * RTCP.
465    *
466    * Since: 0.10.25
467    */
468   g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
469       g_param_spec_string ("port-range", "Port range",
470           "Client port range that can be used to receive RTP and RTCP data, "
471           "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
472           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
473
474   /**
475    * GstRTSPSrc::udp-buffer-size:
476    *
477    * Size of the kernel UDP receive buffer in bytes.
478    *
479    * Since: 0.10.26
480    */
481   g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
482       g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
483           "Size of the kernel UDP receive buffer in bytes, 0=default",
484           0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
485           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
486
487   /**
488    * GstRTSPSrc::short-header:
489    *
490    * Only send the basic RTSP headers for broken encoders.
491    *
492    * Since: 0.10.31
493    */
494   g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
495       g_param_spec_boolean ("short-header", "Short Header",
496           "Only send the basic RTSP headers for broken encoders",
497           DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
498
499   gstelement_class->send_event = gst_rtspsrc_send_event;
500   gstelement_class->change_state = gst_rtspsrc_change_state;
501
502   gstbin_class->handle_message = gst_rtspsrc_handle_message;
503
504   gst_rtsp_ext_list_init ();
505 }
506
507
508 static void
509 gst_rtspsrc_init (GstRTSPSrc * src, GstRTSPSrcClass * g_class)
510 {
511 #ifdef G_OS_WIN32
512   WSADATA wsa_data;
513
514   if (WSAStartup (MAKEWORD (2, 2), &wsa_data) != 0) {
515     GST_ERROR_OBJECT (src, "WSAStartup failed: 0x%08x", WSAGetLastError ());
516   }
517 #endif
518
519   src->conninfo.location = g_strdup (DEFAULT_LOCATION);
520   src->protocols = DEFAULT_PROTOCOLS;
521   src->debug = DEFAULT_DEBUG;
522   src->retry = DEFAULT_RETRY;
523   src->udp_timeout = DEFAULT_TIMEOUT;
524   gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
525   src->latency = DEFAULT_LATENCY_MS;
526   src->connection_speed = DEFAULT_CONNECTION_SPEED;
527   src->nat_method = DEFAULT_NAT_METHOD;
528   src->do_rtcp = DEFAULT_DO_RTCP;
529   gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
530   src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
531   src->user_id = g_strdup (DEFAULT_USER_ID);
532   src->user_pw = g_strdup (DEFAULT_USER_PW);
533   src->buffer_mode = DEFAULT_BUFFER_MODE;
534   src->client_port_range.min = 0;
535   src->client_port_range.max = 0;
536   src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
537   src->short_header = DEFAULT_SHORT_HEADER;
538
539   /* get a list of all extensions */
540   src->extensions = gst_rtsp_ext_list_get ();
541
542   /* connect to send signal */
543   gst_rtsp_ext_list_connect (src->extensions, "send",
544       (GCallback) gst_rtspsrc_send_cb, src);
545
546   /* protects the streaming thread in interleaved mode or the polling
547    * thread in UDP mode. */
548   src->stream_rec_lock = g_new (GStaticRecMutex, 1);
549   g_static_rec_mutex_init (src->stream_rec_lock);
550
551   /* protects our state changes from multiple invocations */
552   src->state_rec_lock = g_new (GStaticRecMutex, 1);
553   g_static_rec_mutex_init (src->state_rec_lock);
554
555   src->state = GST_RTSP_STATE_INVALID;
556
557   GST_OBJECT_FLAG_SET (src, GST_ELEMENT_IS_SOURCE);
558 }
559
560 static void
561 gst_rtspsrc_finalize (GObject * object)
562 {
563   GstRTSPSrc *rtspsrc;
564
565   rtspsrc = GST_RTSPSRC (object);
566
567   gst_rtsp_ext_list_free (rtspsrc->extensions);
568   g_free (rtspsrc->conninfo.location);
569   gst_rtsp_url_free (rtspsrc->conninfo.url);
570   g_free (rtspsrc->conninfo.url_str);
571   g_free (rtspsrc->user_id);
572   g_free (rtspsrc->user_pw);
573
574   if (rtspsrc->sdp) {
575     gst_sdp_message_free (rtspsrc->sdp);
576     rtspsrc->sdp = NULL;
577   }
578
579   /* free locks */
580   g_static_rec_mutex_free (rtspsrc->stream_rec_lock);
581   g_free (rtspsrc->stream_rec_lock);
582   g_static_rec_mutex_free (rtspsrc->state_rec_lock);
583   g_free (rtspsrc->state_rec_lock);
584
585 #ifdef G_OS_WIN32
586   WSACleanup ();
587 #endif
588
589   G_OBJECT_CLASS (parent_class)->finalize (object);
590 }
591
592 /* a proxy string of the format [user:passwd@]host[:port] */
593 static gboolean
594 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
595 {
596   gchar *p, *at, *col;
597
598   g_free (rtsp->proxy_user);
599   rtsp->proxy_user = NULL;
600   g_free (rtsp->proxy_passwd);
601   rtsp->proxy_passwd = NULL;
602   g_free (rtsp->proxy_host);
603   rtsp->proxy_host = NULL;
604   rtsp->proxy_port = 0;
605
606   p = (gchar *) proxy;
607
608   if (p == NULL)
609     return TRUE;
610
611   /* we allow http:// in front but ignore it */
612   if (g_str_has_prefix (p, "http://"))
613     p += 7;
614
615   at = strchr (p, '@');
616   if (at) {
617     /* look for user:passwd */
618     col = strchr (proxy, ':');
619     if (col == NULL || col > at)
620       return FALSE;
621
622     rtsp->proxy_user = g_strndup (p, col - p);
623     col++;
624     rtsp->proxy_passwd = g_strndup (col, at - col);
625
626     /* move to host */
627     p = at + 1;
628   }
629   col = strchr (p, ':');
630
631   if (col) {
632     /* everything before the colon is the hostname */
633     rtsp->proxy_host = g_strndup (p, col - p);
634     p = col + 1;
635     rtsp->proxy_port = strtoul (p, (char **) &p, 10);
636   } else {
637     rtsp->proxy_host = g_strdup (p);
638     rtsp->proxy_port = 8080;
639   }
640   return TRUE;
641 }
642
643 static void
644 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
645 {
646   rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
647   rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
648
649   if (timeout != 0)
650     rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
651   else
652     rtspsrc->ptcp_timeout = NULL;
653 }
654
655 static void
656 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
657     GParamSpec * pspec)
658 {
659   GstRTSPSrc *rtspsrc;
660
661   rtspsrc = GST_RTSPSRC (object);
662
663   switch (prop_id) {
664     case PROP_LOCATION:
665       gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
666           g_value_get_string (value));
667       break;
668     case PROP_PROTOCOLS:
669       rtspsrc->protocols = g_value_get_flags (value);
670       break;
671     case PROP_DEBUG:
672       rtspsrc->debug = g_value_get_boolean (value);
673       break;
674     case PROP_RETRY:
675       rtspsrc->retry = g_value_get_uint (value);
676       break;
677     case PROP_TIMEOUT:
678       rtspsrc->udp_timeout = g_value_get_uint64 (value);
679       break;
680     case PROP_TCP_TIMEOUT:
681       gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
682       break;
683     case PROP_LATENCY:
684       rtspsrc->latency = g_value_get_uint (value);
685       break;
686     case PROP_CONNECTION_SPEED:
687       rtspsrc->connection_speed = g_value_get_uint (value);
688       break;
689     case PROP_NAT_METHOD:
690       rtspsrc->nat_method = g_value_get_enum (value);
691       break;
692     case PROP_DO_RTCP:
693       rtspsrc->do_rtcp = g_value_get_boolean (value);
694       break;
695     case PROP_PROXY:
696       gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
697       break;
698     case PROP_RTP_BLOCKSIZE:
699       rtspsrc->rtp_blocksize = g_value_get_uint (value);
700       break;
701     case PROP_USER_ID:
702       if (rtspsrc->user_id)
703         g_free (rtspsrc->user_id);
704       rtspsrc->user_id = g_value_dup_string (value);
705       break;
706     case PROP_USER_PW:
707       if (rtspsrc->user_pw)
708         g_free (rtspsrc->user_pw);
709       rtspsrc->user_pw = g_value_dup_string (value);
710       break;
711     case PROP_BUFFER_MODE:
712       rtspsrc->buffer_mode = g_value_get_enum (value);
713       break;
714     case PROP_PORT_RANGE:
715     {
716       const gchar *str;
717
718       str = g_value_get_string (value);
719       if (str) {
720         sscanf (str, "%u-%u",
721             &rtspsrc->client_port_range.min, &rtspsrc->client_port_range.max);
722       } else {
723         rtspsrc->client_port_range.min = 0;
724         rtspsrc->client_port_range.max = 0;
725       }
726       break;
727     }
728     case PROP_UDP_BUFFER_SIZE:
729       rtspsrc->udp_buffer_size = g_value_get_int (value);
730       break;
731     case PROP_SHORT_HEADER:
732       rtspsrc->short_header = g_value_get_boolean (value);
733       break;
734     default:
735       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
736       break;
737   }
738 }
739
740 static void
741 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
742     GParamSpec * pspec)
743 {
744   GstRTSPSrc *rtspsrc;
745
746   rtspsrc = GST_RTSPSRC (object);
747
748   switch (prop_id) {
749     case PROP_LOCATION:
750       g_value_set_string (value, rtspsrc->conninfo.location);
751       break;
752     case PROP_PROTOCOLS:
753       g_value_set_flags (value, rtspsrc->protocols);
754       break;
755     case PROP_DEBUG:
756       g_value_set_boolean (value, rtspsrc->debug);
757       break;
758     case PROP_RETRY:
759       g_value_set_uint (value, rtspsrc->retry);
760       break;
761     case PROP_TIMEOUT:
762       g_value_set_uint64 (value, rtspsrc->udp_timeout);
763       break;
764     case PROP_TCP_TIMEOUT:
765     {
766       guint64 timeout;
767
768       timeout = rtspsrc->tcp_timeout.tv_sec * G_USEC_PER_SEC +
769           rtspsrc->tcp_timeout.tv_usec;
770       g_value_set_uint64 (value, timeout);
771       break;
772     }
773     case PROP_LATENCY:
774       g_value_set_uint (value, rtspsrc->latency);
775       break;
776     case PROP_CONNECTION_SPEED:
777       g_value_set_uint (value, rtspsrc->connection_speed);
778       break;
779     case PROP_NAT_METHOD:
780       g_value_set_enum (value, rtspsrc->nat_method);
781       break;
782     case PROP_DO_RTCP:
783       g_value_set_boolean (value, rtspsrc->do_rtcp);
784       break;
785     case PROP_PROXY:
786     {
787       gchar *str;
788
789       if (rtspsrc->proxy_host) {
790         str =
791             g_strdup_printf ("%s:%d", rtspsrc->proxy_host, rtspsrc->proxy_port);
792       } else {
793         str = NULL;
794       }
795       g_value_take_string (value, str);
796       break;
797     }
798     case PROP_RTP_BLOCKSIZE:
799       g_value_set_uint (value, rtspsrc->rtp_blocksize);
800       break;
801     case PROP_USER_ID:
802       g_value_set_string (value, rtspsrc->user_id);
803       break;
804     case PROP_USER_PW:
805       g_value_set_string (value, rtspsrc->user_pw);
806       break;
807     case PROP_BUFFER_MODE:
808       g_value_set_enum (value, rtspsrc->buffer_mode);
809       break;
810     case PROP_PORT_RANGE:
811     {
812       gchar *str;
813
814       if (rtspsrc->client_port_range.min != 0) {
815         str = g_strdup_printf ("%u-%u", rtspsrc->client_port_range.min,
816             rtspsrc->client_port_range.max);
817       } else {
818         str = NULL;
819       }
820       g_value_take_string (value, str);
821       break;
822     }
823     case PROP_UDP_BUFFER_SIZE:
824       g_value_set_int (value, rtspsrc->udp_buffer_size);
825       break;
826     case PROP_SHORT_HEADER:
827       g_value_set_boolean (value, rtspsrc->short_header);
828       break;
829     default:
830       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
831       break;
832   }
833 }
834
835 static gint
836 find_stream_by_id (GstRTSPStream * stream, gint * id)
837 {
838   if (stream->id == *id)
839     return 0;
840
841   return -1;
842 }
843
844 static gint
845 find_stream_by_channel (GstRTSPStream * stream, gint * channel)
846 {
847   if (stream->channel[0] == *channel || stream->channel[1] == *channel)
848     return 0;
849
850   return -1;
851 }
852
853 static gint
854 find_stream_by_pt (GstRTSPStream * stream, gint * pt)
855 {
856   if (stream->pt == *pt)
857     return 0;
858
859   return -1;
860 }
861
862 static gint
863 find_stream_by_udpsrc (GstRTSPStream * stream, gconstpointer a)
864 {
865   GstElement *src = (GstElement *) a;
866
867   if (stream->udpsrc[0] == src)
868     return 0;
869   if (stream->udpsrc[1] == src)
870     return 0;
871
872   return -1;
873 }
874
875 static gint
876 find_stream_by_setup (GstRTSPStream * stream, gconstpointer a)
877 {
878   /* check qualified setup_url */
879   if (!strcmp (stream->conninfo.location, (gchar *) a))
880     return 0;
881   /* check original control_url */
882   if (!strcmp (stream->control_url, (gchar *) a))
883     return 0;
884
885   /* check if qualified setup_url ends with string */
886   if (g_str_has_suffix (stream->control_url, (gchar *) a))
887     return 0;
888
889   return -1;
890 }
891
892 static GstRTSPStream *
893 find_stream (GstRTSPSrc * src, gconstpointer data, gconstpointer func)
894 {
895   GList *lstream;
896
897   /* find and get stream */
898   if ((lstream = g_list_find_custom (src->streams, data, (GCompareFunc) func)))
899     return (GstRTSPStream *) lstream->data;
900
901   return NULL;
902 }
903
904 static const GstSDPBandwidth *
905 gst_rtspsrc_get_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
906     const GstSDPMedia * media, const gchar * type)
907 {
908   guint i, len;
909
910   /* first look in the media specific section */
911   len = gst_sdp_media_bandwidths_len (media);
912   for (i = 0; i < len; i++) {
913     const GstSDPBandwidth *bw = gst_sdp_media_get_bandwidth (media, i);
914
915     if (strcmp (bw->bwtype, type) == 0)
916       return bw;
917   }
918   /* then look in the message specific section */
919   len = gst_sdp_message_bandwidths_len (sdp);
920   for (i = 0; i < len; i++) {
921     const GstSDPBandwidth *bw = gst_sdp_message_get_bandwidth (sdp, i);
922
923     if (strcmp (bw->bwtype, type) == 0)
924       return bw;
925   }
926   return NULL;
927 }
928
929 static void
930 gst_rtspsrc_collect_bandwidth (GstRTSPSrc * src, const GstSDPMessage * sdp,
931     const GstSDPMedia * media, GstRTSPStream * stream)
932 {
933   const GstSDPBandwidth *bw;
934
935   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_AS)))
936     stream->as_bandwidth = bw->bandwidth;
937   else
938     stream->as_bandwidth = -1;
939
940   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RR)))
941     stream->rr_bandwidth = bw->bandwidth;
942   else
943     stream->rr_bandwidth = -1;
944
945   if ((bw = gst_rtspsrc_get_bandwidth (src, sdp, media, GST_SDP_BWTYPE_RS)))
946     stream->rs_bandwidth = bw->bandwidth;
947   else
948     stream->rs_bandwidth = -1;
949 }
950
951 static void
952 gst_rtspsrc_do_stream_connection (GstRTSPSrc * src, GstRTSPStream * stream,
953     const GstSDPConnection * conn)
954 {
955   if (conn->nettype == NULL || strcmp (conn->nettype, "IN") != 0)
956     return;
957
958   if (conn->addrtype == NULL)
959     return;
960
961   /* check for IPV6 */
962   if (strcmp (conn->addrtype, "IP4") == 0)
963     stream->is_ipv6 = FALSE;
964   else if (strcmp (conn->addrtype, "IP6") == 0)
965     stream->is_ipv6 = TRUE;
966   else
967     return;
968
969   /* save address */
970   g_free (stream->destination);
971   stream->destination = g_strdup (conn->address);
972
973   /* check for multicast */
974   stream->is_multicast =
975       gst_sdp_address_is_multicast (conn->nettype, conn->addrtype,
976       conn->address);
977   stream->ttl = conn->ttl;
978 }
979
980 /* Go over the connections for a stream.
981  * - If we are dealing with IPV6, we will setup IPV6 sockets for sending and
982  *   receiving.
983  * - If we are dealing with a localhost address, we disable multicast
984  */
985 static void
986 gst_rtspsrc_collect_connections (GstRTSPSrc * src, const GstSDPMessage * sdp,
987     const GstSDPMedia * media, GstRTSPStream * stream)
988 {
989   const GstSDPConnection *conn;
990   guint i, len;
991
992   /* first look in the media specific section */
993   len = gst_sdp_media_connections_len (media);
994   for (i = 0; i < len; i++) {
995     conn = gst_sdp_media_get_connection (media, i);
996
997     gst_rtspsrc_do_stream_connection (src, stream, conn);
998   }
999   /* then look in the message specific section */
1000   if ((conn = gst_sdp_message_get_connection (sdp))) {
1001     gst_rtspsrc_do_stream_connection (src, stream, conn);
1002   }
1003 }
1004
1005 static GstRTSPStream *
1006 gst_rtspsrc_create_stream (GstRTSPSrc * src, GstSDPMessage * sdp, gint idx)
1007 {
1008   GstRTSPStream *stream;
1009   const gchar *control_url;
1010   const gchar *payload;
1011   const GstSDPMedia *media;
1012
1013   /* get media, should not return NULL */
1014   media = gst_sdp_message_get_media (sdp, idx);
1015   if (media == NULL)
1016     return NULL;
1017
1018   stream = g_new0 (GstRTSPStream, 1);
1019   stream->parent = src;
1020   /* we mark the pad as not linked, we will mark it as OK when we add the pad to
1021    * the element. */
1022   stream->last_ret = GST_FLOW_NOT_LINKED;
1023   stream->added = FALSE;
1024   stream->disabled = FALSE;
1025   stream->id = src->numstreams++;
1026   stream->eos = FALSE;
1027   stream->discont = TRUE;
1028   stream->seqbase = -1;
1029   stream->timebase = -1;
1030
1031   /* collect bandwidth information for this steam. FIXME, configure in the RTP
1032    * session manager to scale RTCP. */
1033   gst_rtspsrc_collect_bandwidth (src, sdp, media, stream);
1034
1035   /* collect connection info */
1036   gst_rtspsrc_collect_connections (src, sdp, media, stream);
1037
1038   /* we must have a payload. No payload means we cannot create caps */
1039   /* FIXME, handle multiple formats. The problem here is that we just want to
1040    * take the first available format that we can handle but in order to do that
1041    * we need to scan for depayloader plugins. Scanning for payloader plugins is
1042    * also suboptimal because the user maybe just wants to save the raw stream
1043    * and then we don't care. */
1044   if ((payload = gst_sdp_media_get_format (media, 0))) {
1045     stream->pt = atoi (payload);
1046     /* convert caps */
1047     stream->caps = gst_rtspsrc_media_to_caps (stream->pt, media);
1048
1049     GST_DEBUG ("mapping sdp session level attributes to caps");
1050     gst_rtspsrc_sdp_attributes_to_caps (sdp->attributes, stream->caps);
1051     GST_DEBUG ("mapping sdp media level attributes to caps");
1052     gst_rtspsrc_sdp_attributes_to_caps (media->attributes, stream->caps);
1053
1054     if (stream->pt >= 96) {
1055       /* If we have a dynamic payload type, see if we have a stream with the
1056        * same payload number. If there is one, they are part of the same
1057        * container and we only need to add one pad. */
1058       if (find_stream (src, &stream->pt, (gpointer) find_stream_by_pt)) {
1059         stream->container = TRUE;
1060         GST_DEBUG ("found another stream with pt %d, marking as container",
1061             stream->pt);
1062       }
1063     }
1064   }
1065   /* collect port number */
1066   stream->port = gst_sdp_media_get_port (media);
1067
1068   /* get control url to construct the setup url. The setup url is used to
1069    * configure the transport of the stream and is used to identity the stream in
1070    * the RTP-Info header field returned from PLAY. */
1071   control_url = gst_sdp_media_get_attribute_val (media, "control");
1072   if (control_url == NULL)
1073     control_url = gst_sdp_message_get_attribute_val_n (sdp, "control", 0);
1074
1075   GST_DEBUG_OBJECT (src, "stream %d, (%p)", stream->id, stream);
1076   GST_DEBUG_OBJECT (src, " pt: %d", stream->pt);
1077   GST_DEBUG_OBJECT (src, " port: %d", stream->port);
1078   GST_DEBUG_OBJECT (src, " container: %d", stream->container);
1079   GST_DEBUG_OBJECT (src, " caps: %" GST_PTR_FORMAT, stream->caps);
1080   GST_DEBUG_OBJECT (src, " control: %s", GST_STR_NULL (control_url));
1081
1082   if (control_url != NULL) {
1083     stream->control_url = g_strdup (control_url);
1084     /* Build a fully qualified url using the content_base if any or by prefixing
1085      * the original request.
1086      * If the control_url starts with a '/' or a non rtsp: protocol we will most
1087      * likely build a URL that the server will fail to understand, this is ok,
1088      * we will fail then. */
1089     if (g_str_has_prefix (control_url, "rtsp://"))
1090       stream->conninfo.location = g_strdup (control_url);
1091     else {
1092       const gchar *base;
1093       gboolean has_slash;
1094
1095       if (g_strcmp0 (control_url, "*") == 0)
1096         control_url = "";
1097
1098       if (src->control)
1099         base = src->control;
1100       else if (src->content_base)
1101         base = src->content_base;
1102       else if (src->conninfo.url_str)
1103         base = src->conninfo.url_str;
1104       else
1105         base = "/";
1106
1107       /* check if the base ends or control starts with / */
1108       has_slash = g_str_has_prefix (control_url, "/");
1109       has_slash = has_slash || g_str_has_suffix (base, "/");
1110
1111       /* concatenate the two strings, insert / when not present */
1112       stream->conninfo.location =
1113           g_strdup_printf ("%s%s%s", base, has_slash ? "" : "/", control_url);
1114     }
1115   }
1116   GST_DEBUG_OBJECT (src, " setup: %s",
1117       GST_STR_NULL (stream->conninfo.location));
1118
1119   /* we keep track of all streams */
1120   src->streams = g_list_append (src->streams, stream);
1121
1122   return stream;
1123
1124   /* ERRORS */
1125 }
1126
1127 static void
1128 gst_rtspsrc_stream_free (GstRTSPSrc * src, GstRTSPStream * stream)
1129 {
1130   gint i;
1131
1132   GST_DEBUG_OBJECT (src, "free stream %p", stream);
1133
1134   if (stream->caps)
1135     gst_caps_unref (stream->caps);
1136
1137   g_free (stream->destination);
1138   g_free (stream->control_url);
1139   g_free (stream->conninfo.location);
1140
1141   for (i = 0; i < 2; i++) {
1142     if (stream->udpsrc[i]) {
1143       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
1144       gst_bin_remove (GST_BIN_CAST (src), stream->udpsrc[i]);
1145       gst_object_unref (stream->udpsrc[i]);
1146       stream->udpsrc[i] = NULL;
1147     }
1148     if (stream->channelpad[i]) {
1149       gst_object_unref (stream->channelpad[i]);
1150       stream->channelpad[i] = NULL;
1151     }
1152     if (stream->udpsink[i]) {
1153       gst_element_set_state (stream->udpsink[i], GST_STATE_NULL);
1154       gst_bin_remove (GST_BIN_CAST (src), stream->udpsink[i]);
1155       gst_object_unref (stream->udpsink[i]);
1156       stream->udpsink[i] = NULL;
1157     }
1158   }
1159   if (stream->fakesrc) {
1160     gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
1161     gst_bin_remove (GST_BIN_CAST (src), stream->fakesrc);
1162     gst_object_unref (stream->fakesrc);
1163     stream->fakesrc = NULL;
1164   }
1165   if (stream->srcpad) {
1166     gst_pad_set_active (stream->srcpad, FALSE);
1167     if (stream->added) {
1168       gst_element_remove_pad (GST_ELEMENT_CAST (src), stream->srcpad);
1169       stream->added = FALSE;
1170     }
1171     stream->srcpad = NULL;
1172   }
1173   if (stream->rtcppad) {
1174     gst_object_unref (stream->rtcppad);
1175     stream->rtcppad = NULL;
1176   }
1177   if (stream->session) {
1178     g_object_unref (stream->session);
1179     stream->session = NULL;
1180   }
1181   g_free (stream);
1182 }
1183
1184 static void
1185 gst_rtspsrc_cleanup (GstRTSPSrc * src)
1186 {
1187   GList *walk;
1188
1189   GST_DEBUG_OBJECT (src, "cleanup");
1190
1191   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1192     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1193
1194     gst_rtspsrc_stream_free (src, stream);
1195   }
1196   g_list_free (src->streams);
1197   src->streams = NULL;
1198   if (src->manager) {
1199     if (src->manager_sig_id) {
1200       g_signal_handler_disconnect (src->manager, src->manager_sig_id);
1201       src->manager_sig_id = 0;
1202     }
1203     gst_element_set_state (src->manager, GST_STATE_NULL);
1204     gst_bin_remove (GST_BIN_CAST (src), src->manager);
1205     src->manager = NULL;
1206   }
1207   src->numstreams = 0;
1208   if (src->props)
1209     gst_structure_free (src->props);
1210   src->props = NULL;
1211
1212   g_free (src->content_base);
1213   src->content_base = NULL;
1214
1215   g_free (src->control);
1216   src->control = NULL;
1217
1218   if (src->range)
1219     gst_rtsp_range_free (src->range);
1220   src->range = NULL;
1221
1222   /* don't clear the SDP when it was used in the url */
1223   if (src->sdp && !src->from_sdp) {
1224     gst_sdp_message_free (src->sdp);
1225     src->sdp = NULL;
1226   }
1227 }
1228
1229 #define PARSE_INT(p, del, res)          \
1230 G_STMT_START {                          \
1231   gchar *t = p;                         \
1232   p = strstr (p, del);                  \
1233   if (p == NULL)                        \
1234     res = -1;                           \
1235   else {                                \
1236     *p = '\0';                          \
1237     p++;                                \
1238     res = atoi (t);                     \
1239   }                                     \
1240 } G_STMT_END
1241
1242 #define PARSE_STRING(p, del, res)       \
1243 G_STMT_START {                          \
1244   gchar *t = p;                         \
1245   p = strstr (p, del);                  \
1246   if (p == NULL) {                      \
1247     res = NULL;                         \
1248     p = t;                              \
1249   }                                     \
1250   else {                                \
1251     *p = '\0';                          \
1252     p++;                                \
1253     res = t;                            \
1254   }                                     \
1255 } G_STMT_END
1256
1257 #define SKIP_SPACES(p)                  \
1258   while (*p && g_ascii_isspace (*p))    \
1259     p++;
1260
1261 /* rtpmap contains:
1262  *
1263  *  <payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1264  */
1265 static gboolean
1266 gst_rtspsrc_parse_rtpmap (const gchar * rtpmap, gint * payload, gchar ** name,
1267     gint * rate, gchar ** params)
1268 {
1269   gchar *p, *t;
1270
1271   p = (gchar *) rtpmap;
1272
1273   PARSE_INT (p, " ", *payload);
1274   if (*payload == -1)
1275     return FALSE;
1276
1277   SKIP_SPACES (p);
1278   if (*p == '\0')
1279     return FALSE;
1280
1281   PARSE_STRING (p, "/", *name);
1282   if (*name == NULL) {
1283     GST_DEBUG ("no rate, name %s", p);
1284     /* no rate, assume -1 then, this is not supposed to happen but RealMedia
1285      * streams seem to omit the rate. */
1286     *name = p;
1287     *rate = -1;
1288     return TRUE;
1289   }
1290
1291   t = p;
1292   p = strstr (p, "/");
1293   if (p == NULL) {
1294     *rate = atoi (t);
1295     return TRUE;
1296   }
1297   *p = '\0';
1298   p++;
1299   *rate = atoi (t);
1300
1301   t = p;
1302   if (*p == '\0')
1303     return TRUE;
1304   *params = t;
1305
1306   return TRUE;
1307 }
1308
1309 /*
1310  * Mapping SDP attributes to caps
1311  *
1312  * prepend 'a-' to IANA registered sdp attributes names
1313  * (ie: not prefixed with 'x-') in order to avoid
1314  * collision with gstreamer standard caps properties names
1315  */
1316 static void
1317 gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes, GstCaps * caps)
1318 {
1319   if (attributes->len > 0) {
1320     GstStructure *s;
1321     guint i;
1322
1323     s = gst_caps_get_structure (caps, 0);
1324
1325     for (i = 0; i < attributes->len; i++) {
1326       GstSDPAttribute *attr = &g_array_index (attributes, GstSDPAttribute, i);
1327       gchar *tofree, *key;
1328
1329       key = attr->key;
1330
1331       /* skip some of the attribute we already handle */
1332       if (!strcmp (key, "fmtp"))
1333         continue;
1334       if (!strcmp (key, "rtpmap"))
1335         continue;
1336       if (!strcmp (key, "control"))
1337         continue;
1338       if (!strcmp (key, "range"))
1339         continue;
1340
1341       /* string must be valid UTF8 */
1342       if (!g_utf8_validate (attr->value, -1, NULL))
1343         continue;
1344
1345       if (!g_str_has_prefix (key, "x-"))
1346         tofree = key = g_strdup_printf ("a-%s", key);
1347       else
1348         tofree = NULL;
1349
1350       GST_DEBUG ("adding caps: %s=%s", key, attr->value);
1351       gst_structure_set (s, key, G_TYPE_STRING, attr->value, NULL);
1352       g_free (tofree);
1353     }
1354   }
1355 }
1356
1357 /*
1358  *  Mapping of caps to and from SDP fields:
1359  *
1360  *   m=<media> <UDP port> RTP/AVP <payload>
1361  *   a=rtpmap:<payload> <encoding_name>/<clock_rate>[/<encoding_params>]
1362  *   a=fmtp:<payload> <param>[=<value>];...
1363  */
1364 static GstCaps *
1365 gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media)
1366 {
1367   GstCaps *caps;
1368   const gchar *rtpmap;
1369   const gchar *fmtp;
1370   gchar *name = NULL;
1371   gint rate = -1;
1372   gchar *params = NULL;
1373   gchar *tmp;
1374   GstStructure *s;
1375   gint payload = 0;
1376   gboolean ret;
1377
1378   /* get and parse rtpmap */
1379   if ((rtpmap = gst_sdp_media_get_attribute_val (media, "rtpmap"))) {
1380     ret = gst_rtspsrc_parse_rtpmap (rtpmap, &payload, &name, &rate, &params);
1381     if (ret) {
1382       if (payload != pt) {
1383         /* we ignore the rtpmap if the payload type is different. */
1384         g_warning ("rtpmap of wrong payload type, ignoring");
1385         name = NULL;
1386         rate = -1;
1387         params = NULL;
1388       }
1389     } else {
1390       /* if we failed to parse the rtpmap for a dynamic payload type, we have an
1391        * error */
1392       if (pt >= 96)
1393         goto no_rtpmap;
1394       /* else we can ignore */
1395       g_warning ("error parsing rtpmap, ignoring");
1396     }
1397   } else {
1398     /* dynamic payloads need rtpmap or we fail */
1399     if (pt >= 96)
1400       goto no_rtpmap;
1401   }
1402   /* check if we have a rate, if not, we need to look up the rate from the
1403    * default rates based on the payload types. */
1404   if (rate == -1) {
1405     const GstRTPPayloadInfo *info;
1406
1407     if (GST_RTP_PAYLOAD_IS_DYNAMIC (pt)) {
1408       /* dynamic types, use media and encoding_name */
1409       tmp = g_ascii_strdown (media->media, -1);
1410       info = gst_rtp_payload_info_for_name (tmp, name);
1411       g_free (tmp);
1412     } else {
1413       /* static types, use payload type */
1414       info = gst_rtp_payload_info_for_pt (pt);
1415     }
1416
1417     if (info) {
1418       if ((rate = info->clock_rate) == 0)
1419         rate = -1;
1420     }
1421     /* we fail if we cannot find one */
1422     if (rate == -1)
1423       goto no_rate;
1424   }
1425
1426   tmp = g_ascii_strdown (media->media, -1);
1427   caps = gst_caps_new_simple ("application/x-unknown",
1428       "media", G_TYPE_STRING, tmp, "payload", G_TYPE_INT, pt, NULL);
1429   g_free (tmp);
1430   s = gst_caps_get_structure (caps, 0);
1431
1432   gst_structure_set (s, "clock-rate", G_TYPE_INT, rate, NULL);
1433
1434   /* encoding name must be upper case */
1435   if (name != NULL) {
1436     tmp = g_ascii_strup (name, -1);
1437     gst_structure_set (s, "encoding-name", G_TYPE_STRING, tmp, NULL);
1438     g_free (tmp);
1439   }
1440
1441   /* params must be lower case */
1442   if (params != NULL) {
1443     tmp = g_ascii_strdown (params, -1);
1444     gst_structure_set (s, "encoding-params", G_TYPE_STRING, tmp, NULL);
1445     g_free (tmp);
1446   }
1447
1448   /* parse optional fmtp: field */
1449   if ((fmtp = gst_sdp_media_get_attribute_val (media, "fmtp"))) {
1450     gchar *p;
1451     gint payload = 0;
1452
1453     p = (gchar *) fmtp;
1454
1455     /* p is now of the format <payload> <param>[=<value>];... */
1456     PARSE_INT (p, " ", payload);
1457     if (payload != -1 && payload == pt) {
1458       gchar **pairs;
1459       gint i;
1460
1461       /* <param>[=<value>] are separated with ';' */
1462       pairs = g_strsplit (p, ";", 0);
1463       for (i = 0; pairs[i]; i++) {
1464         gchar *valpos;
1465         const gchar *val, *key;
1466
1467         /* the key may not have a '=', the value can have other '='s */
1468         valpos = strstr (pairs[i], "=");
1469         if (valpos) {
1470           /* we have a '=' and thus a value, remove the '=' with \0 */
1471           *valpos = '\0';
1472           /* value is everything between '=' and ';'. We split the pairs at ;
1473            * boundaries so we can take the remainder of the value. Some servers
1474            * put spaces around the value which we strip off here. Alternatively
1475            * we could strip those spaces in the depayloaders should these spaces
1476            * actually carry any meaning in the future. */
1477           val = g_strstrip (valpos + 1);
1478         } else {
1479           /* simple <param>;.. is translated into <param>=1;... */
1480           val = "1";
1481         }
1482         /* strip the key of spaces, convert key to lowercase but not the value. */
1483         key = g_strstrip (pairs[i]);
1484         if (strlen (key) > 1) {
1485           tmp = g_ascii_strdown (key, -1);
1486           gst_structure_set (s, tmp, G_TYPE_STRING, val, NULL);
1487           g_free (tmp);
1488         }
1489       }
1490       g_strfreev (pairs);
1491     }
1492   }
1493   return caps;
1494
1495   /* ERRORS */
1496 no_rtpmap:
1497   {
1498     g_warning ("rtpmap type not given for dynamic payload %d", pt);
1499     return NULL;
1500   }
1501 no_rate:
1502   {
1503     g_warning ("rate unknown for payload type %d", pt);
1504     return NULL;
1505   }
1506 }
1507
1508 static gboolean
1509 gst_rtspsrc_alloc_udp_ports (GstRTSPStream * stream,
1510     gint * rtpport, gint * rtcpport)
1511 {
1512   GstRTSPSrc *src;
1513   GstStateChangeReturn ret;
1514   GstElement *udpsrc0, *udpsrc1;
1515   gint tmp_rtp, tmp_rtcp;
1516   guint count;
1517   const gchar *host;
1518
1519   src = stream->parent;
1520
1521   udpsrc0 = NULL;
1522   udpsrc1 = NULL;
1523   count = 0;
1524
1525   /* Start at next port */
1526   tmp_rtp = src->next_port_num;
1527
1528   if (stream->is_ipv6)
1529     host = "udp://[::0]";
1530   else
1531     host = "udp://0.0.0.0";
1532
1533   /* try to allocate 2 UDP ports, the RTP port should be an even
1534    * number and the RTCP port should be the next (uneven) port */
1535 again:
1536
1537   if (tmp_rtp != 0 && src->client_port_range.max > 0 &&
1538       tmp_rtp >= src->client_port_range.max)
1539     goto no_ports;
1540
1541   udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL);
1542   if (udpsrc0 == NULL)
1543     goto no_udp_protocol;
1544   g_object_set (G_OBJECT (udpsrc0), "port", tmp_rtp, "reuse", FALSE, NULL);
1545
1546   if (src->udp_buffer_size != 0)
1547     g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
1548         NULL);
1549
1550   ret = gst_element_set_state (udpsrc0, GST_STATE_PAUSED);
1551   if (ret == GST_STATE_CHANGE_FAILURE) {
1552     if (tmp_rtp != 0) {
1553       GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTP port %d", tmp_rtp);
1554
1555       tmp_rtp += 2;
1556       if (++count > src->retry)
1557         goto no_ports;
1558
1559       GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1560       gst_element_set_state (udpsrc0, GST_STATE_NULL);
1561       gst_object_unref (udpsrc0);
1562
1563       GST_DEBUG_OBJECT (src, "retry %d", count);
1564       goto again;
1565     }
1566     goto no_udp_protocol;
1567   }
1568
1569   g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
1570   GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
1571
1572   /* check if port is even */
1573   if ((tmp_rtp & 0x01) != 0) {
1574     /* port not even, close and allocate another */
1575     if (++count > src->retry)
1576       goto no_ports;
1577
1578     GST_DEBUG_OBJECT (src, "RTP port not even");
1579
1580     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1581     gst_element_set_state (udpsrc0, GST_STATE_NULL);
1582     gst_object_unref (udpsrc0);
1583
1584     GST_DEBUG_OBJECT (src, "retry %d", count);
1585     tmp_rtp++;
1586     goto again;
1587   }
1588
1589   /* allocate port+1 for RTCP now */
1590   udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL);
1591   if (udpsrc1 == NULL)
1592     goto no_udp_rtcp_protocol;
1593
1594   /* set port */
1595   tmp_rtcp = tmp_rtp + 1;
1596   if (src->client_port_range.max > 0 && tmp_rtcp >= src->client_port_range.max)
1597     goto no_ports;
1598
1599   g_object_set (G_OBJECT (udpsrc1), "port", tmp_rtcp, "reuse", FALSE, NULL);
1600
1601   GST_DEBUG_OBJECT (src, "starting RTCP on port %d", tmp_rtcp);
1602   ret = gst_element_set_state (udpsrc1, GST_STATE_PAUSED);
1603   /* tmp_rtcp port is busy already : retry to make rtp/rtcp pair */
1604   if (ret == GST_STATE_CHANGE_FAILURE) {
1605     GST_DEBUG_OBJECT (src, "Unable to make udpsrc from RTCP port %d", tmp_rtcp);
1606
1607     if (++count > src->retry)
1608       goto no_ports;
1609
1610     GST_DEBUG_OBJECT (src, "free RTP udpsrc");
1611     gst_element_set_state (udpsrc0, GST_STATE_NULL);
1612     gst_object_unref (udpsrc0);
1613
1614     GST_DEBUG_OBJECT (src, "free RTCP udpsrc");
1615     gst_element_set_state (udpsrc1, GST_STATE_NULL);
1616     gst_object_unref (udpsrc1);
1617     udpsrc1 = NULL;
1618
1619     tmp_rtp += 2;
1620     GST_DEBUG_OBJECT (src, "retry %d", count);
1621     goto again;
1622   }
1623
1624   /* all fine, do port check */
1625   g_object_get (G_OBJECT (udpsrc0), "port", rtpport, NULL);
1626   g_object_get (G_OBJECT (udpsrc1), "port", rtcpport, NULL);
1627
1628   /* this should not happen... */
1629   if (*rtpport != tmp_rtp || *rtcpport != tmp_rtcp)
1630     goto port_error;
1631
1632   /* we keep these elements, we configure all in configure_transport when the
1633    * server told us to really use the UDP ports. */
1634   stream->udpsrc[0] = gst_object_ref (udpsrc0);
1635   stream->udpsrc[1] = gst_object_ref (udpsrc1);
1636
1637   /* keep track of next available port number when we have a range
1638    * configured */
1639   if (src->next_port_num != 0)
1640     src->next_port_num = tmp_rtcp + 1;
1641
1642   /* they are ours now */
1643   gst_object_sink (udpsrc0);
1644   gst_object_sink (udpsrc1);
1645
1646   return TRUE;
1647
1648   /* ERRORS */
1649 no_udp_protocol:
1650   {
1651     GST_DEBUG_OBJECT (src, "could not get UDP source");
1652     goto cleanup;
1653   }
1654 no_ports:
1655   {
1656     GST_DEBUG_OBJECT (src, "could not allocate UDP port pair after %d retries",
1657         count);
1658     goto cleanup;
1659   }
1660 no_udp_rtcp_protocol:
1661   {
1662     GST_DEBUG_OBJECT (src, "could not get UDP source for RTCP");
1663     goto cleanup;
1664   }
1665 port_error:
1666   {
1667     GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
1668         tmp_rtp, *rtpport, tmp_rtcp, *rtcpport);
1669     goto cleanup;
1670   }
1671 cleanup:
1672   {
1673     if (udpsrc0) {
1674       gst_element_set_state (udpsrc0, GST_STATE_NULL);
1675       gst_object_unref (udpsrc0);
1676     }
1677     if (udpsrc1) {
1678       gst_element_set_state (udpsrc1, GST_STATE_NULL);
1679       gst_object_unref (udpsrc1);
1680     }
1681     return FALSE;
1682   }
1683 }
1684
1685 static void
1686 gst_rtspsrc_flush (GstRTSPSrc * src, gboolean flush, gboolean playing)
1687 {
1688   GstEvent *event;
1689   gint cmd, i;
1690   GstState state;
1691   GList *walk;
1692   GstClock *clock;
1693   GstClockTime base_time = GST_CLOCK_TIME_NONE;
1694
1695   if (flush) {
1696     event = gst_event_new_flush_start ();
1697     GST_DEBUG_OBJECT (src, "start flush");
1698     cmd = CMD_WAIT;
1699     state = GST_STATE_PAUSED;
1700   } else {
1701     event = gst_event_new_flush_stop ();
1702     GST_DEBUG_OBJECT (src, "stop flush; playing %d", playing);
1703     cmd = CMD_LOOP;
1704     if (playing)
1705       state = GST_STATE_PLAYING;
1706     else
1707       state = GST_STATE_PAUSED;
1708     clock = gst_element_get_clock (GST_ELEMENT_CAST (src));
1709     if (clock) {
1710       base_time = gst_clock_get_time (clock);
1711       gst_object_unref (clock);
1712     }
1713   }
1714   gst_rtspsrc_push_event (src, event, FALSE);
1715   gst_rtspsrc_loop_send_cmd (src, cmd, flush);
1716
1717   /* set up manager before data-flow resumes */
1718   /* to manage jitterbuffer buffer mode */
1719   if (src->manager) {
1720     gst_element_set_base_time (GST_ELEMENT_CAST (src->manager), base_time);
1721     /* and to have base_time trickle further down,
1722      * e.g. to jitterbuffer for its timeout handling */
1723     if (base_time != -1)
1724       gst_element_set_state (GST_ELEMENT_CAST (src->manager), state);
1725   }
1726
1727   /* make running time start start at 0 again */
1728   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1729     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1730
1731     for (i = 0; i < 2; i++) {
1732       /* for udp case */
1733       if (stream->udpsrc[i]) {
1734         if (base_time != -1)
1735           gst_element_set_base_time (stream->udpsrc[i], base_time);
1736         gst_element_set_state (stream->udpsrc[i], state);
1737       }
1738     }
1739   }
1740   /* for tcp interleaved case */
1741   if (base_time != -1)
1742     gst_element_set_base_time (GST_ELEMENT_CAST (src), base_time);
1743 }
1744
1745 static GstRTSPResult
1746 gst_rtspsrc_connection_send (GstRTSPSrc * src, GstRTSPConnection * conn,
1747     GstRTSPMessage * message, GTimeVal * timeout)
1748 {
1749   GstRTSPResult ret;
1750
1751   if (conn)
1752     ret = gst_rtsp_connection_send (conn, message, timeout);
1753   else
1754     ret = GST_RTSP_ERROR;
1755
1756   return ret;
1757 }
1758
1759 static GstRTSPResult
1760 gst_rtspsrc_connection_receive (GstRTSPSrc * src, GstRTSPConnection * conn,
1761     GstRTSPMessage * message, GTimeVal * timeout)
1762 {
1763   GstRTSPResult ret;
1764
1765   if (conn)
1766     ret = gst_rtsp_connection_receive (conn, message, timeout);
1767   else
1768     ret = GST_RTSP_ERROR;
1769
1770   return ret;
1771 }
1772
1773 static void
1774 gst_rtspsrc_get_position (GstRTSPSrc * src)
1775 {
1776   GstQuery *query;
1777   GList *walk;
1778
1779   query = gst_query_new_position (GST_FORMAT_TIME);
1780   /*  should be known somewhere down the stream (e.g. jitterbuffer) */
1781   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1782     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1783     GstFormat fmt;
1784     gint64 pos;
1785
1786     if (stream->srcpad) {
1787       if (gst_pad_query (stream->srcpad, query)) {
1788         gst_query_parse_position (query, &fmt, &pos);
1789         GST_DEBUG_OBJECT (src, "retaining position %" GST_TIME_FORMAT,
1790             GST_TIME_ARGS (pos));
1791         src->last_pos = pos;
1792         return;
1793       }
1794     }
1795   }
1796
1797   src->last_pos = 0;
1798 }
1799
1800 static gboolean
1801 gst_rtspsrc_do_seek (GstRTSPSrc * src, GstSegment * segment)
1802 {
1803   src->state = GST_RTSP_STATE_SEEKING;
1804   /* PLAY will add the range header now. */
1805   src->need_range = TRUE;
1806
1807   return TRUE;
1808 }
1809
1810 static gboolean
1811 gst_rtspsrc_perform_seek (GstRTSPSrc * src, GstEvent * event)
1812 {
1813   gdouble rate;
1814   GstFormat format;
1815   GstSeekFlags flags;
1816   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
1817   gint64 cur, stop;
1818   gboolean flush, skip;
1819   gboolean update;
1820   gboolean playing;
1821   GstSegment seeksegment = { 0, };
1822   GList *walk;
1823
1824   if (event) {
1825     GST_DEBUG_OBJECT (src, "doing seek with event");
1826
1827     gst_event_parse_seek (event, &rate, &format, &flags,
1828         &cur_type, &cur, &stop_type, &stop);
1829
1830     /* no negative rates yet */
1831     if (rate < 0.0)
1832       goto negative_rate;
1833
1834     /* we need TIME format */
1835     if (format != src->segment.format)
1836       goto no_format;
1837   } else {
1838     GST_DEBUG_OBJECT (src, "doing seek without event");
1839     flags = 0;
1840     cur_type = GST_SEEK_TYPE_SET;
1841     stop_type = GST_SEEK_TYPE_SET;
1842   }
1843
1844   /* get flush flag */
1845   flush = flags & GST_SEEK_FLAG_FLUSH;
1846   skip = flags & GST_SEEK_FLAG_SKIP;
1847
1848   /* now we need to make sure the streaming thread is stopped. We do this by
1849    * either sending a FLUSH_START event downstream which will cause the
1850    * streaming thread to stop with a WRONG_STATE.
1851    * For a non-flushing seek we simply pause the task, which will happen as soon
1852    * as it completes one iteration (and thus might block when the sink is
1853    * blocking in preroll). */
1854   if (flush) {
1855     GST_DEBUG_OBJECT (src, "starting flush");
1856     gst_rtspsrc_flush (src, TRUE, FALSE);
1857   } else {
1858     if (src->task) {
1859       gst_task_pause (src->task);
1860     }
1861   }
1862
1863   /* we should now be able to grab the streaming thread because we stopped it
1864    * with the above flush/pause code */
1865   GST_RTSP_STREAM_LOCK (src);
1866
1867   GST_DEBUG_OBJECT (src, "stopped streaming");
1868
1869   /* copy segment, we need this because we still need the old
1870    * segment when we close the current segment. */
1871   memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
1872
1873   /* configure the seek parameters in the seeksegment. We will then have the
1874    * right values in the segment to perform the seek */
1875   if (event) {
1876     GST_DEBUG_OBJECT (src, "configuring seek");
1877     gst_segment_set_seek (&seeksegment, rate, format, flags,
1878         cur_type, cur, stop_type, stop, &update);
1879   }
1880
1881   /* figure out the last position we need to play. If it's configured (stop !=
1882    * -1), use that, else we play until the total duration of the file */
1883   if ((stop = seeksegment.stop) == -1)
1884     stop = seeksegment.duration;
1885
1886   playing = (src->state == GST_RTSP_STATE_PLAYING);
1887
1888   /* if we were playing, pause first */
1889   if (playing) {
1890     /* obtain current position in case seek fails */
1891     gst_rtspsrc_get_position (src);
1892     gst_rtspsrc_pause (src, FALSE, FALSE);
1893   }
1894
1895   gst_rtspsrc_do_seek (src, &seeksegment);
1896
1897   /* and continue playing */
1898   if (playing)
1899     gst_rtspsrc_play (src, &seeksegment, FALSE);
1900
1901   /* prepare for streaming again */
1902   if (flush) {
1903     /* if we started flush, we stop now */
1904     GST_DEBUG_OBJECT (src, "stopping flush");
1905     gst_rtspsrc_flush (src, FALSE, playing);
1906   } else if (src->running) {
1907     /* re-engage loop */
1908     gst_rtspsrc_loop_send_cmd (src, CMD_LOOP, FALSE);
1909
1910     /* we are running the current segment and doing a non-flushing seek,
1911      * close the segment first based on the previous last_stop. */
1912     GST_DEBUG_OBJECT (src, "closing running segment %" G_GINT64_FORMAT
1913         " to %" G_GINT64_FORMAT, src->segment.accum, src->segment.last_stop);
1914
1915     /* queue the segment for sending in the stream thread */
1916     if (src->close_segment)
1917       gst_event_unref (src->close_segment);
1918     src->close_segment = gst_event_new_new_segment (TRUE,
1919         src->segment.rate, src->segment.format,
1920         src->segment.accum, src->segment.last_stop, src->segment.accum);
1921
1922     /* keep track of our last_stop */
1923     seeksegment.accum = src->segment.last_stop;
1924   }
1925
1926   /* now we did the seek and can activate the new segment values */
1927   memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
1928
1929   /* if we're doing a segment seek, post a SEGMENT_START message */
1930   if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
1931     gst_element_post_message (GST_ELEMENT_CAST (src),
1932         gst_message_new_segment_start (GST_OBJECT_CAST (src),
1933             src->segment.format, src->segment.last_stop));
1934   }
1935
1936   /* now create the newsegment */
1937   GST_DEBUG_OBJECT (src, "Creating newsegment from %" G_GINT64_FORMAT
1938       " to %" G_GINT64_FORMAT, src->segment.last_stop, stop);
1939
1940   /* store the newsegment event so it can be sent from the streaming thread. */
1941   if (src->start_segment)
1942     gst_event_unref (src->start_segment);
1943   src->start_segment =
1944       gst_event_new_new_segment (FALSE, src->segment.rate,
1945       src->segment.format, src->segment.last_stop, stop,
1946       src->segment.last_stop);
1947
1948   /* mark discont */
1949   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
1950   for (walk = src->streams; walk; walk = g_list_next (walk)) {
1951     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
1952     stream->discont = TRUE;
1953   }
1954   src->skip = skip;
1955
1956   GST_RTSP_STREAM_UNLOCK (src);
1957
1958   return TRUE;
1959
1960   /* ERRORS */
1961 negative_rate:
1962   {
1963     GST_DEBUG_OBJECT (src, "negative playback rates are not supported yet.");
1964     return FALSE;
1965   }
1966 no_format:
1967   {
1968     GST_DEBUG_OBJECT (src, "unsupported format given, seek aborted.");
1969     return FALSE;
1970   }
1971 }
1972
1973 static gboolean
1974 gst_rtspsrc_handle_src_event (GstPad * pad, GstEvent * event)
1975 {
1976   GstRTSPSrc *src;
1977   gboolean res = TRUE;
1978   gboolean forward;
1979
1980   src = GST_RTSPSRC_CAST (gst_pad_get_parent (pad));
1981
1982   GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
1983       GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
1984
1985   switch (GST_EVENT_TYPE (event)) {
1986     case GST_EVENT_SEEK:
1987       res = gst_rtspsrc_perform_seek (src, event);
1988       forward = FALSE;
1989       break;
1990     case GST_EVENT_QOS:
1991     case GST_EVENT_NAVIGATION:
1992     case GST_EVENT_LATENCY:
1993     default:
1994       forward = TRUE;
1995       break;
1996   }
1997   if (forward) {
1998     GstPad *target;
1999
2000     if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
2001       res = gst_pad_send_event (target, event);
2002       gst_object_unref (target);
2003     } else {
2004       gst_event_unref (event);
2005     }
2006   } else {
2007     gst_event_unref (event);
2008   }
2009   gst_object_unref (src);
2010
2011   return res;
2012 }
2013
2014 /* this is the final event function we receive on the internal source pad when
2015  * we deal with TCP connections */
2016 static gboolean
2017 gst_rtspsrc_handle_internal_src_event (GstPad * pad, GstEvent * event)
2018 {
2019   gboolean res;
2020
2021   GST_DEBUG_OBJECT (pad, "received event %s", 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 (item && (strcmp (item, "stale") == 0) &&
4331         value && (strcmp (value, "TRUE") == 0))
4332       *stale = TRUE;
4333     gst_rtsp_connection_set_auth_param (conn, item, value);
4334     g_free (item);
4335   }
4336
4337   g_slist_free (list);
4338 }
4339
4340 /* Parse a WWW-Authenticate Response header and determine the
4341  * available authentication methods
4342  *
4343  * This code should also cope with the fact that each WWW-Authenticate
4344  * header can contain multiple challenge methods + tokens
4345  *
4346  * At the moment, for Basic auth, we just do a minimal check and don't
4347  * even parse out the realm */
4348 static void
4349 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4350     GstRTSPConnection * conn, gboolean * stale)
4351 {
4352   gchar *start;
4353
4354   g_return_if_fail (hdr != NULL);
4355   g_return_if_fail (methods != NULL);
4356   g_return_if_fail (stale != NULL);
4357
4358   /* Skip whitespace at the start of the string */
4359   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4360
4361   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4362     *methods |= GST_RTSP_AUTH_BASIC;
4363   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4364     *methods |= GST_RTSP_AUTH_DIGEST;
4365     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4366   }
4367 }
4368
4369 /**
4370  * gst_rtspsrc_setup_auth:
4371  * @src: the rtsp source
4372  *
4373  * Configure a username and password and auth method on the
4374  * connection object based on a response we received from the
4375  * peer.
4376  *
4377  * Currently, this requires that a username and password were supplied
4378  * in the uri. In the future, they may be requested on demand by sending
4379  * a message up the bus.
4380  *
4381  * Returns: TRUE if authentication information could be set up correctly.
4382  */
4383 static gboolean
4384 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4385 {
4386   gchar *user = NULL;
4387   gchar *pass = NULL;
4388   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4389   GstRTSPAuthMethod method;
4390   GstRTSPResult auth_result;
4391   GstRTSPUrl *url;
4392   GstRTSPConnection *conn;
4393   gchar *hdr;
4394   gboolean stale = FALSE;
4395
4396   conn = src->conninfo.connection;
4397
4398   /* Identify the available auth methods and see if any are supported */
4399   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4400           &hdr, 0) == GST_RTSP_OK) {
4401     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4402   }
4403
4404   if (avail_methods == GST_RTSP_AUTH_NONE)
4405     goto no_auth_available;
4406
4407   /* For digest auth, if the response indicates that the session
4408    * data are stale, we just update them in the connection object and
4409    * return TRUE to retry the request */
4410   if (stale)
4411     src->tried_url_auth = FALSE;
4412
4413   url = gst_rtsp_connection_get_url (conn);
4414
4415   /* Do we have username and password available? */
4416   if (url != NULL && !src->tried_url_auth && url->user != NULL
4417       && url->passwd != NULL) {
4418     user = url->user;
4419     pass = url->passwd;
4420     src->tried_url_auth = TRUE;
4421     GST_DEBUG_OBJECT (src,
4422         "Attempting authentication using credentials from the URL");
4423   } else {
4424     user = src->user_id;
4425     pass = src->user_pw;
4426     GST_DEBUG_OBJECT (src,
4427         "Attempting authentication using credentials from the properties");
4428   }
4429
4430   /* FIXME: If the url didn't contain username and password or we tried them
4431    * already, request a username and passwd from the application via some kind
4432    * of credentials request message */
4433
4434   /* If we don't have a username and passwd at this point, bail out. */
4435   if (user == NULL || pass == NULL)
4436     goto no_user_pass;
4437
4438   /* Try to configure for each available authentication method, strongest to
4439    * weakest */
4440   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4441     /* Check if this method is available on the server */
4442     if ((method & avail_methods) == 0)
4443       continue;
4444
4445     /* Pass the credentials to the connection to try on the next request */
4446     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4447     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4448      * ignore it and end up retrying later */
4449     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4450       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4451           gst_rtsp_auth_method_to_string (method));
4452       break;
4453     }
4454   }
4455
4456   if (method == GST_RTSP_AUTH_NONE)
4457     goto no_auth_available;
4458
4459   return TRUE;
4460
4461 no_auth_available:
4462   {
4463     /* Output an error indicating that we couldn't connect because there were
4464      * no supported authentication protocols */
4465     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4466         ("No supported authentication protocol was found"));
4467     return FALSE;
4468   }
4469 no_user_pass:
4470   {
4471     /* We don't fire an error message, we just return FALSE and let the
4472      * normal NOT_AUTHORIZED error be propagated */
4473     return FALSE;
4474   }
4475 }
4476
4477 static GstRTSPResult
4478 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4479     GstRTSPMessage * request, GstRTSPMessage * response,
4480     GstRTSPStatusCode * code)
4481 {
4482   GstRTSPResult res;
4483   GstRTSPStatusCode thecode;
4484   gchar *content_base = NULL;
4485   gint try = 0;
4486
4487 again:
4488   if (!src->short_header)
4489     gst_rtsp_ext_list_before_send (src->extensions, request);
4490
4491   GST_DEBUG_OBJECT (src, "sending message");
4492
4493   if (src->debug)
4494     gst_rtsp_message_dump (request);
4495
4496   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4497   if (res < 0)
4498     goto send_error;
4499
4500   gst_rtsp_connection_reset_timeout (conn);
4501
4502 next:
4503   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4504   if (res < 0)
4505     goto receive_error;
4506
4507   if (src->debug)
4508     gst_rtsp_message_dump (response);
4509
4510   switch (response->type) {
4511     case GST_RTSP_MESSAGE_REQUEST:
4512       res = gst_rtspsrc_handle_request (src, conn, response);
4513       if (res == GST_RTSP_EEOF)
4514         goto server_eof;
4515       else if (res < 0)
4516         goto handle_request_failed;
4517       goto next;
4518     case GST_RTSP_MESSAGE_RESPONSE:
4519       /* ok, a response is good */
4520       GST_DEBUG_OBJECT (src, "received response message");
4521       break;
4522     case GST_RTSP_MESSAGE_DATA:
4523       /* get next response */
4524       GST_DEBUG_OBJECT (src, "ignoring data response message");
4525       goto next;
4526     default:
4527       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4528           response->type);
4529       goto next;
4530   }
4531
4532   thecode = response->type_data.response.code;
4533
4534   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4535
4536   /* if the caller wanted the result code, we store it. */
4537   if (code)
4538     *code = thecode;
4539
4540   /* If the request didn't succeed, bail out before doing any more */
4541   if (thecode != GST_RTSP_STS_OK)
4542     return GST_RTSP_OK;
4543
4544   /* store new content base if any */
4545   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4546       &content_base, 0);
4547   if (content_base) {
4548     g_free (src->content_base);
4549     src->content_base = g_strdup (content_base);
4550   }
4551   gst_rtsp_ext_list_after_send (src->extensions, request, response);
4552
4553   return GST_RTSP_OK;
4554
4555   /* ERRORS */
4556 send_error:
4557   {
4558     gchar *str = gst_rtsp_strresult (res);
4559
4560     if (res != GST_RTSP_EINTR) {
4561       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4562           ("Could not send message. (%s)", str));
4563     } else {
4564       GST_WARNING_OBJECT (src, "send interrupted");
4565     }
4566     g_free (str);
4567     return res;
4568   }
4569 receive_error:
4570   {
4571     switch (res) {
4572       case GST_RTSP_EEOF:
4573         GST_WARNING_OBJECT (src, "server closed connection, doing reconnect");
4574         if (try == 0) {
4575           try++;
4576           /* if reconnect succeeds, try again */
4577           if ((res =
4578                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
4579                       FALSE)) == 0)
4580             goto again;
4581         }
4582         /* only try once after reconnect, then fallthrough and error out */
4583       default:
4584       {
4585         gchar *str = gst_rtsp_strresult (res);
4586
4587         if (res != GST_RTSP_EINTR) {
4588           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4589               ("Could not receive message. (%s)", str));
4590         } else {
4591           GST_WARNING_OBJECT (src, "receive interrupted");
4592         }
4593         g_free (str);
4594         break;
4595       }
4596     }
4597     return res;
4598   }
4599 handle_request_failed:
4600   {
4601     /* ERROR was posted */
4602     gst_rtsp_message_unset (response);
4603     return res;
4604   }
4605 server_eof:
4606   {
4607     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4608     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4609         ("The server closed the connection."));
4610     gst_rtsp_message_unset (response);
4611     return res;
4612   }
4613 }
4614
4615 /**
4616  * gst_rtspsrc_send:
4617  * @src: the rtsp source
4618  * @conn: the connection to send on
4619  * @request: must point to a valid request
4620  * @response: must point to an empty #GstRTSPMessage
4621  * @code: an optional code result
4622  *
4623  * send @request and retrieve the response in @response. optionally @code can be
4624  * non-NULL in which case it will contain the status code of the response.
4625  *
4626  * If This function returns #GST_RTSP_OK, @response will contain a valid response
4627  * message that should be cleaned with gst_rtsp_message_unset() after usage.
4628  *
4629  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
4630  * @response message) if the response code was not 200 (OK).
4631  *
4632  * If the attempt results in an authentication failure, then this will attempt
4633  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
4634  * the request.
4635  *
4636  * Returns: #GST_RTSP_OK if the processing was successful.
4637  */
4638 static GstRTSPResult
4639 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4640     GstRTSPMessage * request, GstRTSPMessage * response,
4641     GstRTSPStatusCode * code)
4642 {
4643   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
4644   GstRTSPResult res = GST_RTSP_ERROR;
4645   gint count;
4646   gboolean retry;
4647   GstRTSPMethod method = GST_RTSP_INVALID;
4648
4649   count = 0;
4650   do {
4651     retry = FALSE;
4652
4653     /* make sure we don't loop forever */
4654     if (count++ > 8)
4655       break;
4656
4657     /* save method so we can disable it when the server complains */
4658     method = request->type_data.request.method;
4659
4660     if ((res =
4661             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
4662       goto error;
4663
4664     switch (int_code) {
4665       case GST_RTSP_STS_UNAUTHORIZED:
4666         if (gst_rtspsrc_setup_auth (src, response)) {
4667           /* Try the request/response again after configuring the auth info
4668            * and loop again */
4669           retry = TRUE;
4670         }
4671         break;
4672       default:
4673         break;
4674     }
4675   } while (retry == TRUE);
4676
4677   /* If the user requested the code, let them handle errors, otherwise
4678    * post an error below */
4679   if (code != NULL)
4680     *code = int_code;
4681   else if (int_code != GST_RTSP_STS_OK)
4682     goto error_response;
4683
4684   return res;
4685
4686   /* ERRORS */
4687 error:
4688   {
4689     GST_DEBUG_OBJECT (src, "got error %d", res);
4690     return res;
4691   }
4692 error_response:
4693   {
4694     res = GST_RTSP_ERROR;
4695
4696     switch (response->type_data.response.code) {
4697       case GST_RTSP_STS_NOT_FOUND:
4698         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
4699                 response->type_data.response.reason));
4700         break;
4701       case GST_RTSP_STS_MOVED_PERMANENTLY:
4702       case GST_RTSP_STS_MOVE_TEMPORARILY:
4703       {
4704         gchar *new_location;
4705         GstRTSPLowerTrans transports;
4706
4707         GST_DEBUG_OBJECT (src, "got redirection");
4708         /* if we don't have a Location Header, we must error */
4709         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
4710                 &new_location, 0) < 0)
4711           break;
4712
4713         /* When we receive a redirect result, we go back to the INIT state after
4714          * parsing the new URI. The caller should do the needed steps to issue
4715          * a new setup when it detects this state change. */
4716         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
4717
4718         /* save current transports */
4719         if (src->conninfo.url)
4720           transports = src->conninfo.url->transports;
4721         else
4722           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
4723
4724         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location);
4725
4726         /* set old transports */
4727         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
4728           src->conninfo.url->transports = transports;
4729
4730         src->need_redirect = TRUE;
4731         src->state = GST_RTSP_STATE_INIT;
4732         res = GST_RTSP_OK;
4733         break;
4734       }
4735       case GST_RTSP_STS_NOT_ACCEPTABLE:
4736       case GST_RTSP_STS_NOT_IMPLEMENTED:
4737       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
4738         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
4739             gst_rtsp_method_as_text (method));
4740         src->methods &= ~method;
4741         res = GST_RTSP_OK;
4742         break;
4743       default:
4744         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4745             ("Got error response: %d (%s).", response->type_data.response.code,
4746                 response->type_data.response.reason));
4747         break;
4748     }
4749     /* if we return ERROR we should unset the response ourselves */
4750     if (res == GST_RTSP_ERROR)
4751       gst_rtsp_message_unset (response);
4752
4753     return res;
4754   }
4755 }
4756
4757 static GstRTSPResult
4758 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
4759     GstRTSPMessage * response, GstRTSPSrc * src)
4760 {
4761   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
4762       NULL);
4763 }
4764
4765
4766 /* parse the response and collect all the supported methods. We need this
4767  * information so that we don't try to send an unsupported request to the
4768  * server.
4769  */
4770 static gboolean
4771 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
4772 {
4773   GstRTSPHeaderField field;
4774   gchar *respoptions;
4775   gchar **options;
4776   gint indx = 0;
4777   gint i;
4778
4779   /* reset supported methods */
4780   src->methods = 0;
4781
4782   /* Try Allow Header first */
4783   field = GST_RTSP_HDR_ALLOW;
4784   while (TRUE) {
4785     respoptions = NULL;
4786     gst_rtsp_message_get_header (response, field, &respoptions, indx);
4787     if (indx == 0 && !respoptions) {
4788       /* if no Allow header was found then try the Public header... */
4789       field = GST_RTSP_HDR_PUBLIC;
4790       gst_rtsp_message_get_header (response, field, &respoptions, indx);
4791     }
4792     if (!respoptions)
4793       break;
4794
4795     /* If we get here, the server gave a list of supported methods, parse
4796      * them here. The string is like:
4797      *
4798      * OPTIONS, DESCRIBE, ANNOUNCE, PLAY, SETUP, ...
4799      */
4800     options = g_strsplit (respoptions, ",", 0);
4801
4802     for (i = 0; options[i]; i++) {
4803       gchar *stripped;
4804       gint method;
4805
4806       stripped = g_strstrip (options[i]);
4807       method = gst_rtsp_find_method (stripped);
4808
4809       /* keep bitfield of supported methods */
4810       if (method != GST_RTSP_INVALID)
4811         src->methods |= method;
4812     }
4813     g_strfreev (options);
4814
4815     indx++;
4816   }
4817
4818   if (src->methods == 0) {
4819     /* neither Allow nor Public are required, assume the server supports
4820      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
4821      * well. */
4822     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
4823     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
4824   }
4825   /* always assume PLAY, FIXME, extensions should be able to override
4826    * this */
4827   src->methods |= GST_RTSP_PLAY;
4828   /* also assume it will support Range */
4829   src->seekable = TRUE;
4830
4831   /* we need describe and setup */
4832   if (!(src->methods & GST_RTSP_DESCRIBE))
4833     goto no_describe;
4834   if (!(src->methods & GST_RTSP_SETUP))
4835     goto no_setup;
4836
4837   return TRUE;
4838
4839   /* ERRORS */
4840 no_describe:
4841   {
4842     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4843         ("Server does not support DESCRIBE."));
4844     return FALSE;
4845   }
4846 no_setup:
4847   {
4848     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4849         ("Server does not support SETUP."));
4850     return FALSE;
4851   }
4852 }
4853
4854 /* masks to be kept in sync with the hardcoded protocol order of preference
4855  * in code below */
4856 static guint protocol_masks[] = {
4857   GST_RTSP_LOWER_TRANS_UDP,
4858   GST_RTSP_LOWER_TRANS_UDP_MCAST,
4859   GST_RTSP_LOWER_TRANS_TCP,
4860   0
4861 };
4862
4863 static GstRTSPResult
4864 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
4865     GstRTSPLowerTrans protocols, gchar ** transports)
4866 {
4867   GstRTSPResult res;
4868   GString *result;
4869   gboolean add_udp_str;
4870
4871   *transports = NULL;
4872
4873   res =
4874       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
4875
4876   if (res < 0)
4877     goto failed;
4878
4879   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
4880
4881   /* extension listed transports, use those */
4882   if (*transports != NULL)
4883     return GST_RTSP_OK;
4884
4885   /* it's the default */
4886   add_udp_str = FALSE;
4887
4888   /* the default RTSP transports */
4889   result = g_string_new ("");
4890   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
4891     GST_DEBUG_OBJECT (src, "adding UDP unicast");
4892
4893     g_string_append (result, "RTP/AVP");
4894     if (add_udp_str)
4895       g_string_append (result, "/UDP");
4896     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
4897   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
4898     GST_DEBUG_OBJECT (src, "adding UDP multicast");
4899
4900     /* we don't have to allocate any UDP ports yet, if the selected transport
4901      * turns out to be multicast we can create them and join the multicast
4902      * group indicated in the transport reply */
4903     if (result->len > 0)
4904       g_string_append (result, ",");
4905     g_string_append (result, "RTP/AVP");
4906     if (add_udp_str)
4907       g_string_append (result, "/UDP");
4908     g_string_append (result, ";multicast");
4909   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
4910     GST_DEBUG_OBJECT (src, "adding TCP");
4911
4912     if (result->len > 0)
4913       g_string_append (result, ",");
4914     g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
4915   }
4916   *transports = g_string_free (result, FALSE);
4917
4918   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
4919
4920   return GST_RTSP_OK;
4921
4922   /* ERRORS */
4923 failed:
4924   {
4925     return res;
4926   }
4927 }
4928
4929 static GstRTSPResult
4930 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
4931     gint orig_rtpport, gint orig_rtcpport)
4932 {
4933   GstRTSPSrc *src;
4934   gint nr_udp, nr_int;
4935   gchar *next, *p;
4936   gint rtpport = 0, rtcpport = 0;
4937   GString *str;
4938
4939   src = stream->parent;
4940
4941   /* find number of placeholders first */
4942   if (strstr (*transports, "%%i2"))
4943     nr_int = 2;
4944   else if (strstr (*transports, "%%i1"))
4945     nr_int = 1;
4946   else
4947     nr_int = 0;
4948
4949   if (strstr (*transports, "%%u2"))
4950     nr_udp = 2;
4951   else if (strstr (*transports, "%%u1"))
4952     nr_udp = 1;
4953   else
4954     nr_udp = 0;
4955
4956   if (nr_udp == 0 && nr_int == 0)
4957     goto done;
4958
4959   if (nr_udp > 0) {
4960     if (!orig_rtpport || !orig_rtcpport) {
4961       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
4962         goto failed;
4963     } else {
4964       rtpport = orig_rtpport;
4965       rtcpport = orig_rtcpport;
4966     }
4967   }
4968
4969   str = g_string_new ("");
4970   p = *transports;
4971   while ((next = strstr (p, "%%"))) {
4972     g_string_append_len (str, p, next - p);
4973     if (next[2] == 'u') {
4974       if (next[3] == '1')
4975         g_string_append_printf (str, "%d", rtpport);
4976       else if (next[3] == '2')
4977         g_string_append_printf (str, "%d", rtcpport);
4978     }
4979     if (next[2] == 'i') {
4980       if (next[3] == '1')
4981         g_string_append_printf (str, "%d", src->free_channel);
4982       else if (next[3] == '2')
4983         g_string_append_printf (str, "%d", src->free_channel + 1);
4984     }
4985
4986     p = next + 4;
4987   }
4988   /* append final part */
4989   g_string_append (str, p);
4990
4991   g_free (*transports);
4992   *transports = g_string_free (str, FALSE);
4993
4994 done:
4995   return GST_RTSP_OK;
4996
4997   /* ERRORS */
4998 failed:
4999   {
5000     return GST_RTSP_ERROR;
5001   }
5002 }
5003
5004 static gboolean
5005 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
5006 {
5007   gboolean res = FALSE;
5008
5009   if (stream->caps) {
5010     GstStructure *s;
5011     const gchar *enc = NULL;
5012
5013     s = gst_caps_get_structure (stream->caps, 0);
5014     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
5015       res = (strstr (enc, "-REAL") != NULL);
5016     }
5017   }
5018   return res;
5019 }
5020
5021 /* Perform the SETUP request for all the streams.
5022  *
5023  * We ask the server for a specific transport, which initially includes all the
5024  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5025  * two local UDP ports that we send to the server.
5026  *
5027  * Once the server replied with a transport, we configure the other streams
5028  * with the same transport.
5029  *
5030  * This function will also configure the stream for the selected transport,
5031  * which basically means creating the pipeline.
5032  */
5033 static GstRTSPResult
5034 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5035 {
5036   GList *walk;
5037   GstRTSPResult res = GST_RTSP_ERROR;
5038   GstRTSPMessage request = { 0 };
5039   GstRTSPMessage response = { 0 };
5040   GstRTSPStream *stream = NULL;
5041   GstRTSPLowerTrans protocols;
5042   GstRTSPStatusCode code;
5043   gboolean unsupported_real = FALSE;
5044   gint rtpport, rtcpport;
5045   GstRTSPUrl *url;
5046   gchar *hval;
5047
5048   if (src->conninfo.connection) {
5049     url = gst_rtsp_connection_get_url (src->conninfo.connection);
5050     /* we initially allow all configured lower transports. based on the URL
5051      * transports and the replies from the server we narrow them down. */
5052     protocols = url->transports & src->cur_protocols;
5053   } else {
5054     url = NULL;
5055     protocols = src->cur_protocols;
5056   }
5057
5058   if (protocols == 0)
5059     goto no_protocols;
5060
5061   /* reset some state */
5062   src->free_channel = 0;
5063   src->interleaved = FALSE;
5064   src->need_activate = FALSE;
5065   /* keep track of next port number, 0 is random */
5066   src->next_port_num = src->client_port_range.min;
5067   rtpport = rtcpport = 0;
5068
5069   if (G_UNLIKELY (src->streams == NULL))
5070     goto no_streams;
5071
5072   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5073     GstRTSPConnection *conn;
5074     gchar *transports;
5075     gint retry = 0;
5076     guint mask = 0;
5077
5078     stream = (GstRTSPStream *) walk->data;
5079
5080     /* see if we need to configure this stream */
5081     if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5082       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5083           stream);
5084       stream->disabled = TRUE;
5085       continue;
5086     }
5087
5088     /* merge/overwrite global caps */
5089     if (stream->caps) {
5090       guint j, num;
5091       GstStructure *s;
5092
5093       s = gst_caps_get_structure (stream->caps, 0);
5094
5095       num = gst_structure_n_fields (src->props);
5096       for (j = 0; j < num; j++) {
5097         const gchar *name;
5098         const GValue *val;
5099
5100         name = gst_structure_nth_field_name (src->props, j);
5101         val = gst_structure_get_value (src->props, name);
5102         gst_structure_set_value (s, name, val);
5103
5104         GST_DEBUG_OBJECT (src, "copied %s", name);
5105       }
5106     }
5107
5108     /* skip setup if we have no URL for it */
5109     if (stream->conninfo.location == NULL) {
5110       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5111       continue;
5112     }
5113
5114     if (src->conninfo.connection == NULL) {
5115       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5116         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5117         continue;
5118       }
5119       conn = stream->conninfo.connection;
5120     } else {
5121       conn = src->conninfo.connection;
5122     }
5123     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5124         stream->conninfo.location);
5125
5126     /* if we have a multicast connection, only suggest multicast from now on */
5127     if (stream->is_multicast)
5128       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5129
5130   next_protocol:
5131     /* first selectable protocol */
5132     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5133       mask++;
5134     if (!protocol_masks[mask])
5135       goto no_protocols;
5136
5137   retry:
5138     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5139         protocol_masks[mask]);
5140     /* create a string with first transport in line */
5141     transports = NULL;
5142     res = gst_rtspsrc_create_transports_string (src,
5143         protocols & protocol_masks[mask], &transports);
5144     if (res < 0 || transports == NULL)
5145       goto setup_transport_failed;
5146
5147     if (strlen (transports) == 0) {
5148       g_free (transports);
5149       GST_DEBUG_OBJECT (src, "no transports found");
5150       mask++;
5151       goto next_protocol;
5152     }
5153
5154     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5155
5156     /* replace placeholders with real values, this function will optionally
5157      * allocate UDP ports and other info needed to execute the setup request */
5158     res = gst_rtspsrc_prepare_transports (stream, &transports,
5159         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5160     if (res < 0) {
5161       g_free (transports);
5162       goto setup_transport_failed;
5163     }
5164
5165     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5166
5167     /* create SETUP request */
5168     res =
5169         gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5170         stream->conninfo.location);
5171     if (res < 0) {
5172       g_free (transports);
5173       goto create_request_failed;
5174     }
5175
5176     /* select transport, copy is made when adding to header so we can free it. */
5177     gst_rtsp_message_add_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5178     g_free (transports);
5179
5180     /* if the user wants a non default RTP packet size we add the blocksize
5181      * parameter */
5182     if (src->rtp_blocksize > 0) {
5183       hval = g_strdup_printf ("%d", src->rtp_blocksize);
5184       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5185       g_free (hval);
5186     }
5187
5188     if (async)
5189       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5190               stream->id));
5191
5192     /* handle the code ourselves */
5193     if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5194       goto send_error;
5195
5196     switch (code) {
5197       case GST_RTSP_STS_OK:
5198         break;
5199       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5200         gst_rtsp_message_unset (&request);
5201         gst_rtsp_message_unset (&response);
5202         /* cleanup of leftover transport */
5203         gst_rtspsrc_stream_free_udp (stream);
5204         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5205          * we might be in this case */
5206         if (stream->container && rtpport && rtcpport && !retry) {
5207           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5208               rtpport, rtcpport);
5209           retry++;
5210           goto retry;
5211         }
5212         /* this transport did not go down well, but we may have others to try
5213          * that we did not send yet, try those and only give up then
5214          * but not without checking for lost cause/extension so we can
5215          * post a nicer/more useful error message later */
5216         if (!unsupported_real)
5217           unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5218         /* select next available protocol, give up on this stream if none */
5219         mask++;
5220         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5221           mask++;
5222         if (!protocol_masks[mask] || unsupported_real)
5223           continue;
5224         else
5225           goto retry;
5226       default:
5227         /* cleanup of leftover transport and move to the next stream */
5228         gst_rtspsrc_stream_free_udp (stream);
5229         goto response_error;
5230     }
5231
5232     /* parse response transport */
5233     {
5234       gchar *resptrans = NULL;
5235       GstRTSPTransport transport = { 0 };
5236
5237       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5238           &resptrans, 0);
5239       if (!resptrans) {
5240         gst_rtspsrc_stream_free_udp (stream);
5241         goto no_transport;
5242       }
5243
5244       /* parse transport, go to next stream on parse error */
5245       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5246         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5247         goto next;
5248       }
5249
5250       /* update allowed transports for other streams. once the transport of
5251        * one stream has been determined, we make sure that all other streams
5252        * are configured in the same way */
5253       switch (transport.lower_transport) {
5254         case GST_RTSP_LOWER_TRANS_TCP:
5255           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5256           protocols = GST_RTSP_LOWER_TRANS_TCP;
5257           src->interleaved = TRUE;
5258           /* update free channels */
5259           src->free_channel =
5260               MAX (transport.interleaved.min, src->free_channel);
5261           src->free_channel =
5262               MAX (transport.interleaved.max, src->free_channel);
5263           src->free_channel++;
5264           break;
5265         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5266           /* only allow multicast for other streams */
5267           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5268           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5269           break;
5270         case GST_RTSP_LOWER_TRANS_UDP:
5271           /* only allow unicast for other streams */
5272           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5273           protocols = GST_RTSP_LOWER_TRANS_UDP;
5274           break;
5275         default:
5276           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5277               transport.lower_transport);
5278           break;
5279       }
5280
5281       if (!stream->container || (!src->interleaved && !retry)) {
5282         /* now configure the stream with the selected transport */
5283         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5284           GST_DEBUG_OBJECT (src,
5285               "could not configure stream %p transport, skipping stream",
5286               stream);
5287           goto next;
5288         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5289           /* retain the first allocated UDP port pair */
5290           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5291           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5292         }
5293       }
5294       /* we need to activate at least one streams when we detect activity */
5295       src->need_activate = TRUE;
5296     next:
5297       /* clean up our transport struct */
5298       gst_rtsp_transport_init (&transport);
5299       /* clean up used RTSP messages */
5300       gst_rtsp_message_unset (&request);
5301       gst_rtsp_message_unset (&response);
5302     }
5303   }
5304
5305   /* store the transport protocol that was configured */
5306   src->cur_protocols = protocols;
5307
5308   gst_rtsp_ext_list_stream_select (src->extensions, url);
5309
5310   /* if there is nothing to activate, error out */
5311   if (!src->need_activate)
5312     goto nothing_to_activate;
5313
5314   return res;
5315
5316   /* ERRORS */
5317 no_protocols:
5318   {
5319     /* no transport possible, post an error and stop */
5320     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5321         ("Could not connect to server, no protocols left"));
5322     return GST_RTSP_ERROR;
5323   }
5324 no_streams:
5325   {
5326     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5327         ("SDP contains no streams"));
5328     return GST_RTSP_ERROR;
5329   }
5330 create_request_failed:
5331   {
5332     gchar *str = gst_rtsp_strresult (res);
5333
5334     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5335         ("Could not create request. (%s)", str));
5336     g_free (str);
5337     goto cleanup_error;
5338   }
5339 setup_transport_failed:
5340   {
5341     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5342         ("Could not setup transport."));
5343     res = GST_RTSP_ERROR;
5344     goto cleanup_error;
5345   }
5346 response_error:
5347   {
5348     const gchar *str = gst_rtsp_status_as_text (code);
5349
5350     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5351         ("Error (%d): %s", code, GST_STR_NULL (str)));
5352     res = GST_RTSP_ERROR;
5353     goto cleanup_error;
5354   }
5355 send_error:
5356   {
5357     gchar *str = gst_rtsp_strresult (res);
5358
5359     if (res != GST_RTSP_EINTR) {
5360       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5361           ("Could not send message. (%s)", str));
5362     } else {
5363       GST_WARNING_OBJECT (src, "send interrupted");
5364     }
5365     g_free (str);
5366     goto cleanup_error;
5367   }
5368 no_transport:
5369   {
5370     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5371         ("Server did not select transport."));
5372     res = GST_RTSP_ERROR;
5373     goto cleanup_error;
5374   }
5375 nothing_to_activate:
5376   {
5377     /* none of the available error codes is really right .. */
5378     if (unsupported_real) {
5379       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5380           (_("No supported stream was found. You might need to install a "
5381                   "GStreamer RTSP extension plugin for Real media streams.")),
5382           (NULL));
5383     } else {
5384       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5385           (_("No supported stream was found. You might need to allow "
5386                   "more transport protocols or may otherwise be missing "
5387                   "the right GStreamer RTSP extension plugin.")), (NULL));
5388     }
5389     return GST_RTSP_ERROR;
5390   }
5391 cleanup_error:
5392   {
5393     gst_rtsp_message_unset (&request);
5394     gst_rtsp_message_unset (&response);
5395     return res;
5396   }
5397 }
5398
5399 static gboolean
5400 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5401     GstSegment * segment)
5402 {
5403   gint64 seconds;
5404   GstRTSPTimeRange *therange;
5405
5406   if (src->range)
5407     gst_rtsp_range_free (src->range);
5408
5409   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5410     GST_DEBUG_OBJECT (src, "parsed range %s", range);
5411     src->range = therange;
5412   } else {
5413     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5414     src->range = NULL;
5415     gst_segment_init (segment, GST_FORMAT_TIME);
5416     return FALSE;
5417   }
5418
5419   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
5420       therange->min.type, therange->min.seconds, therange->max.type,
5421       therange->max.seconds);
5422
5423   if (therange->min.type == GST_RTSP_TIME_NOW)
5424     seconds = 0;
5425   else if (therange->min.type == GST_RTSP_TIME_END)
5426     seconds = 0;
5427   else
5428     seconds = therange->min.seconds * GST_SECOND;
5429
5430   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5431       GST_TIME_ARGS (seconds));
5432
5433   /* we need to start playback without clipping from the position reported by
5434    * the server */
5435   segment->start = seconds;
5436   segment->last_stop = seconds;
5437
5438   if (therange->max.type == GST_RTSP_TIME_NOW)
5439     seconds = -1;
5440   else if (therange->max.type == GST_RTSP_TIME_END)
5441     seconds = -1;
5442   else
5443     seconds = therange->max.seconds * GST_SECOND;
5444
5445   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5446       GST_TIME_ARGS (seconds));
5447
5448   /* live (WMS) server might send overflowed large max as its idea of infinity,
5449    * compensate to prevent problems later on */
5450   if (seconds != -1 && seconds < 0) {
5451     seconds = -1;
5452     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5453   }
5454
5455   /* live (WMS) might send min == max, which is not worth recording */
5456   if (segment->duration == -1 && seconds == segment->start)
5457     seconds = -1;
5458
5459   /* don't change duration with unknown value, we might have a valid value
5460    * there that we want to keep. */
5461   if (seconds != -1)
5462     gst_segment_set_duration (segment, GST_FORMAT_TIME, seconds);
5463
5464   return TRUE;
5465 }
5466
5467 /* must be called with the RTSP state lock */
5468 static GstRTSPResult
5469 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5470     gboolean async)
5471 {
5472   GstRTSPResult res;
5473   gint i, n_streams;
5474
5475   /* prepare global stream caps properties */
5476   if (src->props)
5477     gst_structure_remove_all_fields (src->props);
5478   else
5479     src->props = gst_structure_empty_new ("RTSPProperties");
5480
5481   if (src->debug)
5482     gst_sdp_message_dump (sdp);
5483
5484   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
5485
5486   gst_segment_init (&src->segment, GST_FORMAT_TIME);
5487
5488   /* parse range for duration reporting. */
5489   {
5490     const gchar *range;
5491
5492     for (i = 0;; i++) {
5493       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
5494       if (range == NULL)
5495         break;
5496
5497       /* keep track of the range and configure it in the segment */
5498       if (gst_rtspsrc_parse_range (src, range, &src->segment))
5499         break;
5500     }
5501   }
5502   /* try to find a global control attribute. Note that a '*' means that we should
5503    * do aggregate control with the current url (so we don't do anything and
5504    * leave the current connection as is) */
5505   {
5506     const gchar *control;
5507
5508     for (i = 0;; i++) {
5509       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
5510       if (control == NULL)
5511         break;
5512
5513       /* only take fully qualified urls */
5514       if (g_str_has_prefix (control, "rtsp://"))
5515         break;
5516     }
5517     if (control) {
5518       g_free (src->conninfo.location);
5519       src->conninfo.location = g_strdup (control);
5520       /* make a connection for this, if there was a connection already, nothing
5521        * happens. */
5522       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
5523         GST_ERROR_OBJECT (src, "could not connect");
5524       }
5525     }
5526     /* we need to keep the control url separate from the connection url because
5527      * the rules for constructing the media control url need it */
5528     g_free (src->control);
5529     src->control = g_strdup (control);
5530   }
5531
5532   /* create streams */
5533   n_streams = gst_sdp_message_medias_len (sdp);
5534   for (i = 0; i < n_streams; i++) {
5535     gst_rtspsrc_create_stream (src, sdp, i);
5536   }
5537
5538   src->state = GST_RTSP_STATE_INIT;
5539
5540   /* setup streams */
5541   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
5542     goto setup_failed;
5543
5544   /* reset our state */
5545   src->need_range = TRUE;
5546   src->skip = FALSE;
5547
5548   src->state = GST_RTSP_STATE_READY;
5549
5550   return res;
5551
5552   /* ERRORS */
5553 setup_failed:
5554   {
5555     GST_ERROR_OBJECT (src, "setup failed");
5556     return res;
5557   }
5558 }
5559
5560 static GstRTSPResult
5561 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
5562     gboolean async)
5563 {
5564   GstRTSPResult res;
5565   GstRTSPMessage request = { 0 };
5566   GstRTSPMessage response = { 0 };
5567   guint8 *data;
5568   guint size;
5569   gchar *respcont = NULL;
5570
5571 restart:
5572   src->need_redirect = FALSE;
5573
5574   /* can't continue without a valid url */
5575   if (G_UNLIKELY (src->conninfo.url == NULL)) {
5576     res = GST_RTSP_EINVAL;
5577     goto no_url;
5578   }
5579   src->tried_url_auth = FALSE;
5580
5581   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
5582     goto connect_failed;
5583
5584   /* create OPTIONS */
5585   GST_DEBUG_OBJECT (src, "create options...");
5586   res =
5587       gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
5588       src->conninfo.url_str);
5589   if (res < 0)
5590     goto create_request_failed;
5591
5592   /* send OPTIONS */
5593   GST_DEBUG_OBJECT (src, "send options...");
5594
5595   if (async)
5596     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
5597
5598   if ((res =
5599           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5600               NULL)) < 0)
5601     goto send_error;
5602
5603   /* parse OPTIONS */
5604   if (!gst_rtspsrc_parse_methods (src, &response))
5605     goto methods_error;
5606
5607   /* create DESCRIBE */
5608   GST_DEBUG_OBJECT (src, "create describe...");
5609   res =
5610       gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
5611       src->conninfo.url_str);
5612   if (res < 0)
5613     goto create_request_failed;
5614
5615   /* we only accept SDP for now */
5616   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
5617       "application/sdp");
5618
5619   /* send DESCRIBE */
5620   GST_DEBUG_OBJECT (src, "send describe...");
5621
5622   if (async)
5623     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
5624
5625   if ((res =
5626           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
5627               NULL)) < 0)
5628     goto send_error;
5629
5630   /* we only perform redirect for the describe, currently */
5631   if (src->need_redirect) {
5632     /* close connection, we don't have to send a TEARDOWN yet, ignore the
5633      * result. */
5634     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5635
5636     gst_rtsp_message_unset (&request);
5637     gst_rtsp_message_unset (&response);
5638
5639     /* and now retry */
5640     goto restart;
5641   }
5642
5643   /* it could be that the DESCRIBE method was not implemented */
5644   if (!src->methods & GST_RTSP_DESCRIBE)
5645     goto no_describe;
5646
5647   /* check if reply is SDP */
5648   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
5649       0);
5650   /* could not be set but since the request returned OK, we assume it
5651    * was SDP, else check it. */
5652   if (respcont) {
5653     if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
5654       goto wrong_content_type;
5655   }
5656
5657   /* get message body and parse as SDP */
5658   gst_rtsp_message_get_body (&response, &data, &size);
5659   if (data == NULL || size == 0)
5660     goto no_describe;
5661
5662   GST_DEBUG_OBJECT (src, "parse SDP...");
5663   gst_sdp_message_new (sdp);
5664   gst_sdp_message_parse_buffer (data, size, *sdp);
5665
5666   /* clean up any messages */
5667   gst_rtsp_message_unset (&request);
5668   gst_rtsp_message_unset (&response);
5669
5670   return res;
5671
5672   /* ERRORS */
5673 no_url:
5674   {
5675     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
5676         ("No valid RTSP URL was provided"));
5677     goto cleanup_error;
5678   }
5679 connect_failed:
5680   {
5681     gchar *str = gst_rtsp_strresult (res);
5682
5683     if (res != GST_RTSP_EINTR) {
5684       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
5685           ("Failed to connect. (%s)", str));
5686     } else {
5687       GST_WARNING_OBJECT (src, "connect interrupted");
5688     }
5689     g_free (str);
5690     goto cleanup_error;
5691   }
5692 create_request_failed:
5693   {
5694     gchar *str = gst_rtsp_strresult (res);
5695
5696     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5697         ("Could not create request. (%s)", str));
5698     g_free (str);
5699     goto cleanup_error;
5700   }
5701 send_error:
5702   {
5703     /* Don't post a message - the rtsp_send method will have
5704      * taken care of it because we passed NULL for the response code */
5705     goto cleanup_error;
5706   }
5707 methods_error:
5708   {
5709     /* error was posted */
5710     res = GST_RTSP_ERROR;
5711     goto cleanup_error;
5712   }
5713 wrong_content_type:
5714   {
5715     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5716         ("Server does not support SDP, got %s.", respcont));
5717     res = GST_RTSP_ERROR;
5718     goto cleanup_error;
5719   }
5720 no_describe:
5721   {
5722     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5723         ("Server can not provide an SDP."));
5724     res = GST_RTSP_ERROR;
5725     goto cleanup_error;
5726   }
5727 cleanup_error:
5728   {
5729     if (src->conninfo.connection) {
5730       GST_DEBUG_OBJECT (src, "free connection");
5731       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5732     }
5733     gst_rtsp_message_unset (&request);
5734     gst_rtsp_message_unset (&response);
5735     return res;
5736   }
5737 }
5738
5739 static GstRTSPResult
5740 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
5741 {
5742   GstRTSPResult ret;
5743
5744   src->methods =
5745       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
5746
5747   if (src->sdp == NULL) {
5748     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
5749       goto no_sdp;
5750   }
5751
5752   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
5753     goto open_failed;
5754
5755 done:
5756   if (async)
5757     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
5758
5759   return ret;
5760
5761   /* ERRORS */
5762 no_sdp:
5763   {
5764     GST_WARNING_OBJECT (src, "can't get sdp");
5765     src->open_error = TRUE;
5766     goto done;
5767   }
5768 open_failed:
5769   {
5770     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
5771     src->open_error = TRUE;
5772     goto done;
5773   }
5774 }
5775
5776 static GstRTSPResult
5777 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
5778 {
5779   GstRTSPMessage request = { 0 };
5780   GstRTSPMessage response = { 0 };
5781   GstRTSPResult res = GST_RTSP_OK;
5782   GList *walk;
5783   gchar *control;
5784
5785   GST_DEBUG_OBJECT (src, "TEARDOWN...");
5786
5787   if (src->state < GST_RTSP_STATE_READY) {
5788     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
5789     goto close;
5790   }
5791
5792   if (only_close)
5793     goto close;
5794
5795   /* construct a control url */
5796   if (src->control)
5797     control = src->control;
5798   else
5799     control = src->conninfo.url_str;
5800
5801   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
5802     goto not_supported;
5803
5804   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5805     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5806     gchar *setup_url;
5807     GstRTSPConnInfo *info;
5808
5809     /* try aggregate control first but do non-aggregate control otherwise */
5810     if (control)
5811       setup_url = control;
5812     else if ((setup_url = stream->conninfo.location) == NULL)
5813       continue;
5814
5815     if (src->conninfo.connection) {
5816       info = &src->conninfo;
5817     } else if (stream->conninfo.connection) {
5818       info = &stream->conninfo;
5819     } else {
5820       continue;
5821     }
5822     if (!info->connected)
5823       goto next;
5824
5825     /* do TEARDOWN */
5826     res =
5827         gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
5828     if (res < 0)
5829       goto create_request_failed;
5830
5831     if (async)
5832       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
5833
5834     if ((res =
5835             gst_rtspsrc_send (src, info->connection, &request, &response,
5836                 NULL)) < 0)
5837       goto send_error;
5838
5839     /* FIXME, parse result? */
5840     gst_rtsp_message_unset (&request);
5841     gst_rtsp_message_unset (&response);
5842
5843   next:
5844     /* early exit when we did aggregate control */
5845     if (control)
5846       break;
5847   }
5848
5849 close:
5850   /* close connections */
5851   GST_DEBUG_OBJECT (src, "closing connection...");
5852   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
5853   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5854     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5855     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
5856   }
5857
5858   /* cleanup */
5859   gst_rtspsrc_cleanup (src);
5860
5861   src->state = GST_RTSP_STATE_INVALID;
5862
5863   if (async)
5864     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
5865
5866   return res;
5867
5868   /* ERRORS */
5869 create_request_failed:
5870   {
5871     gchar *str = gst_rtsp_strresult (res);
5872
5873     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5874         ("Could not create request. (%s)", str));
5875     g_free (str);
5876     goto close;
5877   }
5878 send_error:
5879   {
5880     gchar *str = gst_rtsp_strresult (res);
5881
5882     gst_rtsp_message_unset (&request);
5883     if (res != GST_RTSP_EINTR) {
5884       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5885           ("Could not send message. (%s)", str));
5886     } else {
5887       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
5888     }
5889     g_free (str);
5890     goto close;
5891   }
5892 not_supported:
5893   {
5894     GST_DEBUG_OBJECT (src,
5895         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
5896     goto close;
5897   }
5898 }
5899
5900 /* RTP-Info is of the format:
5901  *
5902  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
5903  *
5904  * rtptime corresponds to the timestamp for the NPT time given in the header
5905  * seqbase corresponds to the next sequence number we received. This number
5906  * indicates the first seqnum after the seek and should be used to discard
5907  * packets that are from before the seek.
5908  */
5909 static gboolean
5910 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
5911 {
5912   gchar **infos;
5913   gint i, j;
5914
5915   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
5916
5917   infos = g_strsplit (rtpinfo, ",", 0);
5918   for (i = 0; infos[i]; i++) {
5919     gchar **fields;
5920     GstRTSPStream *stream;
5921     gint32 seqbase;
5922     gint64 timebase;
5923
5924     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
5925
5926     /* init values, types of seqbase and timebase are bigger than needed so we
5927      * can store -1 as uninitialized values */
5928     stream = NULL;
5929     seqbase = -1;
5930     timebase = -1;
5931
5932     /* parse url, find stream for url.
5933      * parse seq and rtptime. The seq number should be configured in the rtp
5934      * depayloader or session manager to detect gaps. Same for the rtptime, it
5935      * should be used to create an initial time newsegment. */
5936     fields = g_strsplit (infos[i], ";", 0);
5937     for (j = 0; fields[j]; j++) {
5938       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
5939       /* remove leading whitespace */
5940       fields[j] = g_strchug (fields[j]);
5941       if (g_str_has_prefix (fields[j], "url=")) {
5942         /* get the url and the stream */
5943         stream =
5944             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
5945       } else if (g_str_has_prefix (fields[j], "seq=")) {
5946         seqbase = atoi (fields[j] + 4);
5947       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
5948         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
5949       }
5950     }
5951     g_strfreev (fields);
5952     /* now we need to store the values for the caps of the stream */
5953     if (stream != NULL) {
5954       GST_DEBUG_OBJECT (src,
5955           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
5956           stream, seqbase, timebase);
5957
5958       /* we have a stream, configure detected params */
5959       stream->seqbase = seqbase;
5960       stream->timebase = timebase;
5961     }
5962   }
5963   g_strfreev (infos);
5964
5965   return TRUE;
5966 }
5967
5968 static void
5969 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
5970 {
5971   guint64 interval;
5972   GList *walk;
5973
5974   interval = strtoul (rtcp, NULL, 10);
5975   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
5976
5977   if (!interval)
5978     return;
5979
5980   interval *= GST_MSECOND;
5981
5982   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5983     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
5984
5985     /* already (optionally) retrieved this when configuring manager */
5986     if (stream->session) {
5987       GObject *rtpsession = stream->session;
5988
5989       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
5990           rtpsession);
5991       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
5992     }
5993   }
5994
5995   /* now it happens that (Xenon) server sending this may also provide bogus
5996    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
5997    * and just use RTP-Info to sync */
5998   if (src->manager) {
5999     GObjectClass *klass;
6000
6001     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
6002     if (g_object_class_find_property (klass, "rtcp-sync")) {
6003       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
6004       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
6005     }
6006   }
6007 }
6008
6009 static gdouble
6010 gst_rtspsrc_get_float (const gchar * dstr)
6011 {
6012   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6013
6014   /* canonicalise floating point string so we can handle float strings
6015    * in the form "24.930" or "24,930" irrespective of the current locale */
6016   g_strlcpy (s, dstr, sizeof (s));
6017   g_strdelimit (s, ",", '.');
6018   return g_ascii_strtod (s, NULL);
6019 }
6020
6021 static gchar *
6022 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
6023 {
6024   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6025
6026   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
6027     g_strlcpy (val_str, "now", sizeof (val_str));
6028   } else {
6029     if (segment->last_stop == 0) {
6030       g_strlcpy (val_str, "0", sizeof (val_str));
6031     } else {
6032       g_ascii_dtostr (val_str, sizeof (val_str),
6033           ((gdouble) segment->last_stop) / GST_SECOND);
6034     }
6035   }
6036   return g_strdup_printf ("npt=%s-", val_str);
6037 }
6038
6039 static void
6040 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
6041 {
6042   stream->timebase = -1;
6043   stream->seqbase = -1;
6044   if (stream->caps) {
6045     GstStructure *s;
6046
6047     stream->caps = gst_caps_make_writable (stream->caps);
6048     s = gst_caps_get_structure (stream->caps, 0);
6049     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
6050   }
6051 }
6052
6053 static GstRTSPResult
6054 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
6055 {
6056   GstRTSPResult res = GST_RTSP_OK;
6057
6058   if (src->state < GST_RTSP_STATE_READY) {
6059     res = GST_RTSP_ERROR;
6060     if (src->open_error) {
6061       GST_DEBUG_OBJECT (src, "the stream was in error");
6062       goto done;
6063     }
6064     if (async)
6065       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
6066
6067     if ((res = gst_rtspsrc_open (src, async)) < 0) {
6068       GST_DEBUG_OBJECT (src, "failed to open stream");
6069       goto done;
6070     }
6071   }
6072
6073 done:
6074   return res;
6075 }
6076
6077 static GstRTSPResult
6078 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6079 {
6080   GstRTSPMessage request = { 0 };
6081   GstRTSPMessage response = { 0 };
6082   GstRTSPResult res = GST_RTSP_OK;
6083   GList *walk;
6084   gchar *hval;
6085   gint hval_idx;
6086   gchar *control;
6087
6088   GST_DEBUG_OBJECT (src, "PLAY...");
6089
6090   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6091     goto open_failed;
6092
6093   if (!(src->methods & GST_RTSP_PLAY))
6094     goto not_supported;
6095
6096   if (src->state == GST_RTSP_STATE_PLAYING)
6097     goto was_playing;
6098
6099   if (!src->conninfo.connection || !src->conninfo.connected)
6100     goto done;
6101
6102   /* send some dummy packets before we activate the receive in the
6103    * udp sources */
6104   gst_rtspsrc_send_dummy_packets (src);
6105
6106   /* activate receive elements;
6107    * only in async case, since receive elements may not have been affected
6108    * by overall state change (e.g. not around yet),
6109    * do not mess with state in sync case (e.g. seeking) */
6110   if (async)
6111     gst_element_set_state (GST_ELEMENT_CAST (src), GST_STATE_PLAYING);
6112
6113   /* construct a control url */
6114   if (src->control)
6115     control = src->control;
6116   else
6117     control = src->conninfo.url_str;
6118
6119   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6120     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6121     gchar *setup_url;
6122     GstRTSPConnection *conn;
6123
6124     /* try aggregate control first but do non-aggregate control otherwise */
6125     if (control)
6126       setup_url = control;
6127     else if ((setup_url = stream->conninfo.location) == NULL)
6128       continue;
6129
6130     if (src->conninfo.connection) {
6131       conn = src->conninfo.connection;
6132     } else if (stream->conninfo.connection) {
6133       conn = stream->conninfo.connection;
6134     } else {
6135       continue;
6136     }
6137
6138     /* do play */
6139     res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6140     if (res < 0)
6141       goto create_request_failed;
6142
6143     if (src->need_range) {
6144       hval = gen_range_header (src, segment);
6145
6146       gst_rtsp_message_add_header (&request, GST_RTSP_HDR_RANGE, hval);
6147       g_free (hval);
6148     }
6149
6150     if (segment->rate != 1.0) {
6151       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6152
6153       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6154       if (src->skip)
6155         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6156       else
6157         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6158     }
6159
6160     if (async)
6161       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6162
6163     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6164       goto send_error;
6165
6166     /* seek may have silently failed as it is not supported */
6167     if (!(src->methods & GST_RTSP_PLAY)) {
6168       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6169       /* obviously it is supported as we made it here */
6170       src->methods |= GST_RTSP_PLAY;
6171       src->seekable = FALSE;
6172       /* but there is nothing to parse in the response,
6173        * so convey we have no idea and not to expect anything particular */
6174       clear_rtp_base (src, stream);
6175       if (control) {
6176         GList *run;
6177
6178         /* need to do for all streams */
6179         for (run = src->streams; run; run = g_list_next (run))
6180           clear_rtp_base (src, (GstRTSPStream *) run->data);
6181       }
6182       /* NOTE the above also disables npt based eos detection */
6183       /* and below forces position to 0,
6184        * which is visible feedback we lost the plot */
6185       segment->start = segment->last_stop = src->last_pos;
6186     }
6187
6188     gst_rtsp_message_unset (&request);
6189
6190     /* parse RTP npt field. This is the current position in the stream (Normal
6191      * Play Time) and should be put in the NEWSEGMENT position field. */
6192     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6193             0) == GST_RTSP_OK)
6194       gst_rtspsrc_parse_range (src, hval, segment);
6195
6196     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6197     segment->rate = 1.0;
6198
6199     /* parse Speed header. This is the intended playback rate of the stream
6200      * and should be put in the NEWSEGMENT rate field. */
6201     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6202             0) == GST_RTSP_OK) {
6203       segment->rate = gst_rtspsrc_get_float (hval);
6204     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6205             &hval, 0) == GST_RTSP_OK) {
6206       segment->rate = gst_rtspsrc_get_float (hval);
6207     }
6208
6209     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6210      * for the RTP packets. If this is not present, we assume all starts from 0...
6211      * This is info for the RTP session manager that we pass to it in caps. */
6212     hval_idx = 0;
6213     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6214             &hval, hval_idx++) == GST_RTSP_OK)
6215       gst_rtspsrc_parse_rtpinfo (src, hval);
6216
6217     /* some servers indicate RTCP parameters in PLAY response,
6218      * rather than properly in SDP */
6219     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6220             &hval, 0) == GST_RTSP_OK)
6221       gst_rtspsrc_handle_rtcp_interval (src, hval);
6222
6223     gst_rtsp_message_unset (&response);
6224
6225     /* early exit when we did aggregate control */
6226     if (control)
6227       break;
6228   }
6229   /* set again when needed */
6230   src->need_range = FALSE;
6231
6232   /* configure the caps of the streams after we parsed all headers. */
6233   gst_rtspsrc_configure_caps (src, segment);
6234
6235   src->running = TRUE;
6236   src->base_time = -1;
6237   src->state = GST_RTSP_STATE_PLAYING;
6238
6239   /* mark discont */
6240   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6241   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6242     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6243     stream->discont = TRUE;
6244   }
6245
6246 done:
6247   if (async)
6248     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6249
6250   return res;
6251
6252   /* ERRORS */
6253 open_failed:
6254   {
6255     GST_DEBUG_OBJECT (src, "failed to open stream");
6256     goto done;
6257   }
6258 not_supported:
6259   {
6260     GST_DEBUG_OBJECT (src, "PLAY is not supported");
6261     goto done;
6262   }
6263 was_playing:
6264   {
6265     GST_DEBUG_OBJECT (src, "we were already PLAYING");
6266     goto done;
6267   }
6268 create_request_failed:
6269   {
6270     gchar *str = gst_rtsp_strresult (res);
6271
6272     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6273         ("Could not create request. (%s)", str));
6274     g_free (str);
6275     goto done;
6276   }
6277 send_error:
6278   {
6279     gchar *str = gst_rtsp_strresult (res);
6280
6281     gst_rtsp_message_unset (&request);
6282     if (res != GST_RTSP_EINTR) {
6283       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6284           ("Could not send message. (%s)", str));
6285     } else {
6286       GST_WARNING_OBJECT (src, "PLAY interrupted");
6287     }
6288     g_free (str);
6289     goto done;
6290   }
6291 }
6292
6293 static GstRTSPResult
6294 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean idle, gboolean async)
6295 {
6296   GstRTSPResult res = GST_RTSP_OK;
6297   GstRTSPMessage request = { 0 };
6298   GstRTSPMessage response = { 0 };
6299   GList *walk;
6300   gchar *control;
6301
6302   GST_DEBUG_OBJECT (src, "PAUSE...");
6303
6304   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6305     goto open_failed;
6306
6307   if (!(src->methods & GST_RTSP_PAUSE))
6308     goto not_supported;
6309
6310   if (src->state == GST_RTSP_STATE_READY)
6311     goto was_paused;
6312
6313   if (!src->conninfo.connection || !src->conninfo.connected)
6314     goto no_connection;
6315
6316   /* construct a control url */
6317   if (src->control)
6318     control = src->control;
6319   else
6320     control = src->conninfo.url_str;
6321
6322   /* loop over the streams. We might exit the loop early when we could do an
6323    * aggregate control */
6324   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6325     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6326     GstRTSPConnection *conn;
6327     gchar *setup_url;
6328
6329     /* try aggregate control first but do non-aggregate control otherwise */
6330     if (control)
6331       setup_url = control;
6332     else if ((setup_url = stream->conninfo.location) == NULL)
6333       continue;
6334
6335     if (src->conninfo.connection) {
6336       conn = src->conninfo.connection;
6337     } else if (stream->conninfo.connection) {
6338       conn = stream->conninfo.connection;
6339     } else {
6340       continue;
6341     }
6342
6343     if (async)
6344       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6345           ("Sending PAUSE request"));
6346
6347     if ((res =
6348             gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6349                 setup_url)) < 0)
6350       goto create_request_failed;
6351
6352     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6353       goto send_error;
6354
6355     gst_rtsp_message_unset (&request);
6356     gst_rtsp_message_unset (&response);
6357
6358     /* exit early when we did agregate control */
6359     if (control)
6360       break;
6361   }
6362
6363 no_connection:
6364   src->state = GST_RTSP_STATE_READY;
6365
6366 done:
6367   if (async)
6368     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6369
6370   return res;
6371
6372   /* ERRORS */
6373 open_failed:
6374   {
6375     GST_DEBUG_OBJECT (src, "failed to open stream");
6376     goto done;
6377   }
6378 not_supported:
6379   {
6380     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6381     goto done;
6382   }
6383 was_paused:
6384   {
6385     GST_DEBUG_OBJECT (src, "we were already PAUSED");
6386     goto done;
6387   }
6388 create_request_failed:
6389   {
6390     gchar *str = gst_rtsp_strresult (res);
6391
6392     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6393         ("Could not create request. (%s)", str));
6394     g_free (str);
6395     goto done;
6396   }
6397 send_error:
6398   {
6399     gchar *str = gst_rtsp_strresult (res);
6400
6401     gst_rtsp_message_unset (&request);
6402     if (res != GST_RTSP_EINTR) {
6403       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6404           ("Could not send message. (%s)", str));
6405     } else {
6406       GST_WARNING_OBJECT (src, "PAUSE interrupted");
6407     }
6408     g_free (str);
6409     goto done;
6410   }
6411 }
6412
6413 static void
6414 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6415 {
6416   GstRTSPSrc *rtspsrc;
6417
6418   rtspsrc = GST_RTSPSRC (bin);
6419
6420   switch (GST_MESSAGE_TYPE (message)) {
6421     case GST_MESSAGE_EOS:
6422       gst_message_unref (message);
6423       break;
6424     case GST_MESSAGE_ELEMENT:
6425     {
6426       const GstStructure *s = gst_message_get_structure (message);
6427
6428       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6429         gboolean ignore_timeout;
6430
6431         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6432
6433         GST_OBJECT_LOCK (rtspsrc);
6434         ignore_timeout = rtspsrc->ignore_timeout;
6435         rtspsrc->ignore_timeout = TRUE;
6436         GST_OBJECT_UNLOCK (rtspsrc);
6437
6438         /* we only act on the first udp timeout message, others are irrelevant
6439          * and can be ignored. */
6440         if (!ignore_timeout)
6441           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, TRUE);
6442         /* eat and free */
6443         gst_message_unref (message);
6444         return;
6445       }
6446       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6447       break;
6448     }
6449     case GST_MESSAGE_ERROR:
6450     {
6451       GstObject *udpsrc;
6452       GstRTSPStream *stream;
6453       GstFlowReturn ret;
6454
6455       udpsrc = GST_MESSAGE_SRC (message);
6456
6457       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
6458           GST_ELEMENT_NAME (udpsrc));
6459
6460       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
6461       if (!stream)
6462         goto forward;
6463
6464       /* we ignore the RTCP udpsrc */
6465       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
6466         goto done;
6467
6468       /* if we get error messages from the udp sources, that's not a problem as
6469        * long as not all of them error out. We also don't really know what the
6470        * problem is, the message does not give enough detail... */
6471       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
6472       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
6473       if (ret != GST_FLOW_OK)
6474         goto forward;
6475
6476     done:
6477       gst_message_unref (message);
6478       break;
6479
6480     forward:
6481       /* fatal but not our message, forward */
6482       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6483       break;
6484     }
6485     default:
6486     {
6487       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6488       break;
6489     }
6490   }
6491 }
6492
6493 /* the thread where everything happens */
6494 static void
6495 gst_rtspsrc_thread (GstRTSPSrc * src)
6496 {
6497   gint cmd;
6498   GstRTSPResult ret;
6499   gboolean running = FALSE;
6500
6501   GST_OBJECT_LOCK (src);
6502   cmd = src->loop_cmd;
6503   src->loop_cmd = CMD_WAIT;
6504   GST_DEBUG_OBJECT (src, "got command %d", cmd);
6505
6506   /* we got the message command, so ensure communication is possible again */
6507   gst_rtspsrc_connection_flush (src, FALSE);
6508
6509   /* we allow these to be interrupted */
6510   if (cmd == CMD_LOOP || cmd == CMD_CLOSE || cmd == CMD_PAUSE)
6511     src->waiting = TRUE;
6512   GST_OBJECT_UNLOCK (src);
6513
6514   switch (cmd) {
6515     case CMD_OPEN:
6516       ret = gst_rtspsrc_open (src, TRUE);
6517       break;
6518     case CMD_PLAY:
6519       ret = gst_rtspsrc_play (src, &src->segment, TRUE);
6520       if (ret == GST_RTSP_OK)
6521         running = TRUE;
6522       break;
6523     case CMD_PAUSE:
6524       ret = gst_rtspsrc_pause (src, TRUE, TRUE);
6525       if (ret == GST_RTSP_OK)
6526         running = TRUE;
6527       break;
6528     case CMD_CLOSE:
6529       ret = gst_rtspsrc_close (src, TRUE, FALSE);
6530       break;
6531     case CMD_LOOP:
6532       running = gst_rtspsrc_loop (src);
6533       break;
6534     case CMD_RECONNECT:
6535       ret = gst_rtspsrc_reconnect (src, FALSE);
6536       if (ret == GST_RTSP_OK)
6537         running = TRUE;
6538       break;
6539     default:
6540       break;
6541   }
6542
6543   GST_OBJECT_LOCK (src);
6544   /* and go back to sleep */
6545   if (src->loop_cmd == CMD_WAIT) {
6546     if (running)
6547       src->loop_cmd = CMD_LOOP;
6548     else if (src->task)
6549       gst_task_pause (src->task);
6550   }
6551   /* reset waiting */
6552   src->waiting = FALSE;
6553   GST_OBJECT_UNLOCK (src);
6554 }
6555
6556 static gboolean
6557 gst_rtspsrc_start (GstRTSPSrc * src)
6558 {
6559   GST_DEBUG_OBJECT (src, "starting");
6560
6561   GST_OBJECT_LOCK (src);
6562
6563   src->loop_cmd = CMD_WAIT;
6564
6565   if (src->task == NULL) {
6566     src->task = gst_task_create ((GstTaskFunction) gst_rtspsrc_thread, src);
6567     if (src->task == NULL)
6568       goto task_error;
6569
6570     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
6571   }
6572   GST_OBJECT_UNLOCK (src);
6573
6574   return TRUE;
6575
6576   /* ERRORS */
6577 task_error:
6578   {
6579     GST_ERROR_OBJECT (src, "failed to create task");
6580     return FALSE;
6581   }
6582 }
6583
6584 static gboolean
6585 gst_rtspsrc_stop (GstRTSPSrc * src)
6586 {
6587   GstTask *task;
6588
6589   GST_DEBUG_OBJECT (src, "stopping");
6590
6591   /* also cancels pending task */
6592   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, TRUE);
6593
6594   GST_OBJECT_LOCK (src);
6595   if ((task = src->task)) {
6596     src->task = NULL;
6597     GST_OBJECT_UNLOCK (src);
6598
6599     gst_task_stop (task);
6600
6601     /* make sure it is not running */
6602     GST_RTSP_STREAM_LOCK (src);
6603     GST_RTSP_STREAM_UNLOCK (src);
6604
6605     /* now wait for the task to finish */
6606     gst_task_join (task);
6607
6608     /* and free the task */
6609     gst_object_unref (GST_OBJECT (task));
6610
6611     GST_OBJECT_LOCK (src);
6612   }
6613   GST_OBJECT_UNLOCK (src);
6614
6615   /* ensure synchronously all is closed and clean */
6616   gst_rtspsrc_close (src, FALSE, TRUE);
6617
6618   return TRUE;
6619 }
6620
6621 static GstStateChangeReturn
6622 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
6623 {
6624   GstRTSPSrc *rtspsrc;
6625   GstStateChangeReturn ret;
6626
6627   rtspsrc = GST_RTSPSRC (element);
6628
6629   switch (transition) {
6630     case GST_STATE_CHANGE_NULL_TO_READY:
6631       if (!gst_rtspsrc_start (rtspsrc))
6632         goto start_failed;
6633       break;
6634     case GST_STATE_CHANGE_READY_TO_PAUSED:
6635       /* init some state */
6636       rtspsrc->cur_protocols = rtspsrc->protocols;
6637       /* first attempt, don't ignore timeouts */
6638       rtspsrc->ignore_timeout = FALSE;
6639       rtspsrc->open_error = FALSE;
6640       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, FALSE);
6641       break;
6642     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6643     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6644       /* unblock the tcp tasks and make the loop waiting */
6645       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, TRUE);
6646       break;
6647     case GST_STATE_CHANGE_PAUSED_TO_READY:
6648       break;
6649     default:
6650       break;
6651   }
6652
6653   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6654   if (ret == GST_STATE_CHANGE_FAILURE)
6655     goto done;
6656
6657   switch (transition) {
6658     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6659       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, FALSE);
6660       break;
6661     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6662       /* send pause request and keep the idle task around */
6663       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, FALSE);
6664       ret = GST_STATE_CHANGE_NO_PREROLL;
6665       break;
6666     case GST_STATE_CHANGE_READY_TO_PAUSED:
6667       ret = GST_STATE_CHANGE_NO_PREROLL;
6668       break;
6669     case GST_STATE_CHANGE_PAUSED_TO_READY:
6670       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, FALSE);
6671       break;
6672     case GST_STATE_CHANGE_READY_TO_NULL:
6673       gst_rtspsrc_stop (rtspsrc);
6674       break;
6675     default:
6676       break;
6677   }
6678
6679 done:
6680   return ret;
6681
6682 start_failed:
6683   {
6684     GST_DEBUG_OBJECT (rtspsrc, "start failed");
6685     return GST_STATE_CHANGE_FAILURE;
6686   }
6687 }
6688
6689 static gboolean
6690 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
6691 {
6692   gboolean res;
6693   GstRTSPSrc *rtspsrc;
6694
6695   rtspsrc = GST_RTSPSRC (element);
6696
6697   if (GST_EVENT_IS_DOWNSTREAM (event)) {
6698     res = gst_rtspsrc_push_event (rtspsrc, event, TRUE);
6699   } else {
6700     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
6701   }
6702
6703   return res;
6704 }
6705
6706
6707 /*** GSTURIHANDLER INTERFACE *************************************************/
6708
6709 static GstURIType
6710 gst_rtspsrc_uri_get_type (void)
6711 {
6712   return GST_URI_SRC;
6713 }
6714
6715 static gchar **
6716 gst_rtspsrc_uri_get_protocols (void)
6717 {
6718   static const gchar *protocols[] =
6719       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp", NULL };
6720
6721   return (gchar **) protocols;
6722 }
6723
6724 static const gchar *
6725 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
6726 {
6727   GstRTSPSrc *src = GST_RTSPSRC (handler);
6728
6729   /* should not dup */
6730   return src->conninfo.location;
6731 }
6732
6733 static gboolean
6734 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri)
6735 {
6736   GstRTSPSrc *src;
6737   GstRTSPResult res;
6738   GstRTSPUrl *newurl = NULL;
6739   GstSDPMessage *sdp = NULL;
6740
6741   src = GST_RTSPSRC (handler);
6742
6743   /* same URI, we're fine */
6744   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
6745     goto was_ok;
6746
6747   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
6748     if ((res = gst_sdp_message_new (&sdp) < 0))
6749       goto sdp_failed;
6750
6751     GST_DEBUG_OBJECT (src, "parsing SDP message");
6752     if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
6753       goto invalid_sdp;
6754   } else {
6755     /* try to parse */
6756     GST_DEBUG_OBJECT (src, "parsing URI");
6757     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
6758       goto parse_error;
6759   }
6760
6761   /* if worked, free previous and store new url object along with the original
6762    * location. */
6763   GST_DEBUG_OBJECT (src, "configuring URI");
6764   g_free (src->conninfo.location);
6765   src->conninfo.location = g_strdup (uri);
6766   gst_rtsp_url_free (src->conninfo.url);
6767   src->conninfo.url = newurl;
6768   g_free (src->conninfo.url_str);
6769   if (newurl)
6770     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
6771   else
6772     src->conninfo.url_str = NULL;
6773
6774   if (src->sdp)
6775     gst_sdp_message_free (src->sdp);
6776   src->sdp = sdp;
6777   src->from_sdp = sdp != NULL;
6778
6779   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
6780   GST_DEBUG_OBJECT (src, "request uri is: %s",
6781       GST_STR_NULL (src->conninfo.url_str));
6782
6783   return TRUE;
6784
6785   /* Special cases */
6786 was_ok:
6787   {
6788     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
6789     return TRUE;
6790   }
6791 sdp_failed:
6792   {
6793     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
6794     return FALSE;
6795   }
6796 invalid_sdp:
6797   {
6798     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
6799         GST_STR_NULL (uri));
6800     gst_sdp_message_free (sdp);
6801     return FALSE;
6802   }
6803 parse_error:
6804   {
6805     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
6806         GST_STR_NULL (uri), res);
6807     return FALSE;
6808   }
6809 }
6810
6811 static void
6812 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
6813 {
6814   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
6815
6816   iface->get_type = gst_rtspsrc_uri_get_type;
6817   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
6818   iface->get_uri = gst_rtspsrc_uri_get_uri;
6819   iface->set_uri = gst_rtspsrc_uri_set_uri;
6820 }