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