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   LAST_SIGNAL
127 };
128
129 enum _GstRtspSrcRtcpSyncMode
130 {
131   RTCP_SYNC_ALWAYS,
132   RTCP_SYNC_INITIAL,
133   RTCP_SYNC_RTP
134 };
135
136 enum _GstRtspSrcBufferMode
137 {
138   BUFFER_MODE_NONE,
139   BUFFER_MODE_SLAVE,
140   BUFFER_MODE_BUFFER,
141   BUFFER_MODE_AUTO,
142   BUFFER_MODE_SYNCED
143 };
144
145 #define GST_TYPE_RTSP_SRC_BUFFER_MODE (gst_rtsp_src_buffer_mode_get_type())
146 static GType
147 gst_rtsp_src_buffer_mode_get_type (void)
148 {
149   static GType buffer_mode_type = 0;
150   static const GEnumValue buffer_modes[] = {
151     {BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
152     {BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
153     {BUFFER_MODE_BUFFER, "Do low/high watermark buffering", "buffer"},
154     {BUFFER_MODE_AUTO, "Choose mode depending on stream live", "auto"},
155     {BUFFER_MODE_SYNCED, "Synchronized sender and receiver clocks", "synced"},
156     {0, NULL, NULL},
157   };
158
159   if (!buffer_mode_type) {
160     buffer_mode_type =
161         g_enum_register_static ("GstRTSPSrcBufferMode", buffer_modes);
162   }
163   return buffer_mode_type;
164 }
165
166 #define DEFAULT_LOCATION         NULL
167 #define DEFAULT_PROTOCOLS        GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | GST_RTSP_LOWER_TRANS_TCP
168 #define DEFAULT_DEBUG            FALSE
169 #define DEFAULT_RETRY            20
170 #define DEFAULT_TIMEOUT          5000000
171 #define DEFAULT_UDP_BUFFER_SIZE  0x80000
172 #define DEFAULT_TCP_TIMEOUT      20000000
173 #define DEFAULT_LATENCY_MS       2000
174 #define DEFAULT_DROP_ON_LATENCY  FALSE
175 #define DEFAULT_DO_RETRANSMISSION 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_DO_RETRANSMISSION,
206   PROP_CONNECTION_SPEED,
207   PROP_NAT_METHOD,
208   PROP_DO_RTCP,
209   PROP_DO_RTSP_KEEP_ALIVE,
210   PROP_PROXY,
211   PROP_PROXY_ID,
212   PROP_PROXY_PW,
213   PROP_RTP_BLOCKSIZE,
214   PROP_USER_ID,
215   PROP_USER_PW,
216   PROP_BUFFER_MODE,
217   PROP_PORT_RANGE,
218   PROP_UDP_BUFFER_SIZE,
219   PROP_SHORT_HEADER,
220   PROP_PROBATION,
221   PROP_UDP_RECONNECT,
222   PROP_MULTICAST_IFACE,
223   PROP_NTP_SYNC,
224   PROP_USE_PIPELINE_CLOCK,
225   PROP_SDES,
226   PROP_TLS_VALIDATION_FLAGS,
227   PROP_LAST
228 };
229
230 #define GST_TYPE_RTSP_NAT_METHOD (gst_rtsp_nat_method_get_type())
231 static GType
232 gst_rtsp_nat_method_get_type (void)
233 {
234   static GType rtsp_nat_method_type = 0;
235   static const GEnumValue rtsp_nat_method[] = {
236     {GST_RTSP_NAT_NONE, "None", "none"},
237     {GST_RTSP_NAT_DUMMY, "Send Dummy packets", "dummy"},
238     {0, NULL, NULL},
239   };
240
241   if (!rtsp_nat_method_type) {
242     rtsp_nat_method_type =
243         g_enum_register_static ("GstRTSPNatMethod", rtsp_nat_method);
244   }
245   return rtsp_nat_method_type;
246 }
247
248 static void gst_rtspsrc_finalize (GObject * object);
249
250 static void gst_rtspsrc_set_property (GObject * object, guint prop_id,
251     const GValue * value, GParamSpec * pspec);
252 static void gst_rtspsrc_get_property (GObject * object, guint prop_id,
253     GValue * value, GParamSpec * pspec);
254
255 static GstClock *gst_rtspsrc_provide_clock (GstElement * element);
256
257 static void gst_rtspsrc_uri_handler_init (gpointer g_iface,
258     gpointer iface_data);
259
260 static void gst_rtspsrc_sdp_attributes_to_caps (GArray * attributes,
261     GstCaps * caps);
262
263 static gboolean gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy);
264 static void gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout);
265
266 static GstCaps *gst_rtspsrc_media_to_caps (gint pt, const GstSDPMedia * media);
267
268 static GstStateChangeReturn gst_rtspsrc_change_state (GstElement * element,
269     GstStateChange transition);
270 static gboolean gst_rtspsrc_send_event (GstElement * element, GstEvent * event);
271 static void gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message);
272
273 static gboolean gst_rtspsrc_setup_auth (GstRTSPSrc * src,
274     GstRTSPMessage * response);
275
276 static gboolean gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd,
277     gint mask);
278 static GstRTSPResult gst_rtspsrc_send_cb (GstRTSPExtension * ext,
279     GstRTSPMessage * request, GstRTSPMessage * response, GstRTSPSrc * src);
280
281 static GstRTSPResult gst_rtspsrc_open (GstRTSPSrc * src, gboolean async);
282 static GstRTSPResult gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment,
283     gboolean async);
284 static GstRTSPResult gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async);
285 static GstRTSPResult gst_rtspsrc_close (GstRTSPSrc * src, gboolean async,
286     gboolean only_close);
287
288 static gboolean gst_rtspsrc_uri_set_uri (GstURIHandler * handler,
289     const gchar * uri, GError ** error);
290 static gchar *gst_rtspsrc_uri_get_uri (GstURIHandler * handler);
291
292 static gboolean gst_rtspsrc_activate_streams (GstRTSPSrc * src);
293 static gboolean gst_rtspsrc_loop (GstRTSPSrc * src);
294 static gboolean gst_rtspsrc_stream_push_event (GstRTSPSrc * src,
295     GstRTSPStream * stream, GstEvent * event);
296 static gboolean gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event);
297
298 /* commands we send to out loop to notify it of events */
299 #define CMD_OPEN        (1 << 0)
300 #define CMD_PLAY        (1 << 1)
301 #define CMD_PAUSE       (1 << 2)
302 #define CMD_CLOSE       (1 << 3)
303 #define CMD_WAIT        (1 << 4)
304 #define CMD_RECONNECT   (1 << 5)
305 #define CMD_LOOP        (1 << 6)
306
307 /* mask for all commands */
308 #define CMD_ALL         ((CMD_LOOP << 1) - 1)
309
310 #define GST_ELEMENT_PROGRESS(el, type, code, text)      \
311 G_STMT_START {                                          \
312   gchar *__txt = _gst_element_error_printf text;        \
313   gst_element_post_message (GST_ELEMENT_CAST (el),      \
314       gst_message_new_progress (GST_OBJECT_CAST (el),   \
315           GST_PROGRESS_TYPE_ ##type, code, __txt));     \
316   g_free (__txt);                                       \
317 } G_STMT_END
318
319 static guint gst_rtspsrc_signals[LAST_SIGNAL] = { 0 };
320
321 #define gst_rtspsrc_parent_class parent_class
322 G_DEFINE_TYPE_WITH_CODE (GstRTSPSrc, gst_rtspsrc, GST_TYPE_BIN,
323     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_rtspsrc_uri_handler_init));
324
325 static gboolean
326 default_select_stream (GstRTSPSrc * src, guint id, GstCaps * caps)
327 {
328   GST_DEBUG_OBJECT (src, "default handler");
329   return TRUE;
330 }
331
332 static gboolean
333 select_stream_accum (GSignalInvocationHint * ihint,
334     GValue * return_accu, const GValue * handler_return, gpointer data)
335 {
336   gboolean myboolean;
337
338   myboolean = g_value_get_boolean (handler_return);
339   GST_DEBUG ("accum %d", myboolean);
340   g_value_set_boolean (return_accu, myboolean);
341
342   /* stop emission if FALSE */
343   return myboolean;
344 }
345
346 static void
347 gst_rtspsrc_class_init (GstRTSPSrcClass * klass)
348 {
349   GObjectClass *gobject_class;
350   GstElementClass *gstelement_class;
351   GstBinClass *gstbin_class;
352
353   gobject_class = (GObjectClass *) klass;
354   gstelement_class = (GstElementClass *) klass;
355   gstbin_class = (GstBinClass *) klass;
356
357   GST_DEBUG_CATEGORY_INIT (rtspsrc_debug, "rtspsrc", 0, "RTSP src");
358
359   gobject_class->set_property = gst_rtspsrc_set_property;
360   gobject_class->get_property = gst_rtspsrc_get_property;
361
362   gobject_class->finalize = gst_rtspsrc_finalize;
363
364   g_object_class_install_property (gobject_class, PROP_LOCATION,
365       g_param_spec_string ("location", "RTSP Location",
366           "Location of the RTSP url to read",
367           DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
368
369   g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
370       g_param_spec_flags ("protocols", "Protocols",
371           "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
372           DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
373
374   g_object_class_install_property (gobject_class, PROP_DEBUG,
375       g_param_spec_boolean ("debug", "Debug",
376           "Dump request and response messages to stdout",
377           DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
378
379   g_object_class_install_property (gobject_class, PROP_RETRY,
380       g_param_spec_uint ("retry", "Retry",
381           "Max number of retries when allocating RTP ports.",
382           0, G_MAXUINT16, DEFAULT_RETRY,
383           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
384
385   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
386       g_param_spec_uint64 ("timeout", "Timeout",
387           "Retry TCP transport after UDP timeout microseconds (0 = disabled)",
388           0, G_MAXUINT64, DEFAULT_TIMEOUT,
389           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
390
391   g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
392       g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
393           "Fail after timeout microseconds on TCP connections (0 = disabled)",
394           0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
395           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
396
397   g_object_class_install_property (gobject_class, PROP_LATENCY,
398       g_param_spec_uint ("latency", "Buffer latency in ms",
399           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
400           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
401
402   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
403       g_param_spec_boolean ("drop-on-latency",
404           "Drop buffers when maximum latency is reached",
405           "Tells the jitterbuffer to never exceed the given latency in size",
406           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
407
408   g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
409       g_param_spec_boolean ("do-retransmission", "Do retransmission",
410           "Send retransmission events upstream when a packet is late",
411           DEFAULT_DO_RETRANSMISSION,
412           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
413
414   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
415       g_param_spec_uint64 ("connection-speed", "Connection Speed",
416           "Network connection speed in kbps (0 = unknown)",
417           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
418           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
419
420   g_object_class_install_property (gobject_class, PROP_NAT_METHOD,
421       g_param_spec_enum ("nat-method", "NAT Method",
422           "Method to use for traversing firewalls and NAT",
423           GST_TYPE_RTSP_NAT_METHOD, DEFAULT_NAT_METHOD,
424           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
425
426   /**
427    * GstRTSPSrc:do-rtcp:
428    *
429    * Enable RTCP support. Some old server don't like RTCP and then this property
430    * needs to be set to FALSE.
431    */
432   g_object_class_install_property (gobject_class, PROP_DO_RTCP,
433       g_param_spec_boolean ("do-rtcp", "Do RTCP",
434           "Send RTCP packets, disable for old incompatible server.",
435           DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
436
437   /**
438    * GstRTSPSrc:do-rtsp-keep-alive:
439    *
440    * Enable RTSP keep alive support. Some old server don't like RTSP
441    * keep alive and then this property needs to be set to FALSE.
442    */
443   g_object_class_install_property (gobject_class, PROP_DO_RTSP_KEEP_ALIVE,
444       g_param_spec_boolean ("do-rtsp-keep-alive", "Do RTSP Keep Alive",
445           "Send RTSP keep alive packets, disable for old incompatible server.",
446           DEFAULT_DO_RTSP_KEEP_ALIVE,
447           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
448
449   /**
450    * GstRTSPSrc:proxy:
451    *
452    * Set the proxy parameters. This has to be a string of the format
453    * [http://][user:passwd@]host[:port].
454    */
455   g_object_class_install_property (gobject_class, PROP_PROXY,
456       g_param_spec_string ("proxy", "Proxy",
457           "Proxy settings for HTTP tunneling. Format: [http://][user:passwd@]host[:port]",
458           DEFAULT_PROXY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
459   /**
460    * GstRTSPSrc:proxy-id:
461    *
462    * Sets the proxy URI user id for authentication. If the URI set via the
463    * "proxy" property contains a user-id already, that will take precedence.
464    *
465    * Since: 1.2
466    */
467   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
468       g_param_spec_string ("proxy-id", "proxy-id",
469           "HTTP proxy URI user id for authentication", "",
470           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
471   /**
472    * GstRTSPSrc:proxy-pw:
473    *
474    * Sets the proxy URI password for authentication. If the URI set via the
475    * "proxy" property contains a password already, that will take precedence.
476    *
477    * Since: 1.2
478    */
479   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
480       g_param_spec_string ("proxy-pw", "proxy-pw",
481           "HTTP proxy URI user password for authentication", "",
482           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
483
484   /**
485    * GstRTSPSrc:rtp-blocksize:
486    *
487    * RTP package size to suggest to server.
488    */
489   g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
490       g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
491           "RTP package size to suggest to server (0 = disabled)",
492           0, 65536, DEFAULT_RTP_BLOCKSIZE,
493           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
494
495   g_object_class_install_property (gobject_class,
496       PROP_USER_ID,
497       g_param_spec_string ("user-id", "user-id",
498           "RTSP location URI user id for authentication", DEFAULT_USER_ID,
499           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
500   g_object_class_install_property (gobject_class, PROP_USER_PW,
501       g_param_spec_string ("user-pw", "user-pw",
502           "RTSP location URI user password for authentication", DEFAULT_USER_PW,
503           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
504
505   /**
506    * GstRTSPSrc:buffer-mode:
507    *
508    * Control the buffering and timestamping mode used by the jitterbuffer.
509    */
510   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
511       g_param_spec_enum ("buffer-mode", "Buffer Mode",
512           "Control the buffering algorithm in use",
513           GST_TYPE_RTSP_SRC_BUFFER_MODE, DEFAULT_BUFFER_MODE,
514           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
515
516   /**
517    * GstRTSPSrc:port-range:
518    *
519    * Configure the client port numbers that can be used to recieve RTP and
520    * RTCP.
521    */
522   g_object_class_install_property (gobject_class, PROP_PORT_RANGE,
523       g_param_spec_string ("port-range", "Port range",
524           "Client port range that can be used to receive RTP and RTCP data, "
525           "eg. 3000-3005 (NULL = no restrictions)", DEFAULT_PORT_RANGE,
526           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
527
528   /**
529    * GstRTSPSrc:udp-buffer-size:
530    *
531    * Size of the kernel UDP receive buffer in bytes.
532    */
533   g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
534       g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
535           "Size of the kernel UDP receive buffer in bytes, 0=default",
536           0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
537           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
538
539   /**
540    * GstRTSPSrc:short-header:
541    *
542    * Only send the basic RTSP headers for broken encoders.
543    */
544   g_object_class_install_property (gobject_class, PROP_SHORT_HEADER,
545       g_param_spec_boolean ("short-header", "Short Header",
546           "Only send the basic RTSP headers for broken encoders",
547           DEFAULT_SHORT_HEADER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
548
549   g_object_class_install_property (gobject_class, PROP_PROBATION,
550       g_param_spec_uint ("probation", "Number of probations",
551           "Consecutive packet sequence numbers to accept the source",
552           0, G_MAXUINT, DEFAULT_PROBATION,
553           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
554
555   g_object_class_install_property (gobject_class, PROP_UDP_RECONNECT,
556       g_param_spec_boolean ("udp-reconnect", "Reconnect to the server",
557           "Reconnect to the server if RTSP connection is closed when doing UDP",
558           DEFAULT_UDP_RECONNECT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
559
560   g_object_class_install_property (gobject_class, PROP_MULTICAST_IFACE,
561       g_param_spec_string ("multicast-iface", "Multicast Interface",
562           "The network interface on which to join the multicast group",
563           DEFAULT_MULTICAST_IFACE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
564
565   g_object_class_install_property (gobject_class, PROP_NTP_SYNC,
566       g_param_spec_boolean ("ntp-sync", "Sync on NTP clock",
567           "Synchronize received streams to the NTP clock", DEFAULT_NTP_SYNC,
568           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
569
570   g_object_class_install_property (gobject_class, PROP_USE_PIPELINE_CLOCK,
571       g_param_spec_boolean ("use-pipeline-clock", "Use pipeline clock",
572           "Use the pipeline running-time to set the NTP time in the RTCP SR messages",
573           DEFAULT_USE_PIPELINE_CLOCK,
574           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
575
576   g_object_class_install_property (gobject_class, PROP_SDES,
577       g_param_spec_boxed ("sdes", "SDES",
578           "The SDES items of this session",
579           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
580
581   /**
582    * GstRTSPSrc::tls-validation-flags:
583    *
584    * TLS certificate validation flags used to validate server
585    * certificate.
586    *
587    * Since: 1.2.1
588    */
589   g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
590       g_param_spec_flags ("tls-validation-flags", "TLS validation flags",
591           "TLS certificate validation flags used to validate the server certificate",
592           G_TYPE_TLS_CERTIFICATE_FLAGS, DEFAULT_TLS_VALIDATION_FLAGS,
593           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
594
595   /**
596    * GstRTSPSrc::handle-request:
597    * @rtspsrc: a #GstRTSPSrc
598    * @request: a #GstRTSPMessage
599    * @response: a #GstRTSPMessage
600    *
601    * Handle a server request in @request and prepare @response.
602    *
603    * This signal is called from the streaming thread, you should therefore not
604    * do any state changes on @rtspsrc because this might deadlock. If you want
605    * to modify the state as a result of this signal, post a
606    * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
607    * in some other way.
608    *
609    * Since: 1.2
610    */
611   gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST] =
612       g_signal_new ("handle-request", G_TYPE_FROM_CLASS (klass), 0,
613       0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
614       G_TYPE_POINTER, G_TYPE_POINTER);
615
616   /**
617    * GstRTSPSrc::on-sdp:
618    * @rtspsrc: a #GstRTSPSrc
619    * @sdp: a #GstSDPMessage
620    *
621    * Emited when the client has retrieved the SDP and before it configures the
622    * streams in the SDP. @sdp can be inspected and modified.
623    *
624    * This signal is called from the streaming thread, you should therefore not
625    * do any state changes on @rtspsrc because this might deadlock. If you want
626    * to modify the state as a result of this signal, post a
627    * #GST_MESSAGE_REQUEST_STATE message on the bus or signal the main thread
628    * in some other way.
629    *
630    * Since: 1.2
631    */
632   gst_rtspsrc_signals[SIGNAL_ON_SDP] =
633       g_signal_new ("on-sdp", G_TYPE_FROM_CLASS (klass), 0,
634       0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 1,
635       GST_TYPE_SDP_MESSAGE | G_SIGNAL_TYPE_STATIC_SCOPE);
636
637   /**
638    * GstRTSPSrc::select-stream:
639    * @rtspsrc: a #GstRTSPSrc
640    * @num: the stream number
641    * @caps: the stream caps
642    *
643    * Emited before the client decides to configure the stream @num with
644    * @caps.
645    *
646    * Returns: %TRUE when the stream should be selected, %FALSE when the stream
647    * is to be ignored.
648    *
649    * Since: 1.2
650    */
651   gst_rtspsrc_signals[SIGNAL_SELECT_STREAM] =
652       g_signal_new_class_handler ("select-stream", G_TYPE_FROM_CLASS (klass),
653       G_SIGNAL_RUN_FIRST | G_SIGNAL_RUN_CLEANUP,
654       (GCallback) default_select_stream, select_stream_accum, NULL,
655       g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_UINT,
656       GST_TYPE_CAPS);
657
658   gstelement_class->send_event = gst_rtspsrc_send_event;
659   gstelement_class->provide_clock = gst_rtspsrc_provide_clock;
660   gstelement_class->change_state = gst_rtspsrc_change_state;
661
662   gst_element_class_add_pad_template (gstelement_class,
663       gst_static_pad_template_get (&rtptemplate));
664
665   gst_element_class_set_static_metadata (gstelement_class,
666       "RTSP packet receiver", "Source/Network",
667       "Receive data over the network via RTSP (RFC 2326)",
668       "Wim Taymans <wim@fluendo.com>, "
669       "Thijs Vermeir <thijs.vermeir@barco.com>, "
670       "Lutz Mueller <lutz@topfrose.de>");
671
672   gstbin_class->handle_message = gst_rtspsrc_handle_message;
673
674   gst_rtsp_ext_list_init ();
675 }
676
677 static void
678 gst_rtspsrc_init (GstRTSPSrc * src)
679 {
680   src->conninfo.location = g_strdup (DEFAULT_LOCATION);
681   src->protocols = DEFAULT_PROTOCOLS;
682   src->debug = DEFAULT_DEBUG;
683   src->retry = DEFAULT_RETRY;
684   src->udp_timeout = DEFAULT_TIMEOUT;
685   gst_rtspsrc_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
686   src->latency = DEFAULT_LATENCY_MS;
687   src->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
688   src->do_retransmission = DEFAULT_DO_RETRANSMISSION;
689   src->connection_speed = DEFAULT_CONNECTION_SPEED;
690   src->nat_method = DEFAULT_NAT_METHOD;
691   src->do_rtcp = DEFAULT_DO_RTCP;
692   src->do_rtsp_keep_alive = DEFAULT_DO_RTSP_KEEP_ALIVE;
693   gst_rtspsrc_set_proxy (src, DEFAULT_PROXY);
694   src->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
695   src->user_id = g_strdup (DEFAULT_USER_ID);
696   src->user_pw = g_strdup (DEFAULT_USER_PW);
697   src->buffer_mode = DEFAULT_BUFFER_MODE;
698   src->client_port_range.min = 0;
699   src->client_port_range.max = 0;
700   src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
701   src->short_header = DEFAULT_SHORT_HEADER;
702   src->probation = DEFAULT_PROBATION;
703   src->udp_reconnect = DEFAULT_UDP_RECONNECT;
704   src->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
705   src->ntp_sync = DEFAULT_NTP_SYNC;
706   src->use_pipeline_clock = DEFAULT_USE_PIPELINE_CLOCK;
707   src->sdes = NULL;
708   src->tls_validation_flags = DEFAULT_TLS_VALIDATION_FLAGS;
709
710   /* get a list of all extensions */
711   src->extensions = gst_rtsp_ext_list_get ();
712
713   /* connect to send signal */
714   gst_rtsp_ext_list_connect (src->extensions, "send",
715       (GCallback) gst_rtspsrc_send_cb, src);
716
717   /* protects the streaming thread in interleaved mode or the polling
718    * thread in UDP mode. */
719   g_rec_mutex_init (&src->stream_rec_lock);
720
721   /* protects our state changes from multiple invocations */
722   g_rec_mutex_init (&src->state_rec_lock);
723
724   src->state = GST_RTSP_STATE_INVALID;
725
726   GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
727 }
728
729 static void
730 gst_rtspsrc_finalize (GObject * object)
731 {
732   GstRTSPSrc *rtspsrc;
733
734   rtspsrc = GST_RTSPSRC (object);
735
736   gst_rtsp_ext_list_free (rtspsrc->extensions);
737   g_free (rtspsrc->conninfo.location);
738   gst_rtsp_url_free (rtspsrc->conninfo.url);
739   g_free (rtspsrc->conninfo.url_str);
740   g_free (rtspsrc->user_id);
741   g_free (rtspsrc->user_pw);
742   g_free (rtspsrc->multi_iface);
743
744   if (rtspsrc->sdp) {
745     gst_sdp_message_free (rtspsrc->sdp);
746     rtspsrc->sdp = NULL;
747   }
748   if (rtspsrc->provided_clock)
749     gst_object_unref (rtspsrc->provided_clock);
750
751   if (rtspsrc->sdes)
752     gst_structure_free (rtspsrc->sdes);
753
754   /* free locks */
755   g_rec_mutex_clear (&rtspsrc->stream_rec_lock);
756   g_rec_mutex_clear (&rtspsrc->state_rec_lock);
757
758   G_OBJECT_CLASS (parent_class)->finalize (object);
759 }
760
761 static GstClock *
762 gst_rtspsrc_provide_clock (GstElement * element)
763 {
764   GstRTSPSrc *src = GST_RTSPSRC (element);
765   GstClock *clock;
766
767   if ((clock = src->provided_clock) != NULL)
768     gst_object_ref (clock);
769
770   return clock;
771 }
772
773 /* a proxy string of the format [user:passwd@]host[:port] */
774 static gboolean
775 gst_rtspsrc_set_proxy (GstRTSPSrc * rtsp, const gchar * proxy)
776 {
777   gchar *p, *at, *col;
778
779   g_free (rtsp->proxy_user);
780   rtsp->proxy_user = NULL;
781   g_free (rtsp->proxy_passwd);
782   rtsp->proxy_passwd = NULL;
783   g_free (rtsp->proxy_host);
784   rtsp->proxy_host = NULL;
785   rtsp->proxy_port = 0;
786
787   p = (gchar *) proxy;
788
789   if (p == NULL)
790     return TRUE;
791
792   /* we allow http:// in front but ignore it */
793   if (g_str_has_prefix (p, "http://"))
794     p += 7;
795
796   at = strchr (p, '@');
797   if (at) {
798     /* look for user:passwd */
799     col = strchr (proxy, ':');
800     if (col == NULL || col > at)
801       return FALSE;
802
803     rtsp->proxy_user = g_strndup (p, col - p);
804     col++;
805     rtsp->proxy_passwd = g_strndup (col, at - col);
806
807     /* move to host */
808     p = at + 1;
809   } else {
810     if (rtsp->prop_proxy_id != NULL && *rtsp->prop_proxy_id != '\0')
811       rtsp->proxy_user = g_strdup (rtsp->prop_proxy_id);
812     if (rtsp->prop_proxy_pw != NULL && *rtsp->prop_proxy_pw != '\0')
813       rtsp->proxy_passwd = g_strdup (rtsp->prop_proxy_pw);
814     if (rtsp->proxy_user != NULL || rtsp->proxy_passwd != NULL) {
815       GST_LOG_OBJECT (rtsp, "set proxy user/pw from properties: %s:%s",
816           GST_STR_NULL (rtsp->proxy_user), GST_STR_NULL (rtsp->proxy_passwd));
817     }
818   }
819   col = strchr (p, ':');
820
821   if (col) {
822     /* everything before the colon is the hostname */
823     rtsp->proxy_host = g_strndup (p, col - p);
824     p = col + 1;
825     rtsp->proxy_port = strtoul (p, (char **) &p, 10);
826   } else {
827     rtsp->proxy_host = g_strdup (p);
828     rtsp->proxy_port = 8080;
829   }
830   return TRUE;
831 }
832
833 static void
834 gst_rtspsrc_set_tcp_timeout (GstRTSPSrc * rtspsrc, guint64 timeout)
835 {
836   rtspsrc->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
837   rtspsrc->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
838
839   if (timeout != 0)
840     rtspsrc->ptcp_timeout = &rtspsrc->tcp_timeout;
841   else
842     rtspsrc->ptcp_timeout = NULL;
843 }
844
845 static void
846 gst_rtspsrc_set_property (GObject * object, guint prop_id, const GValue * value,
847     GParamSpec * pspec)
848 {
849   GstRTSPSrc *rtspsrc;
850
851   rtspsrc = GST_RTSPSRC (object);
852
853   switch (prop_id) {
854     case PROP_LOCATION:
855       gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (rtspsrc),
856           g_value_get_string (value), NULL);
857       break;
858     case PROP_PROTOCOLS:
859       rtspsrc->protocols = g_value_get_flags (value);
860       break;
861     case PROP_DEBUG:
862       rtspsrc->debug = g_value_get_boolean (value);
863       break;
864     case PROP_RETRY:
865       rtspsrc->retry = g_value_get_uint (value);
866       break;
867     case PROP_TIMEOUT:
868       rtspsrc->udp_timeout = g_value_get_uint64 (value);
869       break;
870     case PROP_TCP_TIMEOUT:
871       gst_rtspsrc_set_tcp_timeout (rtspsrc, g_value_get_uint64 (value));
872       break;
873     case PROP_LATENCY:
874       rtspsrc->latency = g_value_get_uint (value);
875       break;
876     case PROP_DROP_ON_LATENCY:
877       rtspsrc->drop_on_latency = g_value_get_boolean (value);
878       break;
879     case PROP_DO_RETRANSMISSION:
880       rtspsrc->do_retransmission = g_value_get_boolean (value);
881       break;
882     case PROP_CONNECTION_SPEED:
883       rtspsrc->connection_speed = g_value_get_uint64 (value);
884       break;
885     case PROP_NAT_METHOD:
886       rtspsrc->nat_method = g_value_get_enum (value);
887       break;
888     case PROP_DO_RTCP:
889       rtspsrc->do_rtcp = g_value_get_boolean (value);
890       break;
891     case PROP_DO_RTSP_KEEP_ALIVE:
892       rtspsrc->do_rtsp_keep_alive = g_value_get_boolean (value);
893       break;
894     case PROP_PROXY:
895       gst_rtspsrc_set_proxy (rtspsrc, g_value_get_string (value));
896       break;
897     case PROP_PROXY_ID:
898       if (rtspsrc->prop_proxy_id)
899         g_free (rtspsrc->prop_proxy_id);
900       rtspsrc->prop_proxy_id = g_value_dup_string (value);
901       break;
902     case PROP_PROXY_PW:
903       if (rtspsrc->prop_proxy_pw)
904         g_free (rtspsrc->prop_proxy_pw);
905       rtspsrc->prop_proxy_pw = g_value_dup_string (value);
906       break;
907     case PROP_RTP_BLOCKSIZE:
908       rtspsrc->rtp_blocksize = g_value_get_uint (value);
909       break;
910     case PROP_USER_ID:
911       if (rtspsrc->user_id)
912         g_free (rtspsrc->user_id);
913       rtspsrc->user_id = g_value_dup_string (value);
914       break;
915     case PROP_USER_PW:
916       if (rtspsrc->user_pw)
917         g_free (rtspsrc->user_pw);
918       rtspsrc->user_pw = g_value_dup_string (value);
919       break;
920     case PROP_BUFFER_MODE:
921       rtspsrc->buffer_mode = g_value_get_enum (value);
922       break;
923     case PROP_PORT_RANGE:
924     {
925       const gchar *str;
926
927       str = g_value_get_string (value);
928       if (str) {
929         sscanf (str, "%u-%u",
930             &rtspsrc->client_port_range.min, &rtspsrc->client_port_range.max);
931       } else {
932         rtspsrc->client_port_range.min = 0;
933         rtspsrc->client_port_range.max = 0;
934       }
935       break;
936     }
937     case PROP_UDP_BUFFER_SIZE:
938       rtspsrc->udp_buffer_size = g_value_get_int (value);
939       break;
940     case PROP_SHORT_HEADER:
941       rtspsrc->short_header = g_value_get_boolean (value);
942       break;
943     case PROP_PROBATION:
944       rtspsrc->probation = g_value_get_uint (value);
945       break;
946     case PROP_UDP_RECONNECT:
947       rtspsrc->udp_reconnect = g_value_get_boolean (value);
948       break;
949     case PROP_MULTICAST_IFACE:
950       g_free (rtspsrc->multi_iface);
951
952       if (g_value_get_string (value) == NULL)
953         rtspsrc->multi_iface = g_strdup (DEFAULT_MULTICAST_IFACE);
954       else
955         rtspsrc->multi_iface = g_value_dup_string (value);
956       break;
957     case PROP_NTP_SYNC:
958       rtspsrc->ntp_sync = g_value_get_boolean (value);
959       break;
960     case PROP_USE_PIPELINE_CLOCK:
961       rtspsrc->use_pipeline_clock = g_value_get_boolean (value);
962       break;
963     case PROP_SDES:
964       rtspsrc->sdes = g_value_dup_boxed (value);
965       break;
966     case PROP_TLS_VALIDATION_FLAGS:
967       rtspsrc->tls_validation_flags = g_value_get_flags (value);
968       break;
969     default:
970       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
971       break;
972   }
973 }
974
975 static void
976 gst_rtspsrc_get_property (GObject * object, guint prop_id, GValue * value,
977     GParamSpec * pspec)
978 {
979   GstRTSPSrc *rtspsrc;
980
981   rtspsrc = GST_RTSPSRC (object);
982
983   switch (prop_id) {
984     case PROP_LOCATION:
985       g_value_set_string (value, rtspsrc->conninfo.location);
986       break;
987     case PROP_PROTOCOLS:
988       g_value_set_flags (value, rtspsrc->protocols);
989       break;
990     case PROP_DEBUG:
991       g_value_set_boolean (value, rtspsrc->debug);
992       break;
993     case PROP_RETRY:
994       g_value_set_uint (value, rtspsrc->retry);
995       break;
996     case PROP_TIMEOUT:
997       g_value_set_uint64 (value, rtspsrc->udp_timeout);
998       break;
999     case PROP_TCP_TIMEOUT:
1000     {
1001       guint64 timeout;
1002
1003       timeout = rtspsrc->tcp_timeout.tv_sec * G_USEC_PER_SEC +
1004           rtspsrc->tcp_timeout.tv_usec;
1005       g_value_set_uint64 (value, timeout);
1006       break;
1007     }
1008     case PROP_LATENCY:
1009       g_value_set_uint (value, rtspsrc->latency);
1010       break;
1011     case PROP_DROP_ON_LATENCY:
1012       g_value_set_boolean (value, rtspsrc->drop_on_latency);
1013       break;
1014     case PROP_DO_RETRANSMISSION:
1015       g_value_set_boolean (value, rtspsrc->do_retransmission);
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       if (g_object_class_find_property (klass, "do-retransmission")) {
2782         g_object_set (src->manager, "do-retransmission", src->do_retransmission,
2783             NULL);
2784       }
2785
2786       /* buffer mode pauses are handled by adding offsets to buffer times,
2787        * but some depayloaders may have a hard time syncing output times
2788        * with such input times, e.g. container ones, most notably ASF */
2789       /* TODO alternatives are having an event that indicates these shifts,
2790        * or having rtsp extensions provide suggestion on buffer mode */
2791       need_slave = stream->container;
2792       if (stream->caps && (s = gst_caps_get_structure (stream->caps, 0)) &&
2793           (encoding = gst_structure_get_string (s, "encoding-name")))
2794         need_slave = need_slave || (strcmp (encoding, "X-ASF-PF") == 0);
2795       /* valid duration implies not likely live pipeline,
2796        * so slaving in jitterbuffer does not make much sense
2797        * (and might mess things up due to bursts) */
2798       if (GST_CLOCK_TIME_IS_VALID (src->segment.duration) &&
2799           src->segment.duration && !need_slave) {
2800         src->use_buffering = TRUE;
2801       } else {
2802         src->use_buffering = FALSE;
2803       }
2804
2805       set_manager_buffer_mode (src);
2806
2807       /* connect to signals if we did not already do so */
2808       GST_DEBUG_OBJECT (src, "connect to signals on session manager, stream %p",
2809           stream);
2810       src->manager_sig_id =
2811           g_signal_connect (src->manager, "pad-added",
2812           (GCallback) new_manager_pad, src);
2813       src->manager_ptmap_id =
2814           g_signal_connect (src->manager, "request-pt-map",
2815           (GCallback) request_pt_map, src);
2816
2817       g_signal_connect (src->manager, "on-npt-stop", (GCallback) on_npt_stop,
2818           src);
2819     }
2820
2821     /* we stream directly to the manager, get some pads. Each RTSP stream goes
2822      * into a separate RTP session. */
2823     name = g_strdup_printf ("recv_rtp_sink_%u", stream->id);
2824     stream->channelpad[0] = gst_element_get_request_pad (src->manager, name);
2825     g_free (name);
2826     name = g_strdup_printf ("recv_rtcp_sink_%u", stream->id);
2827     stream->channelpad[1] = gst_element_get_request_pad (src->manager, name);
2828     g_free (name);
2829
2830     /* now configure the bandwidth in the manager */
2831     if (g_signal_lookup ("get-internal-session",
2832             G_OBJECT_TYPE (src->manager)) != 0) {
2833       GObject *rtpsession;
2834
2835       g_signal_emit_by_name (src->manager, "get-internal-session", stream->id,
2836           &rtpsession);
2837       if (rtpsession) {
2838         GST_INFO_OBJECT (src, "configure bandwidth in session %p", rtpsession);
2839
2840         stream->session = rtpsession;
2841
2842         if (stream->as_bandwidth != -1) {
2843           GST_INFO_OBJECT (src, "setting AS: %f",
2844               (gdouble) (stream->as_bandwidth * 1000));
2845           g_object_set (rtpsession, "bandwidth",
2846               (gdouble) (stream->as_bandwidth * 1000), NULL);
2847         }
2848         if (stream->rr_bandwidth != -1) {
2849           GST_INFO_OBJECT (src, "setting RR: %u", stream->rr_bandwidth);
2850           g_object_set (rtpsession, "rtcp-rr-bandwidth", stream->rr_bandwidth,
2851               NULL);
2852         }
2853         if (stream->rs_bandwidth != -1) {
2854           GST_INFO_OBJECT (src, "setting RS: %u", stream->rs_bandwidth);
2855           g_object_set (rtpsession, "rtcp-rs-bandwidth", stream->rs_bandwidth,
2856               NULL);
2857         }
2858
2859         g_object_set (rtpsession, "probation", src->probation, NULL);
2860
2861         g_signal_connect (rtpsession, "on-bye-ssrc", (GCallback) on_bye_ssrc,
2862             stream);
2863         g_signal_connect (rtpsession, "on-bye-timeout", (GCallback) on_timeout,
2864             stream);
2865         g_signal_connect (rtpsession, "on-timeout", (GCallback) on_timeout,
2866             stream);
2867         g_signal_connect (rtpsession, "on-ssrc-active",
2868             (GCallback) on_ssrc_active, stream);
2869       }
2870     }
2871   }
2872
2873 use_no_manager:
2874   return TRUE;
2875
2876   /* ERRORS */
2877 no_manager:
2878   {
2879     GST_DEBUG_OBJECT (src, "cannot get a session manager");
2880     return FALSE;
2881   }
2882 manager_failed:
2883   {
2884     GST_DEBUG_OBJECT (src, "no session manager element %s found", manager);
2885     return FALSE;
2886   }
2887 start_manager_failure:
2888   {
2889     GST_DEBUG_OBJECT (src, "could not start session manager");
2890     return FALSE;
2891   }
2892 }
2893
2894 /* free the UDP sources allocated when negotiating a transport.
2895  * This function is called when the server negotiated to a transport where the
2896  * UDP sources are not needed anymore, such as TCP or multicast. */
2897 static void
2898 gst_rtspsrc_stream_free_udp (GstRTSPStream * stream)
2899 {
2900   gint i;
2901
2902   for (i = 0; i < 2; i++) {
2903     if (stream->udpsrc[i]) {
2904       GST_DEBUG ("free UDP source %d for stream %p", i, stream);
2905       gst_element_set_state (stream->udpsrc[i], GST_STATE_NULL);
2906       gst_object_unref (stream->udpsrc[i]);
2907       stream->udpsrc[i] = NULL;
2908     }
2909   }
2910 }
2911
2912 /* for TCP, create pads to send and receive data to and from the manager and to
2913  * intercept various events and queries
2914  */
2915 static gboolean
2916 gst_rtspsrc_stream_configure_tcp (GstRTSPSrc * src, GstRTSPStream * stream,
2917     GstRTSPTransport * transport, GstPad ** outpad)
2918 {
2919   gchar *name;
2920   GstPadTemplate *template;
2921   GstPad *pad0, *pad1;
2922
2923   /* configure for interleaved delivery, nothing needs to be done
2924    * here, the loop function will call the chain functions of the
2925    * session manager. */
2926   stream->channel[0] = transport->interleaved.min;
2927   stream->channel[1] = transport->interleaved.max;
2928   GST_DEBUG_OBJECT (src, "stream %p on channels %d-%d", stream,
2929       stream->channel[0], stream->channel[1]);
2930
2931   /* we can remove the allocated UDP ports now */
2932   gst_rtspsrc_stream_free_udp (stream);
2933
2934   /* no session manager, send data to srcpad directly */
2935   if (!stream->channelpad[0]) {
2936     GST_DEBUG_OBJECT (src, "no manager, creating pad");
2937
2938     /* create a new pad we will use to stream to */
2939     name = g_strdup_printf ("stream_%u", stream->id);
2940     template = gst_static_pad_template_get (&rtptemplate);
2941     stream->channelpad[0] = gst_pad_new_from_template (template, name);
2942     gst_object_unref (template);
2943     g_free (name);
2944
2945     /* set caps and activate */
2946     gst_pad_use_fixed_caps (stream->channelpad[0]);
2947     gst_pad_set_active (stream->channelpad[0], TRUE);
2948
2949     *outpad = gst_object_ref (stream->channelpad[0]);
2950   } else {
2951     GST_DEBUG_OBJECT (src, "using manager source pad");
2952
2953     template = gst_static_pad_template_get (&anysrctemplate);
2954
2955     /* allocate pads for sending the channel data into the manager */
2956     pad0 = gst_pad_new_from_template (template, "internalsrc_0");
2957     gst_pad_link_full (pad0, stream->channelpad[0], GST_PAD_LINK_CHECK_NOTHING);
2958     gst_object_unref (stream->channelpad[0]);
2959     stream->channelpad[0] = pad0;
2960     gst_pad_set_event_function (pad0, gst_rtspsrc_handle_internal_src_event);
2961     gst_pad_set_query_function (pad0, gst_rtspsrc_handle_internal_src_query);
2962     gst_pad_set_element_private (pad0, src);
2963     gst_pad_set_active (pad0, TRUE);
2964
2965     if (stream->channelpad[1]) {
2966       /* if we have a sinkpad for the other channel, create a pad and link to the
2967        * manager. */
2968       pad1 = gst_pad_new_from_template (template, "internalsrc_1");
2969       gst_pad_set_event_function (pad1, gst_rtspsrc_handle_internal_src_event);
2970       gst_pad_link_full (pad1, stream->channelpad[1],
2971           GST_PAD_LINK_CHECK_NOTHING);
2972       gst_object_unref (stream->channelpad[1]);
2973       stream->channelpad[1] = pad1;
2974       gst_pad_set_active (pad1, TRUE);
2975     }
2976     gst_object_unref (template);
2977   }
2978   /* setup RTCP transport back to the server if we have to. */
2979   if (src->manager && src->do_rtcp) {
2980     GstPad *pad;
2981
2982     template = gst_static_pad_template_get (&anysinktemplate);
2983
2984     stream->rtcppad = gst_pad_new_from_template (template, "internalsink_0");
2985     gst_pad_set_chain_function (stream->rtcppad, gst_rtspsrc_sink_chain);
2986     gst_pad_set_element_private (stream->rtcppad, stream);
2987     gst_pad_set_active (stream->rtcppad, TRUE);
2988
2989     /* get session RTCP pad */
2990     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
2991     pad = gst_element_get_request_pad (src->manager, name);
2992     g_free (name);
2993
2994     /* and link */
2995     if (pad) {
2996       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
2997       gst_object_unref (pad);
2998     }
2999
3000     gst_object_unref (template);
3001   }
3002   return TRUE;
3003 }
3004
3005 static void
3006 gst_rtspsrc_get_transport_info (GstRTSPSrc * src, GstRTSPStream * stream,
3007     GstRTSPTransport * transport, const gchar ** destination, gint * min,
3008     gint * max, guint * ttl)
3009 {
3010   if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
3011     if (destination) {
3012       if (!(*destination = transport->destination))
3013         *destination = stream->destination;
3014     }
3015     if (min && max) {
3016       /* transport first */
3017       *min = transport->port.min;
3018       *max = transport->port.max;
3019       if (*min == -1 && *max == -1) {
3020         /* then try from SDP */
3021         if (stream->port != 0) {
3022           *min = stream->port;
3023           *max = stream->port + 1;
3024         }
3025       }
3026     }
3027
3028     if (ttl) {
3029       if (!(*ttl = transport->ttl))
3030         *ttl = stream->ttl;
3031     }
3032   } else {
3033     if (destination) {
3034       /* first take the source, then the endpoint to figure out where to send
3035        * the RTCP. */
3036       if (!(*destination = transport->source)) {
3037         if (src->conninfo.connection)
3038           *destination = gst_rtsp_connection_get_ip (src->conninfo.connection);
3039         else if (stream->conninfo.connection)
3040           *destination =
3041               gst_rtsp_connection_get_ip (stream->conninfo.connection);
3042       }
3043     }
3044     if (min && max) {
3045       /* for unicast we only expect the ports here */
3046       *min = transport->server_port.min;
3047       *max = transport->server_port.max;
3048     }
3049   }
3050 }
3051
3052 /* For multicast create UDP sources and join the multicast group. */
3053 static gboolean
3054 gst_rtspsrc_stream_configure_mcast (GstRTSPSrc * src, GstRTSPStream * stream,
3055     GstRTSPTransport * transport, GstPad ** outpad)
3056 {
3057   gchar *uri;
3058   const gchar *destination;
3059   gint min, max;
3060
3061   GST_DEBUG_OBJECT (src, "creating UDP sources for multicast");
3062
3063   /* we can remove the allocated UDP ports now */
3064   gst_rtspsrc_stream_free_udp (stream);
3065
3066   gst_rtspsrc_get_transport_info (src, stream, transport, &destination, &min,
3067       &max, NULL);
3068
3069   /* we need a destination now */
3070   if (destination == NULL)
3071     goto no_destination;
3072
3073   /* we really need ports now or we won't be able to receive anything at all */
3074   if (min == -1 && max == -1)
3075     goto no_ports;
3076
3077   GST_DEBUG_OBJECT (src, "have destination '%s' and ports (%d)-(%d)",
3078       destination, min, max);
3079
3080   /* creating UDP source for RTP */
3081   if (min != -1) {
3082     uri = g_strdup_printf ("udp://%s:%d", destination, min);
3083     stream->udpsrc[0] =
3084         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3085     g_free (uri);
3086     if (stream->udpsrc[0] == NULL)
3087       goto no_element;
3088
3089     /* take ownership */
3090     gst_object_ref_sink (stream->udpsrc[0]);
3091
3092     if (src->udp_buffer_size != 0)
3093       g_object_set (G_OBJECT (stream->udpsrc[0]), "buffer-size",
3094           src->udp_buffer_size, NULL);
3095
3096     if (src->multi_iface != NULL)
3097       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3098           src->multi_iface, NULL);
3099
3100     /* change state */
3101     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3102     gst_element_set_state (stream->udpsrc[0], GST_STATE_PAUSED);
3103   }
3104
3105   /* creating another UDP source for RTCP */
3106   if (max != -1) {
3107     GstCaps *caps;
3108
3109     uri = g_strdup_printf ("udp://%s:%d", destination, max);
3110     stream->udpsrc[1] =
3111         gst_element_make_from_uri (GST_URI_SRC, uri, NULL, NULL);
3112     g_free (uri);
3113     if (stream->udpsrc[1] == NULL)
3114       goto no_element;
3115
3116     caps = gst_caps_new_empty_simple ("application/x-rtcp");
3117     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3118     gst_caps_unref (caps);
3119
3120     /* take ownership */
3121     gst_object_ref_sink (stream->udpsrc[1]);
3122
3123     if (src->multi_iface != NULL)
3124       g_object_set (G_OBJECT (stream->udpsrc[0]), "multicast-iface",
3125           src->multi_iface, NULL);
3126
3127     gst_element_set_state (stream->udpsrc[1], GST_STATE_PAUSED);
3128   }
3129   return TRUE;
3130
3131   /* ERRORS */
3132 no_element:
3133   {
3134     GST_DEBUG_OBJECT (src, "no UDP source element found");
3135     return FALSE;
3136   }
3137 no_destination:
3138   {
3139     GST_DEBUG_OBJECT (src, "no destination found");
3140     return FALSE;
3141   }
3142 no_ports:
3143   {
3144     GST_DEBUG_OBJECT (src, "no ports found");
3145     return FALSE;
3146   }
3147 }
3148
3149 /* configure the remainder of the UDP ports */
3150 static gboolean
3151 gst_rtspsrc_stream_configure_udp (GstRTSPSrc * src, GstRTSPStream * stream,
3152     GstRTSPTransport * transport, GstPad ** outpad)
3153 {
3154   /* we manage the UDP elements now. For unicast, the UDP sources where
3155    * allocated in the stream when we suggested a transport. */
3156   if (stream->udpsrc[0]) {
3157     gst_element_set_locked_state (stream->udpsrc[0], TRUE);
3158     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[0]);
3159
3160     GST_DEBUG_OBJECT (src, "setting up UDP source");
3161
3162     /* configure a timeout on the UDP port. When the timeout message is
3163      * posted, we assume UDP transport is not possible. We reconnect using TCP
3164      * if we can. */
3165     g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout",
3166         src->udp_timeout * 1000, NULL);
3167
3168     /* get output pad of the UDP source. */
3169     *outpad = gst_element_get_static_pad (stream->udpsrc[0], "src");
3170
3171     /* save it so we can unblock */
3172     stream->blockedpad = *outpad;
3173
3174     /* configure pad block on the pad. As soon as there is dataflow on the
3175      * UDP source, we know that UDP is not blocked by a firewall and we can
3176      * configure all the streams to let the application autoplug decoders. */
3177     stream->blockid =
3178         gst_pad_add_probe (stream->blockedpad,
3179         GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, pad_blocked, src, NULL);
3180
3181     if (stream->channelpad[0]) {
3182       GST_DEBUG_OBJECT (src, "connecting UDP source 0 to manager");
3183       /* configure for UDP delivery, we need to connect the UDP pads to
3184        * the session plugin. */
3185       gst_pad_link_full (*outpad, stream->channelpad[0],
3186           GST_PAD_LINK_CHECK_NOTHING);
3187       gst_object_unref (*outpad);
3188       *outpad = NULL;
3189       /* we connected to pad-added signal to get pads from the manager */
3190     } else {
3191       GST_DEBUG_OBJECT (src, "using UDP src pad as output");
3192     }
3193   }
3194
3195   /* RTCP port */
3196   if (stream->udpsrc[1]) {
3197     GstCaps *caps;
3198
3199     gst_element_set_locked_state (stream->udpsrc[1], TRUE);
3200     gst_bin_add (GST_BIN_CAST (src), stream->udpsrc[1]);
3201
3202     caps = gst_caps_new_empty_simple ("application/x-rtcp");
3203     g_object_set (stream->udpsrc[1], "caps", caps, NULL);
3204     gst_caps_unref (caps);
3205
3206     if (stream->channelpad[1]) {
3207       GstPad *pad;
3208
3209       GST_DEBUG_OBJECT (src, "connecting UDP source 1 to manager");
3210
3211       pad = gst_element_get_static_pad (stream->udpsrc[1], "src");
3212       gst_pad_link_full (pad, stream->channelpad[1],
3213           GST_PAD_LINK_CHECK_NOTHING);
3214       gst_object_unref (pad);
3215     } else {
3216       /* leave unlinked */
3217     }
3218   }
3219   return TRUE;
3220 }
3221
3222 /* configure the UDP sink back to the server for status reports */
3223 static gboolean
3224 gst_rtspsrc_stream_configure_udp_sinks (GstRTSPSrc * src,
3225     GstRTSPStream * stream, GstRTSPTransport * transport)
3226 {
3227   GstPad *pad;
3228   gint rtp_port, rtcp_port;
3229   gboolean do_rtp, do_rtcp;
3230   const gchar *destination;
3231   gchar *uri, *name;
3232   guint ttl = 0;
3233   GSocket *socket;
3234
3235   /* get transport info */
3236   gst_rtspsrc_get_transport_info (src, stream, transport, &destination,
3237       &rtp_port, &rtcp_port, &ttl);
3238
3239   /* see what we need to do */
3240   do_rtp = (rtp_port != -1);
3241   /* it's possible that the server does not want us to send RTCP in which case
3242    * the port is -1 */
3243   do_rtcp = (rtcp_port != -1 && src->manager != NULL && src->do_rtcp);
3244
3245   /* we need a destination when we have RTP or RTCP ports */
3246   if (destination == NULL && (do_rtp || do_rtcp))
3247     goto no_destination;
3248
3249   /* try to construct the fakesrc to the RTP port of the server to open up any
3250    * NAT firewalls */
3251   if (do_rtp) {
3252     GST_DEBUG_OBJECT (src, "configure RTP UDP sink for %s:%d", destination,
3253         rtp_port);
3254
3255     uri = g_strdup_printf ("udp://%s:%d", destination, rtp_port);
3256     stream->udpsink[0] =
3257         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3258     g_free (uri);
3259     if (stream->udpsink[0] == NULL)
3260       goto no_sink_element;
3261
3262     /* don't join multicast group, we will have the source socket do that */
3263     /* no sync or async state changes needed */
3264     g_object_set (G_OBJECT (stream->udpsink[0]), "auto-multicast", FALSE,
3265         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3266     if (ttl > 0)
3267       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3268
3269     if (stream->udpsrc[0]) {
3270       /* configure socket, we give it the same UDP socket as the udpsrc for RTP
3271        * so that NAT firewalls will open a hole for us */
3272       g_object_get (G_OBJECT (stream->udpsrc[0]), "used-socket", &socket, NULL);
3273       GST_DEBUG_OBJECT (src, "RTP UDP src has sock %p", socket);
3274       /* configure socket and make sure udpsink does not close it when shutting
3275        * down, it belongs to udpsrc after all. */
3276       g_object_set (G_OBJECT (stream->udpsink[0]), "socket", socket,
3277           "close-socket", FALSE, NULL);
3278       g_object_unref (socket);
3279     }
3280
3281     /* the source for the dummy packets to open up NAT */
3282     stream->fakesrc = gst_element_factory_make ("fakesrc", NULL);
3283     if (stream->fakesrc == NULL)
3284       goto no_fakesrc_element;
3285
3286     /* random data in 5 buffers, a size of 200 bytes should be fine */
3287     g_object_set (G_OBJECT (stream->fakesrc), "filltype", 3, "num-buffers", 5,
3288         "sizetype", 2, "sizemax", 200, "silent", TRUE, NULL);
3289
3290     /* we don't want to consider this a sink */
3291     GST_OBJECT_FLAG_UNSET (stream->udpsink[0], GST_ELEMENT_FLAG_SINK);
3292
3293     /* keep everything locked */
3294     gst_element_set_locked_state (stream->udpsink[0], TRUE);
3295     gst_element_set_locked_state (stream->fakesrc, TRUE);
3296
3297     gst_object_ref (stream->udpsink[0]);
3298     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[0]);
3299     gst_object_ref (stream->fakesrc);
3300     gst_bin_add (GST_BIN_CAST (src), stream->fakesrc);
3301
3302     gst_element_link_pads_full (stream->fakesrc, "src", stream->udpsink[0],
3303         "sink", GST_PAD_LINK_CHECK_NOTHING);
3304   }
3305   if (do_rtcp) {
3306     GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
3307         rtcp_port);
3308
3309     uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
3310     stream->udpsink[1] =
3311         gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
3312     g_free (uri);
3313     if (stream->udpsink[1] == NULL)
3314       goto no_sink_element;
3315
3316     /* don't join multicast group, we will have the source socket do that */
3317     /* no sync or async state changes needed */
3318     g_object_set (G_OBJECT (stream->udpsink[1]), "auto-multicast", FALSE,
3319         "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
3320     if (ttl > 0)
3321       g_object_set (G_OBJECT (stream->udpsink[0]), "ttl", ttl, NULL);
3322
3323     if (stream->udpsrc[1]) {
3324       /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
3325        * because some servers check the port number of where it sends RTCP to identify
3326        * the RTCP packets it receives */
3327       g_object_get (G_OBJECT (stream->udpsrc[1]), "used-socket", &socket, NULL);
3328       GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
3329       /* configure socket and make sure udpsink does not close it when shutting
3330        * down, it belongs to udpsrc after all. */
3331       g_object_set (G_OBJECT (stream->udpsink[1]), "socket", socket,
3332           "close-socket", FALSE, NULL);
3333       g_object_unref (socket);
3334     }
3335
3336     /* we don't want to consider this a sink */
3337     GST_OBJECT_FLAG_UNSET (stream->udpsink[1], GST_ELEMENT_FLAG_SINK);
3338
3339     /* we keep this playing always */
3340     gst_element_set_locked_state (stream->udpsink[1], TRUE);
3341     gst_element_set_state (stream->udpsink[1], GST_STATE_PLAYING);
3342
3343     gst_object_ref (stream->udpsink[1]);
3344     gst_bin_add (GST_BIN_CAST (src), stream->udpsink[1]);
3345
3346     stream->rtcppad = gst_element_get_static_pad (stream->udpsink[1], "sink");
3347
3348     /* get session RTCP pad */
3349     name = g_strdup_printf ("send_rtcp_src_%u", stream->id);
3350     pad = gst_element_get_request_pad (src->manager, name);
3351     g_free (name);
3352
3353     /* and link */
3354     if (pad) {
3355       gst_pad_link_full (pad, stream->rtcppad, GST_PAD_LINK_CHECK_NOTHING);
3356       gst_object_unref (pad);
3357     }
3358   }
3359
3360   return TRUE;
3361
3362   /* ERRORS */
3363 no_destination:
3364   {
3365     GST_DEBUG_OBJECT (src, "no destination address specified");
3366     return FALSE;
3367   }
3368 no_sink_element:
3369   {
3370     GST_DEBUG_OBJECT (src, "no UDP sink element found");
3371     return FALSE;
3372   }
3373 no_fakesrc_element:
3374   {
3375     GST_DEBUG_OBJECT (src, "no fakesrc element found");
3376     return FALSE;
3377   }
3378 }
3379
3380 /* sets up all elements needed for streaming over the specified transport.
3381  * Does not yet expose the element pads, this will be done when there is actuall
3382  * dataflow detected, which might never happen when UDP is blocked in a
3383  * firewall, for example.
3384  */
3385 static gboolean
3386 gst_rtspsrc_stream_configure_transport (GstRTSPStream * stream,
3387     GstRTSPTransport * transport)
3388 {
3389   GstRTSPSrc *src;
3390   GstPad *outpad = NULL;
3391   GstPadTemplate *template;
3392   gchar *name;
3393   GstStructure *s;
3394   const gchar *media_type;
3395
3396   src = stream->parent;
3397
3398   GST_DEBUG_OBJECT (src, "configuring transport for stream %p", stream);
3399
3400   s = gst_caps_get_structure (stream->caps, 0);
3401
3402   /* get the proper media type for this stream now */
3403   if (gst_rtsp_transport_get_media_type (transport, &media_type) < 0)
3404     goto unknown_transport;
3405   if (!media_type)
3406     goto unknown_transport;
3407
3408   /* configure the final media type */
3409   GST_DEBUG_OBJECT (src, "setting media type to %s", media_type);
3410   gst_structure_set_name (s, media_type);
3411
3412   /* try to get and configure a manager, channelpad[0-1] will be configured with
3413    * the pads for the manager, or NULL when no manager is needed. */
3414   if (!gst_rtspsrc_stream_configure_manager (src, stream, transport))
3415     goto no_manager;
3416
3417   switch (transport->lower_transport) {
3418     case GST_RTSP_LOWER_TRANS_TCP:
3419       if (!gst_rtspsrc_stream_configure_tcp (src, stream, transport, &outpad))
3420         goto transport_failed;
3421       break;
3422     case GST_RTSP_LOWER_TRANS_UDP_MCAST:
3423       if (!gst_rtspsrc_stream_configure_mcast (src, stream, transport, &outpad))
3424         goto transport_failed;
3425       /* fallthrough, the rest is the same for UDP and MCAST */
3426     case GST_RTSP_LOWER_TRANS_UDP:
3427       if (!gst_rtspsrc_stream_configure_udp (src, stream, transport, &outpad))
3428         goto transport_failed;
3429       /* configure udpsinks back to the server for RTCP messages and for the
3430        * dummy RTP messages to open NAT. */
3431       if (!gst_rtspsrc_stream_configure_udp_sinks (src, stream, transport))
3432         goto transport_failed;
3433       break;
3434     default:
3435       goto unknown_transport;
3436   }
3437
3438   if (outpad) {
3439     GST_DEBUG_OBJECT (src, "creating ghostpad");
3440
3441     gst_pad_use_fixed_caps (outpad);
3442
3443     /* create ghostpad, don't add just yet, this will be done when we activate
3444      * the stream. */
3445     name = g_strdup_printf ("stream_%u", stream->id);
3446     template = gst_static_pad_template_get (&rtptemplate);
3447     stream->srcpad = gst_ghost_pad_new_from_template (name, outpad, template);
3448     gst_pad_set_event_function (stream->srcpad, gst_rtspsrc_handle_src_event);
3449     gst_pad_set_query_function (stream->srcpad, gst_rtspsrc_handle_src_query);
3450     gst_object_unref (template);
3451     g_free (name);
3452
3453     gst_object_unref (outpad);
3454   }
3455   /* mark pad as ok */
3456   stream->last_ret = GST_FLOW_OK;
3457
3458   return TRUE;
3459
3460   /* ERRORS */
3461 transport_failed:
3462   {
3463     GST_DEBUG_OBJECT (src, "failed to configure transport");
3464     return FALSE;
3465   }
3466 unknown_transport:
3467   {
3468     GST_DEBUG_OBJECT (src, "unknown transport");
3469     return FALSE;
3470   }
3471 no_manager:
3472   {
3473     GST_DEBUG_OBJECT (src, "cannot get a session manager");
3474     return FALSE;
3475   }
3476 }
3477
3478 /* send a couple of dummy random packets on the receiver RTP port to the server,
3479  * this should make a firewall think we initiated the data transfer and
3480  * hopefully allow packets to go from the sender port to our RTP receiver port */
3481 static gboolean
3482 gst_rtspsrc_send_dummy_packets (GstRTSPSrc * src)
3483 {
3484   GList *walk;
3485
3486   if (src->nat_method != GST_RTSP_NAT_DUMMY)
3487     return TRUE;
3488
3489   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3490     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3491
3492     if (stream->fakesrc && stream->udpsink[0]) {
3493       GST_DEBUG_OBJECT (src, "sending dummy packet to stream %p", stream);
3494       gst_element_set_state (stream->udpsink[0], GST_STATE_NULL);
3495       gst_element_set_state (stream->fakesrc, GST_STATE_NULL);
3496       gst_element_set_state (stream->udpsink[0], GST_STATE_PLAYING);
3497       gst_element_set_state (stream->fakesrc, GST_STATE_PLAYING);
3498     }
3499   }
3500   return TRUE;
3501 }
3502
3503 /* Adds the source pads of all configured streams to the element.
3504  * This code is performed when we detected dataflow.
3505  *
3506  * We detect dataflow from either the _loop function or with pad probes on the
3507  * udp sources.
3508  */
3509 static gboolean
3510 gst_rtspsrc_activate_streams (GstRTSPSrc * src)
3511 {
3512   GList *walk;
3513
3514   GST_DEBUG_OBJECT (src, "activating streams");
3515
3516   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3517     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3518
3519     if (stream->udpsrc[0]) {
3520       /* remove timeout, we are streaming now and timeouts will be handled by
3521        * the session manager and jitter buffer */
3522       g_object_set (G_OBJECT (stream->udpsrc[0]), "timeout", (guint64) 0, NULL);
3523     }
3524     if (stream->srcpad) {
3525       GST_DEBUG_OBJECT (src, "activating stream pad %p", stream);
3526       gst_pad_set_active (stream->srcpad, TRUE);
3527
3528       /* if we don't have a session manager, set the caps now. If we have a
3529        * session, we will get a notification of the pad and the caps. */
3530       if (!src->manager) {
3531         GST_DEBUG_OBJECT (src, "setting pad caps for stream %p", stream);
3532         gst_pad_set_caps (stream->srcpad, stream->caps);
3533       }
3534       /* add the pad */
3535       if (!stream->added) {
3536         GST_DEBUG_OBJECT (src, "adding stream pad %p", stream);
3537         gst_element_add_pad (GST_ELEMENT_CAST (src), stream->srcpad);
3538         stream->added = TRUE;
3539       }
3540     }
3541   }
3542
3543   /* unblock all pads */
3544   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3545     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3546
3547     if (stream->blockid) {
3548       GST_DEBUG_OBJECT (src, "unblocking stream pad %p", stream);
3549       gst_pad_remove_probe (stream->blockedpad, stream->blockid);
3550       stream->blockid = 0;
3551     }
3552   }
3553
3554   return TRUE;
3555 }
3556
3557 static void
3558 gst_rtspsrc_configure_caps (GstRTSPSrc * src, GstSegment * segment,
3559     gboolean reset_manager)
3560 {
3561   GList *walk;
3562   guint64 start, stop;
3563   gdouble play_speed, play_scale;
3564
3565   GST_DEBUG_OBJECT (src, "configuring stream caps");
3566
3567   start = segment->position;
3568   stop = segment->duration;
3569   play_speed = segment->rate;
3570   play_scale = segment->applied_rate;
3571
3572   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3573     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3574     GstCaps *caps;
3575
3576     if ((caps = stream->caps)) {
3577       caps = gst_caps_make_writable (caps);
3578       /* update caps */
3579       if (stream->timebase != -1)
3580         gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
3581             (guint) stream->timebase, NULL);
3582       if (stream->seqbase != -1)
3583         gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
3584             (guint) stream->seqbase, NULL);
3585       gst_caps_set_simple (caps, "npt-start", G_TYPE_UINT64, start, NULL);
3586       if (stop != -1)
3587         gst_caps_set_simple (caps, "npt-stop", G_TYPE_UINT64, stop, NULL);
3588       gst_caps_set_simple (caps, "play-speed", G_TYPE_DOUBLE, play_speed, NULL);
3589       gst_caps_set_simple (caps, "play-scale", G_TYPE_DOUBLE, play_scale, NULL);
3590
3591       stream->caps = caps;
3592     }
3593     GST_DEBUG_OBJECT (src, "stream %p, caps %" GST_PTR_FORMAT, stream, caps);
3594   }
3595   if (reset_manager && src->manager) {
3596     GST_DEBUG_OBJECT (src, "clear session");
3597     g_signal_emit_by_name (src->manager, "clear-pt-map", NULL);
3598   }
3599 }
3600
3601 static GstFlowReturn
3602 gst_rtspsrc_combine_flows (GstRTSPSrc * src, GstRTSPStream * stream,
3603     GstFlowReturn ret)
3604 {
3605   GList *streams;
3606
3607   /* store the value */
3608   stream->last_ret = ret;
3609
3610   /* if it's success we can return the value right away */
3611   if (ret == GST_FLOW_OK)
3612     goto done;
3613
3614   /* any other error that is not-linked can be returned right
3615    * away */
3616   if (ret != GST_FLOW_NOT_LINKED)
3617     goto done;
3618
3619   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3620   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3621     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3622
3623     ret = ostream->last_ret;
3624     /* some other return value (must be SUCCESS but we can return
3625      * other values as well) */
3626     if (ret != GST_FLOW_NOT_LINKED)
3627       goto done;
3628   }
3629   /* if we get here, all other pads were unlinked and we return
3630    * NOT_LINKED then */
3631 done:
3632   return ret;
3633 }
3634
3635 static gboolean
3636 gst_rtspsrc_stream_push_event (GstRTSPSrc * src, GstRTSPStream * stream,
3637     GstEvent * event)
3638 {
3639   gboolean res = TRUE;
3640
3641   /* only streams that have a connection to the outside world */
3642   if (stream->container || stream->disabled)
3643     goto done;
3644
3645   if (stream->udpsrc[0]) {
3646     gst_event_ref (event);
3647     res = gst_element_send_event (stream->udpsrc[0], event);
3648   } else if (stream->channelpad[0]) {
3649     gst_event_ref (event);
3650     if (GST_PAD_IS_SRC (stream->channelpad[0]))
3651       res = gst_pad_push_event (stream->channelpad[0], event);
3652     else
3653       res = gst_pad_send_event (stream->channelpad[0], event);
3654   }
3655
3656   if (stream->udpsrc[1]) {
3657     gst_event_ref (event);
3658     res &= gst_element_send_event (stream->udpsrc[1], event);
3659   } else if (stream->channelpad[1]) {
3660     gst_event_ref (event);
3661     if (GST_PAD_IS_SRC (stream->channelpad[1]))
3662       res &= gst_pad_push_event (stream->channelpad[1], event);
3663     else
3664       res &= gst_pad_send_event (stream->channelpad[1], event);
3665   }
3666
3667 done:
3668   gst_event_unref (event);
3669
3670   return res;
3671 }
3672
3673 static gboolean
3674 gst_rtspsrc_push_event (GstRTSPSrc * src, GstEvent * event)
3675 {
3676   GList *streams;
3677   gboolean res = TRUE;
3678
3679   for (streams = src->streams; streams; streams = g_list_next (streams)) {
3680     GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
3681
3682     gst_event_ref (event);
3683     res &= gst_rtspsrc_stream_push_event (src, ostream, event);
3684   }
3685   gst_event_unref (event);
3686
3687   return res;
3688 }
3689
3690 static GstRTSPResult
3691 gst_rtsp_conninfo_connect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3692     gboolean async)
3693 {
3694   GstRTSPResult res;
3695
3696   if (info->connection == NULL) {
3697     if (info->url == NULL) {
3698       GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
3699       if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
3700         goto parse_error;
3701     }
3702
3703     /* create connection */
3704     GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
3705     if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
3706       goto could_not_create;
3707
3708     if (info->url_str)
3709       g_free (info->url_str);
3710     info->url_str = gst_rtsp_url_get_request_uri (info->url);
3711
3712     GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
3713
3714     if (info->url->transports & GST_RTSP_LOWER_TRANS_TLS) {
3715       if (!gst_rtsp_connection_set_tls_validation_flags (info->connection,
3716               src->tls_validation_flags))
3717         GST_WARNING_OBJECT (src, "Unable to set TLS validation flags");
3718     }
3719
3720     if (info->url->transports & GST_RTSP_LOWER_TRANS_HTTP)
3721       gst_rtsp_connection_set_tunneled (info->connection, TRUE);
3722
3723     if (src->proxy_host) {
3724       GST_DEBUG_OBJECT (src, "setting proxy %s:%d", src->proxy_host,
3725           src->proxy_port);
3726       gst_rtsp_connection_set_proxy (info->connection, src->proxy_host,
3727           src->proxy_port);
3728     }
3729   }
3730
3731   if (!info->connected) {
3732     /* connect */
3733     if (async)
3734       GST_ELEMENT_PROGRESS (src, CONTINUE, "connect",
3735           ("Connecting to %s", info->location));
3736     GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
3737     if ((res =
3738             gst_rtsp_connection_connect (info->connection,
3739                 src->ptcp_timeout)) < 0)
3740       goto could_not_connect;
3741
3742     info->connected = TRUE;
3743   }
3744   return GST_RTSP_OK;
3745
3746   /* ERRORS */
3747 parse_error:
3748   {
3749     GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
3750     return res;
3751   }
3752 could_not_create:
3753   {
3754     gchar *str = gst_rtsp_strresult (res);
3755     GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
3756     g_free (str);
3757     return res;
3758   }
3759 could_not_connect:
3760   {
3761     gchar *str = gst_rtsp_strresult (res);
3762     GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
3763     g_free (str);
3764     return res;
3765   }
3766 }
3767
3768 static GstRTSPResult
3769 gst_rtsp_conninfo_close (GstRTSPSrc * src, GstRTSPConnInfo * info,
3770     gboolean free)
3771 {
3772   GST_RTSP_STATE_LOCK (src);
3773   if (info->connected) {
3774     GST_DEBUG_OBJECT (src, "closing connection...");
3775     gst_rtsp_connection_close (info->connection);
3776     info->connected = FALSE;
3777   }
3778   if (free && info->connection) {
3779     /* free connection */
3780     GST_DEBUG_OBJECT (src, "freeing connection...");
3781     gst_rtsp_connection_free (info->connection);
3782     info->connection = NULL;
3783   }
3784   GST_RTSP_STATE_UNLOCK (src);
3785   return GST_RTSP_OK;
3786 }
3787
3788 static GstRTSPResult
3789 gst_rtsp_conninfo_reconnect (GstRTSPSrc * src, GstRTSPConnInfo * info,
3790     gboolean async)
3791 {
3792   GstRTSPResult res;
3793
3794   GST_DEBUG_OBJECT (src, "reconnecting connection...");
3795   gst_rtsp_conninfo_close (src, info, FALSE);
3796   res = gst_rtsp_conninfo_connect (src, info, async);
3797
3798   return res;
3799 }
3800
3801 static void
3802 gst_rtspsrc_connection_flush (GstRTSPSrc * src, gboolean flush)
3803 {
3804   GList *walk;
3805
3806   GST_DEBUG_OBJECT (src, "set flushing %d", flush);
3807   GST_RTSP_STATE_LOCK (src);
3808   if (src->conninfo.connection && src->conninfo.flushing != flush) {
3809     GST_DEBUG_OBJECT (src, "connection flush");
3810     gst_rtsp_connection_flush (src->conninfo.connection, flush);
3811     src->conninfo.flushing = flush;
3812   }
3813   for (walk = src->streams; walk; walk = g_list_next (walk)) {
3814     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
3815     if (stream->conninfo.connection && stream->conninfo.flushing != flush) {
3816       GST_DEBUG_OBJECT (src, "stream %p flush", stream);
3817       gst_rtsp_connection_flush (stream->conninfo.connection, flush);
3818       stream->conninfo.flushing = flush;
3819     }
3820   }
3821   GST_RTSP_STATE_UNLOCK (src);
3822 }
3823
3824 /* FIXME, handle server request, reply with OK, for now */
3825 static GstRTSPResult
3826 gst_rtspsrc_handle_request (GstRTSPSrc * src, GstRTSPConnection * conn,
3827     GstRTSPMessage * request)
3828 {
3829   GstRTSPMessage response = { 0 };
3830   GstRTSPResult res;
3831
3832   GST_DEBUG_OBJECT (src, "got server request message");
3833
3834   if (src->debug)
3835     gst_rtsp_message_dump (request);
3836
3837   res = gst_rtsp_ext_list_receive_request (src->extensions, request);
3838
3839   if (res == GST_RTSP_ENOTIMPL) {
3840     /* default implementation, send OK */
3841     GST_DEBUG_OBJECT (src, "prepare OK reply");
3842     res =
3843         gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, "OK",
3844         request);
3845     if (res < 0)
3846       goto send_error;
3847
3848     /* let app parse and reply */
3849     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_HANDLE_REQUEST],
3850         0, request, &response);
3851
3852     if (src->debug)
3853       gst_rtsp_message_dump (&response);
3854
3855     res = gst_rtspsrc_connection_send (src, conn, &response, NULL);
3856     if (res < 0)
3857       goto send_error;
3858
3859     gst_rtsp_message_unset (&response);
3860   } else if (res == GST_RTSP_EEOF)
3861     return res;
3862
3863   return GST_RTSP_OK;
3864
3865   /* ERRORS */
3866 send_error:
3867   {
3868     gst_rtsp_message_unset (&response);
3869     return res;
3870   }
3871 }
3872
3873 /* send server keep-alive */
3874 static GstRTSPResult
3875 gst_rtspsrc_send_keep_alive (GstRTSPSrc * src)
3876 {
3877   GstRTSPMessage request = { 0 };
3878   GstRTSPResult res;
3879   GstRTSPMethod method;
3880   const gchar *control;
3881
3882   if (src->do_rtsp_keep_alive == FALSE) {
3883     GST_DEBUG_OBJECT (src, "do-rtsp-keep-alive is FALSE, not sending.");
3884     gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3885     return GST_RTSP_OK;
3886   }
3887
3888   GST_DEBUG_OBJECT (src, "creating server keep-alive");
3889
3890   /* find a method to use for keep-alive */
3891   if (src->methods & GST_RTSP_GET_PARAMETER)
3892     method = GST_RTSP_GET_PARAMETER;
3893   else
3894     method = GST_RTSP_OPTIONS;
3895
3896   control = get_aggregate_control (src);
3897   if (control == NULL)
3898     goto no_control;
3899
3900   res = gst_rtsp_message_init_request (&request, method, control);
3901   if (res < 0)
3902     goto send_error;
3903
3904   if (src->debug)
3905     gst_rtsp_message_dump (&request);
3906
3907   res =
3908       gst_rtspsrc_connection_send (src, src->conninfo.connection, &request,
3909       NULL);
3910   if (res < 0)
3911     goto send_error;
3912
3913   gst_rtsp_connection_reset_timeout (src->conninfo.connection);
3914   gst_rtsp_message_unset (&request);
3915
3916   return GST_RTSP_OK;
3917
3918   /* ERRORS */
3919 no_control:
3920   {
3921     GST_WARNING_OBJECT (src, "no control url to send keepalive");
3922     return GST_RTSP_OK;
3923   }
3924 send_error:
3925   {
3926     gchar *str = gst_rtsp_strresult (res);
3927
3928     gst_rtsp_message_unset (&request);
3929     GST_ELEMENT_WARNING (src, RESOURCE, WRITE, (NULL),
3930         ("Could not send keep-alive. (%s)", str));
3931     g_free (str);
3932     return res;
3933   }
3934 }
3935
3936 static GstFlowReturn
3937 gst_rtspsrc_handle_data (GstRTSPSrc * src, GstRTSPMessage * message)
3938 {
3939   GstFlowReturn ret = GST_FLOW_OK;
3940   gint channel;
3941   GstRTSPStream *stream;
3942   GstPad *outpad = NULL;
3943   guint8 *data;
3944   guint size;
3945   GstBuffer *buf;
3946   gboolean is_rtcp;
3947   GstEvent *event;
3948
3949   channel = message->type_data.data.channel;
3950
3951   stream = find_stream (src, &channel, (gpointer) find_stream_by_channel);
3952   if (!stream)
3953     goto unknown_stream;
3954
3955   if (channel == stream->channel[0]) {
3956     outpad = stream->channelpad[0];
3957     is_rtcp = FALSE;
3958   } else if (channel == stream->channel[1]) {
3959     outpad = stream->channelpad[1];
3960     is_rtcp = TRUE;
3961   } else {
3962     is_rtcp = FALSE;
3963   }
3964
3965   /* take a look at the body to figure out what we have */
3966   gst_rtsp_message_get_body (message, &data, &size);
3967   if (size < 2)
3968     goto invalid_length;
3969
3970   /* channels are not correct on some servers, do extra check */
3971   if (data[1] >= 200 && data[1] <= 204) {
3972     /* hmm RTCP message switch to the RTCP pad of the same stream. */
3973     outpad = stream->channelpad[1];
3974     is_rtcp = TRUE;
3975   }
3976
3977   /* we have no clue what this is, just ignore then. */
3978   if (outpad == NULL)
3979     goto unknown_stream;
3980
3981   /* take the message body for further processing */
3982   gst_rtsp_message_steal_body (message, &data, &size);
3983
3984   /* strip the trailing \0 */
3985   size -= 1;
3986
3987   buf = gst_buffer_new ();
3988   gst_buffer_append_memory (buf,
3989       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
3990
3991   /* don't need message anymore */
3992   gst_rtsp_message_unset (message);
3993
3994   GST_DEBUG_OBJECT (src, "pushing data of size %d on channel %d", size,
3995       channel);
3996
3997   if (src->need_activate) {
3998     gchar *stream_id;
3999     GstEvent *event;
4000     GChecksum *cs;
4001     gchar *uri;
4002     GList *streams;
4003     guint group_id = gst_util_group_id_next ();
4004
4005     /* generate an SHA256 sum of the URI */
4006     cs = g_checksum_new (G_CHECKSUM_SHA256);
4007     uri = src->conninfo.location;
4008     g_checksum_update (cs, (const guchar *) uri, strlen (uri));
4009
4010     for (streams = src->streams; streams; streams = g_list_next (streams)) {
4011       GstRTSPStream *ostream = (GstRTSPStream *) streams->data;
4012
4013       stream_id =
4014           g_strdup_printf ("%s/%d", g_checksum_get_string (cs), ostream->id);
4015       event = gst_event_new_stream_start (stream_id);
4016       gst_event_set_group_id (event, group_id);
4017
4018       g_free (stream_id);
4019       gst_rtspsrc_stream_push_event (src, ostream, event);
4020     }
4021     g_checksum_free (cs);
4022
4023     gst_rtspsrc_activate_streams (src);
4024     src->need_activate = FALSE;
4025   }
4026   if ((event = src->start_segment) != NULL) {
4027     src->start_segment = NULL;
4028     gst_rtspsrc_push_event (src, event);
4029   }
4030
4031   if (src->base_time == -1) {
4032     /* Take current running_time. This timestamp will be put on
4033      * the first buffer of each stream because we are a live source and so we
4034      * timestamp with the running_time. When we are dealing with TCP, we also
4035      * only timestamp the first buffer (using the DISCONT flag) because a server
4036      * typically bursts data, for which we don't want to compensate by speeding
4037      * up the media. The other timestamps will be interpollated from this one
4038      * using the RTP timestamps. */
4039     GST_OBJECT_LOCK (src);
4040     if (GST_ELEMENT_CLOCK (src)) {
4041       GstClockTime now;
4042       GstClockTime base_time;
4043
4044       now = gst_clock_get_time (GST_ELEMENT_CLOCK (src));
4045       base_time = GST_ELEMENT_CAST (src)->base_time;
4046
4047       src->base_time = now - base_time;
4048
4049       GST_DEBUG_OBJECT (src, "first buffer at time %" GST_TIME_FORMAT ", base %"
4050           GST_TIME_FORMAT, GST_TIME_ARGS (now), GST_TIME_ARGS (base_time));
4051     }
4052     GST_OBJECT_UNLOCK (src);
4053   }
4054
4055   if (stream->discont && !is_rtcp) {
4056     /* mark first RTP buffer as discont */
4057     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4058     stream->discont = FALSE;
4059     /* first buffer gets the timestamp, other buffers are not timestamped and
4060      * their presentation time will be interpollated from the rtp timestamps. */
4061     GST_DEBUG_OBJECT (src, "setting timestamp %" GST_TIME_FORMAT,
4062         GST_TIME_ARGS (src->base_time));
4063
4064     GST_BUFFER_TIMESTAMP (buf) = src->base_time;
4065   }
4066
4067   /* chain to the peer pad */
4068   if (GST_PAD_IS_SINK (outpad))
4069     ret = gst_pad_chain (outpad, buf);
4070   else
4071     ret = gst_pad_push (outpad, buf);
4072
4073   if (!is_rtcp) {
4074     /* combine all stream flows for the data transport */
4075     ret = gst_rtspsrc_combine_flows (src, stream, ret);
4076   }
4077   return ret;
4078
4079   /* ERRORS */
4080 unknown_stream:
4081   {
4082     GST_DEBUG_OBJECT (src, "unknown stream on channel %d, ignored", channel);
4083     gst_rtsp_message_unset (message);
4084     return GST_FLOW_OK;
4085   }
4086 invalid_length:
4087   {
4088     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4089         ("Short message received, ignoring."));
4090     gst_rtsp_message_unset (message);
4091     return GST_FLOW_OK;
4092   }
4093 }
4094
4095 static GstFlowReturn
4096 gst_rtspsrc_loop_interleaved (GstRTSPSrc * src)
4097 {
4098   GstRTSPMessage message = { 0 };
4099   GstRTSPResult res;
4100   GstFlowReturn ret = GST_FLOW_OK;
4101   GTimeVal tv_timeout;
4102
4103   while (TRUE) {
4104     /* get the next timeout interval */
4105     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4106
4107     /* see if the timeout period expired */
4108     if ((tv_timeout.tv_sec | tv_timeout.tv_usec) == 0) {
4109       GST_DEBUG_OBJECT (src, "timout, sending keep-alive");
4110       /* send keep-alive, only act on interrupt, a warning will be posted for
4111        * other errors. */
4112       if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4113         goto interrupt;
4114       /* get new timeout */
4115       gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4116     }
4117
4118     GST_DEBUG_OBJECT (src, "doing receive with timeout %ld seconds, %ld usec",
4119         tv_timeout.tv_sec, tv_timeout.tv_usec);
4120
4121     /* protect the connection with the connection lock so that we can see when
4122      * we are finished doing server communication */
4123     res =
4124         gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4125         &message, src->ptcp_timeout);
4126
4127     switch (res) {
4128       case GST_RTSP_OK:
4129         GST_DEBUG_OBJECT (src, "we received a server message");
4130         break;
4131       case GST_RTSP_EINTR:
4132         /* we got interrupted this means we need to stop */
4133         goto interrupt;
4134       case GST_RTSP_ETIMEOUT:
4135         /* no reply, send keep alive */
4136         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4137         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4138           goto interrupt;
4139         continue;
4140       case GST_RTSP_EEOF:
4141         /* go EOS when the server closed the connection */
4142         goto server_eof;
4143       default:
4144         goto receive_error;
4145     }
4146
4147     switch (message.type) {
4148       case GST_RTSP_MESSAGE_REQUEST:
4149         /* server sends us a request message, handle it */
4150         res =
4151             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4152             &message);
4153         if (res == GST_RTSP_EEOF)
4154           goto server_eof;
4155         else if (res < 0)
4156           goto handle_request_failed;
4157         break;
4158       case GST_RTSP_MESSAGE_RESPONSE:
4159         /* we ignore response messages */
4160         GST_DEBUG_OBJECT (src, "ignoring response message");
4161         if (src->debug)
4162           gst_rtsp_message_dump (&message);
4163         break;
4164       case GST_RTSP_MESSAGE_DATA:
4165         GST_DEBUG_OBJECT (src, "got data message");
4166         ret = gst_rtspsrc_handle_data (src, &message);
4167         if (ret != GST_FLOW_OK)
4168           goto handle_data_failed;
4169         break;
4170       default:
4171         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4172             message.type);
4173         break;
4174     }
4175   }
4176   g_assert_not_reached ();
4177
4178   /* ERRORS */
4179 server_eof:
4180   {
4181     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4182     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4183         ("The server closed the connection."));
4184     src->conninfo.connected = FALSE;
4185     gst_rtsp_message_unset (&message);
4186     return GST_FLOW_EOS;
4187   }
4188 interrupt:
4189   {
4190     gst_rtsp_message_unset (&message);
4191     GST_DEBUG_OBJECT (src, "got interrupted");
4192     return GST_FLOW_FLUSHING;
4193   }
4194 receive_error:
4195   {
4196     gchar *str = gst_rtsp_strresult (res);
4197
4198     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4199         ("Could not receive message. (%s)", str));
4200     g_free (str);
4201
4202     gst_rtsp_message_unset (&message);
4203     return GST_FLOW_ERROR;
4204   }
4205 handle_request_failed:
4206   {
4207     gchar *str = gst_rtsp_strresult (res);
4208
4209     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4210         ("Could not handle server message. (%s)", str));
4211     g_free (str);
4212     gst_rtsp_message_unset (&message);
4213     return GST_FLOW_ERROR;
4214   }
4215 handle_data_failed:
4216   {
4217     GST_DEBUG_OBJECT (src, "could no handle data message");
4218     return ret;
4219   }
4220 }
4221
4222 static GstFlowReturn
4223 gst_rtspsrc_loop_udp (GstRTSPSrc * src)
4224 {
4225   GstRTSPResult res;
4226   GstRTSPMessage message = { 0 };
4227   gint retry = 0;
4228
4229   while (TRUE) {
4230     GTimeVal tv_timeout;
4231
4232     /* get the next timeout interval */
4233     gst_rtsp_connection_next_timeout (src->conninfo.connection, &tv_timeout);
4234
4235     GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
4236         (gint) tv_timeout.tv_sec);
4237
4238     gst_rtsp_message_unset (&message);
4239
4240     /* we should continue reading the TCP socket because the server might
4241      * send us requests. When the session timeout expires, we need to send a
4242      * keep-alive request to keep the session open. */
4243     res = gst_rtspsrc_connection_receive (src, src->conninfo.connection,
4244         &message, &tv_timeout);
4245
4246     switch (res) {
4247       case GST_RTSP_OK:
4248         GST_DEBUG_OBJECT (src, "we received a server message");
4249         break;
4250       case GST_RTSP_EINTR:
4251         /* we got interrupted, see what we have to do */
4252         goto interrupt;
4253       case GST_RTSP_ETIMEOUT:
4254         /* send keep-alive, ignore the result, a warning will be posted. */
4255         GST_DEBUG_OBJECT (src, "timeout, sending keep-alive");
4256         if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4257           goto interrupt;
4258         continue;
4259       case GST_RTSP_EEOF:
4260         /* server closed the connection. not very fatal for UDP, reconnect and
4261          * see what happens. */
4262         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4263             ("The server closed the connection."));
4264         if (src->udp_reconnect) {
4265           if ((res =
4266                   gst_rtsp_conninfo_reconnect (src, &src->conninfo, FALSE)) < 0)
4267             goto connect_error;
4268         } else {
4269           goto server_eof;
4270         }
4271         continue;
4272       case GST_RTSP_ENET:
4273         GST_DEBUG_OBJECT (src, "An ethernet problem occured.");
4274       default:
4275         GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4276             ("Unhandled return value %d.", res));
4277         goto receive_error;
4278     }
4279
4280     switch (message.type) {
4281       case GST_RTSP_MESSAGE_REQUEST:
4282         /* server sends us a request message, handle it */
4283         res =
4284             gst_rtspsrc_handle_request (src, src->conninfo.connection,
4285             &message);
4286         if (res == GST_RTSP_EEOF)
4287           goto server_eof;
4288         else if (res < 0)
4289           goto handle_request_failed;
4290         break;
4291       case GST_RTSP_MESSAGE_RESPONSE:
4292         /* we ignore response and data messages */
4293         GST_DEBUG_OBJECT (src, "ignoring response message");
4294         if (src->debug)
4295           gst_rtsp_message_dump (&message);
4296         if (message.type_data.response.code == GST_RTSP_STS_UNAUTHORIZED) {
4297           GST_DEBUG_OBJECT (src, "but is Unauthorized response ...");
4298           if (gst_rtspsrc_setup_auth (src, &message) && !(retry++)) {
4299             GST_DEBUG_OBJECT (src, "so retrying keep-alive");
4300             if ((res = gst_rtspsrc_send_keep_alive (src)) == GST_RTSP_EINTR)
4301               goto interrupt;
4302           }
4303         } else {
4304           retry = 0;
4305         }
4306         break;
4307       case GST_RTSP_MESSAGE_DATA:
4308         /* we ignore response and data messages */
4309         GST_DEBUG_OBJECT (src, "ignoring data message");
4310         break;
4311       default:
4312         GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4313             message.type);
4314         break;
4315     }
4316   }
4317   g_assert_not_reached ();
4318
4319   /* we get here when the connection got interrupted */
4320 interrupt:
4321   {
4322     gst_rtsp_message_unset (&message);
4323     GST_DEBUG_OBJECT (src, "got interrupted");
4324     return GST_FLOW_FLUSHING;
4325   }
4326 connect_error:
4327   {
4328     gchar *str = gst_rtsp_strresult (res);
4329     GstFlowReturn ret;
4330
4331     src->conninfo.connected = FALSE;
4332     if (res != GST_RTSP_EINTR) {
4333       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
4334           ("Could not connect to server. (%s)", str));
4335       g_free (str);
4336       ret = GST_FLOW_ERROR;
4337     } else {
4338       ret = GST_FLOW_FLUSHING;
4339     }
4340     return ret;
4341   }
4342 receive_error:
4343   {
4344     gchar *str = gst_rtsp_strresult (res);
4345
4346     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4347         ("Could not receive message. (%s)", str));
4348     g_free (str);
4349     return GST_FLOW_ERROR;
4350   }
4351 handle_request_failed:
4352   {
4353     gchar *str = gst_rtsp_strresult (res);
4354     GstFlowReturn ret;
4355
4356     gst_rtsp_message_unset (&message);
4357     if (res != GST_RTSP_EINTR) {
4358       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
4359           ("Could not handle server message. (%s)", str));
4360       g_free (str);
4361       ret = GST_FLOW_ERROR;
4362     } else {
4363       ret = GST_FLOW_FLUSHING;
4364     }
4365     return ret;
4366   }
4367 server_eof:
4368   {
4369     GST_DEBUG_OBJECT (src, "we got an eof from the server");
4370     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4371         ("The server closed the connection."));
4372     src->conninfo.connected = FALSE;
4373     gst_rtsp_message_unset (&message);
4374     return GST_FLOW_EOS;
4375   }
4376 }
4377
4378 static GstRTSPResult
4379 gst_rtspsrc_reconnect (GstRTSPSrc * src, gboolean async)
4380 {
4381   GstRTSPResult res = GST_RTSP_OK;
4382   gboolean restart;
4383
4384   GST_DEBUG_OBJECT (src, "doing reconnect");
4385
4386   GST_OBJECT_LOCK (src);
4387   /* only restart when the pads were not yet activated, else we were
4388    * streaming over UDP */
4389   restart = src->need_activate;
4390   GST_OBJECT_UNLOCK (src);
4391
4392   /* no need to restart, we're done */
4393   if (!restart)
4394     goto done;
4395
4396   /* we can try only TCP now */
4397   src->cur_protocols = GST_RTSP_LOWER_TRANS_TCP;
4398
4399   /* close and cleanup our state */
4400   if ((res = gst_rtspsrc_close (src, async, FALSE)) < 0)
4401     goto done;
4402
4403   /* see if we have TCP left to try. Also don't try TCP when we were configured
4404    * with an SDP. */
4405   if (!(src->protocols & GST_RTSP_LOWER_TRANS_TCP) || src->from_sdp)
4406     goto no_protocols;
4407
4408   /* We post a warning message now to inform the user
4409    * that nothing happened. It's most likely a firewall thing. */
4410   GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
4411       ("Could not receive any UDP packets for %.4f seconds, maybe your "
4412           "firewall is blocking it. Retrying using a TCP connection.",
4413           gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4414
4415   /* open new connection using tcp */
4416   if (gst_rtspsrc_open (src, async) < 0)
4417     goto open_failed;
4418
4419   /* start playback */
4420   if (gst_rtspsrc_play (src, &src->segment, async) < 0)
4421     goto play_failed;
4422
4423 done:
4424   return res;
4425
4426   /* ERRORS */
4427 no_protocols:
4428   {
4429     src->cur_protocols = 0;
4430     /* no transport possible, post an error and stop */
4431     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
4432         ("Could not receive any UDP packets for %.4f seconds, maybe your "
4433             "firewall is blocking it. No other protocols to try.",
4434             gst_guint64_to_gdouble (src->udp_timeout / 1000000.0)));
4435     return GST_RTSP_ERROR;
4436   }
4437 open_failed:
4438   {
4439     GST_DEBUG_OBJECT (src, "open failed");
4440     return GST_RTSP_OK;
4441   }
4442 play_failed:
4443   {
4444     GST_DEBUG_OBJECT (src, "play failed");
4445     return GST_RTSP_OK;
4446   }
4447 }
4448
4449 static void
4450 gst_rtspsrc_loop_start_cmd (GstRTSPSrc * src, gint cmd)
4451 {
4452   switch (cmd) {
4453     case CMD_OPEN:
4454       GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
4455       break;
4456     case CMD_PLAY:
4457       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PLAY request"));
4458       break;
4459     case CMD_PAUSE:
4460       GST_ELEMENT_PROGRESS (src, START, "request", ("Sending PAUSE request"));
4461       break;
4462     case CMD_CLOSE:
4463       GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
4464       break;
4465     default:
4466       break;
4467   }
4468 }
4469
4470 static void
4471 gst_rtspsrc_loop_complete_cmd (GstRTSPSrc * src, gint cmd)
4472 {
4473   switch (cmd) {
4474     case CMD_OPEN:
4475       GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
4476       break;
4477     case CMD_PLAY:
4478       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PLAY request"));
4479       break;
4480     case CMD_PAUSE:
4481       GST_ELEMENT_PROGRESS (src, COMPLETE, "request", ("Sent PAUSE request"));
4482       break;
4483     case CMD_CLOSE:
4484       GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
4485       break;
4486     default:
4487       break;
4488   }
4489 }
4490
4491 static void
4492 gst_rtspsrc_loop_cancel_cmd (GstRTSPSrc * src, gint cmd)
4493 {
4494   switch (cmd) {
4495     case CMD_OPEN:
4496       GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
4497       break;
4498     case CMD_PLAY:
4499       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PLAY canceled"));
4500       break;
4501     case CMD_PAUSE:
4502       GST_ELEMENT_PROGRESS (src, CANCELED, "request", ("PAUSE canceled"));
4503       break;
4504     case CMD_CLOSE:
4505       GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
4506       break;
4507     default:
4508       break;
4509   }
4510 }
4511
4512 static void
4513 gst_rtspsrc_loop_error_cmd (GstRTSPSrc * src, gint cmd)
4514 {
4515   switch (cmd) {
4516     case CMD_OPEN:
4517       GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
4518       break;
4519     case CMD_PLAY:
4520       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PLAY failed"));
4521       break;
4522     case CMD_PAUSE:
4523       GST_ELEMENT_PROGRESS (src, ERROR, "request", ("PAUSE failed"));
4524       break;
4525     case CMD_CLOSE:
4526       GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
4527       break;
4528     default:
4529       break;
4530   }
4531 }
4532
4533 static void
4534 gst_rtspsrc_loop_end_cmd (GstRTSPSrc * src, gint cmd, GstRTSPResult ret)
4535 {
4536   if (ret == GST_RTSP_OK)
4537     gst_rtspsrc_loop_complete_cmd (src, cmd);
4538   else if (ret == GST_RTSP_EINTR)
4539     gst_rtspsrc_loop_cancel_cmd (src, cmd);
4540   else
4541     gst_rtspsrc_loop_error_cmd (src, cmd);
4542 }
4543
4544 static gboolean
4545 gst_rtspsrc_loop_send_cmd (GstRTSPSrc * src, gint cmd, gint mask)
4546 {
4547   gint old;
4548   gboolean flushed = FALSE;
4549
4550   /* start new request */
4551   gst_rtspsrc_loop_start_cmd (src, cmd);
4552
4553   GST_DEBUG_OBJECT (src, "sending cmd %d", cmd);
4554
4555   GST_OBJECT_LOCK (src);
4556   old = src->pending_cmd;
4557   if (old == CMD_RECONNECT) {
4558     GST_DEBUG_OBJECT (src, "ignore, we were reconnecting");
4559     cmd = CMD_RECONNECT;
4560   }
4561   if (old != CMD_WAIT) {
4562     src->pending_cmd = CMD_WAIT;
4563     GST_OBJECT_UNLOCK (src);
4564     /* cancel previous request */
4565     GST_DEBUG_OBJECT (src, "cancel previous request %d", old);
4566     gst_rtspsrc_loop_cancel_cmd (src, old);
4567     GST_OBJECT_LOCK (src);
4568   }
4569   src->pending_cmd = cmd;
4570   /* interrupt if allowed */
4571   if (src->busy_cmd & mask) {
4572     GST_DEBUG_OBJECT (src, "connection flush busy %d", src->busy_cmd);
4573     gst_rtspsrc_connection_flush (src, TRUE);
4574     flushed = TRUE;
4575   } else {
4576     GST_DEBUG_OBJECT (src, "not interrupting busy cmd %d", src->busy_cmd);
4577   }
4578   if (src->task)
4579     gst_task_start (src->task);
4580   GST_OBJECT_UNLOCK (src);
4581
4582   return flushed;
4583 }
4584
4585 static gboolean
4586 gst_rtspsrc_loop (GstRTSPSrc * src)
4587 {
4588   GstFlowReturn ret;
4589
4590   if (!src->conninfo.connection || !src->conninfo.connected)
4591     goto no_connection;
4592
4593   if (src->interleaved)
4594     ret = gst_rtspsrc_loop_interleaved (src);
4595   else
4596     ret = gst_rtspsrc_loop_udp (src);
4597
4598   if (ret != GST_FLOW_OK)
4599     goto pause;
4600
4601   return TRUE;
4602
4603   /* ERRORS */
4604 no_connection:
4605   {
4606     GST_WARNING_OBJECT (src, "we are not connected");
4607     ret = GST_FLOW_FLUSHING;
4608     goto pause;
4609   }
4610 pause:
4611   {
4612     const gchar *reason = gst_flow_get_name (ret);
4613
4614     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
4615     src->running = FALSE;
4616     if (ret == GST_FLOW_EOS) {
4617       /* perform EOS logic */
4618       if (src->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4619         gst_element_post_message (GST_ELEMENT_CAST (src),
4620             gst_message_new_segment_done (GST_OBJECT_CAST (src),
4621                 src->segment.format, src->segment.position));
4622         gst_rtspsrc_push_event (src,
4623             gst_event_new_segment_done (src->segment.format,
4624                 src->segment.position));
4625       } else {
4626         gst_rtspsrc_push_event (src, gst_event_new_eos ());
4627       }
4628     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4629       /* for fatal errors we post an error message, post the error before the
4630        * EOS so the app knows about the error first. */
4631       GST_ELEMENT_ERROR (src, STREAM, FAILED,
4632           ("Internal data flow error."),
4633           ("streaming task paused, reason %s (%d)", reason, ret));
4634       gst_rtspsrc_push_event (src, gst_event_new_eos ());
4635     }
4636     gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_LOOP);
4637     return FALSE;
4638   }
4639 }
4640
4641 #ifndef GST_DISABLE_GST_DEBUG
4642 static const gchar *
4643 gst_rtsp_auth_method_to_string (GstRTSPAuthMethod method)
4644 {
4645   gint index = 0;
4646
4647   while (method != 0) {
4648     index++;
4649     method >>= 1;
4650   }
4651   switch (index) {
4652     case 0:
4653       return "None";
4654     case 1:
4655       return "Basic";
4656     case 2:
4657       return "Digest";
4658   }
4659
4660   return "Unknown";
4661 }
4662 #endif
4663
4664 static const gchar *
4665 gst_rtspsrc_skip_lws (const gchar * s)
4666 {
4667   while (g_ascii_isspace (*s))
4668     s++;
4669   return s;
4670 }
4671
4672 static const gchar *
4673 gst_rtspsrc_unskip_lws (const gchar * s, const gchar * start)
4674 {
4675   while (s > start && g_ascii_isspace (*(s - 1)))
4676     s--;
4677   return s;
4678 }
4679
4680 static const gchar *
4681 gst_rtspsrc_skip_commas (const gchar * s)
4682 {
4683   /* The grammar allows for multiple commas */
4684   while (g_ascii_isspace (*s) || *s == ',')
4685     s++;
4686   return s;
4687 }
4688
4689 static const gchar *
4690 gst_rtspsrc_skip_item (const gchar * s)
4691 {
4692   gboolean quoted = FALSE;
4693   const gchar *start = s;
4694
4695   /* A list item ends at the last non-whitespace character
4696    * before a comma which is not inside a quoted-string. Or at
4697    * the end of the string.
4698    */
4699   while (*s) {
4700     if (*s == '"')
4701       quoted = !quoted;
4702     else if (quoted) {
4703       if (*s == '\\' && *(s + 1))
4704         s++;
4705     } else {
4706       if (*s == ',')
4707         break;
4708     }
4709     s++;
4710   }
4711
4712   return gst_rtspsrc_unskip_lws (s, start);
4713 }
4714
4715 static void
4716 gst_rtsp_decode_quoted_string (gchar * quoted_string)
4717 {
4718   gchar *src, *dst;
4719
4720   src = quoted_string + 1;
4721   dst = quoted_string;
4722   while (*src && *src != '"') {
4723     if (*src == '\\' && *(src + 1))
4724       src++;
4725     *dst++ = *src++;
4726   }
4727   *dst = '\0';
4728 }
4729
4730 /* Extract the authentication tokens that the server provided for each method
4731  * into an array of structures and give those to the connection object.
4732  */
4733 static void
4734 gst_rtspsrc_parse_digest_challenge (GstRTSPConnection * conn,
4735     const gchar * header, gboolean * stale)
4736 {
4737   GSList *list = NULL, *iter;
4738   const gchar *end;
4739   gchar *item, *eq, *name_end, *value;
4740
4741   g_return_if_fail (stale != NULL);
4742
4743   gst_rtsp_connection_clear_auth_params (conn);
4744   *stale = FALSE;
4745
4746   /* Parse a header whose content is described by RFC2616 as
4747    * "#something", where "something" does not itself contain commas,
4748    * except as part of quoted-strings, into a list of allocated strings.
4749    */
4750   header = gst_rtspsrc_skip_commas (header);
4751   while (*header) {
4752     end = gst_rtspsrc_skip_item (header);
4753     list = g_slist_prepend (list, g_strndup (header, end - header));
4754     header = gst_rtspsrc_skip_commas (end);
4755   }
4756   if (!list)
4757     return;
4758
4759   list = g_slist_reverse (list);
4760   for (iter = list; iter; iter = iter->next) {
4761     item = iter->data;
4762
4763     eq = strchr (item, '=');
4764     if (eq) {
4765       name_end = (gchar *) gst_rtspsrc_unskip_lws (eq, item);
4766       if (name_end == item) {
4767         /* That's no good... */
4768         g_free (item);
4769         continue;
4770       }
4771
4772       *name_end = '\0';
4773
4774       value = (gchar *) gst_rtspsrc_skip_lws (eq + 1);
4775       if (*value == '"')
4776         gst_rtsp_decode_quoted_string (value);
4777     } else
4778       value = NULL;
4779
4780     if (item && (strcmp (item, "stale") == 0) &&
4781         value && (strcmp (value, "TRUE") == 0))
4782       *stale = TRUE;
4783     gst_rtsp_connection_set_auth_param (conn, item, value);
4784     g_free (item);
4785   }
4786
4787   g_slist_free (list);
4788 }
4789
4790 /* Parse a WWW-Authenticate Response header and determine the
4791  * available authentication methods
4792  *
4793  * This code should also cope with the fact that each WWW-Authenticate
4794  * header can contain multiple challenge methods + tokens
4795  *
4796  * At the moment, for Basic auth, we just do a minimal check and don't
4797  * even parse out the realm */
4798 static void
4799 gst_rtspsrc_parse_auth_hdr (gchar * hdr, GstRTSPAuthMethod * methods,
4800     GstRTSPConnection * conn, gboolean * stale)
4801 {
4802   gchar *start;
4803
4804   g_return_if_fail (hdr != NULL);
4805   g_return_if_fail (methods != NULL);
4806   g_return_if_fail (stale != NULL);
4807
4808   /* Skip whitespace at the start of the string */
4809   for (start = hdr; start[0] != '\0' && g_ascii_isspace (start[0]); start++);
4810
4811   if (g_ascii_strncasecmp (start, "basic", 5) == 0)
4812     *methods |= GST_RTSP_AUTH_BASIC;
4813   else if (g_ascii_strncasecmp (start, "digest ", 7) == 0) {
4814     *methods |= GST_RTSP_AUTH_DIGEST;
4815     gst_rtspsrc_parse_digest_challenge (conn, &start[7], stale);
4816   }
4817 }
4818
4819 /**
4820  * gst_rtspsrc_setup_auth:
4821  * @src: the rtsp source
4822  *
4823  * Configure a username and password and auth method on the
4824  * connection object based on a response we received from the
4825  * peer.
4826  *
4827  * Currently, this requires that a username and password were supplied
4828  * in the uri. In the future, they may be requested on demand by sending
4829  * a message up the bus.
4830  *
4831  * Returns: TRUE if authentication information could be set up correctly.
4832  */
4833 static gboolean
4834 gst_rtspsrc_setup_auth (GstRTSPSrc * src, GstRTSPMessage * response)
4835 {
4836   gchar *user = NULL;
4837   gchar *pass = NULL;
4838   GstRTSPAuthMethod avail_methods = GST_RTSP_AUTH_NONE;
4839   GstRTSPAuthMethod method;
4840   GstRTSPResult auth_result;
4841   GstRTSPUrl *url;
4842   GstRTSPConnection *conn;
4843   gchar *hdr;
4844   gboolean stale = FALSE;
4845
4846   conn = src->conninfo.connection;
4847
4848   /* Identify the available auth methods and see if any are supported */
4849   if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_WWW_AUTHENTICATE,
4850           &hdr, 0) == GST_RTSP_OK) {
4851     gst_rtspsrc_parse_auth_hdr (hdr, &avail_methods, conn, &stale);
4852   }
4853
4854   if (avail_methods == GST_RTSP_AUTH_NONE)
4855     goto no_auth_available;
4856
4857   /* For digest auth, if the response indicates that the session
4858    * data are stale, we just update them in the connection object and
4859    * return TRUE to retry the request */
4860   if (stale)
4861     src->tried_url_auth = FALSE;
4862
4863   url = gst_rtsp_connection_get_url (conn);
4864
4865   /* Do we have username and password available? */
4866   if (url != NULL && !src->tried_url_auth && url->user != NULL
4867       && url->passwd != NULL) {
4868     user = url->user;
4869     pass = url->passwd;
4870     src->tried_url_auth = TRUE;
4871     GST_DEBUG_OBJECT (src,
4872         "Attempting authentication using credentials from the URL");
4873   } else {
4874     user = src->user_id;
4875     pass = src->user_pw;
4876     GST_DEBUG_OBJECT (src,
4877         "Attempting authentication using credentials from the properties");
4878   }
4879
4880   /* FIXME: If the url didn't contain username and password or we tried them
4881    * already, request a username and passwd from the application via some kind
4882    * of credentials request message */
4883
4884   /* If we don't have a username and passwd at this point, bail out. */
4885   if (user == NULL || pass == NULL)
4886     goto no_user_pass;
4887
4888   /* Try to configure for each available authentication method, strongest to
4889    * weakest */
4890   for (method = GST_RTSP_AUTH_MAX; method != GST_RTSP_AUTH_NONE; method >>= 1) {
4891     /* Check if this method is available on the server */
4892     if ((method & avail_methods) == 0)
4893       continue;
4894
4895     /* Pass the credentials to the connection to try on the next request */
4896     auth_result = gst_rtsp_connection_set_auth (conn, method, user, pass);
4897     /* INVAL indicates an invalid username/passwd were supplied, so we'll just
4898      * ignore it and end up retrying later */
4899     if (auth_result == GST_RTSP_OK || auth_result == GST_RTSP_EINVAL) {
4900       GST_DEBUG_OBJECT (src, "Attempting %s authentication",
4901           gst_rtsp_auth_method_to_string (method));
4902       break;
4903     }
4904   }
4905
4906   if (method == GST_RTSP_AUTH_NONE)
4907     goto no_auth_available;
4908
4909   return TRUE;
4910
4911 no_auth_available:
4912   {
4913     /* Output an error indicating that we couldn't connect because there were
4914      * no supported authentication protocols */
4915     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
4916         ("No supported authentication protocol was found"));
4917     return FALSE;
4918   }
4919 no_user_pass:
4920   {
4921     /* We don't fire an error message, we just return FALSE and let the
4922      * normal NOT_AUTHORIZED error be propagated */
4923     return FALSE;
4924   }
4925 }
4926
4927 static GstRTSPResult
4928 gst_rtspsrc_try_send (GstRTSPSrc * src, GstRTSPConnection * conn,
4929     GstRTSPMessage * request, GstRTSPMessage * response,
4930     GstRTSPStatusCode * code)
4931 {
4932   GstRTSPResult res;
4933   GstRTSPStatusCode thecode;
4934   gchar *content_base = NULL;
4935   gint try = 0;
4936
4937 again:
4938   if (!src->short_header)
4939     gst_rtsp_ext_list_before_send (src->extensions, request);
4940
4941   GST_DEBUG_OBJECT (src, "sending message");
4942
4943   if (src->debug)
4944     gst_rtsp_message_dump (request);
4945
4946   res = gst_rtspsrc_connection_send (src, conn, request, src->ptcp_timeout);
4947   if (res < 0)
4948     goto send_error;
4949
4950   gst_rtsp_connection_reset_timeout (conn);
4951
4952 next:
4953   res = gst_rtspsrc_connection_receive (src, conn, response, src->ptcp_timeout);
4954   if (res < 0)
4955     goto receive_error;
4956
4957   if (src->debug)
4958     gst_rtsp_message_dump (response);
4959
4960   switch (response->type) {
4961     case GST_RTSP_MESSAGE_REQUEST:
4962       res = gst_rtspsrc_handle_request (src, conn, response);
4963       if (res == GST_RTSP_EEOF)
4964         goto server_eof;
4965       else if (res < 0)
4966         goto handle_request_failed;
4967       goto next;
4968     case GST_RTSP_MESSAGE_RESPONSE:
4969       /* ok, a response is good */
4970       GST_DEBUG_OBJECT (src, "received response message");
4971       break;
4972     case GST_RTSP_MESSAGE_DATA:
4973       /* get next response */
4974       GST_DEBUG_OBJECT (src, "handle data response message");
4975       gst_rtspsrc_handle_data (src, response);
4976       goto next;
4977     default:
4978       GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
4979           response->type);
4980       goto next;
4981   }
4982
4983   thecode = response->type_data.response.code;
4984
4985   GST_DEBUG_OBJECT (src, "got response message %d", thecode);
4986
4987   /* if the caller wanted the result code, we store it. */
4988   if (code)
4989     *code = thecode;
4990
4991   /* If the request didn't succeed, bail out before doing any more */
4992   if (thecode != GST_RTSP_STS_OK)
4993     return GST_RTSP_OK;
4994
4995   /* store new content base if any */
4996   gst_rtsp_message_get_header (response, GST_RTSP_HDR_CONTENT_BASE,
4997       &content_base, 0);
4998   if (content_base) {
4999     g_free (src->content_base);
5000     src->content_base = g_strdup (content_base);
5001   }
5002   gst_rtsp_ext_list_after_send (src->extensions, request, response);
5003
5004   return GST_RTSP_OK;
5005
5006   /* ERRORS */
5007 send_error:
5008   {
5009     gchar *str = gst_rtsp_strresult (res);
5010
5011     if (res != GST_RTSP_EINTR) {
5012       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5013           ("Could not send message. (%s)", str));
5014     } else {
5015       GST_WARNING_OBJECT (src, "send interrupted");
5016     }
5017     g_free (str);
5018     return res;
5019   }
5020 receive_error:
5021   {
5022     switch (res) {
5023       case GST_RTSP_EEOF:
5024         GST_WARNING_OBJECT (src, "server closed connection");
5025         if ((try == 0) && !src->interleaved && src->udp_reconnect) {
5026           try++;
5027           /* if reconnect succeeds, try again */
5028           if ((res =
5029                   gst_rtsp_conninfo_reconnect (src, &src->conninfo,
5030                       FALSE)) == 0)
5031             goto again;
5032         }
5033         /* only try once after reconnect, then fallthrough and error out */
5034       default:
5035       {
5036         gchar *str = gst_rtsp_strresult (res);
5037
5038         if (res != GST_RTSP_EINTR) {
5039           GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5040               ("Could not receive message. (%s)", str));
5041         } else {
5042           GST_WARNING_OBJECT (src, "receive interrupted");
5043         }
5044         g_free (str);
5045         break;
5046       }
5047     }
5048     return res;
5049   }
5050 handle_request_failed:
5051   {
5052     /* ERROR was posted */
5053     gst_rtsp_message_unset (response);
5054     return res;
5055   }
5056 server_eof:
5057   {
5058     GST_DEBUG_OBJECT (src, "we got an eof from the server");
5059     GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
5060         ("The server closed the connection."));
5061     gst_rtsp_message_unset (response);
5062     return res;
5063   }
5064 }
5065
5066 /**
5067  * gst_rtspsrc_send:
5068  * @src: the rtsp source
5069  * @conn: the connection to send on
5070  * @request: must point to a valid request
5071  * @response: must point to an empty #GstRTSPMessage
5072  * @code: an optional code result
5073  *
5074  * send @request and retrieve the response in @response. optionally @code can be
5075  * non-NULL in which case it will contain the status code of the response.
5076  *
5077  * If This function returns #GST_RTSP_OK, @response will contain a valid response
5078  * message that should be cleaned with gst_rtsp_message_unset() after usage.
5079  *
5080  * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
5081  * @response message) if the response code was not 200 (OK).
5082  *
5083  * If the attempt results in an authentication failure, then this will attempt
5084  * to retrieve authentication credentials via gst_rtspsrc_setup_auth and retry
5085  * the request.
5086  *
5087  * Returns: #GST_RTSP_OK if the processing was successful.
5088  */
5089 static GstRTSPResult
5090 gst_rtspsrc_send (GstRTSPSrc * src, GstRTSPConnection * conn,
5091     GstRTSPMessage * request, GstRTSPMessage * response,
5092     GstRTSPStatusCode * code)
5093 {
5094   GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
5095   GstRTSPResult res = GST_RTSP_ERROR;
5096   gint count;
5097   gboolean retry;
5098   GstRTSPMethod method = GST_RTSP_INVALID;
5099
5100   count = 0;
5101   do {
5102     retry = FALSE;
5103
5104     /* make sure we don't loop forever */
5105     if (count++ > 8)
5106       break;
5107
5108     /* save method so we can disable it when the server complains */
5109     method = request->type_data.request.method;
5110
5111     if ((res =
5112             gst_rtspsrc_try_send (src, conn, request, response, &int_code)) < 0)
5113       goto error;
5114
5115     switch (int_code) {
5116       case GST_RTSP_STS_UNAUTHORIZED:
5117         if (gst_rtspsrc_setup_auth (src, response)) {
5118           /* Try the request/response again after configuring the auth info
5119            * and loop again */
5120           retry = TRUE;
5121         }
5122         break;
5123       default:
5124         break;
5125     }
5126   } while (retry == TRUE);
5127
5128   /* If the user requested the code, let them handle errors, otherwise
5129    * post an error below */
5130   if (code != NULL)
5131     *code = int_code;
5132   else if (int_code != GST_RTSP_STS_OK)
5133     goto error_response;
5134
5135   return res;
5136
5137   /* ERRORS */
5138 error:
5139   {
5140     GST_DEBUG_OBJECT (src, "got error %d", res);
5141     return res;
5142   }
5143 error_response:
5144   {
5145     res = GST_RTSP_ERROR;
5146
5147     switch (response->type_data.response.code) {
5148       case GST_RTSP_STS_NOT_FOUND:
5149         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
5150                 response->type_data.response.reason));
5151         break;
5152       case GST_RTSP_STS_MOVED_PERMANENTLY:
5153       case GST_RTSP_STS_MOVE_TEMPORARILY:
5154       {
5155         gchar *new_location;
5156         GstRTSPLowerTrans transports;
5157
5158         GST_DEBUG_OBJECT (src, "got redirection");
5159         /* if we don't have a Location Header, we must error */
5160         if (gst_rtsp_message_get_header (response, GST_RTSP_HDR_LOCATION,
5161                 &new_location, 0) < 0)
5162           break;
5163
5164         /* When we receive a redirect result, we go back to the INIT state after
5165          * parsing the new URI. The caller should do the needed steps to issue
5166          * a new setup when it detects this state change. */
5167         GST_DEBUG_OBJECT (src, "redirection to %s", new_location);
5168
5169         /* save current transports */
5170         if (src->conninfo.url)
5171           transports = src->conninfo.url->transports;
5172         else
5173           transports = GST_RTSP_LOWER_TRANS_UNKNOWN;
5174
5175         gst_rtspsrc_uri_set_uri (GST_URI_HANDLER (src), new_location, NULL);
5176
5177         /* set old transports */
5178         if (src->conninfo.url && transports != GST_RTSP_LOWER_TRANS_UNKNOWN)
5179           src->conninfo.url->transports = transports;
5180
5181         src->need_redirect = TRUE;
5182         src->state = GST_RTSP_STATE_INIT;
5183         res = GST_RTSP_OK;
5184         break;
5185       }
5186       case GST_RTSP_STS_NOT_ACCEPTABLE:
5187       case GST_RTSP_STS_NOT_IMPLEMENTED:
5188       case GST_RTSP_STS_METHOD_NOT_ALLOWED:
5189         GST_WARNING_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
5190             gst_rtsp_method_as_text (method));
5191         src->methods &= ~method;
5192         res = GST_RTSP_OK;
5193         break;
5194       default:
5195         GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5196             ("Got error response: %d (%s).", response->type_data.response.code,
5197                 response->type_data.response.reason));
5198         break;
5199     }
5200     /* if we return ERROR we should unset the response ourselves */
5201     if (res == GST_RTSP_ERROR)
5202       gst_rtsp_message_unset (response);
5203
5204     return res;
5205   }
5206 }
5207
5208 static GstRTSPResult
5209 gst_rtspsrc_send_cb (GstRTSPExtension * ext, GstRTSPMessage * request,
5210     GstRTSPMessage * response, GstRTSPSrc * src)
5211 {
5212   return gst_rtspsrc_send (src, src->conninfo.connection, request, response,
5213       NULL);
5214 }
5215
5216
5217 /* parse the response and collect all the supported methods. We need this
5218  * information so that we don't try to send an unsupported request to the
5219  * server.
5220  */
5221 static gboolean
5222 gst_rtspsrc_parse_methods (GstRTSPSrc * src, GstRTSPMessage * response)
5223 {
5224   GstRTSPHeaderField field;
5225   gchar *respoptions;
5226   gint indx = 0;
5227
5228   /* reset supported methods */
5229   src->methods = 0;
5230
5231   /* Try Allow Header first */
5232   field = GST_RTSP_HDR_ALLOW;
5233   while (TRUE) {
5234     respoptions = NULL;
5235     gst_rtsp_message_get_header (response, field, &respoptions, indx);
5236     if (indx == 0 && !respoptions) {
5237       /* if no Allow header was found then try the Public header... */
5238       field = GST_RTSP_HDR_PUBLIC;
5239       gst_rtsp_message_get_header (response, field, &respoptions, indx);
5240     }
5241     if (!respoptions)
5242       break;
5243
5244     src->methods |= gst_rtsp_options_from_text (respoptions);
5245
5246     indx++;
5247   }
5248
5249   if (src->methods == 0) {
5250     /* neither Allow nor Public are required, assume the server supports
5251      * at least DESCRIBE, SETUP, we always assume it supports PLAY as
5252      * well. */
5253     GST_DEBUG_OBJECT (src, "could not get OPTIONS");
5254     src->methods = GST_RTSP_DESCRIBE | GST_RTSP_SETUP;
5255   }
5256   /* always assume PLAY, FIXME, extensions should be able to override
5257    * this */
5258   src->methods |= GST_RTSP_PLAY;
5259   /* also assume it will support Range */
5260   src->seekable = TRUE;
5261
5262   /* we need describe and setup */
5263   if (!(src->methods & GST_RTSP_DESCRIBE))
5264     goto no_describe;
5265   if (!(src->methods & GST_RTSP_SETUP))
5266     goto no_setup;
5267
5268   return TRUE;
5269
5270   /* ERRORS */
5271 no_describe:
5272   {
5273     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5274         ("Server does not support DESCRIBE."));
5275     return FALSE;
5276   }
5277 no_setup:
5278   {
5279     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
5280         ("Server does not support SETUP."));
5281     return FALSE;
5282   }
5283 }
5284
5285 /* masks to be kept in sync with the hardcoded protocol order of preference
5286  * in code below */
5287 static guint protocol_masks[] = {
5288   GST_RTSP_LOWER_TRANS_UDP,
5289   GST_RTSP_LOWER_TRANS_UDP_MCAST,
5290   GST_RTSP_LOWER_TRANS_TCP,
5291   0
5292 };
5293
5294 static GstRTSPResult
5295 gst_rtspsrc_create_transports_string (GstRTSPSrc * src,
5296     GstRTSPLowerTrans protocols, gchar ** transports)
5297 {
5298   GstRTSPResult res;
5299   GString *result;
5300   gboolean add_udp_str;
5301
5302   *transports = NULL;
5303
5304   res =
5305       gst_rtsp_ext_list_get_transports (src->extensions, protocols, transports);
5306
5307   if (res < 0)
5308     goto failed;
5309
5310   GST_DEBUG_OBJECT (src, "got transports %s", GST_STR_NULL (*transports));
5311
5312   /* extension listed transports, use those */
5313   if (*transports != NULL)
5314     return GST_RTSP_OK;
5315
5316   /* it's the default */
5317   add_udp_str = FALSE;
5318
5319   /* the default RTSP transports */
5320   result = g_string_new ("");
5321   if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
5322     GST_DEBUG_OBJECT (src, "adding UDP unicast");
5323
5324     g_string_append (result, "RTP/AVP");
5325     if (add_udp_str)
5326       g_string_append (result, "/UDP");
5327     g_string_append (result, ";unicast;client_port=%%u1-%%u2");
5328   } else if (protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST) {
5329     GST_DEBUG_OBJECT (src, "adding UDP multicast");
5330
5331     /* we don't have to allocate any UDP ports yet, if the selected transport
5332      * turns out to be multicast we can create them and join the multicast
5333      * group indicated in the transport reply */
5334     if (result->len > 0)
5335       g_string_append (result, ",");
5336     g_string_append (result, "RTP/AVP");
5337     if (add_udp_str)
5338       g_string_append (result, "/UDP");
5339     g_string_append (result, ";multicast");
5340     if (src->next_port_num != 0) {
5341       if (src->client_port_range.max > 0 &&
5342           src->next_port_num >= src->client_port_range.max)
5343         goto no_ports;
5344
5345       g_string_append_printf (result, ";client_port=%d-%d",
5346           src->next_port_num, src->next_port_num + 1);
5347     }
5348   } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
5349     GST_DEBUG_OBJECT (src, "adding TCP");
5350
5351     if (result->len > 0)
5352       g_string_append (result, ",");
5353     g_string_append (result, "RTP/AVP/TCP;unicast;interleaved=%%i1-%%i2");
5354   }
5355   *transports = g_string_free (result, FALSE);
5356
5357   GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
5358
5359   return GST_RTSP_OK;
5360
5361   /* ERRORS */
5362 failed:
5363   {
5364     GST_ERROR ("extension gave error %d", res);
5365     return res;
5366   }
5367 no_ports:
5368   {
5369     GST_ERROR ("no more ports available");
5370     return GST_RTSP_ERROR;
5371   }
5372 }
5373
5374 static GstRTSPResult
5375 gst_rtspsrc_prepare_transports (GstRTSPStream * stream, gchar ** transports,
5376     gint orig_rtpport, gint orig_rtcpport)
5377 {
5378   GstRTSPSrc *src;
5379   gint nr_udp, nr_int;
5380   gchar *next, *p;
5381   gint rtpport = 0, rtcpport = 0;
5382   GString *str;
5383
5384   src = stream->parent;
5385
5386   /* find number of placeholders first */
5387   if (strstr (*transports, "%%i2"))
5388     nr_int = 2;
5389   else if (strstr (*transports, "%%i1"))
5390     nr_int = 1;
5391   else
5392     nr_int = 0;
5393
5394   if (strstr (*transports, "%%u2"))
5395     nr_udp = 2;
5396   else if (strstr (*transports, "%%u1"))
5397     nr_udp = 1;
5398   else
5399     nr_udp = 0;
5400
5401   if (nr_udp == 0 && nr_int == 0)
5402     goto done;
5403
5404   if (nr_udp > 0) {
5405     if (!orig_rtpport || !orig_rtcpport) {
5406       if (!gst_rtspsrc_alloc_udp_ports (stream, &rtpport, &rtcpport))
5407         goto failed;
5408     } else {
5409       rtpport = orig_rtpport;
5410       rtcpport = orig_rtcpport;
5411     }
5412   }
5413
5414   str = g_string_new ("");
5415   p = *transports;
5416   while ((next = strstr (p, "%%"))) {
5417     g_string_append_len (str, p, next - p);
5418     if (next[2] == 'u') {
5419       if (next[3] == '1')
5420         g_string_append_printf (str, "%d", rtpport);
5421       else if (next[3] == '2')
5422         g_string_append_printf (str, "%d", rtcpport);
5423     }
5424     if (next[2] == 'i') {
5425       if (next[3] == '1')
5426         g_string_append_printf (str, "%d", src->free_channel);
5427       else if (next[3] == '2')
5428         g_string_append_printf (str, "%d", src->free_channel + 1);
5429     }
5430
5431     p = next + 4;
5432   }
5433   /* append final part */
5434   g_string_append (str, p);
5435
5436   g_free (*transports);
5437   *transports = g_string_free (str, FALSE);
5438
5439 done:
5440   return GST_RTSP_OK;
5441
5442   /* ERRORS */
5443 failed:
5444   {
5445     GST_ERROR ("failed to allocate udp ports");
5446     return GST_RTSP_ERROR;
5447   }
5448 }
5449
5450 static gboolean
5451 gst_rtspsrc_stream_is_real_media (GstRTSPStream * stream)
5452 {
5453   gboolean res = FALSE;
5454
5455   if (stream->caps) {
5456     GstStructure *s;
5457     const gchar *enc = NULL;
5458
5459     s = gst_caps_get_structure (stream->caps, 0);
5460     if ((enc = gst_structure_get_string (s, "encoding-name"))) {
5461       res = (strstr (enc, "-REAL") != NULL);
5462     }
5463   }
5464   return res;
5465 }
5466
5467 /* Perform the SETUP request for all the streams.
5468  *
5469  * We ask the server for a specific transport, which initially includes all the
5470  * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
5471  * two local UDP ports that we send to the server.
5472  *
5473  * Once the server replied with a transport, we configure the other streams
5474  * with the same transport.
5475  *
5476  * This function will also configure the stream for the selected transport,
5477  * which basically means creating the pipeline.
5478  */
5479 static GstRTSPResult
5480 gst_rtspsrc_setup_streams (GstRTSPSrc * src, gboolean async)
5481 {
5482   GList *walk;
5483   GstRTSPResult res = GST_RTSP_ERROR;
5484   GstRTSPMessage request = { 0 };
5485   GstRTSPMessage response = { 0 };
5486   GstRTSPStream *stream = NULL;
5487   GstRTSPLowerTrans protocols;
5488   GstRTSPStatusCode code;
5489   gboolean unsupported_real = FALSE;
5490   gint rtpport, rtcpport;
5491   GstRTSPUrl *url;
5492   gchar *hval;
5493
5494   if (src->conninfo.connection) {
5495     url = gst_rtsp_connection_get_url (src->conninfo.connection);
5496     /* we initially allow all configured lower transports. based on the URL
5497      * transports and the replies from the server we narrow them down. */
5498     protocols = url->transports & src->cur_protocols;
5499   } else {
5500     url = NULL;
5501     protocols = src->cur_protocols;
5502   }
5503
5504   if (protocols == 0)
5505     goto no_protocols;
5506
5507   /* reset some state */
5508   src->free_channel = 0;
5509   src->interleaved = FALSE;
5510   src->need_activate = FALSE;
5511   /* keep track of next port number, 0 is random */
5512   src->next_port_num = src->client_port_range.min;
5513   rtpport = rtcpport = 0;
5514
5515   if (G_UNLIKELY (src->streams == NULL))
5516     goto no_streams;
5517
5518   for (walk = src->streams; walk; walk = g_list_next (walk)) {
5519     GstRTSPConnection *conn;
5520     gchar *transports;
5521     gint retry = 0;
5522     guint mask = 0;
5523     gboolean selected;
5524
5525     stream = (GstRTSPStream *) walk->data;
5526
5527     /* see if we need to configure this stream */
5528     if (!gst_rtsp_ext_list_configure_stream (src->extensions, stream->caps)) {
5529       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by extension",
5530           stream);
5531       stream->disabled = TRUE;
5532       continue;
5533     }
5534
5535     g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_SELECT_STREAM], 0,
5536         stream->id, stream->caps, &selected);
5537     if (!selected) {
5538       GST_DEBUG_OBJECT (src, "skipping stream %p, disabled by signal", stream);
5539       stream->disabled = TRUE;
5540       continue;
5541     }
5542     stream->disabled = FALSE;
5543
5544     /* merge/overwrite global caps */
5545     if (stream->caps) {
5546       guint j, num;
5547       GstStructure *s;
5548
5549       s = gst_caps_get_structure (stream->caps, 0);
5550
5551       num = gst_structure_n_fields (src->props);
5552       for (j = 0; j < num; j++) {
5553         const gchar *name;
5554         const GValue *val;
5555
5556         name = gst_structure_nth_field_name (src->props, j);
5557         val = gst_structure_get_value (src->props, name);
5558         gst_structure_set_value (s, name, val);
5559
5560         GST_DEBUG_OBJECT (src, "copied %s", name);
5561       }
5562     }
5563
5564     /* skip setup if we have no URL for it */
5565     if (stream->conninfo.location == NULL) {
5566       GST_DEBUG_OBJECT (src, "skipping stream %p, no setup", stream);
5567       continue;
5568     }
5569
5570     if (src->conninfo.connection == NULL) {
5571       if (!gst_rtsp_conninfo_connect (src, &stream->conninfo, async)) {
5572         GST_DEBUG_OBJECT (src, "skipping stream %p, failed to connect", stream);
5573         continue;
5574       }
5575       conn = stream->conninfo.connection;
5576     } else {
5577       conn = src->conninfo.connection;
5578     }
5579     GST_DEBUG_OBJECT (src, "doing setup of stream %p with %s", stream,
5580         stream->conninfo.location);
5581
5582     /* if we have a multicast connection, only suggest multicast from now on */
5583     if (stream->is_multicast)
5584       protocols &= GST_RTSP_LOWER_TRANS_UDP_MCAST;
5585
5586   next_protocol:
5587     /* first selectable protocol */
5588     while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5589       mask++;
5590     if (!protocol_masks[mask])
5591       goto no_protocols;
5592
5593   retry:
5594     GST_DEBUG_OBJECT (src, "protocols = 0x%x, protocol mask = 0x%x", protocols,
5595         protocol_masks[mask]);
5596     /* create a string with first transport in line */
5597     transports = NULL;
5598     res = gst_rtspsrc_create_transports_string (src,
5599         protocols & protocol_masks[mask], &transports);
5600     if (res < 0 || transports == NULL)
5601       goto setup_transport_failed;
5602
5603     if (strlen (transports) == 0) {
5604       g_free (transports);
5605       GST_DEBUG_OBJECT (src, "no transports found");
5606       mask++;
5607       goto next_protocol;
5608     }
5609
5610     GST_DEBUG_OBJECT (src, "replace ports in %s", GST_STR_NULL (transports));
5611
5612     /* replace placeholders with real values, this function will optionally
5613      * allocate UDP ports and other info needed to execute the setup request */
5614     res = gst_rtspsrc_prepare_transports (stream, &transports,
5615         retry > 0 ? rtpport : 0, retry > 0 ? rtcpport : 0);
5616     if (res < 0) {
5617       g_free (transports);
5618       goto setup_transport_failed;
5619     }
5620
5621     GST_DEBUG_OBJECT (src, "transport is now %s", GST_STR_NULL (transports));
5622
5623     /* create SETUP request */
5624     res =
5625         gst_rtsp_message_init_request (&request, GST_RTSP_SETUP,
5626         stream->conninfo.location);
5627     if (res < 0) {
5628       g_free (transports);
5629       goto create_request_failed;
5630     }
5631
5632     /* select transport */
5633     gst_rtsp_message_take_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
5634
5635     /* if the user wants a non default RTP packet size we add the blocksize
5636      * parameter */
5637     if (src->rtp_blocksize > 0) {
5638       hval = g_strdup_printf ("%d", src->rtp_blocksize);
5639       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
5640     }
5641
5642     if (async)
5643       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("SETUP stream %d",
5644               stream->id));
5645
5646     /* handle the code ourselves */
5647     if ((res = gst_rtspsrc_send (src, conn, &request, &response, &code) < 0))
5648       goto send_error;
5649
5650     switch (code) {
5651       case GST_RTSP_STS_OK:
5652         break;
5653       case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
5654         gst_rtsp_message_unset (&request);
5655         gst_rtsp_message_unset (&response);
5656         /* cleanup of leftover transport */
5657         gst_rtspsrc_stream_free_udp (stream);
5658         /* MS WMServer RTSP MUST use same UDP pair in all SETUP requests;
5659          * we might be in this case */
5660         if (stream->container && rtpport && rtcpport && !retry) {
5661           GST_DEBUG_OBJECT (src, "retrying with original port pair %u-%u",
5662               rtpport, rtcpport);
5663           retry++;
5664           goto retry;
5665         }
5666         /* this transport did not go down well, but we may have others to try
5667          * that we did not send yet, try those and only give up then
5668          * but not without checking for lost cause/extension so we can
5669          * post a nicer/more useful error message later */
5670         if (!unsupported_real)
5671           unsupported_real = gst_rtspsrc_stream_is_real_media (stream);
5672         /* select next available protocol, give up on this stream if none */
5673         mask++;
5674         while (protocol_masks[mask] && !(protocols & protocol_masks[mask]))
5675           mask++;
5676         if (!protocol_masks[mask] || unsupported_real)
5677           continue;
5678         else
5679           goto retry;
5680       default:
5681         /* cleanup of leftover transport and move to the next stream */
5682         gst_rtspsrc_stream_free_udp (stream);
5683         goto response_error;
5684     }
5685
5686     /* parse response transport */
5687     {
5688       gchar *resptrans = NULL;
5689       GstRTSPTransport transport = { 0 };
5690
5691       gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
5692           &resptrans, 0);
5693       if (!resptrans) {
5694         gst_rtspsrc_stream_free_udp (stream);
5695         goto no_transport;
5696       }
5697
5698       /* parse transport, go to next stream on parse error */
5699       if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
5700         GST_WARNING_OBJECT (src, "failed to parse transport %s", resptrans);
5701         goto next;
5702       }
5703
5704       /* update allowed transports for other streams. once the transport of
5705        * one stream has been determined, we make sure that all other streams
5706        * are configured in the same way */
5707       switch (transport.lower_transport) {
5708         case GST_RTSP_LOWER_TRANS_TCP:
5709           GST_DEBUG_OBJECT (src, "stream %p as TCP interleaved", stream);
5710           protocols = GST_RTSP_LOWER_TRANS_TCP;
5711           src->interleaved = TRUE;
5712           /* update free channels */
5713           src->free_channel =
5714               MAX (transport.interleaved.min, src->free_channel);
5715           src->free_channel =
5716               MAX (transport.interleaved.max, src->free_channel);
5717           src->free_channel++;
5718           break;
5719         case GST_RTSP_LOWER_TRANS_UDP_MCAST:
5720           /* only allow multicast for other streams */
5721           GST_DEBUG_OBJECT (src, "stream %p as UDP multicast", stream);
5722           protocols = GST_RTSP_LOWER_TRANS_UDP_MCAST;
5723           /* if the server selected our ports, increment our counters so that
5724            * we select a new port later */
5725           if (src->next_port_num == transport.port.min &&
5726               src->next_port_num + 1 == transport.port.max) {
5727             src->next_port_num += 2;
5728           }
5729           break;
5730         case GST_RTSP_LOWER_TRANS_UDP:
5731           /* only allow unicast for other streams */
5732           GST_DEBUG_OBJECT (src, "stream %p as UDP unicast", stream);
5733           protocols = GST_RTSP_LOWER_TRANS_UDP;
5734           break;
5735         default:
5736           GST_DEBUG_OBJECT (src, "stream %p unknown transport %d", stream,
5737               transport.lower_transport);
5738           break;
5739       }
5740
5741       if (!stream->container || (!src->interleaved && !retry)) {
5742         /* now configure the stream with the selected transport */
5743         if (!gst_rtspsrc_stream_configure_transport (stream, &transport)) {
5744           GST_DEBUG_OBJECT (src,
5745               "could not configure stream %p transport, skipping stream",
5746               stream);
5747           goto next;
5748         } else if (stream->udpsrc[0] && stream->udpsrc[1]) {
5749           /* retain the first allocated UDP port pair */
5750           g_object_get (G_OBJECT (stream->udpsrc[0]), "port", &rtpport, NULL);
5751           g_object_get (G_OBJECT (stream->udpsrc[1]), "port", &rtcpport, NULL);
5752         }
5753       }
5754       /* we need to activate at least one streams when we detect activity */
5755       src->need_activate = TRUE;
5756     next:
5757       /* clean up our transport struct */
5758       gst_rtsp_transport_init (&transport);
5759       /* clean up used RTSP messages */
5760       gst_rtsp_message_unset (&request);
5761       gst_rtsp_message_unset (&response);
5762     }
5763   }
5764
5765   /* store the transport protocol that was configured */
5766   src->cur_protocols = protocols;
5767
5768   gst_rtsp_ext_list_stream_select (src->extensions, url);
5769
5770   /* if there is nothing to activate, error out */
5771   if (!src->need_activate)
5772     goto nothing_to_activate;
5773
5774   return res;
5775
5776   /* ERRORS */
5777 no_protocols:
5778   {
5779     /* no transport possible, post an error and stop */
5780     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
5781         ("Could not connect to server, no protocols left"));
5782     return GST_RTSP_ERROR;
5783   }
5784 no_streams:
5785   {
5786     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5787         ("SDP contains no streams"));
5788     return GST_RTSP_ERROR;
5789   }
5790 create_request_failed:
5791   {
5792     gchar *str = gst_rtsp_strresult (res);
5793
5794     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
5795         ("Could not create request. (%s)", str));
5796     g_free (str);
5797     goto cleanup_error;
5798   }
5799 setup_transport_failed:
5800   {
5801     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5802         ("Could not setup transport."));
5803     res = GST_RTSP_ERROR;
5804     goto cleanup_error;
5805   }
5806 response_error:
5807   {
5808     const gchar *str = gst_rtsp_status_as_text (code);
5809
5810     GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5811         ("Error (%d): %s", code, GST_STR_NULL (str)));
5812     res = GST_RTSP_ERROR;
5813     goto cleanup_error;
5814   }
5815 send_error:
5816   {
5817     gchar *str = gst_rtsp_strresult (res);
5818
5819     if (res != GST_RTSP_EINTR) {
5820       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
5821           ("Could not send message. (%s)", str));
5822     } else {
5823       GST_WARNING_OBJECT (src, "send interrupted");
5824     }
5825     g_free (str);
5826     goto cleanup_error;
5827   }
5828 no_transport:
5829   {
5830     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
5831         ("Server did not select transport."));
5832     res = GST_RTSP_ERROR;
5833     goto cleanup_error;
5834   }
5835 nothing_to_activate:
5836   {
5837     /* none of the available error codes is really right .. */
5838     if (unsupported_real) {
5839       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5840           (_("No supported stream was found. You might need to install a "
5841                   "GStreamer RTSP extension plugin for Real media streams.")),
5842           (NULL));
5843     } else {
5844       GST_ELEMENT_ERROR (src, STREAM, CODEC_NOT_FOUND,
5845           (_("No supported stream was found. You might need to allow "
5846                   "more transport protocols or may otherwise be missing "
5847                   "the right GStreamer RTSP extension plugin.")), (NULL));
5848     }
5849     return GST_RTSP_ERROR;
5850   }
5851 cleanup_error:
5852   {
5853     gst_rtsp_message_unset (&request);
5854     gst_rtsp_message_unset (&response);
5855     return res;
5856   }
5857 }
5858
5859 static gboolean
5860 gst_rtspsrc_parse_range (GstRTSPSrc * src, const gchar * range,
5861     GstSegment * segment)
5862 {
5863   gint64 seconds;
5864   GstRTSPTimeRange *therange;
5865
5866   if (src->range)
5867     gst_rtsp_range_free (src->range);
5868
5869   if (gst_rtsp_range_parse (range, &therange) == GST_RTSP_OK) {
5870     GST_DEBUG_OBJECT (src, "parsed range %s", range);
5871     src->range = therange;
5872   } else {
5873     GST_DEBUG_OBJECT (src, "failed to parse range %s", range);
5874     src->range = NULL;
5875     gst_segment_init (segment, GST_FORMAT_TIME);
5876     return FALSE;
5877   }
5878
5879   GST_DEBUG_OBJECT (src, "range: type %d, min %f - type %d,  max %f ",
5880       therange->min.type, therange->min.seconds, therange->max.type,
5881       therange->max.seconds);
5882
5883   if (therange->min.type == GST_RTSP_TIME_NOW)
5884     seconds = 0;
5885   else if (therange->min.type == GST_RTSP_TIME_END)
5886     seconds = 0;
5887   else
5888     seconds = therange->min.seconds * GST_SECOND;
5889
5890   GST_DEBUG_OBJECT (src, "range: min %" GST_TIME_FORMAT,
5891       GST_TIME_ARGS (seconds));
5892
5893   /* we need to start playback without clipping from the position reported by
5894    * the server */
5895   segment->start = seconds;
5896   segment->position = seconds;
5897
5898   if (therange->max.type == GST_RTSP_TIME_NOW)
5899     seconds = -1;
5900   else if (therange->max.type == GST_RTSP_TIME_END)
5901     seconds = -1;
5902   else
5903     seconds = therange->max.seconds * GST_SECOND;
5904
5905   GST_DEBUG_OBJECT (src, "range: max %" GST_TIME_FORMAT,
5906       GST_TIME_ARGS (seconds));
5907
5908   /* live (WMS) server might send overflowed large max as its idea of infinity,
5909    * compensate to prevent problems later on */
5910   if (seconds != -1 && seconds < 0) {
5911     seconds = -1;
5912     GST_DEBUG_OBJECT (src, "insane range, set to NONE");
5913   }
5914
5915   /* live (WMS) might send min == max, which is not worth recording */
5916   if (segment->duration == -1 && seconds == segment->start)
5917     seconds = -1;
5918
5919   /* don't change duration with unknown value, we might have a valid value
5920    * there that we want to keep. */
5921   if (seconds != -1)
5922     segment->duration = seconds;
5923
5924   return TRUE;
5925 }
5926
5927 /* Parse clock profived by the server with following syntax:
5928  *
5929  * "GstNetTimeProvider <wrapped-clock> <server-IP:port> <clock-time>"
5930  */
5931 static gboolean
5932 gst_rtspsrc_parse_gst_clock (GstRTSPSrc * src, const gchar * gstclock)
5933 {
5934   gboolean res = FALSE;
5935
5936   if (g_str_has_prefix (gstclock, "GstNetTimeProvider ")) {
5937     gchar **fields = NULL, **parts = NULL;
5938     gchar *remote_ip, *str;
5939     gint port;
5940     GstClockTime base_time;
5941     GstClock *netclock;
5942
5943     fields = g_strsplit (gstclock, " ", 0);
5944
5945     /* wrapped clock, not very interesting for now */
5946     if (fields[1] == NULL)
5947       goto cleanup;
5948
5949     /* remote IP address and port */
5950     if ((str = fields[2]) == NULL)
5951       goto cleanup;
5952
5953     parts = g_strsplit (str, ":", 0);
5954
5955     if ((remote_ip = parts[0]) == NULL)
5956       goto cleanup;
5957
5958     if ((str = parts[1]) == NULL)
5959       goto cleanup;
5960
5961     port = atoi (str);
5962     if (port == 0)
5963       goto cleanup;
5964
5965     /* base-time */
5966     if ((str = fields[3]) == NULL)
5967       goto cleanup;
5968
5969     base_time = g_ascii_strtoull (str, NULL, 10);
5970
5971     netclock =
5972         gst_net_client_clock_new ((gchar *) "GstRTSPClock", remote_ip, port,
5973         base_time);
5974
5975     if (src->provided_clock)
5976       gst_object_unref (src->provided_clock);
5977     src->provided_clock = netclock;
5978
5979     gst_element_post_message (GST_ELEMENT_CAST (src),
5980         gst_message_new_clock_provide (GST_OBJECT_CAST (src),
5981             src->provided_clock, TRUE));
5982
5983     res = TRUE;
5984   cleanup:
5985     g_strfreev (fields);
5986     g_strfreev (parts);
5987   }
5988   return res;
5989 }
5990
5991 /* must be called with the RTSP state lock */
5992 static GstRTSPResult
5993 gst_rtspsrc_open_from_sdp (GstRTSPSrc * src, GstSDPMessage * sdp,
5994     gboolean async)
5995 {
5996   GstRTSPResult res;
5997   gint i, n_streams;
5998
5999   /* prepare global stream caps properties */
6000   if (src->props)
6001     gst_structure_remove_all_fields (src->props);
6002   else
6003     src->props = gst_structure_new_empty ("RTSPProperties");
6004
6005   if (src->debug)
6006     gst_sdp_message_dump (sdp);
6007
6008   gst_rtsp_ext_list_parse_sdp (src->extensions, sdp, src->props);
6009
6010   /* let the app inspect and change the SDP */
6011   g_signal_emit (src, gst_rtspsrc_signals[SIGNAL_ON_SDP], 0, sdp);
6012
6013   gst_segment_init (&src->segment, GST_FORMAT_TIME);
6014
6015   /* parse range for duration reporting. */
6016   {
6017     const gchar *range;
6018
6019     for (i = 0;; i++) {
6020       range = gst_sdp_message_get_attribute_val_n (sdp, "range", i);
6021       if (range == NULL)
6022         break;
6023
6024       /* keep track of the range and configure it in the segment */
6025       if (gst_rtspsrc_parse_range (src, range, &src->segment))
6026         break;
6027     }
6028   }
6029   /* parse clock information. This is GStreamer specific, a server can tell the
6030    * client what clock it is using and wrap that in a network clock. The
6031    * advantage of that is that we can slave to it. */
6032   {
6033     const gchar *gstclock;
6034
6035     for (i = 0;; i++) {
6036       gstclock = gst_sdp_message_get_attribute_val_n (sdp, "x-gst-clock", i);
6037       if (gstclock == NULL)
6038         break;
6039
6040       /* parse the clock and expose it in the provide_clock method */
6041       if (gst_rtspsrc_parse_gst_clock (src, gstclock))
6042         break;
6043     }
6044   }
6045   /* try to find a global control attribute. Note that a '*' means that we should
6046    * do aggregate control with the current url (so we don't do anything and
6047    * leave the current connection as is) */
6048   {
6049     const gchar *control;
6050
6051     for (i = 0;; i++) {
6052       control = gst_sdp_message_get_attribute_val_n (sdp, "control", i);
6053       if (control == NULL)
6054         break;
6055
6056       /* only take fully qualified urls */
6057       if (g_str_has_prefix (control, "rtsp://"))
6058         break;
6059     }
6060     if (control) {
6061       g_free (src->conninfo.location);
6062       src->conninfo.location = g_strdup (control);
6063       /* make a connection for this, if there was a connection already, nothing
6064        * happens. */
6065       if (gst_rtsp_conninfo_connect (src, &src->conninfo, async) < 0) {
6066         GST_ERROR_OBJECT (src, "could not connect");
6067       }
6068     }
6069     /* we need to keep the control url separate from the connection url because
6070      * the rules for constructing the media control url need it */
6071     g_free (src->control);
6072     src->control = g_strdup (control);
6073   }
6074
6075   /* create streams */
6076   n_streams = gst_sdp_message_medias_len (sdp);
6077   for (i = 0; i < n_streams; i++) {
6078     gst_rtspsrc_create_stream (src, sdp, i);
6079   }
6080
6081   src->state = GST_RTSP_STATE_INIT;
6082
6083   /* setup streams */
6084   if ((res = gst_rtspsrc_setup_streams (src, async)) < 0)
6085     goto setup_failed;
6086
6087   /* reset our state */
6088   src->need_range = TRUE;
6089   src->skip = FALSE;
6090
6091   src->state = GST_RTSP_STATE_READY;
6092
6093   return res;
6094
6095   /* ERRORS */
6096 setup_failed:
6097   {
6098     GST_ERROR_OBJECT (src, "setup failed");
6099     gst_rtspsrc_cleanup (src);
6100     return res;
6101   }
6102 }
6103
6104 static GstRTSPResult
6105 gst_rtspsrc_retrieve_sdp (GstRTSPSrc * src, GstSDPMessage ** sdp,
6106     gboolean async)
6107 {
6108   GstRTSPResult res;
6109   GstRTSPMessage request = { 0 };
6110   GstRTSPMessage response = { 0 };
6111   guint8 *data;
6112   guint size;
6113   gchar *respcont = NULL;
6114
6115 restart:
6116   src->need_redirect = FALSE;
6117
6118   /* can't continue without a valid url */
6119   if (G_UNLIKELY (src->conninfo.url == NULL)) {
6120     res = GST_RTSP_EINVAL;
6121     goto no_url;
6122   }
6123   src->tried_url_auth = FALSE;
6124
6125   if ((res = gst_rtsp_conninfo_connect (src, &src->conninfo, async)) < 0)
6126     goto connect_failed;
6127
6128   /* create OPTIONS */
6129   GST_DEBUG_OBJECT (src, "create options...");
6130   res =
6131       gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,
6132       src->conninfo.url_str);
6133   if (res < 0)
6134     goto create_request_failed;
6135
6136   /* send OPTIONS */
6137   GST_DEBUG_OBJECT (src, "send options...");
6138
6139   if (async)
6140     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving server options"));
6141
6142   if ((res =
6143           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6144               NULL)) < 0)
6145     goto send_error;
6146
6147   /* parse OPTIONS */
6148   if (!gst_rtspsrc_parse_methods (src, &response))
6149     goto methods_error;
6150
6151   /* create DESCRIBE */
6152   GST_DEBUG_OBJECT (src, "create describe...");
6153   res =
6154       gst_rtsp_message_init_request (&request, GST_RTSP_DESCRIBE,
6155       src->conninfo.url_str);
6156   if (res < 0)
6157     goto create_request_failed;
6158
6159   /* we only accept SDP for now */
6160   gst_rtsp_message_add_header (&request, GST_RTSP_HDR_ACCEPT,
6161       "application/sdp");
6162
6163   /* send DESCRIBE */
6164   GST_DEBUG_OBJECT (src, "send describe...");
6165
6166   if (async)
6167     GST_ELEMENT_PROGRESS (src, CONTINUE, "open", ("Retrieving media info"));
6168
6169   if ((res =
6170           gst_rtspsrc_send (src, src->conninfo.connection, &request, &response,
6171               NULL)) < 0)
6172     goto send_error;
6173
6174   /* we only perform redirect for the describe, currently */
6175   if (src->need_redirect) {
6176     /* close connection, we don't have to send a TEARDOWN yet, ignore the
6177      * result. */
6178     gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6179
6180     gst_rtsp_message_unset (&request);
6181     gst_rtsp_message_unset (&response);
6182
6183     /* and now retry */
6184     goto restart;
6185   }
6186
6187   /* it could be that the DESCRIBE method was not implemented */
6188   if (!src->methods & GST_RTSP_DESCRIBE)
6189     goto no_describe;
6190
6191   /* check if reply is SDP */
6192   gst_rtsp_message_get_header (&response, GST_RTSP_HDR_CONTENT_TYPE, &respcont,
6193       0);
6194   /* could not be set but since the request returned OK, we assume it
6195    * was SDP, else check it. */
6196   if (respcont) {
6197     if (!g_ascii_strcasecmp (respcont, "application/sdp") == 0)
6198       goto wrong_content_type;
6199   }
6200
6201   /* get message body and parse as SDP */
6202   gst_rtsp_message_get_body (&response, &data, &size);
6203   if (data == NULL || size == 0)
6204     goto no_describe;
6205
6206   GST_DEBUG_OBJECT (src, "parse SDP...");
6207   gst_sdp_message_new (sdp);
6208   gst_sdp_message_parse_buffer (data, size, *sdp);
6209
6210   /* clean up any messages */
6211   gst_rtsp_message_unset (&request);
6212   gst_rtsp_message_unset (&response);
6213
6214   return res;
6215
6216   /* ERRORS */
6217 no_url:
6218   {
6219     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
6220         ("No valid RTSP URL was provided"));
6221     goto cleanup_error;
6222   }
6223 connect_failed:
6224   {
6225     gchar *str = gst_rtsp_strresult (res);
6226
6227     if (res != GST_RTSP_EINTR) {
6228       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
6229           ("Failed to connect. (%s)", str));
6230     } else {
6231       GST_WARNING_OBJECT (src, "connect interrupted");
6232     }
6233     g_free (str);
6234     goto cleanup_error;
6235   }
6236 create_request_failed:
6237   {
6238     gchar *str = gst_rtsp_strresult (res);
6239
6240     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6241         ("Could not create request. (%s)", str));
6242     g_free (str);
6243     goto cleanup_error;
6244   }
6245 send_error:
6246   {
6247     /* Don't post a message - the rtsp_send method will have
6248      * taken care of it because we passed NULL for the response code */
6249     goto cleanup_error;
6250   }
6251 methods_error:
6252   {
6253     /* error was posted */
6254     res = GST_RTSP_ERROR;
6255     goto cleanup_error;
6256   }
6257 wrong_content_type:
6258   {
6259     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6260         ("Server does not support SDP, got %s.", respcont));
6261     res = GST_RTSP_ERROR;
6262     goto cleanup_error;
6263   }
6264 no_describe:
6265   {
6266     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
6267         ("Server can not provide an SDP."));
6268     res = GST_RTSP_ERROR;
6269     goto cleanup_error;
6270   }
6271 cleanup_error:
6272   {
6273     if (src->conninfo.connection) {
6274       GST_DEBUG_OBJECT (src, "free connection");
6275       gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6276     }
6277     gst_rtsp_message_unset (&request);
6278     gst_rtsp_message_unset (&response);
6279     return res;
6280   }
6281 }
6282
6283 static GstRTSPResult
6284 gst_rtspsrc_open (GstRTSPSrc * src, gboolean async)
6285 {
6286   GstRTSPResult ret;
6287
6288   src->methods =
6289       GST_RTSP_SETUP | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_TEARDOWN;
6290
6291   if (src->sdp == NULL) {
6292     if ((ret = gst_rtspsrc_retrieve_sdp (src, &src->sdp, async)) < 0)
6293       goto no_sdp;
6294   }
6295
6296   if ((ret = gst_rtspsrc_open_from_sdp (src, src->sdp, async)) < 0)
6297     goto open_failed;
6298
6299 done:
6300   if (async)
6301     gst_rtspsrc_loop_end_cmd (src, CMD_OPEN, ret);
6302
6303   return ret;
6304
6305   /* ERRORS */
6306 no_sdp:
6307   {
6308     GST_WARNING_OBJECT (src, "can't get sdp");
6309     src->open_error = TRUE;
6310     goto done;
6311   }
6312 open_failed:
6313   {
6314     GST_WARNING_OBJECT (src, "can't setup streaming from sdp");
6315     src->open_error = TRUE;
6316     goto done;
6317   }
6318 }
6319
6320 static GstRTSPResult
6321 gst_rtspsrc_close (GstRTSPSrc * src, gboolean async, gboolean only_close)
6322 {
6323   GstRTSPMessage request = { 0 };
6324   GstRTSPMessage response = { 0 };
6325   GstRTSPResult res = GST_RTSP_OK;
6326   GList *walk;
6327   const gchar *control;
6328
6329   GST_DEBUG_OBJECT (src, "TEARDOWN...");
6330
6331   gst_rtspsrc_set_state (src, GST_STATE_READY);
6332
6333   if (src->state < GST_RTSP_STATE_READY) {
6334     GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
6335     goto close;
6336   }
6337
6338   if (only_close)
6339     goto close;
6340
6341   /* construct a control url */
6342   control = get_aggregate_control (src);
6343
6344   if (!(src->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
6345     goto not_supported;
6346
6347   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6348     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6349     const gchar *setup_url;
6350     GstRTSPConnInfo *info;
6351
6352     /* try aggregate control first but do non-aggregate control otherwise */
6353     if (control)
6354       setup_url = control;
6355     else if ((setup_url = stream->conninfo.location) == NULL)
6356       continue;
6357
6358     if (src->conninfo.connection) {
6359       info = &src->conninfo;
6360     } else if (stream->conninfo.connection) {
6361       info = &stream->conninfo;
6362     } else {
6363       continue;
6364     }
6365     if (!info->connected)
6366       goto next;
6367
6368     /* do TEARDOWN */
6369     res =
6370         gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, setup_url);
6371     if (res < 0)
6372       goto create_request_failed;
6373
6374     if (async)
6375       GST_ELEMENT_PROGRESS (src, CONTINUE, "close", ("Closing stream"));
6376
6377     if ((res =
6378             gst_rtspsrc_send (src, info->connection, &request, &response,
6379                 NULL)) < 0)
6380       goto send_error;
6381
6382     /* FIXME, parse result? */
6383     gst_rtsp_message_unset (&request);
6384     gst_rtsp_message_unset (&response);
6385
6386   next:
6387     /* early exit when we did aggregate control */
6388     if (control)
6389       break;
6390   }
6391
6392 close:
6393   /* close connections */
6394   GST_DEBUG_OBJECT (src, "closing connection...");
6395   gst_rtsp_conninfo_close (src, &src->conninfo, TRUE);
6396   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6397     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6398     gst_rtsp_conninfo_close (src, &stream->conninfo, TRUE);
6399   }
6400
6401   /* cleanup */
6402   gst_rtspsrc_cleanup (src);
6403
6404   src->state = GST_RTSP_STATE_INVALID;
6405
6406   if (async)
6407     gst_rtspsrc_loop_end_cmd (src, CMD_CLOSE, res);
6408
6409   return res;
6410
6411   /* ERRORS */
6412 create_request_failed:
6413   {
6414     gchar *str = gst_rtsp_strresult (res);
6415
6416     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6417         ("Could not create request. (%s)", str));
6418     g_free (str);
6419     goto close;
6420   }
6421 send_error:
6422   {
6423     gchar *str = gst_rtsp_strresult (res);
6424
6425     gst_rtsp_message_unset (&request);
6426     if (res != GST_RTSP_EINTR) {
6427       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6428           ("Could not send message. (%s)", str));
6429     } else {
6430       GST_WARNING_OBJECT (src, "TEARDOWN interrupted");
6431     }
6432     g_free (str);
6433     goto close;
6434   }
6435 not_supported:
6436   {
6437     GST_DEBUG_OBJECT (src,
6438         "TEARDOWN and PLAY not supported, can't do TEARDOWN");
6439     goto close;
6440   }
6441 }
6442
6443 /* RTP-Info is of the format:
6444  *
6445  * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
6446  *
6447  * rtptime corresponds to the timestamp for the NPT time given in the header
6448  * seqbase corresponds to the next sequence number we received. This number
6449  * indicates the first seqnum after the seek and should be used to discard
6450  * packets that are from before the seek.
6451  */
6452 static gboolean
6453 gst_rtspsrc_parse_rtpinfo (GstRTSPSrc * src, gchar * rtpinfo)
6454 {
6455   gchar **infos;
6456   gint i, j;
6457
6458   GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
6459
6460   infos = g_strsplit (rtpinfo, ",", 0);
6461   for (i = 0; infos[i]; i++) {
6462     gchar **fields;
6463     GstRTSPStream *stream;
6464     gint32 seqbase;
6465     gint64 timebase;
6466
6467     GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
6468
6469     /* init values, types of seqbase and timebase are bigger than needed so we
6470      * can store -1 as uninitialized values */
6471     stream = NULL;
6472     seqbase = -1;
6473     timebase = -1;
6474
6475     /* parse url, find stream for url.
6476      * parse seq and rtptime. The seq number should be configured in the rtp
6477      * depayloader or session manager to detect gaps. Same for the rtptime, it
6478      * should be used to create an initial time newsegment. */
6479     fields = g_strsplit (infos[i], ";", 0);
6480     for (j = 0; fields[j]; j++) {
6481       GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
6482       /* remove leading whitespace */
6483       fields[j] = g_strchug (fields[j]);
6484       if (g_str_has_prefix (fields[j], "url=")) {
6485         /* get the url and the stream */
6486         stream =
6487             find_stream (src, (fields[j] + 4), (gpointer) find_stream_by_setup);
6488       } else if (g_str_has_prefix (fields[j], "seq=")) {
6489         seqbase = atoi (fields[j] + 4);
6490       } else if (g_str_has_prefix (fields[j], "rtptime=")) {
6491         timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
6492       }
6493     }
6494     g_strfreev (fields);
6495     /* now we need to store the values for the caps of the stream */
6496     if (stream != NULL) {
6497       GST_DEBUG_OBJECT (src,
6498           "found stream %p, setting: seqbase %d, timebase %" G_GINT64_FORMAT,
6499           stream, seqbase, timebase);
6500
6501       /* we have a stream, configure detected params */
6502       stream->seqbase = seqbase;
6503       stream->timebase = timebase;
6504     }
6505   }
6506   g_strfreev (infos);
6507
6508   return TRUE;
6509 }
6510
6511 static void
6512 gst_rtspsrc_handle_rtcp_interval (GstRTSPSrc * src, gchar * rtcp)
6513 {
6514   guint64 interval;
6515   GList *walk;
6516
6517   interval = strtoul (rtcp, NULL, 10);
6518   GST_DEBUG_OBJECT (src, "rtcp interval: %" G_GUINT64_FORMAT " ms", interval);
6519
6520   if (!interval)
6521     return;
6522
6523   interval *= GST_MSECOND;
6524
6525   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6526     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6527
6528     /* already (optionally) retrieved this when configuring manager */
6529     if (stream->session) {
6530       GObject *rtpsession = stream->session;
6531
6532       GST_DEBUG_OBJECT (src, "configure rtcp interval in session %p",
6533           rtpsession);
6534       g_object_set (rtpsession, "rtcp-min-interval", interval, NULL);
6535     }
6536   }
6537
6538   /* now it happens that (Xenon) server sending this may also provide bogus
6539    * RTCP SR sync data (i.e. with quite some jitter), so never mind those
6540    * and just use RTP-Info to sync */
6541   if (src->manager) {
6542     GObjectClass *klass;
6543
6544     klass = G_OBJECT_GET_CLASS (G_OBJECT (src->manager));
6545     if (g_object_class_find_property (klass, "rtcp-sync")) {
6546       GST_DEBUG_OBJECT (src, "configuring rtp sync method");
6547       g_object_set (src->manager, "rtcp-sync", RTCP_SYNC_RTP, NULL);
6548     }
6549   }
6550 }
6551
6552 static gdouble
6553 gst_rtspsrc_get_float (const gchar * dstr)
6554 {
6555   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6556
6557   /* canonicalise floating point string so we can handle float strings
6558    * in the form "24.930" or "24,930" irrespective of the current locale */
6559   g_strlcpy (s, dstr, sizeof (s));
6560   g_strdelimit (s, ",", '.');
6561   return g_ascii_strtod (s, NULL);
6562 }
6563
6564 static gchar *
6565 gen_range_header (GstRTSPSrc * src, GstSegment * segment)
6566 {
6567   gchar val_str[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
6568
6569   if (src->range && src->range->min.type == GST_RTSP_TIME_NOW) {
6570     g_strlcpy (val_str, "now", sizeof (val_str));
6571   } else {
6572     if (segment->position == 0) {
6573       g_strlcpy (val_str, "0", sizeof (val_str));
6574     } else {
6575       g_ascii_dtostr (val_str, sizeof (val_str),
6576           ((gdouble) segment->position) / GST_SECOND);
6577     }
6578   }
6579   return g_strdup_printf ("npt=%s-", val_str);
6580 }
6581
6582 static void
6583 clear_rtp_base (GstRTSPSrc * src, GstRTSPStream * stream)
6584 {
6585   stream->timebase = -1;
6586   stream->seqbase = -1;
6587   if (stream->caps) {
6588     GstStructure *s;
6589
6590     stream->caps = gst_caps_make_writable (stream->caps);
6591     s = gst_caps_get_structure (stream->caps, 0);
6592     gst_structure_remove_fields (s, "clock-base", "seqnum-base", NULL);
6593   }
6594 }
6595
6596 static GstRTSPResult
6597 gst_rtspsrc_ensure_open (GstRTSPSrc * src, gboolean async)
6598 {
6599   GstRTSPResult res = GST_RTSP_OK;
6600
6601   if (src->state < GST_RTSP_STATE_READY) {
6602     res = GST_RTSP_ERROR;
6603     if (src->open_error) {
6604       GST_DEBUG_OBJECT (src, "the stream was in error");
6605       goto done;
6606     }
6607     if (async)
6608       gst_rtspsrc_loop_start_cmd (src, CMD_OPEN);
6609
6610     if ((res = gst_rtspsrc_open (src, async)) < 0) {
6611       GST_DEBUG_OBJECT (src, "failed to open stream");
6612       goto done;
6613     }
6614   }
6615
6616 done:
6617   return res;
6618 }
6619
6620 static GstRTSPResult
6621 gst_rtspsrc_play (GstRTSPSrc * src, GstSegment * segment, gboolean async)
6622 {
6623   GstRTSPMessage request = { 0 };
6624   GstRTSPMessage response = { 0 };
6625   GstRTSPResult res = GST_RTSP_OK;
6626   GList *walk;
6627   gchar *hval;
6628   gint hval_idx;
6629   const gchar *control;
6630
6631   GST_DEBUG_OBJECT (src, "PLAY...");
6632
6633   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6634     goto open_failed;
6635
6636   if (!(src->methods & GST_RTSP_PLAY))
6637     goto not_supported;
6638
6639   if (src->state == GST_RTSP_STATE_PLAYING)
6640     goto was_playing;
6641
6642   if (!src->conninfo.connection || !src->conninfo.connected)
6643     goto done;
6644
6645   /* send some dummy packets before we activate the receive in the
6646    * udp sources */
6647   gst_rtspsrc_send_dummy_packets (src);
6648
6649   /* require new SR packets */
6650   if (src->manager)
6651     g_signal_emit_by_name (src->manager, "reset-sync", NULL);
6652
6653   gst_rtspsrc_set_state (src, GST_STATE_PLAYING);
6654
6655   /* construct a control url */
6656   control = get_aggregate_control (src);
6657
6658   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6659     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6660     const gchar *setup_url;
6661     GstRTSPConnection *conn;
6662
6663     /* try aggregate control first but do non-aggregate control otherwise */
6664     if (control)
6665       setup_url = control;
6666     else if ((setup_url = stream->conninfo.location) == NULL)
6667       continue;
6668
6669     if (src->conninfo.connection) {
6670       conn = src->conninfo.connection;
6671     } else if (stream->conninfo.connection) {
6672       conn = stream->conninfo.connection;
6673     } else {
6674       continue;
6675     }
6676
6677     /* do play */
6678     res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, setup_url);
6679     if (res < 0)
6680       goto create_request_failed;
6681
6682     if (src->need_range) {
6683       hval = gen_range_header (src, segment);
6684
6685       gst_rtsp_message_take_header (&request, GST_RTSP_HDR_RANGE, hval);
6686
6687       /* store the newsegment event so it can be sent from the streaming thread. */
6688       if (src->start_segment)
6689         gst_event_unref (src->start_segment);
6690       src->start_segment = gst_event_new_segment (&src->segment);
6691     }
6692
6693     if (segment->rate != 1.0) {
6694       gchar hval[G_ASCII_DTOSTR_BUF_SIZE];
6695
6696       g_ascii_dtostr (hval, sizeof (hval), segment->rate);
6697       if (src->skip)
6698         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SCALE, hval);
6699       else
6700         gst_rtsp_message_add_header (&request, GST_RTSP_HDR_SPEED, hval);
6701     }
6702
6703     if (async)
6704       GST_ELEMENT_PROGRESS (src, CONTINUE, "request", ("Sending PLAY request"));
6705
6706     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6707       goto send_error;
6708
6709     /* seek may have silently failed as it is not supported */
6710     if (!(src->methods & GST_RTSP_PLAY)) {
6711       GST_DEBUG_OBJECT (src, "PLAY Range not supported; re-enable PLAY");
6712       /* obviously it is supported as we made it here */
6713       src->methods |= GST_RTSP_PLAY;
6714       src->seekable = FALSE;
6715       /* but there is nothing to parse in the response,
6716        * so convey we have no idea and not to expect anything particular */
6717       clear_rtp_base (src, stream);
6718       if (control) {
6719         GList *run;
6720
6721         /* need to do for all streams */
6722         for (run = src->streams; run; run = g_list_next (run))
6723           clear_rtp_base (src, (GstRTSPStream *) run->data);
6724       }
6725       /* NOTE the above also disables npt based eos detection */
6726       /* and below forces position to 0,
6727        * which is visible feedback we lost the plot */
6728       segment->start = segment->position = src->last_pos;
6729     }
6730
6731     gst_rtsp_message_unset (&request);
6732
6733     /* parse RTP npt field. This is the current position in the stream (Normal
6734      * Play Time) and should be put in the NEWSEGMENT position field. */
6735     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RANGE, &hval,
6736             0) == GST_RTSP_OK)
6737       gst_rtspsrc_parse_range (src, hval, segment);
6738
6739     /* assume 1.0 rate now, overwrite when the SCALE or SPEED headers are present. */
6740     segment->rate = 1.0;
6741
6742     /* parse Speed header. This is the intended playback rate of the stream
6743      * and should be put in the NEWSEGMENT rate field. */
6744     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SPEED, &hval,
6745             0) == GST_RTSP_OK) {
6746       segment->rate = gst_rtspsrc_get_float (hval);
6747     } else if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_SCALE,
6748             &hval, 0) == GST_RTSP_OK) {
6749       segment->rate = gst_rtspsrc_get_float (hval);
6750     }
6751
6752     /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
6753      * for the RTP packets. If this is not present, we assume all starts from 0...
6754      * This is info for the RTP session manager that we pass to it in caps. */
6755     hval_idx = 0;
6756     while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
6757             &hval, hval_idx++) == GST_RTSP_OK)
6758       gst_rtspsrc_parse_rtpinfo (src, hval);
6759
6760     /* some servers indicate RTCP parameters in PLAY response,
6761      * rather than properly in SDP */
6762     if (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTCP_INTERVAL,
6763             &hval, 0) == GST_RTSP_OK)
6764       gst_rtspsrc_handle_rtcp_interval (src, hval);
6765
6766     gst_rtsp_message_unset (&response);
6767
6768     /* early exit when we did aggregate control */
6769     if (control)
6770       break;
6771   }
6772   /* configure the caps of the streams after we parsed all headers. Only reset
6773    * the manager object when we set a new Range header (we did a seek) */
6774   gst_rtspsrc_configure_caps (src, segment, src->need_range);
6775
6776   /* set again when needed */
6777   src->need_range = FALSE;
6778
6779   src->running = TRUE;
6780   src->base_time = -1;
6781   src->state = GST_RTSP_STATE_PLAYING;
6782
6783   /* mark discont */
6784   GST_DEBUG_OBJECT (src, "mark DISCONT, we did a seek to another position");
6785   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6786     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6787     stream->discont = TRUE;
6788   }
6789
6790 done:
6791   if (async)
6792     gst_rtspsrc_loop_end_cmd (src, CMD_PLAY, res);
6793
6794   return res;
6795
6796   /* ERRORS */
6797 open_failed:
6798   {
6799     GST_DEBUG_OBJECT (src, "failed to open stream");
6800     goto done;
6801   }
6802 not_supported:
6803   {
6804     GST_DEBUG_OBJECT (src, "PLAY is not supported");
6805     goto done;
6806   }
6807 was_playing:
6808   {
6809     GST_DEBUG_OBJECT (src, "we were already PLAYING");
6810     goto done;
6811   }
6812 create_request_failed:
6813   {
6814     gchar *str = gst_rtsp_strresult (res);
6815
6816     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6817         ("Could not create request. (%s)", str));
6818     g_free (str);
6819     goto done;
6820   }
6821 send_error:
6822   {
6823     gchar *str = gst_rtsp_strresult (res);
6824
6825     gst_rtsp_message_unset (&request);
6826     if (res != GST_RTSP_EINTR) {
6827       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6828           ("Could not send message. (%s)", str));
6829     } else {
6830       GST_WARNING_OBJECT (src, "PLAY interrupted");
6831     }
6832     g_free (str);
6833     goto done;
6834   }
6835 }
6836
6837 static GstRTSPResult
6838 gst_rtspsrc_pause (GstRTSPSrc * src, gboolean async)
6839 {
6840   GstRTSPResult res = GST_RTSP_OK;
6841   GstRTSPMessage request = { 0 };
6842   GstRTSPMessage response = { 0 };
6843   GList *walk;
6844   const gchar *control;
6845
6846   GST_DEBUG_OBJECT (src, "PAUSE...");
6847
6848   if ((res = gst_rtspsrc_ensure_open (src, async)) < 0)
6849     goto open_failed;
6850
6851   if (!(src->methods & GST_RTSP_PAUSE))
6852     goto not_supported;
6853
6854   if (src->state == GST_RTSP_STATE_READY)
6855     goto was_paused;
6856
6857   if (!src->conninfo.connection || !src->conninfo.connected)
6858     goto no_connection;
6859
6860   /* construct a control url */
6861   control = get_aggregate_control (src);
6862
6863   /* loop over the streams. We might exit the loop early when we could do an
6864    * aggregate control */
6865   for (walk = src->streams; walk; walk = g_list_next (walk)) {
6866     GstRTSPStream *stream = (GstRTSPStream *) walk->data;
6867     GstRTSPConnection *conn;
6868     const gchar *setup_url;
6869
6870     /* try aggregate control first but do non-aggregate control otherwise */
6871     if (control)
6872       setup_url = control;
6873     else if ((setup_url = stream->conninfo.location) == NULL)
6874       continue;
6875
6876     if (src->conninfo.connection) {
6877       conn = src->conninfo.connection;
6878     } else if (stream->conninfo.connection) {
6879       conn = stream->conninfo.connection;
6880     } else {
6881       continue;
6882     }
6883
6884     if (async)
6885       GST_ELEMENT_PROGRESS (src, CONTINUE, "request",
6886           ("Sending PAUSE request"));
6887
6888     if ((res =
6889             gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE,
6890                 setup_url)) < 0)
6891       goto create_request_failed;
6892
6893     if ((res = gst_rtspsrc_send (src, conn, &request, &response, NULL)) < 0)
6894       goto send_error;
6895
6896     gst_rtsp_message_unset (&request);
6897     gst_rtsp_message_unset (&response);
6898
6899     /* exit early when we did agregate control */
6900     if (control)
6901       break;
6902   }
6903
6904   /* change element states now */
6905   gst_rtspsrc_set_state (src, GST_STATE_PAUSED);
6906
6907 no_connection:
6908   src->state = GST_RTSP_STATE_READY;
6909
6910 done:
6911   if (async)
6912     gst_rtspsrc_loop_end_cmd (src, CMD_PAUSE, res);
6913
6914   return res;
6915
6916   /* ERRORS */
6917 open_failed:
6918   {
6919     GST_DEBUG_OBJECT (src, "failed to open stream");
6920     goto done;
6921   }
6922 not_supported:
6923   {
6924     GST_DEBUG_OBJECT (src, "PAUSE is not supported");
6925     goto done;
6926   }
6927 was_paused:
6928   {
6929     GST_DEBUG_OBJECT (src, "we were already PAUSED");
6930     goto done;
6931   }
6932 create_request_failed:
6933   {
6934     gchar *str = gst_rtsp_strresult (res);
6935
6936     GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
6937         ("Could not create request. (%s)", str));
6938     g_free (str);
6939     goto done;
6940   }
6941 send_error:
6942   {
6943     gchar *str = gst_rtsp_strresult (res);
6944
6945     gst_rtsp_message_unset (&request);
6946     if (res != GST_RTSP_EINTR) {
6947       GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
6948           ("Could not send message. (%s)", str));
6949     } else {
6950       GST_WARNING_OBJECT (src, "PAUSE interrupted");
6951     }
6952     g_free (str);
6953     goto done;
6954   }
6955 }
6956
6957 static void
6958 gst_rtspsrc_handle_message (GstBin * bin, GstMessage * message)
6959 {
6960   GstRTSPSrc *rtspsrc;
6961
6962   rtspsrc = GST_RTSPSRC (bin);
6963
6964   switch (GST_MESSAGE_TYPE (message)) {
6965     case GST_MESSAGE_EOS:
6966       gst_message_unref (message);
6967       break;
6968     case GST_MESSAGE_ELEMENT:
6969     {
6970       const GstStructure *s = gst_message_get_structure (message);
6971
6972       if (gst_structure_has_name (s, "GstUDPSrcTimeout")) {
6973         gboolean ignore_timeout;
6974
6975         GST_DEBUG_OBJECT (bin, "timeout on UDP port");
6976
6977         GST_OBJECT_LOCK (rtspsrc);
6978         ignore_timeout = rtspsrc->ignore_timeout;
6979         rtspsrc->ignore_timeout = TRUE;
6980         GST_OBJECT_UNLOCK (rtspsrc);
6981
6982         /* we only act on the first udp timeout message, others are irrelevant
6983          * and can be ignored. */
6984         if (!ignore_timeout)
6985           gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_RECONNECT, CMD_LOOP);
6986         /* eat and free */
6987         gst_message_unref (message);
6988         return;
6989       }
6990       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
6991       break;
6992     }
6993     case GST_MESSAGE_ERROR:
6994     {
6995       GstObject *udpsrc;
6996       GstRTSPStream *stream;
6997       GstFlowReturn ret;
6998
6999       udpsrc = GST_MESSAGE_SRC (message);
7000
7001       GST_DEBUG_OBJECT (rtspsrc, "got error from %s",
7002           GST_ELEMENT_NAME (udpsrc));
7003
7004       stream = find_stream (rtspsrc, udpsrc, (gpointer) find_stream_by_udpsrc);
7005       if (!stream)
7006         goto forward;
7007
7008       /* we ignore the RTCP udpsrc */
7009       if (stream->udpsrc[1] == GST_ELEMENT_CAST (udpsrc))
7010         goto done;
7011
7012       /* if we get error messages from the udp sources, that's not a problem as
7013        * long as not all of them error out. We also don't really know what the
7014        * problem is, the message does not give enough detail... */
7015       ret = gst_rtspsrc_combine_flows (rtspsrc, stream, GST_FLOW_NOT_LINKED);
7016       GST_DEBUG_OBJECT (rtspsrc, "combined flows: %s", gst_flow_get_name (ret));
7017       if (ret != GST_FLOW_OK)
7018         goto forward;
7019
7020     done:
7021       gst_message_unref (message);
7022       break;
7023
7024     forward:
7025       /* fatal but not our message, forward */
7026       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7027       break;
7028     }
7029     default:
7030     {
7031       GST_BIN_CLASS (parent_class)->handle_message (bin, message);
7032       break;
7033     }
7034   }
7035 }
7036
7037 /* the thread where everything happens */
7038 static void
7039 gst_rtspsrc_thread (GstRTSPSrc * src)
7040 {
7041   gint cmd;
7042
7043   GST_OBJECT_LOCK (src);
7044   cmd = src->pending_cmd;
7045   if (cmd == CMD_RECONNECT || cmd == CMD_PLAY || cmd == CMD_PAUSE
7046       || cmd == CMD_LOOP || cmd == CMD_OPEN)
7047     src->pending_cmd = CMD_LOOP;
7048   else
7049     src->pending_cmd = CMD_WAIT;
7050   GST_DEBUG_OBJECT (src, "got command %d", cmd);
7051
7052   /* we got the message command, so ensure communication is possible again */
7053   gst_rtspsrc_connection_flush (src, FALSE);
7054
7055   src->busy_cmd = cmd;
7056   GST_OBJECT_UNLOCK (src);
7057
7058   switch (cmd) {
7059     case CMD_OPEN:
7060       gst_rtspsrc_open (src, TRUE);
7061       break;
7062     case CMD_PLAY:
7063       gst_rtspsrc_play (src, &src->segment, TRUE);
7064       break;
7065     case CMD_PAUSE:
7066       gst_rtspsrc_pause (src, TRUE);
7067       break;
7068     case CMD_CLOSE:
7069       gst_rtspsrc_close (src, TRUE, FALSE);
7070       break;
7071     case CMD_LOOP:
7072       gst_rtspsrc_loop (src);
7073       break;
7074     case CMD_RECONNECT:
7075       gst_rtspsrc_reconnect (src, FALSE);
7076       break;
7077     default:
7078       break;
7079   }
7080
7081   GST_OBJECT_LOCK (src);
7082   /* and go back to sleep */
7083   if (src->pending_cmd == CMD_WAIT) {
7084     if (src->task)
7085       gst_task_pause (src->task);
7086   }
7087   /* reset waiting */
7088   src->busy_cmd = CMD_WAIT;
7089   GST_OBJECT_UNLOCK (src);
7090 }
7091
7092 static gboolean
7093 gst_rtspsrc_start (GstRTSPSrc * src)
7094 {
7095   GST_DEBUG_OBJECT (src, "starting");
7096
7097   GST_OBJECT_LOCK (src);
7098
7099   src->pending_cmd = CMD_WAIT;
7100
7101   if (src->task == NULL) {
7102     src->task = gst_task_new ((GstTaskFunction) gst_rtspsrc_thread, src, NULL);
7103     if (src->task == NULL)
7104       goto task_error;
7105
7106     gst_task_set_lock (src->task, GST_RTSP_STREAM_GET_LOCK (src));
7107   }
7108   GST_OBJECT_UNLOCK (src);
7109
7110   return TRUE;
7111
7112   /* ERRORS */
7113 task_error:
7114   {
7115     GST_ERROR_OBJECT (src, "failed to create task");
7116     return FALSE;
7117   }
7118 }
7119
7120 static gboolean
7121 gst_rtspsrc_stop (GstRTSPSrc * src)
7122 {
7123   GstTask *task;
7124
7125   GST_DEBUG_OBJECT (src, "stopping");
7126
7127   /* also cancels pending task */
7128   gst_rtspsrc_loop_send_cmd (src, CMD_WAIT, CMD_ALL);
7129
7130   GST_OBJECT_LOCK (src);
7131   if ((task = src->task)) {
7132     src->task = NULL;
7133     GST_OBJECT_UNLOCK (src);
7134
7135     gst_task_stop (task);
7136
7137     /* make sure it is not running */
7138     GST_RTSP_STREAM_LOCK (src);
7139     GST_RTSP_STREAM_UNLOCK (src);
7140
7141     /* now wait for the task to finish */
7142     gst_task_join (task);
7143
7144     /* and free the task */
7145     gst_object_unref (GST_OBJECT (task));
7146
7147     GST_OBJECT_LOCK (src);
7148   }
7149   GST_OBJECT_UNLOCK (src);
7150
7151   /* ensure synchronously all is closed and clean */
7152   gst_rtspsrc_close (src, FALSE, TRUE);
7153
7154   return TRUE;
7155 }
7156
7157 static GstStateChangeReturn
7158 gst_rtspsrc_change_state (GstElement * element, GstStateChange transition)
7159 {
7160   GstRTSPSrc *rtspsrc;
7161   GstStateChangeReturn ret;
7162
7163   rtspsrc = GST_RTSPSRC (element);
7164
7165   switch (transition) {
7166     case GST_STATE_CHANGE_NULL_TO_READY:
7167       if (!gst_rtspsrc_start (rtspsrc))
7168         goto start_failed;
7169       break;
7170     case GST_STATE_CHANGE_READY_TO_PAUSED:
7171       /* init some state */
7172       rtspsrc->cur_protocols = rtspsrc->protocols;
7173       /* first attempt, don't ignore timeouts */
7174       rtspsrc->ignore_timeout = FALSE;
7175       rtspsrc->open_error = FALSE;
7176       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_OPEN, 0);
7177       break;
7178     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7179       set_manager_buffer_mode (rtspsrc);
7180       /* fall-through */
7181     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7182       /* unblock the tcp tasks and make the loop waiting */
7183       if (gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_WAIT, CMD_LOOP)) {
7184         /* make sure it is waiting before we send PAUSE or PLAY below */
7185         GST_RTSP_STREAM_LOCK (rtspsrc);
7186         GST_RTSP_STREAM_UNLOCK (rtspsrc);
7187       }
7188       break;
7189     case GST_STATE_CHANGE_PAUSED_TO_READY:
7190       break;
7191     default:
7192       break;
7193   }
7194
7195   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7196   if (ret == GST_STATE_CHANGE_FAILURE)
7197     goto done;
7198
7199   switch (transition) {
7200     case GST_STATE_CHANGE_NULL_TO_READY:
7201       ret = GST_STATE_CHANGE_SUCCESS;
7202       break;
7203     case GST_STATE_CHANGE_READY_TO_PAUSED:
7204       ret = GST_STATE_CHANGE_NO_PREROLL;
7205       break;
7206     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
7207       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PLAY, 0);
7208       ret = GST_STATE_CHANGE_SUCCESS;
7209       break;
7210     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
7211       /* send pause request and keep the idle task around */
7212       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_PAUSE, CMD_LOOP);
7213       ret = GST_STATE_CHANGE_NO_PREROLL;
7214       break;
7215     case GST_STATE_CHANGE_PAUSED_TO_READY:
7216       gst_rtspsrc_loop_send_cmd (rtspsrc, CMD_CLOSE, CMD_PAUSE);
7217       ret = GST_STATE_CHANGE_SUCCESS;
7218       break;
7219     case GST_STATE_CHANGE_READY_TO_NULL:
7220       gst_rtspsrc_stop (rtspsrc);
7221       ret = GST_STATE_CHANGE_SUCCESS;
7222       break;
7223     default:
7224       break;
7225   }
7226
7227 done:
7228   return ret;
7229
7230 start_failed:
7231   {
7232     GST_DEBUG_OBJECT (rtspsrc, "start failed");
7233     return GST_STATE_CHANGE_FAILURE;
7234   }
7235 }
7236
7237 static gboolean
7238 gst_rtspsrc_send_event (GstElement * element, GstEvent * event)
7239 {
7240   gboolean res;
7241   GstRTSPSrc *rtspsrc;
7242
7243   rtspsrc = GST_RTSPSRC (element);
7244
7245   if (GST_EVENT_IS_DOWNSTREAM (event)) {
7246     res = gst_rtspsrc_push_event (rtspsrc, event);
7247   } else {
7248     res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
7249   }
7250
7251   return res;
7252 }
7253
7254
7255 /*** GSTURIHANDLER INTERFACE *************************************************/
7256
7257 static GstURIType
7258 gst_rtspsrc_uri_get_type (GType type)
7259 {
7260   return GST_URI_SRC;
7261 }
7262
7263 static const gchar *const *
7264 gst_rtspsrc_uri_get_protocols (GType type)
7265 {
7266   static const gchar *protocols[] =
7267       { "rtsp", "rtspu", "rtspt", "rtsph", "rtsp-sdp",
7268     "rtsps", "rtspsu", "rtspst", "rtspsh", NULL
7269   };
7270
7271   return protocols;
7272 }
7273
7274 static gchar *
7275 gst_rtspsrc_uri_get_uri (GstURIHandler * handler)
7276 {
7277   GstRTSPSrc *src = GST_RTSPSRC (handler);
7278
7279   /* FIXME: make thread-safe */
7280   return g_strdup (src->conninfo.location);
7281 }
7282
7283 static gboolean
7284 gst_rtspsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri,
7285     GError ** error)
7286 {
7287   GstRTSPSrc *src;
7288   GstRTSPResult res;
7289   GstRTSPUrl *newurl = NULL;
7290   GstSDPMessage *sdp = NULL;
7291
7292   src = GST_RTSPSRC (handler);
7293
7294   /* same URI, we're fine */
7295   if (src->conninfo.location && uri && !strcmp (uri, src->conninfo.location))
7296     goto was_ok;
7297
7298   if (g_str_has_prefix (uri, "rtsp-sdp://")) {
7299     if ((res = gst_sdp_message_new (&sdp) < 0))
7300       goto sdp_failed;
7301
7302     GST_DEBUG_OBJECT (src, "parsing SDP message");
7303     if ((res = gst_sdp_message_parse_uri (uri, sdp) < 0))
7304       goto invalid_sdp;
7305   } else {
7306     /* try to parse */
7307     GST_DEBUG_OBJECT (src, "parsing URI");
7308     if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
7309       goto parse_error;
7310   }
7311
7312   /* if worked, free previous and store new url object along with the original
7313    * location. */
7314   GST_DEBUG_OBJECT (src, "configuring URI");
7315   g_free (src->conninfo.location);
7316   src->conninfo.location = g_strdup (uri);
7317   gst_rtsp_url_free (src->conninfo.url);
7318   src->conninfo.url = newurl;
7319   g_free (src->conninfo.url_str);
7320   if (newurl)
7321     src->conninfo.url_str = gst_rtsp_url_get_request_uri (src->conninfo.url);
7322   else
7323     src->conninfo.url_str = NULL;
7324
7325   if (src->sdp)
7326     gst_sdp_message_free (src->sdp);
7327   src->sdp = sdp;
7328   src->from_sdp = sdp != NULL;
7329
7330   GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
7331   GST_DEBUG_OBJECT (src, "request uri is: %s",
7332       GST_STR_NULL (src->conninfo.url_str));
7333
7334   return TRUE;
7335
7336   /* Special cases */
7337 was_ok:
7338   {
7339     GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
7340     return TRUE;
7341   }
7342 sdp_failed:
7343   {
7344     GST_ERROR_OBJECT (src, "Could not create new SDP (%d)", res);
7345     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7346         "Could not create SDP");
7347     return FALSE;
7348   }
7349 invalid_sdp:
7350   {
7351     GST_ERROR_OBJECT (src, "Not a valid SDP (%d) '%s'", res,
7352         GST_STR_NULL (uri));
7353     gst_sdp_message_free (sdp);
7354     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7355         "Invalid SDP");
7356     return FALSE;
7357   }
7358 parse_error:
7359   {
7360     GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
7361         GST_STR_NULL (uri), res);
7362     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
7363         "Invalid RTSP URI");
7364     return FALSE;
7365   }
7366 }
7367
7368 static void
7369 gst_rtspsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
7370 {
7371   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
7372
7373   iface->get_type = gst_rtspsrc_uri_get_type;
7374   iface->get_protocols = gst_rtspsrc_uri_get_protocols;
7375   iface->get_uri = gst_rtspsrc_uri_get_uri;
7376   iface->set_uri = gst_rtspsrc_uri_set_uri;
7377 }