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