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