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