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