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