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