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