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