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